halephant_core/auth/scram/
client.rs1use 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
30pub 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 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 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 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 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 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 let server_key = hmac_sha256(&self.salted_password, b"Server Key");
166 let client_final_without_proof = {
167 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 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
198pub 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 framed
217 .send(FrontendMessage::PasswordMessage(client.initial_response()))
218 .await?;
219
220 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 let client_final = client.handle_server_first(&server_first).await?;
239 framed
240 .send(FrontendMessage::PasswordMessage(client_final))
241 .await?;
242
243 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 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}