Skip to main content

halephant_core/auth/scram/
client.rs

1//! Client-side SCRAM-SHA-256: state machine + wire driver for when
2//! halephant authenticates against an upstream PostgreSQL server.
3//!
4//! `ScramClient` is the pure state machine. `authenticate` is the
5//! full wire exchange: given an already-framed upstream connection
6//! and a plaintext password, it sends the SASL initial response,
7//! drives the round-trip, and consumes the upstream's
8//! `AuthenticationOk`.
9//!
10//! Symmetric with [`super::server`] but inverted along the wire:
11//! halephant is the party *proving* knowledge of the password here,
12//! not the party verifying a proof.
13
14use base64::Engine;
15use base64::engine::general_purpose::STANDARD as B64;
16use futures_util::{SinkExt, StreamExt};
17use rand::Rng;
18use sha2::Sha256;
19use subtle::ConstantTimeEq;
20use tokio::net::TcpStream;
21use tokio_util::codec::Framed;
22
23use crate::errors;
24use crate::proto::backend::BackendMessage;
25use crate::proto::codec::BackendCodec;
26use crate::proto::frontend::FrontendMessage;
27
28use super::crypto::{extract_attr, hmac_sha256, sha256};
29
30// ---------------------------------------------------------------------------
31// ScramClient — the state machine
32// ---------------------------------------------------------------------------
33
34/// Client-side SCRAM-SHA-256 state machine. Holds the plaintext
35/// password and the derived keys for one authentication exchange.
36/// Construct a fresh instance per upstream connection.
37pub struct ScramClient {
38    password: String,
39    nonce: String,
40    client_first_bare: String,
41    server_first: String,
42    salted_password: [u8; 32],
43}
44
45impl ScramClient {
46    pub fn new(password: &str) -> Self {
47        let mut nonce_bytes = [0u8; 18];
48        rand::rng().fill(&mut nonce_bytes);
49        let nonce = B64.encode(nonce_bytes);
50
51        let client_first_bare = format!("n=,r={nonce}");
52
53        Self {
54            password: password.to_owned(),
55            nonce,
56            client_first_bare,
57            server_first: String::new(),
58            salted_password: [0u8; 32],
59        }
60    }
61
62    /// Build the SASLInitialResponse payload (mechanism name + client-first-message).
63    pub fn initial_response(&self) -> Vec<u8> {
64        let mechanism = b"SCRAM-SHA-256\0";
65        let client_first = format!("n,,{}", self.client_first_bare);
66        let data = client_first.as_bytes();
67        let mut buf = Vec::with_capacity(mechanism.len() + 4 + data.len());
68        buf.extend_from_slice(mechanism);
69        buf.extend_from_slice(&(data.len() as i32).to_be_bytes());
70        buf.extend_from_slice(data);
71        buf
72    }
73
74    /// Process the server-first-message (from `AuthenticationSASLContinue`).
75    /// Returns the client-final-message bytes to send as `SASLResponse`.
76    ///
77    /// This method is `async` because it offloads the PBKDF2 key
78    /// derivation to the tokio blocking thread pool. PostgreSQL 15+
79    /// defaults to 600_000 iterations (up from 4_096 in earlier
80    /// versions), which takes hundreds of milliseconds to hash —
81    /// running that synchronously on an async worker would starve
82    /// every other task on the same worker thread for the full
83    /// duration. `VerifierCache::try_get_with` additionally
84    /// coalesces concurrent auth requests, so a cache miss under
85    /// blocking PBKDF2 would freeze every pending authenticator
86    /// waiting on the shared fetch.
87    pub async fn handle_server_first(&mut self, data: &[u8]) -> Result<Vec<u8>, errors::AuthError> {
88        let msg = std::str::from_utf8(data)
89            .map_err(|_| errors::AuthError::Protocol("server-first-message is not UTF-8".into()))?;
90
91        msg.clone_into(&mut self.server_first);
92
93        let combined_nonce = extract_attr(msg, 'r')?;
94        if !combined_nonce.starts_with(&self.nonce) {
95            return Err(errors::AuthError::Protocol(
96                "server nonce does not start with client nonce".into(),
97            ));
98        }
99
100        let salt_b64 = extract_attr(msg, 's')?;
101        let salt = B64
102            .decode(salt_b64)
103            .map_err(|_| errors::AuthError::Protocol("invalid base64 in salt".into()))?;
104        let iterations: u32 = extract_attr(msg, 'i')?
105            .parse()
106            .map_err(|_| errors::AuthError::Protocol("invalid iteration count".into()))?;
107
108        // Derive SaltedPassword via PBKDF2 on the blocking thread
109        // pool — see the method docstring for the motivation. The
110        // password and salt must be owned by the closure because
111        // `spawn_blocking` requires a `'static` bound; `password`
112        // is cloned from `self.password` and `salt` is already the
113        // owned `Vec<u8>` from the B64 decode above.
114        let password = self.password.clone();
115        self.salted_password = tokio::task::spawn_blocking(move || {
116            let mut out = [0u8; 32];
117            pbkdf2::pbkdf2_hmac::<Sha256>(password.as_bytes(), &salt, iterations, &mut out);
118            out
119        })
120        .await
121        .map_err(|e| errors::AuthError::Protocol(format!("pbkdf2 task failed: {e}")))?;
122
123        let client_key = hmac_sha256(&self.salted_password, b"Client Key");
124        let stored_key = sha256(&client_key);
125
126        let client_final_without_proof = format!("c=biws,r={combined_nonce}");
127        let auth_message = format!(
128            "{},{},{}",
129            self.client_first_bare, self.server_first, client_final_without_proof,
130        );
131
132        let client_signature = hmac_sha256(&stored_key, auth_message.as_bytes());
133        let mut client_proof = [0u8; 32];
134        for i in 0..32 {
135            client_proof[i] = client_key[i] ^ client_signature[i];
136        }
137
138        let client_final = format!(
139            "{},p={}",
140            client_final_without_proof,
141            B64.encode(client_proof),
142        );
143
144        Ok(client_final.as_bytes().to_vec())
145    }
146
147    /// Verify the server-final-message (from `AuthenticationSASLFinal`).
148    pub fn handle_server_final(&self, data: &[u8]) -> Result<(), errors::AuthError> {
149        let msg = std::str::from_utf8(data)
150            .map_err(|_| errors::AuthError::Protocol("server-final-message is not UTF-8".into()))?;
151
152        // Check for server error.
153        if msg.starts_with("e=") {
154            return Err(errors::AuthError::Protocol(format!(
155                "SCRAM server error: {msg}"
156            )));
157        }
158
159        let verifier_b64 = extract_attr(msg, 'v')?;
160        let server_signature = B64.decode(verifier_b64).map_err(|_| {
161            errors::AuthError::Protocol("invalid base64 in server signature".into())
162        })?;
163
164        // Recompute expected server signature.
165        let server_key = hmac_sha256(&self.salted_password, b"Server Key");
166        let client_final_without_proof = {
167            // Reconstruct from server_first nonce.
168            let combined_nonce = extract_attr(&self.server_first, 'r').map_err(|_| {
169                errors::AuthError::Protocol("missing nonce in cached server-first".into())
170            })?;
171            format!("c=biws,r={combined_nonce}")
172        };
173        let auth_message = format!(
174            "{},{},{}",
175            self.client_first_bare, self.server_first, client_final_without_proof,
176        );
177        let expected = hmac_sha256(&server_key, auth_message.as_bytes());
178
179        // Constant-time comparison against the expected server
180        // signature. Same reasoning as the server-side proof check:
181        // an attacker impersonating the upstream (MITM or rogue
182        // proxy) could otherwise time-attack this comparison to
183        // brute-force `expected` byte by byte across repeated
184        // authentication attempts. `ct_eq` on `&[u8]` returns
185        // `Choice(0)` if lengths differ, so the explicit length
186        // guard below is redundant for correctness but makes the
187        // 32-byte invariant visible at the call site.
188        if server_signature.len() != 32 || !bool::from(server_signature.ct_eq(&expected[..])) {
189            return Err(errors::AuthError::Protocol(
190                "server signature verification failed".into(),
191            ));
192        }
193
194        Ok(())
195    }
196}
197
198// ---------------------------------------------------------------------------
199// authenticate — the client-side wire driver
200// ---------------------------------------------------------------------------
201
202/// Drive the client side of SCRAM-SHA-256 on an already-framed
203/// upstream connection. Call this after receiving `AuthenticationSasl`
204/// with SCRAM-SHA-256 in the mechanism list. On success,
205/// `AuthenticationOk` has been consumed from the stream.
206///
207/// Symmetric with [`super::server::authenticate`], which drives the
208/// other side of the same exchange with inverted codec direction.
209pub async fn authenticate(
210    framed: &mut Framed<TcpStream, BackendCodec>,
211    password: &str,
212) -> Result<(), errors::AuthError> {
213    let mut client = ScramClient::new(password);
214
215    // Send SASLInitialResponse.
216    framed
217        .send(FrontendMessage::PasswordMessage(client.initial_response()))
218        .await?;
219
220    // Read AuthenticationSASLContinue.
221    let server_first = match framed.next().await.transpose()? {
222        Some(BackendMessage::AuthenticationSaslContinue { data }) => data,
223        Some(BackendMessage::ErrorResponse(err)) => {
224            return Err(errors::AuthError::VerifierFetch(format!(
225                "SCRAM auth error: {}",
226                err.message().unwrap_or("unknown")
227            )));
228        }
229        other => {
230            return Err(errors::AuthError::Protocol(format!(
231                "expected AuthenticationSASLContinue, got {other:?}"
232            )));
233        }
234    };
235
236    // Send SASLResponse (client-final). `handle_server_first` is
237    // async because it offloads PBKDF2 to the blocking thread pool.
238    let client_final = client.handle_server_first(&server_first).await?;
239    framed
240        .send(FrontendMessage::PasswordMessage(client_final))
241        .await?;
242
243    // Read AuthenticationSASLFinal.
244    match framed.next().await.transpose()? {
245        Some(BackendMessage::AuthenticationSaslFinal { data }) => {
246            client.handle_server_final(&data)?;
247        }
248        Some(BackendMessage::ErrorResponse(err)) => {
249            return Err(errors::AuthError::VerifierFetch(format!(
250                "SCRAM auth failed: {}",
251                err.message().unwrap_or("unknown")
252            )));
253        }
254        other => {
255            return Err(errors::AuthError::Protocol(format!(
256                "expected AuthenticationSASLFinal, got {other:?}"
257            )));
258        }
259    }
260
261    // AuthenticationOk follows.
262    match framed.next().await.transpose()? {
263        Some(BackendMessage::AuthenticationOk) => Ok(()),
264        Some(BackendMessage::ErrorResponse(err)) => Err(errors::AuthError::VerifierFetch(format!(
265            "auth failed after SCRAM: {}",
266            err.message().unwrap_or("unknown")
267        ))),
268        other => Err(errors::AuthError::Protocol(format!(
269            "expected AuthenticationOk, got {other:?}"
270        ))),
271    }
272}