1use crate::{Error, ErrorKind, Result, uri::Credential};
5use base64::{Engine, engine::general_purpose::STANDARD};
6use bson::{Binary, Document, doc, spec::BinarySubtype};
7use hmac::{Hmac, KeyInit, Mac};
8use sha2::Digest;
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum Mechanism {
11 Sha1,
12 Sha256,
13}
14impl Mechanism {
15 pub fn parse(s: &str) -> Result<Self> {
16 match s {
17 "SCRAM-SHA-1" => Ok(Self::Sha1),
18 "SCRAM-SHA-256" => Ok(Self::Sha256),
19 _ => Err(auth_error("Unsupported authentication mechanism")),
20 }
21 }
22 pub fn as_str(self) -> &'static str {
23 match self {
24 Self::Sha1 => "SCRAM-SHA-1",
25 Self::Sha256 => "SCRAM-SHA-256",
26 }
27 }
28}
29pub struct Scram {
30 mechanism: Mechanism,
31 nonce: String,
32 first: String,
33 password: String,
34 conversation: Option<i32>,
35 expected: Vec<u8>,
36 state: u8,
37}
38impl Scram {
39 pub fn new(credential: &Credential, mechanism: Mechanism, nonce: &str) -> Result<Self> {
40 if nonce.len() < 16
41 || nonce
42 .bytes()
43 .any(|c| !(0x21..=0x7e).contains(&c) || c == b',')
44 {
45 return Err(auth_error(
46 "Host must provide a cryptographically random printable nonce of at least 16 bytes",
47 ));
48 }
49 let username = credential.username.replace('=', "=3D").replace(',', "=2C");
50 let password = match mechanism {
51 Mechanism::Sha1 => {
52 use std::fmt::Write;
53 let digest = md5::Md5::digest(
54 format!("{}:mongo:{}", credential.username, credential.password).as_bytes(),
55 );
56 let mut hex = String::with_capacity(32);
57 for byte in digest {
58 write!(hex, "{byte:02x}").expect("writing to a String cannot fail");
59 }
60 hex
61 }
62 Mechanism::Sha256 => stringprep::saslprep(&credential.password)
63 .map_err(|_| auth_error("Password cannot be SASLprep normalized"))?
64 .into_owned(),
65 };
66 Ok(Self {
67 mechanism,
68 nonce: nonce.into(),
69 first: format!("n={username},r={nonce}"),
70 password,
71 conversation: None,
72 expected: Vec::new(),
73 state: 0,
74 })
75 }
76 pub fn start(&mut self, source: &str, speculative: bool) -> Document {
77 self.state = 1;
78 let mut d = doc! {"saslStart":1,"mechanism":self.mechanism.as_str(),"payload":binary(format!("n,,{}",self.first).into_bytes()),"options":{"skipEmptyExchange":true}};
79 if speculative {
80 d.insert("db", source);
81 } else {
82 d.insert("$db", source);
83 }
84 d
85 }
86 pub fn receive(&mut self, response: &Document, source: &str) -> Result<Option<Document>> {
87 let id = response
88 .get_i32("conversationId")
89 .map_err(|_| auth_error("Missing SCRAM conversation id"))?;
90 if self.conversation.is_some_and(|v| v != id) {
91 return Err(auth_error("SCRAM conversation id changed"));
92 }
93 self.conversation = Some(id);
94 let payload = response
95 .get_binary_generic("payload")
96 .map_err(|_| auth_error("Missing SCRAM payload"))?;
97 let done = response
98 .get_bool("done")
99 .map_err(|_| auth_error("Missing SCRAM done"))?;
100 let payload =
101 std::str::from_utf8(payload).map_err(|_| auth_error("Invalid SCRAM UTF-8"))?;
102 let next = match self.state {
103 1 => {
104 if done {
105 return Err(auth_error("SCRAM ended before server proof"));
106 }
107 let attrs = parse_attributes(payload)?;
108 if attrs.iter().any(|(k, _)| *k == "m") {
109 return Err(auth_error("Unsupported SCRAM extension"));
110 }
111 let get = |k| {
112 attrs
113 .iter()
114 .find(|(key, _)| *key == k)
115 .map(|(_, v)| *v)
116 .ok_or_else(|| auth_error("Missing SCRAM attribute"))
117 };
118 let nonce = get("r")?;
119 if !nonce.starts_with(&self.nonce) || nonce.len() <= self.nonce.len() {
120 return Err(auth_error(
121 "Server SCRAM nonce does not extend client nonce",
122 ));
123 }
124 let salt = STANDARD
125 .decode(get("s")?)
126 .map_err(|_| auth_error("Invalid SCRAM salt"))?;
127 let rounds = get("i")?
128 .parse::<u32>()
129 .map_err(|_| auth_error("Invalid SCRAM iteration count"))?;
130 if !(4096..=1_000_000).contains(&rounds) {
131 return Err(auth_error(
132 "SCRAM iteration count outside supported range 4096..1000000",
133 ));
134 }
135 let final_bare = format!("c=biws,r={nonce}");
136 let auth_message = format!("{},{payload},{final_bare}", self.first);
137 macro_rules! derive {
138 ($hash:ty,$len:expr) => {{
139 let mut salted = [0u8; $len];
140 pbkdf2::pbkdf2_hmac::<$hash>(
141 self.password.as_bytes(),
142 &salt,
143 rounds,
144 &mut salted,
145 );
146 let mut client = <Hmac<$hash>>::new_from_slice(&salted).unwrap();
147 client.update(b"Client Key");
148 let key = client.finalize().into_bytes();
149 let stored = <$hash>::digest(key);
150 let mut sig = <Hmac<$hash>>::new_from_slice(&stored).unwrap();
151 sig.update(auth_message.as_bytes());
152 let sig = sig.finalize().into_bytes();
153 let proof: Vec<u8> = key.iter().zip(sig).map(|(a, b)| a ^ b).collect();
154 let mut server = <Hmac<$hash>>::new_from_slice(&salted).unwrap();
155 server.update(b"Server Key");
156 let mut expected =
157 <Hmac<$hash>>::new_from_slice(&server.finalize().into_bytes()).unwrap();
158 expected.update(auth_message.as_bytes());
159 self.expected = expected.finalize().into_bytes().to_vec();
160 salted.fill(0);
161 proof
162 }};
163 }
164 let proof = match self.mechanism {
165 Mechanism::Sha1 => derive!(sha1::Sha1, 20),
166 Mechanism::Sha256 => derive!(sha2::Sha256, 32),
167 };
168 self.password.clear();
169 self.state = 2;
170 format!("{final_bare},p={}", STANDARD.encode(proof)).into_bytes()
171 }
172 2 => {
173 let attrs = parse_attributes(payload)?;
174 if attrs.iter().any(|(k, _)| *k == "e") {
175 return Err(auth_error("SCRAM server rejected authentication"));
176 }
177 let signature = attrs
178 .iter()
179 .find(|(k, _)| *k == "v")
180 .ok_or_else(|| auth_error("Missing SCRAM server signature"))?
181 .1;
182 let signature = STANDARD
183 .decode(signature)
184 .map_err(|_| auth_error("Invalid SCRAM server signature"))?;
185 let difference = signature
187 .iter()
188 .zip(&self.expected)
189 .fold(0u8, |acc, (a, b)| acc | (a ^ b));
190 if signature.len() != self.expected.len() || difference != 0 {
191 return Err(auth_error("SCRAM server signature mismatch"));
192 }
193 self.state = if done { 4 } else { 3 };
194 if done {
195 return Ok(None);
196 }
197 Vec::new()
198 }
199 3 => {
200 if !done || !payload.is_empty() {
201 return Err(auth_error("Invalid SCRAM final exchange"));
202 }
203 self.state = 4;
204 return Ok(None);
205 }
206 _ => return Err(auth_error("Unexpected SCRAM response")),
207 };
208 Ok(Some(
209 doc! {"saslContinue":1,"conversationId":id,"payload":binary(next),"$db":source},
210 ))
211 }
212}
213fn parse_attributes(s: &str) -> Result<Vec<(&str, &str)>> {
214 let mut a = Vec::new();
215 for part in s.split(',') {
216 let (k, v) = part
217 .split_once('=')
218 .ok_or_else(|| auth_error("Malformed SCRAM attribute"))?;
219 if k.len() != 1 || a.iter().any(|(x, _)| *x == k) {
220 return Err(auth_error("Duplicate or malformed SCRAM attribute"));
221 }
222 a.push((k, v));
223 }
224 Ok(a)
225}
226fn binary(bytes: Vec<u8>) -> Binary {
227 Binary {
228 subtype: BinarySubtype::Generic,
229 bytes,
230 }
231}
232fn auth_error(s: &'static str) -> Error {
233 Error::new(ErrorKind::Authentication, s)
234}