Skip to main content

halephant_core/auth/scram/
server.rs

1//! Server-side SCRAM-SHA-256: state machine + wire driver for when
2//! halephant authenticates a downstream client.
3//!
4//! `ScramServer` is the pure state machine (RFC 5802). `authenticate`
5//! is the full wire exchange: given an already-framed client
6//! connection and a pre-fetched [`ScramVerifier`], it sends
7//! `AuthenticationSasl`, drives the SCRAM round-trip, and ends with
8//! `AuthenticationOk` downstream.
9//!
10//! The halephant-level concerns — policy checks, verifier fetching,
11//! tracing spans — live in [`crate::auth::Authenticator`] and are
12//! explicitly NOT part of this module. That separation lets the
13//! pure SCRAM exchange be tested with canned verifiers without
14//! pulling in `Config` or `VerifierCache`.
15
16use base64::Engine;
17use base64::engine::general_purpose::STANDARD as B64;
18use futures_util::{SinkExt, StreamExt};
19use rand::Rng;
20use subtle::ConstantTimeEq;
21use tokio::net::TcpStream;
22use tokio_util::codec::Framed;
23
24use crate::errors;
25use crate::proto::backend::BackendMessage;
26use crate::proto::codec::FrontendCodec;
27use crate::proto::frontend::FrontendMessage;
28
29use super::crypto::{extract_attr, hmac_sha256, sha256};
30use super::verifier::ScramVerifier;
31
32// ---------------------------------------------------------------------------
33// ScramServer — the state machine
34// ---------------------------------------------------------------------------
35
36/// Server-side SCRAM-SHA-256 state machine (RFC 5802). Drives a
37/// single authentication exchange; construct a fresh instance per
38/// client.
39pub struct ScramServer {
40    verifier: ScramVerifier,
41    server_nonce: String,
42    client_first_bare: String,
43    server_first: String,
44}
45
46impl ScramServer {
47    pub fn new(verifier: ScramVerifier) -> Self {
48        let mut nonce_bytes = [0u8; 18];
49        rand::rng().fill(&mut nonce_bytes);
50        let server_nonce = B64.encode(nonce_bytes);
51
52        Self {
53            verifier,
54            server_nonce,
55            client_first_bare: String::new(),
56            server_first: String::new(),
57        }
58    }
59
60    /// Process the client-first-message. Returns the server-first-message.
61    ///
62    /// Input: the raw bytes from the SASLInitialResponse (the initial
63    /// client response data, NOT including the mechanism name).
64    pub fn handle_client_first(&mut self, data: &[u8]) -> Result<Vec<u8>, errors::AuthError> {
65        let msg = std::str::from_utf8(data)
66            .map_err(|_| errors::AuthError::Protocol("client-first-message is not UTF-8".into()))?;
67
68        // Strip GS2 header ("n,,") to get client-first-message-bare.
69        let bare = strip_gs2_header(msg)?;
70        bare.clone_into(&mut self.client_first_bare);
71
72        let client_nonce = extract_attr(bare, 'r')?;
73        let combined_nonce = format!("{client_nonce}{}", self.server_nonce);
74
75        self.server_first = format!(
76            "r={},s={},i={}",
77            combined_nonce,
78            B64.encode(&self.verifier.salt),
79            self.verifier.iterations,
80        );
81
82        Ok(self.server_first.as_bytes().to_vec())
83    }
84
85    /// Process the client-final-message. Returns the server-final-message on
86    /// success, or an error if the client proof is invalid.
87    ///
88    /// Input: the raw bytes from the SASLResponse.
89    pub fn handle_client_final(&self, data: &[u8]) -> Result<Vec<u8>, errors::AuthError> {
90        let msg = std::str::from_utf8(data)
91            .map_err(|_| errors::AuthError::Protocol("client-final-message is not UTF-8".into()))?;
92
93        // Verify the nonce matches the combined nonce from server-first (RFC 5802 §5.1).
94        let expected_nonce = extract_attr(&self.server_first, 'r')?;
95        let actual_nonce = extract_attr(msg, 'r')?;
96        if actual_nonce != expected_nonce {
97            return Err(errors::AuthError::Protocol(
98                "nonce mismatch in client-final".into(),
99            ));
100        }
101
102        let proof_b64 = extract_attr(msg, 'p')?;
103
104        // client-final-message-without-proof: everything before ",p=..."
105        let without_proof = msg
106            .rsplit_once(",p=")
107            .map(|(prefix, _)| prefix)
108            .ok_or_else(|| {
109                errors::AuthError::Protocol("missing proof in client-final-message".into())
110            })?;
111
112        // AuthMessage = client-first-bare + "," + server-first + "," + client-final-without-proof
113        let auth_message = format!(
114            "{},{},{}",
115            self.client_first_bare, self.server_first, without_proof,
116        );
117
118        // Verify the client proof.
119        let client_proof = B64
120            .decode(proof_b64)
121            .map_err(|_| errors::AuthError::Protocol("invalid base64 in client proof".into()))?;
122        if client_proof.len() != 32 {
123            return Err(errors::AuthError::Protocol(
124                "client proof is not 32 bytes".into(),
125            ));
126        }
127
128        let client_signature = hmac_sha256(&self.verifier.stored_key, auth_message.as_bytes());
129
130        // ClientKey = ClientProof XOR ClientSignature
131        let mut client_key = [0u8; 32];
132        for i in 0..32 {
133            client_key[i] = client_proof[i] ^ client_signature[i];
134        }
135
136        // Verify SHA-256(ClientKey) == StoredKey using a constant-time
137        // comparison. `[u8; 32]::eq` (and `!=`) short-circuit on the
138        // first differing byte, which turns credential verification
139        // into a timing oracle: an attacker controls the proof bytes
140        // via the SCRAM exchange, so byte-by-byte comparison lets
141        // them brute-force the computed StoredKey one byte at a time
142        // across repeated authentication attempts. `ConstantTimeEq`
143        // compares all bytes unconditionally.
144        let computed_stored_key = sha256(&client_key);
145        if !bool::from(computed_stored_key.ct_eq(&self.verifier.stored_key)) {
146            return Err(errors::AuthError::InvalidCredentials);
147        }
148
149        // Compute server-final-message.
150        let server_signature = hmac_sha256(&self.verifier.server_key, auth_message.as_bytes());
151        let server_final = format!("v={}", B64.encode(server_signature));
152
153        Ok(server_final.as_bytes().to_vec())
154    }
155}
156
157// ---------------------------------------------------------------------------
158// authenticate — the server-side wire driver
159// ---------------------------------------------------------------------------
160
161/// Drive the server side of SCRAM-SHA-256 over an already-framed
162/// downstream client connection.
163///
164/// On success, `AuthenticationOk` has been sent and the client is
165/// authenticated. The caller is responsible for any halephant-level
166/// concerns before this call (policy checks, verifier fetching,
167/// span setup) and after (sending `ParameterStatus`, `BackendKeyData`,
168/// success/failure logging). This function is pure protocol plumbing
169/// — no tracing events, no knowledge of `Config`, no logging.
170///
171/// Symmetric with [`super::client::authenticate`], which drives the
172/// other side of the same exchange with inverted codec direction.
173pub async fn authenticate(
174    client: &mut Framed<TcpStream, FrontendCodec>,
175    verifier: ScramVerifier,
176) -> Result<(), errors::AuthError> {
177    let mut scram = ScramServer::new(verifier);
178
179    // Step 1: Send AuthenticationSASL to request SCRAM-SHA-256.
180    client
181        .send(BackendMessage::AuthenticationSasl {
182            mechanisms: vec!["SCRAM-SHA-256".into()],
183        })
184        .await?;
185
186    // Step 2: Read client's SASLInitialResponse.
187    let initial_data = match client.next().await.transpose()? {
188        Some(FrontendMessage::PasswordMessage(data)) => data,
189        Some(other) => {
190            return Err(errors::AuthError::Protocol(format!(
191                "expected SASLInitialResponse, got {other:?}"
192            )));
193        }
194        None => {
195            return Err(errors::AuthError::Protocol(
196                "client disconnected during SASL".into(),
197            ));
198        }
199    };
200
201    let (mechanism, client_first) = parse_sasl_initial_response(&initial_data)?;
202    if mechanism != "SCRAM-SHA-256" {
203        return Err(errors::AuthError::Protocol(format!(
204            "unsupported SASL mechanism: {mechanism:?}"
205        )));
206    }
207
208    // Step 3: Process client-first, send server-first via AuthenticationSASLContinue.
209    let server_first = scram.handle_client_first(client_first)?;
210    client
211        .send(BackendMessage::AuthenticationSaslContinue { data: server_first })
212        .await?;
213
214    // Step 4: Read client's SASLResponse (client-final-message).
215    let final_data = match client.next().await.transpose()? {
216        Some(FrontendMessage::PasswordMessage(data)) => data,
217        Some(other) => {
218            return Err(errors::AuthError::Protocol(format!(
219                "expected SASLResponse, got {other:?}"
220            )));
221        }
222        None => {
223            return Err(errors::AuthError::Protocol(
224                "client disconnected during SASL".into(),
225            ));
226        }
227    };
228
229    // Step 5: Verify client proof.
230    let server_final = scram.handle_client_final(&final_data)?;
231
232    // Step 6: Send server-final via AuthenticationSASLFinal, then AuthenticationOk.
233    client
234        .feed(BackendMessage::AuthenticationSaslFinal { data: server_final })
235        .await?;
236    client.send(BackendMessage::AuthenticationOk).await?;
237
238    Ok(())
239}
240
241// ---------------------------------------------------------------------------
242// SASLInitialResponse parsing
243// ---------------------------------------------------------------------------
244
245/// Parse the payload of a PasswordMessage that carries a
246/// SASLInitialResponse. Returns `(mechanism_name, initial_response_data)`.
247///
248/// Server-side only: the client sends this message, the server
249/// parses it. Lives here rather than in `crypto.rs` because nothing
250/// on the client side needs to parse its own outbound frames.
251pub fn parse_sasl_initial_response(data: &[u8]) -> Result<(&str, &[u8]), errors::AuthError> {
252    let nul = data
253        .iter()
254        .position(|&b| b == 0)
255        .ok_or_else(|| errors::AuthError::Protocol("missing null in SASLInitialResponse".into()))?;
256    let mechanism = std::str::from_utf8(&data[..nul])
257        .map_err(|_| errors::AuthError::Protocol("invalid UTF-8 in mechanism name".into()))?;
258    let rest = &data[nul + 1..];
259    if rest.len() < 4 {
260        return Err(errors::AuthError::Protocol(
261            "truncated SASLInitialResponse length".into(),
262        ));
263    }
264    let len = i32::from_be_bytes([rest[0], rest[1], rest[2], rest[3]]);
265    let response = if len < 0 {
266        &[]
267    } else {
268        let len = len as usize;
269        if rest.len() < 4 + len {
270            return Err(errors::AuthError::Protocol(
271                "truncated SASLInitialResponse data".into(),
272            ));
273        }
274        &rest[4..4 + len]
275    };
276    Ok((mechanism, response))
277}
278
279// ---------------------------------------------------------------------------
280// Helpers — server-side only
281// ---------------------------------------------------------------------------
282
283/// Parse and validate the GS2 header from a client-first-message,
284/// returning the bare client-first-message (everything after the
285/// header).
286///
287/// The header has the form `<gs2-cbind-flag>,<authzid>,`. RFC 5802
288/// §5.1 defines three values for the cbind flag:
289///
290/// - `n` — client does not support channel binding.
291/// - `y` — client supports channel binding but believes the server
292///   does not. libpq sends this when `channel_binding=prefer` (its
293///   default) and the server's offered mechanism list omits
294///   `-PLUS`, which is halephant's situation because it only
295///   advertises `SCRAM-SHA-256`. Rejecting `y` here would break
296///   every libpq client connecting over TLS with the default
297///   settings, so we accept it.
298/// - `p=<cbind-type>` — client **requires** channel binding of the
299///   named type. Silently treating this as if the client had sent
300///   `n,,` would strip the client's explicit security requirement
301///   — the client believes the authentication is bound to the TLS
302///   channel when it isn't, leaving it vulnerable to a MITM that
303///   downgrades the exchange. Halephant does not implement channel
304///   binding, so `p=...` is rejected with a clear error rather
305///   than silently accepted.
306///
307/// The authzid field (between the two commas) must be empty:
308/// halephant does not support SASL authzid identity switching, so
309/// a non-empty value is rejected rather than silently ignored —
310/// otherwise a client asking to act as a different identity would
311/// be authenticated as the authentication identity with no warning.
312fn strip_gs2_header(msg: &str) -> Result<&str, errors::AuthError> {
313    let after_flag = if let Some(rest) = msg.strip_prefix("n,") {
314        rest
315    } else if let Some(rest) = msg.strip_prefix("y,") {
316        rest
317    } else if msg.starts_with("p=") {
318        return Err(errors::AuthError::Protocol(
319            "channel binding (gs2-cbind-flag 'p=...') is not supported".into(),
320        ));
321    } else {
322        return Err(errors::AuthError::Protocol(
323            "unsupported or malformed gs2-cbind-flag in client-first-message".into(),
324        ));
325    };
326
327    // Authzid must be empty: the next character has to be the
328    // separator comma that ends the GS2 header. A non-empty authzid
329    // (`a=someuser,`) hits the `None` branch here.
330    after_flag.strip_prefix(',').ok_or_else(|| {
331        errors::AuthError::Protocol("non-empty authzid in GS2 header is not supported".into())
332    })
333}