LCOV - code coverage report
Current view: top level - proxy/src/scram - exchange.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 96.8 % 125 121
Test Date: 2025-07-16 12:29:03 Functions: 100.0 % 12 12

            Line data    Source code
       1              : //! Implementation of the SCRAM authentication algorithm.
       2              : 
       3              : use std::convert::Infallible;
       4              : 
       5              : use base64::Engine as _;
       6              : use base64::prelude::BASE64_STANDARD;
       7              : use hmac::{Hmac, Mac};
       8              : use sha2::Sha256;
       9              : 
      10              : use super::ScramKey;
      11              : use super::messages::{
      12              :     ClientFinalMessage, ClientFirstMessage, OwnedServerFirstMessage, SCRAM_RAW_NONCE_LEN,
      13              : };
      14              : use super::pbkdf2::Pbkdf2;
      15              : use super::secret::ServerSecret;
      16              : use super::signature::SignatureBuilder;
      17              : use super::threadpool::ThreadPool;
      18              : use crate::intern::EndpointIdInt;
      19              : use crate::sasl::{self, ChannelBinding, Error as SaslError};
      20              : 
      21              : /// The only channel binding mode we currently support.
      22              : #[derive(Debug)]
      23              : struct TlsServerEndPoint;
      24              : 
      25              : impl std::fmt::Display for TlsServerEndPoint {
      26            6 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      27            6 :         write!(f, "tls-server-end-point")
      28            6 :     }
      29              : }
      30              : 
      31              : impl std::str::FromStr for TlsServerEndPoint {
      32              :     type Err = sasl::Error;
      33              : 
      34            6 :     fn from_str(s: &str) -> Result<Self, Self::Err> {
      35            6 :         match s {
      36            6 :             "tls-server-end-point" => Ok(TlsServerEndPoint),
      37            0 :             _ => Err(sasl::Error::ChannelBindingBadMethod(s.into())),
      38              :         }
      39            6 :     }
      40              : }
      41              : 
      42              : struct SaslSentInner {
      43              :     cbind_flag: ChannelBinding<TlsServerEndPoint>,
      44              :     client_first_message_bare: String,
      45              :     server_first_message: OwnedServerFirstMessage,
      46              : }
      47              : 
      48              : struct SaslInitial {
      49              :     nonce: fn() -> [u8; SCRAM_RAW_NONCE_LEN],
      50              : }
      51              : 
      52              : enum ExchangeState {
      53              :     /// Waiting for [`ClientFirstMessage`].
      54              :     Initial(SaslInitial),
      55              :     /// Waiting for [`ClientFinalMessage`].
      56              :     SaltSent(SaslSentInner),
      57              : }
      58              : 
      59              : /// Server's side of SCRAM auth algorithm.
      60              : pub(crate) struct Exchange<'a> {
      61              :     state: ExchangeState,
      62              :     secret: &'a ServerSecret,
      63              :     tls_server_end_point: crate::tls::TlsServerEndPoint,
      64              : }
      65              : 
      66              : impl<'a> Exchange<'a> {
      67           13 :     pub(crate) fn new(
      68           13 :         secret: &'a ServerSecret,
      69           13 :         nonce: fn() -> [u8; SCRAM_RAW_NONCE_LEN],
      70           13 :         tls_server_end_point: crate::tls::TlsServerEndPoint,
      71           13 :     ) -> Self {
      72           13 :         Self {
      73           13 :             state: ExchangeState::Initial(SaslInitial { nonce }),
      74           13 :             secret,
      75           13 :             tls_server_end_point,
      76           13 :         }
      77           13 :     }
      78              : }
      79              : 
      80              : // copied from <https://github.com/neondatabase/rust-postgres/blob/20031d7a9ee1addeae6e0968e3899ae6bf01cee2/postgres-protocol/src/authentication/sasl.rs#L236-L248>
      81            4 : async fn derive_client_key(
      82            4 :     pool: &ThreadPool,
      83            4 :     endpoint: EndpointIdInt,
      84            4 :     password: &[u8],
      85            4 :     salt: &[u8],
      86            4 :     iterations: u32,
      87            4 : ) -> ScramKey {
      88            4 :     let salted_password = pool
      89            4 :         .spawn_job(endpoint, Pbkdf2::start(password, salt, iterations))
      90            4 :         .await;
      91              : 
      92            4 :     let make_key = |name| {
      93            4 :         let key = Hmac::<Sha256>::new_from_slice(&salted_password)
      94            4 :             .expect("HMAC is able to accept all key sizes")
      95            4 :             .chain_update(name)
      96            4 :             .finalize();
      97              : 
      98            4 :         <[u8; 32]>::from(key.into_bytes())
      99            4 :     };
     100              : 
     101            4 :     make_key(b"Client Key").into()
     102            4 : }
     103              : 
     104            4 : pub(crate) async fn exchange(
     105            4 :     pool: &ThreadPool,
     106            4 :     endpoint: EndpointIdInt,
     107            4 :     secret: &ServerSecret,
     108            4 :     password: &[u8],
     109            4 : ) -> sasl::Result<sasl::Outcome<super::ScramKey>> {
     110            4 :     let salt = BASE64_STANDARD.decode(&*secret.salt_base64)?;
     111            4 :     let client_key = derive_client_key(pool, endpoint, password, &salt, secret.iterations).await;
     112              : 
     113            4 :     if secret.is_password_invalid(&client_key).into() {
     114            1 :         Ok(sasl::Outcome::Failure("password doesn't match"))
     115              :     } else {
     116            3 :         Ok(sasl::Outcome::Success(client_key))
     117              :     }
     118            4 : }
     119              : 
     120              : impl SaslInitial {
     121           13 :     fn transition(
     122           13 :         &self,
     123           13 :         secret: &ServerSecret,
     124           13 :         tls_server_end_point: &crate::tls::TlsServerEndPoint,
     125           13 :         input: &str,
     126           13 :     ) -> sasl::Result<sasl::Step<SaslSentInner, Infallible>> {
     127           13 :         let client_first_message = ClientFirstMessage::parse(input)
     128           13 :             .ok_or(SaslError::BadClientMessage("invalid client-first-message"))?;
     129              : 
     130              :         // If the flag is set to "y" and the server supports channel
     131              :         // binding, the server MUST fail authentication
     132           13 :         if client_first_message.cbind_flag == ChannelBinding::NotSupportedServer
     133            1 :             && tls_server_end_point.supported()
     134              :         {
     135            1 :             return Err(SaslError::ChannelBindingFailed("SCRAM-PLUS not used"));
     136           12 :         }
     137              : 
     138           12 :         let server_first_message = client_first_message.build_server_first_message(
     139           12 :             &(self.nonce)(),
     140           12 :             &secret.salt_base64,
     141           12 :             secret.iterations,
     142              :         );
     143           12 :         let msg = server_first_message.as_str().to_owned();
     144              : 
     145           12 :         let next = SaslSentInner {
     146           12 :             cbind_flag: client_first_message.cbind_flag.and_then(str::parse)?,
     147           12 :             client_first_message_bare: client_first_message.bare.to_owned(),
     148           12 :             server_first_message,
     149              :         };
     150              : 
     151           12 :         Ok(sasl::Step::Continue(next, msg))
     152           13 :     }
     153              : }
     154              : 
     155              : impl SaslSentInner {
     156           12 :     fn transition(
     157           12 :         &self,
     158           12 :         secret: &ServerSecret,
     159           12 :         tls_server_end_point: &crate::tls::TlsServerEndPoint,
     160           12 :         input: &str,
     161           12 :     ) -> sasl::Result<sasl::Step<Infallible, super::ScramKey>> {
     162              :         let Self {
     163           12 :             cbind_flag,
     164           12 :             client_first_message_bare,
     165           12 :             server_first_message,
     166           12 :         } = self;
     167              : 
     168           12 :         let client_final_message = ClientFinalMessage::parse(input)
     169           12 :             .ok_or(SaslError::BadClientMessage("invalid client-final-message"))?;
     170              : 
     171           12 :         let channel_binding = cbind_flag.encode(|_| match tls_server_end_point {
     172            6 :             crate::tls::TlsServerEndPoint::Sha256(x) => Ok(x),
     173            0 :             crate::tls::TlsServerEndPoint::Undefined => Err(SaslError::MissingBinding),
     174            6 :         })?;
     175              : 
     176              :         // This might've been caused by a MITM attack
     177           12 :         if client_final_message.channel_binding != channel_binding {
     178            4 :             return Err(SaslError::ChannelBindingFailed(
     179            4 :                 "insecure connection: secure channel data mismatch",
     180            4 :             ));
     181            8 :         }
     182              : 
     183            8 :         if client_final_message.nonce != server_first_message.nonce() {
     184            0 :             return Err(SaslError::BadClientMessage("combined nonce doesn't match"));
     185            8 :         }
     186              : 
     187            8 :         let signature_builder = SignatureBuilder {
     188            8 :             client_first_message_bare,
     189            8 :             server_first_message: server_first_message.as_str(),
     190            8 :             client_final_message_without_proof: client_final_message.without_proof,
     191            8 :         };
     192              : 
     193            8 :         let client_key = signature_builder
     194            8 :             .build(&secret.stored_key)
     195            8 :             .derive_client_key(&client_final_message.proof);
     196              : 
     197              :         // Auth fails either if keys don't match or it's pre-determined to fail.
     198            8 :         if secret.is_password_invalid(&client_key).into() {
     199            1 :             return Ok(sasl::Step::Failure("password doesn't match"));
     200            7 :         }
     201              : 
     202            7 :         let msg =
     203            7 :             client_final_message.build_server_final_message(signature_builder, &secret.server_key);
     204              : 
     205            7 :         Ok(sasl::Step::Success(client_key, msg))
     206           12 :     }
     207              : }
     208              : 
     209              : impl sasl::Mechanism for Exchange<'_> {
     210              :     type Output = super::ScramKey;
     211              : 
     212           25 :     fn exchange(mut self, input: &str) -> sasl::Result<sasl::Step<Self, Self::Output>> {
     213              :         use ExchangeState;
     214              :         use sasl::Step;
     215           25 :         match &self.state {
     216           13 :             ExchangeState::Initial(init) => {
     217           13 :                 match init.transition(self.secret, &self.tls_server_end_point, input)? {
     218           12 :                     Step::Continue(sent, msg) => {
     219           12 :                         self.state = ExchangeState::SaltSent(sent);
     220           12 :                         Ok(Step::Continue(self, msg))
     221              :                     }
     222            0 :                     Step::Failure(msg) => Ok(Step::Failure(msg)),
     223              :                 }
     224              :             }
     225           12 :             ExchangeState::SaltSent(sent) => {
     226           12 :                 match sent.transition(self.secret, &self.tls_server_end_point, input)? {
     227            7 :                     Step::Success(keys, msg) => Ok(Step::Success(keys, msg)),
     228            1 :                     Step::Failure(msg) => Ok(Step::Failure(msg)),
     229              :                 }
     230              :             }
     231              :         }
     232           25 :     }
     233              : }
        

Generated by: LCOV version 2.1-beta