-
Notifications
You must be signed in to change notification settings - Fork 1.6k
PostgreSQL: Cache salted password and client key #4043
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ThomWright
wants to merge
1
commit into
launchbadge:main
Choose a base branch
from
ThomWright:cache-pg-sasl-client-key
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+133
−13
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,12 @@ | ||
| use std::path::PathBuf; | ||
| use std::sync::{Arc, Mutex}; | ||
|
|
||
| use crate::connection::stream::PgStream; | ||
| use crate::error::Error; | ||
| use crate::message::{Authentication, AuthenticationSasl, SaslInitialResponse, SaslResponse}; | ||
| use crate::message::{ | ||
| Authentication, AuthenticationSasl, AuthenticationSaslContinue, SaslInitialResponse, | ||
| SaslResponse, | ||
| }; | ||
| use crate::rt; | ||
| use crate::PgConnectOptions; | ||
| use hmac::{Hmac, Mac}; | ||
|
|
@@ -16,6 +22,100 @@ const USERNAME_ATTR: &str = "n"; | |
| const CLIENT_PROOF_ATTR: &str = "p"; | ||
| const NONCE_ATTR: &str = "r"; | ||
|
|
||
| /// A single-entry cache for the client key derived from the password. | ||
| /// | ||
| /// Salting the password and deriving the client key can be expensive, so this cache stores the most | ||
| /// recently used client key along with the parameters used to derive it. | ||
| /// | ||
| /// According to [RFC-7677](https://datatracker.ietf.org/doc/html/rfc7677): | ||
| /// | ||
| /// > This computational cost can be avoided by caching the ClientKey (assuming the Salt and hash | ||
| /// > iteration-count is stable). | ||
| #[derive(Debug, Clone)] | ||
| pub struct ClientKeyCache { | ||
| inner: Arc<Mutex<Option<CacheInner>>>, | ||
| } | ||
|
|
||
| #[derive(Debug, PartialEq, Eq)] | ||
| struct CacheKey { | ||
| host: String, | ||
| port: u16, | ||
| socket: Option<PathBuf>, | ||
| database: Option<String>, | ||
| username: String, | ||
| password: String, | ||
| salt: Vec<u8>, | ||
| iterations: u32, | ||
| } | ||
|
|
||
| impl From<(&PgConnectOptions, &AuthenticationSaslContinue)> for CacheKey { | ||
| fn from((options, cont): (&PgConnectOptions, &AuthenticationSaslContinue)) -> Self { | ||
| CacheKey { | ||
| host: options.host.clone(), | ||
| port: options.port, | ||
| socket: options.socket.clone(), | ||
| database: options.database.clone(), | ||
| username: options.username.clone(), | ||
| password: options.password.clone().unwrap_or_default(), | ||
| salt: cont.salt.clone(), | ||
| iterations: cont.iterations, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug)] | ||
| struct CacheInner { | ||
| cache_key: CacheKey, | ||
| salted_password: [u8; 32], | ||
| client_key: Hmac<Sha256>, | ||
| } | ||
|
|
||
| impl ClientKeyCache { | ||
| pub fn new() -> Self { | ||
| ClientKeyCache { | ||
| inner: Arc::new(Mutex::new(None)), | ||
| } | ||
| } | ||
|
|
||
| fn get( | ||
| &self, | ||
| options: &PgConnectOptions, | ||
| cont: &AuthenticationSaslContinue, | ||
| ) -> Option<([u8; 32], Hmac<Sha256>)> { | ||
| let key = CacheKey::from((options, cont)); | ||
|
|
||
| self.inner | ||
| .lock() | ||
| .expect("BUG: panicked while holding a lock") | ||
| .as_ref() | ||
| .and_then(|inner| { | ||
| if inner.cache_key == key { | ||
| Some((inner.salted_password, inner.client_key.clone())) | ||
| } else { | ||
| None | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| fn set( | ||
| &self, | ||
| options: &PgConnectOptions, | ||
| cont: &AuthenticationSaslContinue, | ||
| salted_password: [u8; 32], | ||
| client_key: Hmac<Sha256>, | ||
| ) { | ||
| let mut inner = self | ||
| .inner | ||
| .lock() | ||
| .expect("BUG: panicked while holding a lock"); | ||
| *inner = Some(CacheInner { | ||
| cache_key: CacheKey::from((options, cont)), | ||
| salted_password, | ||
| client_key, | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| pub(crate) async fn authenticate( | ||
| stream: &mut PgStream, | ||
| options: &PgConnectOptions, | ||
|
|
@@ -86,16 +186,29 @@ pub(crate) async fn authenticate( | |
| } | ||
| }; | ||
|
|
||
| // SaltedPassword := Hi(Normalize(password), salt, i) | ||
| let salted_password = hi( | ||
| options.password.as_deref().unwrap_or_default(), | ||
| &cont.salt, | ||
| cont.iterations, | ||
| ) | ||
| .await?; | ||
| let (salted_password, mut mac) = { | ||
| if let Some(cached) = options.sasl_client_key_cache.get(options, &cont) { | ||
| cached | ||
| } else { | ||
| // SaltedPassword := Hi(Normalize(password), salt, i) | ||
| let salted_password = hi( | ||
| options.password.as_deref().unwrap_or_default(), | ||
| &cont.salt, | ||
| cont.iterations, | ||
| ) | ||
| .await?; | ||
|
Comment on lines
+194
to
+199
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You could theoretically save extra blocking threads from being spawned to redundantly calculate the same |
||
|
|
||
| // ClientKey := HMAC(SaltedPassword, "Client Key") | ||
| let mac = Hmac::<Sha256>::new_from_slice(&salted_password).map_err(Error::protocol)?; | ||
|
|
||
| options | ||
| .sasl_client_key_cache | ||
| .set(options, &cont, salted_password, mac.clone()); | ||
|
|
||
| (salted_password, mac) | ||
| } | ||
| }; | ||
|
|
||
| // ClientKey := HMAC(SaltedPassword, "Client Key") | ||
| let mut mac = Hmac::<Sha256>::new_from_slice(&salted_password).map_err(Error::protocol)?; | ||
| mac.update(b"Client Key"); | ||
|
|
||
| let client_key = mac.finalize().into_bytes(); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You shouldn't need to store any of this. Strictly speaking, only 3 things can change the HMAC result:
&mutreference soPgConnectOptions::set_password()can just wipe the cache directly by overwriting it with a new instance.