LCOV - code coverage report
Current view: top level - proxy/src - scram.rs (source / functions) Coverage Total Hit
Test: 2aa98e37cd3250b9a68c97ef6050b16fe702ab33.info Lines: 94.0 % 83 78
Test Date: 2024-08-29 11:33:10 Functions: 100.0 % 13 13

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

Generated by: LCOV version 2.1-beta