Skip to main content

mail_send/smtp/
auth.rs

1/*
2 * SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
3 *
4 * SPDX-License-Identifier: Apache-2.0 OR MIT
5 */
6
7use std::{borrow::Cow, fmt::Display, hash::Hash};
8
9use encodify::base64;
10use smtp_proto::{
11    AUTH_CRAM_MD5, AUTH_DIGEST_MD5, AUTH_LOGIN, AUTH_OAUTHBEARER, AUTH_PLAIN, AUTH_XOAUTH2,
12    EhloResponse, response::generate::BitToString,
13};
14use tokio::io::{AsyncRead, AsyncWrite};
15
16use crate::{Credentials, SmtpClient};
17
18impl<T: AsyncRead + AsyncWrite + Unpin> SmtpClient<T> {
19    pub async fn authenticate<U>(
20        &mut self,
21        credentials: impl AsRef<Credentials<U>>,
22        capabilities: impl AsRef<EhloResponse<String>>,
23    ) -> crate::Result<&mut Self>
24    where
25        U: AsRef<str> + PartialEq + Eq + Hash,
26    {
27        let credentials = credentials.as_ref();
28        let capabilities = capabilities.as_ref();
29        let mut available_mechanisms = match &credentials {
30            Credentials::Plain { .. } => AUTH_CRAM_MD5 | AUTH_DIGEST_MD5 | AUTH_LOGIN | AUTH_PLAIN,
31            Credentials::OAuthBearer { .. } => AUTH_OAUTHBEARER,
32            Credentials::XOauth2 { .. } => AUTH_XOAUTH2,
33        } & capabilities.auth_mechanisms;
34
35        // Try authenticating from most secure to least secure
36        let mut has_err = None;
37        let mut has_failed = false;
38
39        while available_mechanisms != 0 && !has_failed {
40            let mechanism = 1 << ((63 - available_mechanisms.leading_zeros()) as u64);
41            available_mechanisms ^= mechanism;
42            match self.auth(mechanism, credentials).await {
43                Ok(_) => {
44                    return Ok(self);
45                }
46                Err(err) => match err {
47                    crate::Error::UnexpectedReply(reply) => {
48                        has_failed = reply.code() == 535;
49                        has_err = reply.into();
50                    }
51                    crate::Error::UnsupportedAuthMechanism => (),
52                    _ => return Err(err),
53                },
54            }
55        }
56
57        if let Some(has_err) = has_err {
58            Err(crate::Error::AuthenticationFailed(has_err))
59        } else {
60            Err(crate::Error::UnsupportedAuthMechanism)
61        }
62    }
63
64    pub(crate) async fn auth<U>(
65        &mut self,
66        mechanism: u64,
67        credentials: &Credentials<U>,
68    ) -> crate::Result<()>
69    where
70        U: AsRef<str> + PartialEq + Eq + Hash,
71    {
72        let mut reply = if (mechanism & (AUTH_PLAIN | AUTH_XOAUTH2 | AUTH_OAUTHBEARER)) != 0 {
73            let mut command = format!("AUTH {} ", mechanism.to_mechanism());
74            credentials.encode_append(mechanism, "", &mut command)?;
75            command.push_str("\r\n");
76            self.cmd(command.as_bytes()).await?
77        } else {
78            self.cmd(format!("AUTH {}\r\n", mechanism.to_mechanism()).as_bytes())
79                .await?
80        };
81
82        for _ in 0..3 {
83            match reply.code() {
84                334 => {
85                    let mut response = String::new();
86                    credentials.encode_append(mechanism, reply.message(), &mut response)?;
87                    response.push_str("\r\n");
88                    reply = self.cmd(response.as_bytes()).await?;
89                }
90                235 => {
91                    return Ok(());
92                }
93                _ => {
94                    return Err(crate::Error::UnexpectedReply(reply));
95                }
96            }
97        }
98
99        Err(crate::Error::UnexpectedReply(reply))
100    }
101}
102
103#[derive(Debug, Clone)]
104pub enum Error {
105    InvalidChallenge,
106}
107
108impl<T: AsRef<str> + PartialEq + Eq + Hash> Credentials<T> {
109    /// Creates a new `Credentials` instance.
110    pub fn new(username: T, secret: T) -> Self {
111        Credentials::Plain { username, secret }
112    }
113
114    /// Creates a new XOAuth2 `Credentials` instance.
115    pub fn new_xoauth2(username: T, secret: T) -> Self {
116        Credentials::XOauth2 { username, secret }
117    }
118
119    /// Creates a new OAuthBearer `Credentials` instance.
120    pub fn new_oauth(payload: T) -> Self {
121        Credentials::OAuthBearer { token: payload }
122    }
123
124    /// Creates a new OAuthBearer `Credentials` instance from a Bearer token.
125    pub fn new_oauth_from_token(token: T) -> Credentials<String> {
126        Credentials::OAuthBearer {
127            token: format!("auth=Bearer {}\x01\x01", token.as_ref()),
128        }
129    }
130
131    pub fn encode(&self, mechanism: u64, challenge: &str) -> crate::Result<String> {
132        let mut response = String::new();
133        self.encode_append(mechanism, challenge, &mut response)?;
134        Ok(response)
135    }
136
137    pub(crate) fn encode_append(
138        &self,
139        mechanism: u64,
140        challenge: &str,
141        out: &mut String,
142    ) -> crate::Result<()> {
143        base64::STANDARD.encode_append(
144            match (mechanism, self) {
145                (AUTH_PLAIN, Credentials::Plain { username, secret }) => Cow::Owned(format!(
146                    "\u{0}{}\u{0}{}",
147                    username.as_ref(),
148                    secret.as_ref()
149                )),
150
151                (AUTH_LOGIN, Credentials::Plain { username, secret }) => {
152                    let challenge = base64::STANDARD.decode(challenge)?;
153                    let username = username.as_ref();
154                    let secret = secret.as_ref();
155
156                    if b"user name"
157                        .eq_ignore_ascii_case(challenge.get(0..9).ok_or(Error::InvalidChallenge)?)
158                        || b"username".eq_ignore_ascii_case(
159                            // Because Google makes its own standards
160                            challenge.get(0..8).ok_or(Error::InvalidChallenge)?,
161                        )
162                    {
163                        Cow::Borrowed(username)
164                    } else if b"password"
165                        .eq_ignore_ascii_case(challenge.get(0..8).ok_or(Error::InvalidChallenge)?)
166                    {
167                        Cow::Borrowed(secret)
168                    } else {
169                        return Err(Error::InvalidChallenge.into());
170                    }
171                }
172
173                #[cfg(feature = "digest-md5")]
174                (AUTH_DIGEST_MD5, Credentials::Plain { username, secret }) => {
175                    let mut buf = Vec::with_capacity(10);
176                    let mut key = None;
177                    let mut in_quote = false;
178                    let mut values = std::collections::HashMap::new();
179                    let challenge = base64::STANDARD.decode(challenge)?;
180                    let challenge_len = challenge.len();
181                    let username = username.as_ref();
182                    let secret = secret.as_ref();
183
184                    for (pos, byte) in challenge.into_iter().enumerate() {
185                        let add_key = match byte {
186                            b'=' if !in_quote => {
187                                if key.is_none() && !buf.is_empty() {
188                                    key = String::from_utf8_lossy(&buf).into_owned().into();
189                                    buf.clear();
190                                } else {
191                                    return Err(Error::InvalidChallenge.into());
192                                }
193                                false
194                            }
195                            b',' if !in_quote => true,
196                            b'"' => {
197                                in_quote = !in_quote;
198                                false
199                            }
200                            _ => {
201                                buf.push(byte);
202                                false
203                            }
204                        };
205
206                        if (add_key || pos == challenge_len - 1) && key.is_some() && !buf.is_empty()
207                        {
208                            values.insert(
209                                key.take().unwrap(),
210                                String::from_utf8_lossy(&buf).into_owned(),
211                            );
212                            buf.clear();
213                        }
214                    }
215
216                    let (digest_uri, realm, realm_response) =
217                        if let Some(realm) = values.get("realm") {
218                            (
219                                format!("smtp/{realm}"),
220                                realm.as_str(),
221                                format!(",realm=\"{realm}\""),
222                            )
223                        } else {
224                            ("smtp/localhost".to_string(), "", "".to_string())
225                        };
226
227                    let credentials =
228                        md5::compute(format!("{username}:{realm}:{secret}").as_bytes());
229
230                    let a2 = md5::compute(
231                        if values.get("qpop").is_some_and(|v| v == "auth") {
232                            format!("AUTHENTICATE:{digest_uri}")
233                        } else {
234                            format!("AUTHENTICATE:{digest_uri}:00000000000000000000000000000000")
235                        }
236                        .as_bytes(),
237                    );
238
239                    let cnonce_bytes = {
240                        use rand::RngCore;
241                        let mut buf = [0u8; 16];
242                        rand::rng().fill_bytes(&mut buf);
243                        buf
244                    };
245                    #[allow(unused_variables)]
246                    let cnonce = base64::STANDARD.display(&cnonce_bytes);
247
248                    #[cfg(test)]
249                    let cnonce = "OA6MHXh6VqTrRk".to_string();
250                    let nonce = values.remove("nonce").unwrap_or_default();
251                    let qop = values.remove("qop").unwrap_or_default();
252                    let charset = values
253                        .remove("charset")
254                        .unwrap_or_else(|| "utf-8".to_string());
255
256                    Cow::Owned(format!(
257                        concat!(
258                            "charset={},username=\"{}\",realm=\"{}\",nonce=\"{}\",nc=00000001,",
259                            "cnonce=\"{}\",digest-uri=\"{}\",response={:x},qop={}"
260                        ),
261                        charset,
262                        username,
263                        realm_response,
264                        nonce,
265                        cnonce,
266                        digest_uri,
267                        md5::compute(
268                            format!("{credentials:x}:{nonce}:00000001:{cnonce}:{qop}:{a2:x}")
269                                .as_bytes()
270                        ),
271                        qop
272                    ))
273                }
274
275                #[cfg(feature = "cram-md5")]
276                (AUTH_CRAM_MD5, Credentials::Plain { username, secret }) => {
277                    let mut secret_opad: Vec<u8> = vec![0x5c; 64];
278                    let mut secret_ipad: Vec<u8> = vec![0x36; 64];
279                    let username = username.as_ref();
280                    let secret = secret.as_ref();
281
282                    if secret.len() < 64 {
283                        for (pos, byte) in secret.as_bytes().iter().enumerate() {
284                            secret_opad[pos] = *byte ^ 0x5c;
285                            secret_ipad[pos] = *byte ^ 0x36;
286                        }
287                    } else {
288                        for (pos, byte) in md5::compute(secret.as_bytes()).iter().enumerate() {
289                            secret_opad[pos] = *byte ^ 0x5c;
290                            secret_ipad[pos] = *byte ^ 0x36;
291                        }
292                    }
293
294                    base64::STANDARD.decode_append(challenge, &mut secret_ipad)?;
295                    secret_opad.extend_from_slice(&md5::compute(&secret_ipad).0);
296
297                    Cow::Owned(format!("{} {:x}", username, md5::compute(&secret_opad)))
298                }
299
300                (AUTH_XOAUTH2, Credentials::XOauth2 { username, secret }) => Cow::Owned(format!(
301                    "user={}\x01auth=Bearer {}\x01\x01",
302                    username.as_ref(),
303                    secret.as_ref()
304                )),
305                (AUTH_OAUTHBEARER, Credentials::OAuthBearer { token }) => {
306                    Cow::Borrowed(token.as_ref())
307                }
308                _ => return Err(crate::Error::UnsupportedAuthMechanism),
309            }
310            .as_bytes(),
311            out,
312        );
313        Ok(())
314    }
315}
316
317impl<'x> From<(&'x str, &'x str)> for Credentials<&'x str> {
318    fn from(credentials: (&'x str, &'x str)) -> Self {
319        Credentials::Plain {
320            username: credentials.0,
321            secret: credentials.1,
322        }
323    }
324}
325
326impl From<(String, String)> for Credentials<String> {
327    fn from(credentials: (String, String)) -> Self {
328        Credentials::Plain {
329            username: credentials.0,
330            secret: credentials.1,
331        }
332    }
333}
334
335impl<U: AsRef<str> + PartialEq + Eq + Hash> AsRef<Credentials<U>> for Credentials<U> {
336    fn as_ref(&self) -> &Credentials<U> {
337        self
338    }
339}
340
341impl Display for Error {
342    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
343        match self {
344            Error::InvalidChallenge => write!(f, "Invalid challenge received."),
345        }
346    }
347}
348
349#[cfg(test)]
350mod test {
351
352    use smtp_proto::{AUTH_CRAM_MD5, AUTH_DIGEST_MD5, AUTH_LOGIN, AUTH_PLAIN, AUTH_XOAUTH2};
353
354    use crate::smtp::auth::Credentials;
355
356    #[test]
357    fn auth_encode() {
358        // Digest-MD5
359        #[cfg(feature = "digest-md5")]
360        assert_eq!(
361            Credentials::new("chris", "secret")
362                .encode(
363                    AUTH_DIGEST_MD5,
364                    concat!(
365                        "cmVhbG09ImVsd29vZC5pbm5vc29mdC5jb20iLG5vbmNlPSJPQTZNRzl0",
366                        "RVFHbTJoaCIscW9wPSJhdXRoIixhbGdvcml0aG09bWQ1LXNlc3MsY2hh",
367                        "cnNldD11dGYtOA=="
368                    ),
369                )
370                .unwrap(),
371            concat!(
372                "Y2hhcnNldD11dGYtOCx1c2VybmFtZT0iY2hyaXMiLHJlYWxtPSIscmVhbG0",
373                "9ImVsd29vZC5pbm5vc29mdC5jb20iIixub25jZT0iT0E2TUc5dEVRR20yaG",
374                "giLG5jPTAwMDAwMDAxLGNub25jZT0iT0E2TUhYaDZWcVRyUmsiLGRpZ2Vzd",
375                "C11cmk9InNtdHAvZWx3b29kLmlubm9zb2Z0LmNvbSIscmVzcG9uc2U9NDQ2",
376                "NjIxODg3MzlmYzcxOGNlYmYyZjA4MTk4MWI4ZDIscW9wPWF1dGg=",
377            )
378        );
379
380        // Challenge-Response Authentication Mechanism (CRAM)
381        #[cfg(feature = "cram-md5")]
382        assert_eq!(
383            Credentials::new("tim", "tanstaaftanstaaf")
384                .encode(
385                    AUTH_CRAM_MD5,
386                    "PDE4OTYuNjk3MTcwOTUyQHBvc3RvZmZpY2UucmVzdG9uLm1jaS5uZXQ+",
387                )
388                .unwrap(),
389            "dGltIGI5MTNhNjAyYzdlZGE3YTQ5NWI0ZTZlNzMzNGQzODkw"
390        );
391
392        // SASL XOAUTH2
393        assert_eq!(
394            Credentials::XOauth2 {
395                username: "someuser@example.com",
396                secret: "ya29.vF9dft4qmTc2Nvb3RlckBhdHRhdmlzdGEuY29tCg"
397            }
398            .encode(AUTH_XOAUTH2, "",)
399            .unwrap(),
400            concat!(
401                "dXNlcj1zb21ldXNlckBleGFtcGxlLmNvbQFhdXRoPUJlYXJlciB5YTI5Ln",
402                "ZGOWRmdDRxbVRjMk52YjNSbGNrQmhkSFJoZG1semRHRXVZMjl0Q2cBAQ=="
403            )
404        );
405
406        // Login
407        assert_eq!(
408            Credentials::new("tim", "tanstaaftanstaaf")
409                .encode(AUTH_LOGIN, "VXNlciBOYW1lAA==",)
410                .unwrap(),
411            "dGlt"
412        );
413        assert_eq!(
414            Credentials::new("tim", "tanstaaftanstaaf")
415                .encode(AUTH_LOGIN, "UGFzc3dvcmQA",)
416                .unwrap(),
417            "dGFuc3RhYWZ0YW5zdGFhZg=="
418        );
419
420        // Plain
421        assert_eq!(
422            Credentials::new("tim", "tanstaaftanstaaf")
423                .encode(AUTH_PLAIN, "",)
424                .unwrap(),
425            "AHRpbQB0YW5zdGFhZnRhbnN0YWFm"
426        );
427    }
428}