Skip to main content

io_smtp/rfc7677/
auth_scram_sha_256.rs

1//! SMTP SASL SCRAM-SHA-256 coroutine. Always sends the
2//! client-first-message SASL-IR (RFC 4954 §4); verifies the
3//! server's final signature before returning `Ok`.
4//!
5//! SCRAM:         <https://www.rfc-editor.org/rfc/rfc5802>
6//! SCRAM-SHA-256: <https://www.rfc-editor.org/rfc/rfc7677>
7//!
8//! # Example
9//!
10//! ```rust,no_run
11//! use std::{
12//!     borrow::Cow,
13//!     io::{Read, Write},
14//!     net::TcpStream,
15//! };
16//!
17//! use secrecy::SecretString;
18//!
19//! use io_smtp::{
20//!     coroutine::{SmtpCoroutine, SmtpCoroutineState, SmtpYield},
21//!     rfc5321::{SmtpDomain, SmtpEhloDomain},
22//!     rfc7677::auth_scram_sha_256::{SmtpAuthScramSha256, SmtpAuthScramSha256Options},
23//! };
24//!
25//! // Ready stream needed (TCP-connected, TLS-negociated, EHLO consumed)
26//! let mut stream = TcpStream::connect("localhost:25").unwrap();
27//!
28//! let mut buf = [0u8; 4096];
29//!
30//! let password = SecretString::from("secret".to_string());
31//! let nonce = b"fyko+d2lbbFgONRv9qkxdawL";
32//! let domain = SmtpEhloDomain::SmtpDomain(SmtpDomain(Cow::Borrowed("client.example.org")));
33//! let opts = SmtpAuthScramSha256Options::default();
34//! let mut coroutine = SmtpAuthScramSha256::new("alice", &password, nonce, domain, opts);
35//! let mut arg = None;
36//!
37//! loop {
38//!     match coroutine.resume(arg.take()) {
39//!         SmtpCoroutineState::Yielded(SmtpYield::WantsWrite(bytes)) => {
40//!             stream.write_all(&bytes).unwrap();
41//!         }
42//!         SmtpCoroutineState::Yielded(SmtpYield::WantsRead) => {
43//!             let n = stream.read(&mut buf).unwrap();
44//!             arg = Some(&buf[..n]);
45//!         }
46//!         SmtpCoroutineState::Complete(Ok(())) => break,
47//!         SmtpCoroutineState::Complete(Err(err)) => panic!("{err}"),
48//!     }
49//! }
50//! ```
51
52use core::{fmt, str::from_utf8};
53
54use alloc::{
55    borrow::Cow,
56    string::{String, ToString},
57    vec::Vec,
58};
59
60use base64::{Engine, engine::general_purpose::STANDARD as base64};
61use bounded_static::IntoBoundedStatic;
62use hmac::{Hmac, KeyInit, Mac};
63use log::debug;
64use pbkdf2::pbkdf2_hmac;
65use secrecy::{ExposeSecret, SecretBox, SecretString};
66use sha2::{Digest, Sha256};
67use thiserror::Error;
68
69use crate::{
70    coroutine::*,
71    rfc4954::{auth::SmtpAuthCommand, auth_data::SmtpAuthData},
72    rfc5321::{
73        SmtpEhloDomain, SmtpReplyCode,
74        ehlo::{SmtpEhlo, SmtpEhloError},
75    },
76    send::*,
77    smtp_try,
78};
79
80type HmacSha256 = Hmac<Sha256>;
81
82/// The SASL mechanism name as it appears on the wire.
83pub const SCRAM_SHA_256: &str = "SCRAM-SHA-256";
84
85/// Options for [`SmtpAuthScramSha256::new`].
86#[derive(Clone, Debug, Eq, PartialEq)]
87pub struct SmtpAuthScramSha256Options {
88    /// Ignored (SCRAM always sends client-first SASL-IR); kept for
89    /// option surface parity with the other SASL coroutines.
90    pub initial_request: bool,
91    /// Whether to refresh capabilities with an `EHLO` after a successful auth.
92    /// Disabled by default because the mechanism does not add a security layer.
93    pub ensure_capabilities: bool,
94}
95
96impl Default for SmtpAuthScramSha256Options {
97    fn default() -> Self {
98        Self {
99            initial_request: true,
100            ensure_capabilities: false,
101        }
102    }
103}
104
105/// Failure causes during the SMTP AUTH SCRAM-SHA-256 exchange.
106#[derive(Debug, Error)]
107pub enum SmtpAuthScramSha256Error {
108    /// The server rejected the authentication.
109    #[error("SMTP AUTH SCRAM-SHA-256 failed: rejected {code} {message}")]
110    Rejected {
111        /// The reply code.
112        code: u16,
113        /// The reply text.
114        message: String,
115    },
116    /// The server-first-message could not be parsed.
117    #[error("SMTP AUTH SCRAM-SHA-256 failed: server-first-message parse error: {0}")]
118    ParseServerFirst(String),
119    /// The server nonce does not extend the client nonce.
120    #[error("SMTP AUTH SCRAM-SHA-256 failed: server nonce does not start with client nonce")]
121    NonceMismatch,
122    /// The server signature does not match the expected one.
123    #[error("SMTP AUTH SCRAM-SHA-256 failed: server signature mismatch")]
124    ServerSignatureMismatch,
125    /// The underlying command exchange failed.
126    #[error("SMTP AUTH SCRAM-SHA-256 failed: {0}")]
127    Send(#[from] SmtpCommandSendError),
128    /// The post-authentication capability refresh failed.
129    #[error(transparent)]
130    Ehlo(#[from] SmtpEhloError),
131}
132
133/// I/O-free SMTP AUTH SCRAM-SHA-256 coroutine. `nonce` must be
134/// printable ASCII (no commas); RFC 5802 recommends at least 18
135/// bytes of cryptographic randomness.
136pub struct SmtpAuthScramSha256 {
137    state: State,
138    client_first_bare: Vec<u8>,
139    password: SecretString,
140    domain: Option<SmtpEhloDomain<'static>>,
141    expected_server_sig: Vec<u8>,
142    opts: SmtpAuthScramSha256Options,
143}
144
145impl SmtpAuthScramSha256 {
146    /// Creates the coroutine from the credentials, the client nonce
147    /// and the client identity used by the capability refresh.
148    pub fn new(
149        username: &str,
150        password: &SecretString,
151        nonce: &[u8],
152        domain: SmtpEhloDomain<'_>,
153        opts: SmtpAuthScramSha256Options,
154    ) -> Self {
155        let encoded_username = sasl_name(username);
156
157        let mut client_first_bare = Vec::new();
158        client_first_bare.extend_from_slice(b"n=");
159        client_first_bare.extend_from_slice(encoded_username.as_bytes());
160        client_first_bare.extend_from_slice(b",r=");
161        client_first_bare.extend_from_slice(nonce);
162
163        let mut client_first = Vec::new();
164        client_first.extend_from_slice(b"n,,");
165        client_first.extend_from_slice(&client_first_bare);
166
167        let cmd = SmtpAuthCommand {
168            mechanism: Cow::Borrowed(SCRAM_SHA_256),
169            initial_response: Some(SecretBox::new(client_first.into_boxed_slice())),
170        };
171
172        Self {
173            state: State::SendInitial(SmtpCommandSend::new(cmd)),
174            client_first_bare,
175            password: password.clone(),
176            domain: Some(domain.into_static()),
177            expected_server_sig: Vec::new(),
178            opts,
179        }
180    }
181
182    fn compute_client_final(
183        &mut self,
184        server_first: &str,
185    ) -> Result<Vec<u8>, SmtpAuthScramSha256Error> {
186        let mut combined_nonce: Option<&str> = None;
187        let mut salt_b64: Option<&str> = None;
188        let mut iterations: Option<u32> = None;
189
190        for field in server_first.split(',') {
191            if let Some(val) = field.strip_prefix("r=") {
192                combined_nonce = Some(val);
193            } else if let Some(val) = field.strip_prefix("s=") {
194                salt_b64 = Some(val);
195            } else if let Some(val) = field.strip_prefix("i=") {
196                iterations = val.parse().ok();
197            }
198        }
199
200        let combined_nonce = combined_nonce
201            .ok_or_else(|| SmtpAuthScramSha256Error::ParseServerFirst("missing r=".into()))?;
202        let salt_b64 = salt_b64
203            .ok_or_else(|| SmtpAuthScramSha256Error::ParseServerFirst("missing s=".into()))?;
204        let iterations = iterations
205            .ok_or_else(|| SmtpAuthScramSha256Error::ParseServerFirst("missing i=".into()))?;
206
207        let client_nonce = self
208            .client_first_bare
209            .iter()
210            .position(|&b| b == b'r')
211            .and_then(|p| {
212                if self.client_first_bare.get(p + 1) == Some(&b'=') {
213                    Some(&self.client_first_bare[p + 2..])
214                } else {
215                    None
216                }
217            })
218            .unwrap_or(&[]);
219
220        let client_nonce_str = from_utf8(client_nonce).unwrap_or("");
221        if !combined_nonce.starts_with(client_nonce_str) {
222            return Err(SmtpAuthScramSha256Error::NonceMismatch);
223        }
224
225        let salt = base64
226            .decode(salt_b64.as_bytes())
227            .map_err(|e| SmtpAuthScramSha256Error::ParseServerFirst(e.to_string()))?;
228
229        let password_bytes = self.password.expose_secret().as_bytes();
230        let mut salted_password = [0u8; 32];
231        pbkdf2_hmac::<Sha256>(password_bytes, &salt, iterations, &mut salted_password);
232
233        let client_key = hmac_sha256(&salted_password, b"Client Key");
234        let stored_key: [u8; 32] = Sha256::digest(client_key).into();
235
236        let mut client_final_no_proof = Vec::new();
237        client_final_no_proof.extend_from_slice(b"c=biws,r=");
238        client_final_no_proof.extend_from_slice(combined_nonce.as_bytes());
239
240        let mut auth_message: Vec<u8> = Vec::new();
241        auth_message.extend_from_slice(&self.client_first_bare);
242        auth_message.push(b',');
243        auth_message.extend_from_slice(server_first.as_bytes());
244        auth_message.push(b',');
245        auth_message.extend_from_slice(&client_final_no_proof);
246
247        let client_signature = hmac_sha256(&stored_key, &auth_message);
248
249        let mut client_proof = client_key;
250        for (p, s) in client_proof.iter_mut().zip(client_signature.iter()) {
251            *p ^= s;
252        }
253
254        let server_key = hmac_sha256(&salted_password, b"Server Key");
255        let server_signature = hmac_sha256(&server_key, &auth_message);
256        self.expected_server_sig = server_signature.to_vec();
257
258        let mut client_final = client_final_no_proof;
259        client_final.extend_from_slice(b",p=");
260        client_final.extend_from_slice(base64.encode(client_proof).as_bytes());
261
262        Ok(client_final)
263    }
264
265    fn advance_after_auth(&mut self) {
266        debug!("authenticated");
267        if self.opts.ensure_capabilities {
268            let domain = self.domain.take().expect("domain taken twice");
269            self.state = State::Ehlo(SmtpEhlo::new(domain));
270        } else {
271            self.state = State::Done;
272        }
273    }
274}
275
276impl SmtpCoroutine for SmtpAuthScramSha256 {
277    type Yield = SmtpYield;
278    type Return = Result<(), SmtpAuthScramSha256Error>;
279
280    fn resume(&mut self, arg: Option<&[u8]>) -> SmtpCoroutineState<Self::Yield, Self::Return> {
281        loop {
282            match &mut self.state {
283                State::SendInitial(send) => {
284                    let out = smtp_try!(send, arg);
285
286                    if out.response.code != SmtpReplyCode::AUTH_CONTINUE {
287                        let code = out.response.code.code();
288                        let message = out.response.text().to_string();
289                        return SmtpCoroutineState::Complete(Err(
290                            SmtpAuthScramSha256Error::Rejected { code, message },
291                        ));
292                    }
293
294                    let server_first_b64 = out.response.text().0.trim_start();
295                    let server_first_bytes = match base64.decode(server_first_b64.as_bytes()) {
296                        Ok(b) => b,
297                        Err(e) => {
298                            return SmtpCoroutineState::Complete(Err(
299                                SmtpAuthScramSha256Error::ParseServerFirst(e.to_string()),
300                            ));
301                        }
302                    };
303
304                    let server_first = match from_utf8(&server_first_bytes) {
305                        Ok(s) => s.to_string(),
306                        Err(e) => {
307                            return SmtpCoroutineState::Complete(Err(
308                                SmtpAuthScramSha256Error::ParseServerFirst(e.to_string()),
309                            ));
310                        }
311                    };
312
313                    let client_final = match self.compute_client_final(&server_first) {
314                        Ok(b) => b,
315                        Err(err) => return SmtpCoroutineState::Complete(Err(err)),
316                    };
317
318                    let data = SmtpAuthData::r#continue(client_final.into_boxed_slice());
319                    self.state = State::SendFinal(SmtpCommandSend::new(data));
320                    debug!("server-first received, sending client-final");
321                }
322                State::SendFinal(send) => {
323                    let out = smtp_try!(send, arg);
324
325                    if out.response.code != SmtpReplyCode::AUTH_SUCCESSFUL {
326                        let code = out.response.code.code();
327                        let message = out.response.text().to_string();
328                        return SmtpCoroutineState::Complete(Err(
329                            SmtpAuthScramSha256Error::Rejected { code, message },
330                        ));
331                    }
332
333                    let text = out.response.text().0.trim_start();
334                    let text = strip_enhanced_status(text);
335                    if let Ok(server_final_bytes) = base64.decode(text.as_bytes()) {
336                        if let Ok(server_final) = from_utf8(&server_final_bytes) {
337                            if let Some(v) = server_final.strip_prefix("v=") {
338                                if let Ok(server_sig) = base64.decode(v.as_bytes()) {
339                                    if server_sig != self.expected_server_sig {
340                                        return SmtpCoroutineState::Complete(Err(
341                                            SmtpAuthScramSha256Error::ServerSignatureMismatch,
342                                        ));
343                                    }
344                                }
345                            }
346                        }
347                    }
348
349                    self.advance_after_auth();
350                }
351                State::Ehlo(ehlo) => {
352                    let _ = smtp_try!(ehlo, arg);
353                    debug!("capabilities refreshed");
354                    return SmtpCoroutineState::Complete(Ok(()));
355                }
356                State::Done => return SmtpCoroutineState::Complete(Ok(())),
357            }
358        }
359    }
360}
361
362enum State {
363    SendInitial(SmtpCommandSend<SmtpAuthCommand<'static>>),
364    SendFinal(SmtpCommandSend<SmtpAuthData>),
365    Ehlo(SmtpEhlo),
366    Done,
367}
368
369impl fmt::Display for State {
370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371        match self {
372            Self::SendInitial(_) => f.write_str("send client-first"),
373            Self::SendFinal(_) => f.write_str("send client-final"),
374            Self::Ehlo(_) => f.write_str("refresh capabilities"),
375            Self::Done => f.write_str("done"),
376        }
377    }
378}
379
380/// HMAC-SHA-256: `HMAC(key, data) -> [u8; 32]`.
381fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
382    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts any key length");
383    mac.update(data);
384    mac.finalize().into_bytes().into()
385}
386
387/// Encode a username as a SCRAM `saslname` (RFC 5802 §5.1).
388fn sasl_name(username: &str) -> String {
389    let mut out = String::with_capacity(username.len());
390    for ch in username.chars() {
391        match ch {
392            '=' => out.push_str("=3D"),
393            ',' => out.push_str("=2C"),
394            c => out.push(c),
395        }
396    }
397    out
398}
399
400/// Strip a leading enhanced status code (`d.ddd.ddd `) from response
401/// text.
402fn strip_enhanced_status(text: &str) -> &str {
403    let bytes = text.as_bytes();
404    if bytes.len() >= 7 && bytes[0].is_ascii_digit() && bytes[1] == b'.' {
405        if let Some(second_dot) = bytes[2..].iter().position(|&b| b == b'.') {
406            let second_dot = second_dot + 2;
407            if let Some(space) = bytes[second_dot + 1..].iter().position(|&b| b == b' ') {
408                let space = second_dot + 1 + space;
409                return &text[space + 1..];
410            }
411        }
412    }
413    text
414}
415
416#[cfg(test)]
417mod tests {
418    use alloc::{borrow::Cow, format, string::ToString, vec::Vec};
419
420    use base64::{Engine, engine::general_purpose::STANDARD as base64};
421    use secrecy::SecretString;
422
423    use crate::{
424        coroutine::*,
425        rfc5321::{SmtpDomain, SmtpEhloDomain},
426        rfc7677::auth_scram_sha_256::*,
427        send::SmtpCommandSendError,
428    };
429
430    fn domain() -> SmtpEhloDomain<'static> {
431        SmtpEhloDomain::SmtpDomain(SmtpDomain(Cow::Borrowed("example.com")))
432    }
433
434    fn password() -> SecretString {
435        SecretString::from("pencil".to_string())
436    }
437
438    #[test]
439    fn capabilities_are_not_refreshed_by_default() {
440        assert!(!SmtpAuthScramSha256Options::default().ensure_capabilities);
441    }
442
443    #[test]
444    fn rejected_without_continuation_returns_rejected() {
445        let opts = SmtpAuthScramSha256Options::default();
446        let mut auth = SmtpAuthScramSha256::new(
447            "user",
448            &password(),
449            b"fyko+d2lbbFgONRv9qkxdawL",
450            domain(),
451            opts,
452        );
453
454        let _ = expect_wants_write(&mut auth, None);
455        expect_wants_read(&mut auth);
456
457        let err = expect_complete_err(&mut auth, b"504 mechanism disabled\r\n");
458        let SmtpAuthScramSha256Error::Rejected { code, .. } = err else {
459            panic!("expected SmtpAuthScramSha256Error::Rejected, got {err:?}");
460        };
461        assert_eq!(code, 504);
462    }
463
464    #[test]
465    fn invalid_server_first_returns_parse_error() {
466        let opts = SmtpAuthScramSha256Options::default();
467        let mut auth = SmtpAuthScramSha256::new(
468            "user",
469            &password(),
470            b"fyko+d2lbbFgONRv9qkxdawL",
471            domain(),
472            opts,
473        );
474
475        let _ = expect_wants_write(&mut auth, None);
476        expect_wants_read(&mut auth);
477
478        let err = expect_complete_err(&mut auth, b"334 Zm9v\r\n");
479        assert!(matches!(err, SmtpAuthScramSha256Error::ParseServerFirst(_)));
480    }
481
482    #[test]
483    fn final_rejection_returns_rejected() {
484        let opts = SmtpAuthScramSha256Options::default();
485        let mut auth = SmtpAuthScramSha256::new(
486            "user",
487            &password(),
488            b"fyko+d2lbbFgONRv9qkxdawL",
489            domain(),
490            opts,
491        );
492
493        let _ = expect_wants_write(&mut auth, None);
494        expect_wants_read(&mut auth);
495
496        let server_first = "r=fyko+d2lbbFgONRv9qkxdawLserverNonce,s=QSXCR+Q6sek8bf92,i=4096";
497        let challenge = format!("334 {}\r\n", base64.encode(server_first));
498        let _client_final = expect_wants_write(&mut auth, Some(challenge.as_bytes()));
499
500        expect_wants_read(&mut auth);
501
502        let err = expect_complete_err(&mut auth, b"535 authentication failed\r\n");
503        let SmtpAuthScramSha256Error::Rejected { code, .. } = err else {
504            panic!("expected SmtpAuthScramSha256Error::Rejected, got {err:?}");
505        };
506        assert_eq!(code, 535);
507    }
508
509    #[test]
510    fn eof_returns_eof_error() {
511        let opts = SmtpAuthScramSha256Options::default();
512        let mut auth = SmtpAuthScramSha256::new(
513            "user",
514            &password(),
515            b"fyko+d2lbbFgONRv9qkxdawL",
516            domain(),
517            opts,
518        );
519
520        let _ = expect_wants_write(&mut auth, None);
521        expect_wants_read(&mut auth);
522
523        let err = expect_complete_err(&mut auth, b"");
524        assert!(matches!(
525            err,
526            SmtpAuthScramSha256Error::Send(SmtpCommandSendError::Eof)
527        ));
528    }
529
530    fn expect_wants_write(cor: &mut SmtpAuthScramSha256, arg: Option<&[u8]>) -> Vec<u8> {
531        match cor.resume(arg) {
532            SmtpCoroutineState::Yielded(SmtpYield::WantsWrite(bytes)) => bytes,
533            state => panic!("expected WantsWrite, got {state:?}"),
534        }
535    }
536
537    fn expect_wants_read(cor: &mut SmtpAuthScramSha256) {
538        match cor.resume(None) {
539            SmtpCoroutineState::Yielded(SmtpYield::WantsRead) => {}
540            state => panic!("expected WantsRead, got {state:?}"),
541        }
542    }
543
544    fn expect_complete_err(
545        cor: &mut SmtpAuthScramSha256,
546        reply: &[u8],
547    ) -> SmtpAuthScramSha256Error {
548        match cor.resume(Some(reply)) {
549            SmtpCoroutineState::Complete(Err(err)) => err,
550            state => panic!("expected Complete(Err), got {state:?}"),
551        }
552    }
553}