use base64::Engine;
use base64::engine::general_purpose::STANDARD as B64;
use futures_util::{SinkExt, StreamExt};
use rand::Rng;
use subtle::ConstantTimeEq;
use tokio::net::TcpStream;
use tokio_util::codec::Framed;
use crate::errors;
use crate::proto::backend::BackendMessage;
use crate::proto::codec::FrontendCodec;
use crate::proto::frontend::FrontendMessage;
use super::crypto::{extract_attr, hmac_sha256, sha256};
use super::verifier::ScramVerifier;
pub struct ScramServer {
verifier: ScramVerifier,
server_nonce: String,
client_first_bare: String,
server_first: String,
}
impl ScramServer {
pub fn new(verifier: ScramVerifier) -> Self {
let mut nonce_bytes = [0u8; 18];
rand::rng().fill(&mut nonce_bytes);
let server_nonce = B64.encode(nonce_bytes);
Self {
verifier,
server_nonce,
client_first_bare: String::new(),
server_first: String::new(),
}
}
pub fn handle_client_first(&mut self, data: &[u8]) -> Result<Vec<u8>, errors::AuthError> {
let msg = std::str::from_utf8(data)
.map_err(|_| errors::AuthError::Protocol("client-first-message is not UTF-8".into()))?;
let bare = strip_gs2_header(msg)?;
bare.clone_into(&mut self.client_first_bare);
let client_nonce = extract_attr(bare, 'r')?;
let combined_nonce = format!("{client_nonce}{}", self.server_nonce);
self.server_first = format!(
"r={},s={},i={}",
combined_nonce,
B64.encode(&self.verifier.salt),
self.verifier.iterations,
);
Ok(self.server_first.as_bytes().to_vec())
}
pub fn handle_client_final(&self, data: &[u8]) -> Result<Vec<u8>, errors::AuthError> {
let msg = std::str::from_utf8(data)
.map_err(|_| errors::AuthError::Protocol("client-final-message is not UTF-8".into()))?;
let expected_nonce = extract_attr(&self.server_first, 'r')?;
let actual_nonce = extract_attr(msg, 'r')?;
if actual_nonce != expected_nonce {
return Err(errors::AuthError::Protocol(
"nonce mismatch in client-final".into(),
));
}
let proof_b64 = extract_attr(msg, 'p')?;
let without_proof = msg
.rsplit_once(",p=")
.map(|(prefix, _)| prefix)
.ok_or_else(|| {
errors::AuthError::Protocol("missing proof in client-final-message".into())
})?;
let auth_message = format!(
"{},{},{}",
self.client_first_bare, self.server_first, without_proof,
);
let client_proof = B64
.decode(proof_b64)
.map_err(|_| errors::AuthError::Protocol("invalid base64 in client proof".into()))?;
if client_proof.len() != 32 {
return Err(errors::AuthError::Protocol(
"client proof is not 32 bytes".into(),
));
}
let client_signature = hmac_sha256(&self.verifier.stored_key, auth_message.as_bytes());
let mut client_key = [0u8; 32];
for i in 0..32 {
client_key[i] = client_proof[i] ^ client_signature[i];
}
let computed_stored_key = sha256(&client_key);
if !bool::from(computed_stored_key.ct_eq(&self.verifier.stored_key)) {
return Err(errors::AuthError::InvalidCredentials);
}
let server_signature = hmac_sha256(&self.verifier.server_key, auth_message.as_bytes());
let server_final = format!("v={}", B64.encode(server_signature));
Ok(server_final.as_bytes().to_vec())
}
}
pub async fn authenticate(
client: &mut Framed<TcpStream, FrontendCodec>,
verifier: ScramVerifier,
) -> Result<(), errors::AuthError> {
let mut scram = ScramServer::new(verifier);
client
.send(BackendMessage::AuthenticationSasl {
mechanisms: vec!["SCRAM-SHA-256".into()],
})
.await?;
let initial_data = match client.next().await.transpose()? {
Some(FrontendMessage::PasswordMessage(data)) => data,
Some(other) => {
return Err(errors::AuthError::Protocol(format!(
"expected SASLInitialResponse, got {other:?}"
)));
}
None => {
return Err(errors::AuthError::Protocol(
"client disconnected during SASL".into(),
));
}
};
let (mechanism, client_first) = parse_sasl_initial_response(&initial_data)?;
if mechanism != "SCRAM-SHA-256" {
return Err(errors::AuthError::Protocol(format!(
"unsupported SASL mechanism: {mechanism:?}"
)));
}
let server_first = scram.handle_client_first(client_first)?;
client
.send(BackendMessage::AuthenticationSaslContinue { data: server_first })
.await?;
let final_data = match client.next().await.transpose()? {
Some(FrontendMessage::PasswordMessage(data)) => data,
Some(other) => {
return Err(errors::AuthError::Protocol(format!(
"expected SASLResponse, got {other:?}"
)));
}
None => {
return Err(errors::AuthError::Protocol(
"client disconnected during SASL".into(),
));
}
};
let server_final = scram.handle_client_final(&final_data)?;
client
.feed(BackendMessage::AuthenticationSaslFinal { data: server_final })
.await?;
client.send(BackendMessage::AuthenticationOk).await?;
Ok(())
}
pub fn parse_sasl_initial_response(data: &[u8]) -> Result<(&str, &[u8]), errors::AuthError> {
let nul = data
.iter()
.position(|&b| b == 0)
.ok_or_else(|| errors::AuthError::Protocol("missing null in SASLInitialResponse".into()))?;
let mechanism = std::str::from_utf8(&data[..nul])
.map_err(|_| errors::AuthError::Protocol("invalid UTF-8 in mechanism name".into()))?;
let rest = &data[nul + 1..];
if rest.len() < 4 {
return Err(errors::AuthError::Protocol(
"truncated SASLInitialResponse length".into(),
));
}
let len = i32::from_be_bytes([rest[0], rest[1], rest[2], rest[3]]);
let response = if len < 0 {
&[]
} else {
let len = len as usize;
if rest.len() < 4 + len {
return Err(errors::AuthError::Protocol(
"truncated SASLInitialResponse data".into(),
));
}
&rest[4..4 + len]
};
Ok((mechanism, response))
}
fn strip_gs2_header(msg: &str) -> Result<&str, errors::AuthError> {
let after_flag = if let Some(rest) = msg.strip_prefix("n,") {
rest
} else if let Some(rest) = msg.strip_prefix("y,") {
rest
} else if msg.starts_with("p=") {
return Err(errors::AuthError::Protocol(
"channel binding (gs2-cbind-flag 'p=...') is not supported".into(),
));
} else {
return Err(errors::AuthError::Protocol(
"unsupported or malformed gs2-cbind-flag in client-first-message".into(),
));
};
after_flag.strip_prefix(',').ok_or_else(|| {
errors::AuthError::Protocol("non-empty authzid in GS2 header is not supported".into())
})
}