Line data Source code
1 : //! Salted Challenge Response Authentication Mechanism.
2 : //!
3 : //! RFC: <https://datatracker.ietf.org/doc/html/rfc5802>.
4 : //!
5 : //! Reference implementation:
6 : //! * <https://github.com/postgres/postgres/blob/94226d4506e66d6e7cbf4b391f1e7393c1962841/src/backend/libpq/auth-scram.c>
7 : //! * <https://github.com/postgres/postgres/blob/94226d4506e66d6e7cbf4b391f1e7393c1962841/src/interfaces/libpq/fe-auth-scram.c>
8 :
9 : mod countmin;
10 : mod exchange;
11 : mod key;
12 : mod messages;
13 : mod pbkdf2;
14 : mod secret;
15 : mod signature;
16 : pub mod threadpool;
17 :
18 : use base64::Engine as _;
19 : use base64::prelude::BASE64_STANDARD;
20 : pub(crate) use exchange::{Exchange, exchange};
21 : use hmac::{Hmac, Mac};
22 : pub(crate) use key::ScramKey;
23 : pub(crate) use secret::ServerSecret;
24 : use sha2::{Digest, Sha256};
25 :
26 : const SCRAM_SHA_256: &str = "SCRAM-SHA-256";
27 : const SCRAM_SHA_256_PLUS: &str = "SCRAM-SHA-256-PLUS";
28 :
29 : /// A list of supported SCRAM methods.
30 : pub(crate) const METHODS: &[&str] = &[SCRAM_SHA_256_PLUS, SCRAM_SHA_256];
31 : pub(crate) const METHODS_WITHOUT_PLUS: &[&str] = &[SCRAM_SHA_256];
32 :
33 : /// Decode base64 into array without any heap allocations
34 49 : fn base64_decode_array<const N: usize>(input: impl AsRef<[u8]>) -> Option<[u8; N]> {
35 49 : let mut bytes = [0u8; N];
36 :
37 49 : let size = BASE64_STANDARD.decode_slice(input, &mut bytes).ok()?;
38 49 : if size != N {
39 0 : return None;
40 49 : }
41 :
42 49 : Some(bytes)
43 49 : }
44 :
45 : /// This function essentially is `Hmac(sha256, key, input)`.
46 : /// Further reading: <https://datatracker.ietf.org/doc/html/rfc2104>.
47 15 : fn hmac_sha256<'a>(key: &[u8], parts: impl IntoIterator<Item = &'a [u8]>) -> [u8; 32] {
48 15 : let mut mac = Hmac::<Sha256>::new_from_slice(key).expect("bad key size");
49 75 : parts.into_iter().for_each(|s| mac.update(s));
50 :
51 15 : mac.finalize().into_bytes().into()
52 15 : }
53 :
54 12 : fn sha256<'a>(parts: impl IntoIterator<Item = &'a [u8]>) -> [u8; 32] {
55 12 : let mut hasher = Sha256::new();
56 12 : parts.into_iter().for_each(|s| hasher.update(s));
57 :
58 12 : hasher.finalize().into()
59 12 : }
60 :
61 : #[cfg(test)]
62 : mod tests {
63 : use super::threadpool::ThreadPool;
64 : use super::{Exchange, ServerSecret};
65 : use crate::intern::EndpointIdInt;
66 : use crate::sasl::{Mechanism, Step};
67 : use crate::types::EndpointId;
68 :
69 : #[test]
70 1 : fn snapshot() {
71 1 : let iterations = 4096;
72 1 : let salt = "QSXCR+Q6sek8bf92";
73 1 : let stored_key = "FO+9jBb3MUukt6jJnzjPZOWc5ow/Pu6JtPyju0aqaE8=";
74 1 : let server_key = "qxJ1SbmSAi5EcS0J5Ck/cKAm/+Ixa+Kwp63f4OHDgzo=";
75 1 : let secret = format!("SCRAM-SHA-256${iterations}:{salt}${stored_key}:{server_key}",);
76 1 : let secret = ServerSecret::parse(&secret).unwrap();
77 :
78 : const NONCE: [u8; 18] = [
79 : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
80 : ];
81 1 : let mut exchange =
82 1 : Exchange::new(&secret, || NONCE, crate::tls::TlsServerEndPoint::Undefined);
83 :
84 1 : let client_first = "n,,n=user,r=rOprNGfwEbeRWgbNEkqO";
85 1 : let client_final = "c=biws,r=rOprNGfwEbeRWgbNEkqOAQIDBAUGBwgJCgsMDQ4PEBES,p=rw1r5Kph5ThxmaUBC2GAQ6MfXbPnNkFiTIvdb/Rear0=";
86 1 : let server_first =
87 1 : "r=rOprNGfwEbeRWgbNEkqOAQIDBAUGBwgJCgsMDQ4PEBES,s=QSXCR+Q6sek8bf92,i=4096";
88 1 : let server_final = "v=qtUDIofVnIhM7tKn93EQUUt5vgMOldcDVu1HC+OH0o0=";
89 :
90 1 : exchange = match exchange.exchange(client_first).unwrap() {
91 1 : Step::Continue(exchange, message) => {
92 1 : assert_eq!(message, server_first);
93 1 : exchange
94 : }
95 0 : Step::Success(_, _) => panic!("expected continue, got success"),
96 0 : Step::Failure(f) => panic!("{f}"),
97 : };
98 :
99 1 : let key = match exchange.exchange(client_final).unwrap() {
100 1 : Step::Success(key, message) => {
101 1 : assert_eq!(message, server_final);
102 1 : key
103 : }
104 0 : Step::Continue(_, _) => panic!("expected success, got continue"),
105 0 : Step::Failure(f) => panic!("{f}"),
106 : };
107 :
108 1 : assert_eq!(
109 1 : key.as_bytes(),
110 : [
111 : 74, 103, 1, 132, 12, 31, 200, 48, 28, 54, 82, 232, 207, 12, 138, 189, 40, 32, 134,
112 : 27, 125, 170, 232, 35, 171, 167, 166, 41, 70, 228, 182, 112,
113 : ]
114 : );
115 1 : }
116 :
117 2 : async fn run_round_trip_test(server_password: &str, client_password: &str) {
118 2 : let pool = ThreadPool::new(1);
119 :
120 2 : let ep = EndpointId::from("foo");
121 2 : let ep = EndpointIdInt::from(ep);
122 :
123 2 : let scram_secret = ServerSecret::build(server_password).await.unwrap();
124 2 : let outcome = super::exchange(&pool, ep, &scram_secret, client_password.as_bytes())
125 2 : .await
126 2 : .unwrap();
127 :
128 2 : match outcome {
129 1 : crate::sasl::Outcome::Success(_) => {}
130 1 : crate::sasl::Outcome::Failure(r) => panic!("{r}"),
131 : }
132 1 : }
133 :
134 : #[tokio::test]
135 1 : async fn round_trip() {
136 1 : run_round_trip_test("pencil", "pencil").await;
137 1 : }
138 :
139 : #[tokio::test]
140 : #[should_panic(expected = "password doesn't match")]
141 1 : async fn failure() {
142 1 : run_round_trip_test("pencil", "eraser").await;
143 1 : }
144 : }
|