-
Couldn't load subscription status.
- Fork 20
[PM-26354] Add methods to create rotateable key sets from PRF #494
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
iinuwa
wants to merge
3
commits into
main
Choose a base branch
from
km/PM-26177/create-prf-user-key-set
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.
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
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 |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| use crate::{CryptoError, SymmetricCryptoKey, utils::stretch_key}; | ||
|
|
||
| /// Takes the output of a PRF and derives a symmetric key. | ||
| /// | ||
| /// The PRF output must be at least 32 bytes long. | ||
| pub fn derive_symmetric_key_from_prf(prf: &[u8]) -> Result<SymmetricCryptoKey, CryptoError> { | ||
| let (secret, _) = prf.split_at_checked(32).ok_or(CryptoError::InvalidKeyLen)?; | ||
| let secret: [u8; 32] = secret.try_into().expect("length to be 32 bytes"); | ||
| // Don't allow uninitialized PRFs | ||
| if secret.iter().all(|b| *b == b'\0') { | ||
iinuwa marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return Err(CryptoError::ZeroNumber); | ||
| } | ||
| Ok(SymmetricCryptoKey::Aes256CbcHmacKey(stretch_key( | ||
iinuwa marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| &Box::pin(secret.into()), | ||
| )?)) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn test_prf_succeeds() { | ||
| let prf = pseudorandom_bytes(32); | ||
| let key = derive_symmetric_key_from_prf(&prf).unwrap(); | ||
| assert!(matches!(key, SymmetricCryptoKey::Aes256CbcHmacKey(_))); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_zero_key_fails() { | ||
| let prf: Vec<u8> = (0..32).map(|_| 0).collect(); | ||
| let err = derive_symmetric_key_from_prf(&prf).unwrap_err(); | ||
| assert!(matches!(err, CryptoError::ZeroNumber)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_short_prf_fails() { | ||
| let prf = pseudorandom_bytes(9); | ||
| let err = derive_symmetric_key_from_prf(&prf).unwrap_err(); | ||
| assert!(matches!(err, CryptoError::InvalidKeyLen)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_long_prf_truncated_to_proper_length() { | ||
| let long_prf = pseudorandom_bytes(33); | ||
| let prf = pseudorandom_bytes(32); | ||
| let key1 = derive_symmetric_key_from_prf(&long_prf).unwrap(); | ||
| let key2 = derive_symmetric_key_from_prf(&prf).unwrap(); | ||
| assert_eq!(key1, key2); | ||
| } | ||
|
|
||
| /// This returns the same bytes deterministically for a given length. | ||
| fn pseudorandom_bytes(len: usize) -> Vec<u8> { | ||
| (0..len).map(|x| (x % 255) as u8).collect() | ||
| } | ||
| } | ||
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 |
|---|---|---|
| @@ -0,0 +1,202 @@ | ||
| use serde::{Deserialize, Serialize}; | ||
|
|
||
| use crate::{ | ||
| AsymmetricCryptoKey, AsymmetricPublicCryptoKey, CryptoError, EncString, KeyDecryptable, | ||
| KeyEncryptable, KeyIds, KeyStoreContext, Pkcs8PrivateKeyBytes, SpkiPublicKeyBytes, | ||
| SymmetricCryptoKey, UnsignedSharedKey, | ||
| }; | ||
|
|
||
| /// A set of keys where a given `DownstreamKey` is protected by an encrypted public/private | ||
| /// key-pair. The `DownstreamKey` is used to encrypt/decrypt data, while the public/private key-pair | ||
| /// is used to rotate the `DownstreamKey`. | ||
| /// | ||
| /// The `PrivateKey` is protected by an `UpstreamKey`, such as a `DeviceKey`, or `PrfKey`, | ||
| /// and the `PublicKey` is protected by the `DownstreamKey`. This setup allows: | ||
| /// | ||
| /// - Access to `DownstreamKey` by knowing the `UpstreamKey` | ||
| /// - Rotation to a `NewDownstreamKey` by knowing the current `DownstreamKey`, without needing | ||
| /// access to the `UpstreamKey` | ||
| #[derive(Serialize, Deserialize, Debug)] | ||
| #[serde(rename_all = "camelCase", deny_unknown_fields)] | ||
| #[cfg_attr(feature = "uniffi", derive(uniffi::Record))] | ||
| #[cfg_attr( | ||
| feature = "wasm", | ||
| derive(tsify::Tsify), | ||
| tsify(into_wasm_abi, from_wasm_abi) | ||
| )] | ||
| pub struct RotateableKeySet { | ||
| /// `DownstreamKey` protected by encapsulation key | ||
| encapsulated_downstream_key: UnsignedSharedKey, | ||
| /// Encapsulation key protected by `DownstreamKey` | ||
| encrypted_encapsulation_key: EncString, | ||
| /// Decapsulation key protected by `UpstreamKey` | ||
| encrypted_decapsulation_key: EncString, | ||
| } | ||
|
|
||
| impl RotateableKeySet { | ||
| /// Create a set of keys to allow access to the downstream key via the provided | ||
| /// upstream key while allowing the downstream key to be rotated. | ||
| pub fn new<Ids: KeyIds>( | ||
| ctx: &KeyStoreContext<Ids>, | ||
| upstream_key: &SymmetricCryptoKey, | ||
| downstream_key_id: Ids::Symmetric, | ||
| ) -> Result<Self, CryptoError> { | ||
| let key_pair = AsymmetricCryptoKey::make(crate::PublicKeyEncryptionAlgorithm::RsaOaepSha1); | ||
|
|
||
| // This uses this deprecated method and other methods directly on the other keys | ||
| // rather than the key store context because we don't want the keys to | ||
| // wind up being stored in the borrowed context. | ||
| #[allow(deprecated)] | ||
| let downstream_key = ctx.dangerous_get_symmetric_key(downstream_key_id)?; | ||
| // encapsulate downstream key | ||
| let encapsulated_downstream_key = | ||
| UnsignedSharedKey::encapsulate_key_unsigned(downstream_key, &key_pair.to_public_key())?; | ||
|
|
||
| // wrap decapsulation key with upstream key | ||
| let encrypted_decapsulation_key = key_pair.to_der()?.encrypt_with_key(upstream_key)?; | ||
|
|
||
| // wrap encapsulation key with downstream key | ||
| // Note: Usually, a public key is - by definition - public, so this should not be necessary. | ||
| // The specific use-case for this function is to enable rotateable key sets, where | ||
| // the "public key" is not public, with the intent of preventing the server from being able | ||
| // to overwrite the downstream key unlocked by the rotateable keyset. | ||
| let encrypted_encapsulation_key = key_pair | ||
| .to_public_key() | ||
| .to_der()? | ||
| .encrypt_with_key(downstream_key)?; | ||
|
|
||
| Ok(RotateableKeySet { | ||
| encapsulated_downstream_key, | ||
| encrypted_encapsulation_key, | ||
| encrypted_decapsulation_key, | ||
| }) | ||
| } | ||
|
|
||
| // TODO: Eventually, the webauthn-login-strategy service should be migrated | ||
| // to use this method, and we can remove the #[allow(dead_code)] attribute. | ||
| #[allow(dead_code)] | ||
| fn unlock<Ids: KeyIds>( | ||
| &self, | ||
| ctx: &mut KeyStoreContext<Ids>, | ||
| upstream_key: &SymmetricCryptoKey, | ||
| downstream_key_id: Ids::Symmetric, | ||
| ) -> Result<(), CryptoError> { | ||
| let priv_key_bytes: Vec<u8> = self | ||
| .encrypted_decapsulation_key | ||
| .decrypt_with_key(upstream_key)?; | ||
| let decapsulation_key = | ||
| AsymmetricCryptoKey::from_der(&Pkcs8PrivateKeyBytes::from(priv_key_bytes))?; | ||
| let downstream_key = self | ||
| .encapsulated_downstream_key | ||
| .decapsulate_key_unsigned(&decapsulation_key)?; | ||
| #[allow(deprecated)] | ||
| ctx.set_symmetric_key(downstream_key_id, downstream_key)?; | ||
| Ok(()) | ||
| } | ||
| } | ||
|
|
||
| #[allow(dead_code)] | ||
| fn rotate_key_set<Ids: KeyIds>( | ||
| ctx: &KeyStoreContext<Ids>, | ||
| key_set: RotateableKeySet, | ||
| old_downstream_key_id: Ids::Symmetric, | ||
| new_downstream_key_id: Ids::Symmetric, | ||
| ) -> Result<RotateableKeySet, CryptoError> { | ||
| let pub_key_bytes = ctx.decrypt_data_with_symmetric_key( | ||
| old_downstream_key_id, | ||
| &key_set.encrypted_encapsulation_key, | ||
| )?; | ||
| let pub_key = SpkiPublicKeyBytes::from(pub_key_bytes); | ||
| let encapsulation_key = AsymmetricPublicCryptoKey::from_der(&pub_key)?; | ||
| // TODO: There is no method to store only the public key in the store, so we | ||
| // have pull out the downstream key to encapsulate it manually. | ||
| #[allow(deprecated)] | ||
| let new_downstream_key = ctx.dangerous_get_symmetric_key(new_downstream_key_id)?; | ||
| let new_encapsulated_key = | ||
| UnsignedSharedKey::encapsulate_key_unsigned(new_downstream_key, &encapsulation_key)?; | ||
| let new_encrypted_encapsulation_key = pub_key.encrypt_with_key(new_downstream_key)?; | ||
| Ok(RotateableKeySet { | ||
| encapsulated_downstream_key: new_encapsulated_key, | ||
| encrypted_encapsulation_key: new_encrypted_encapsulation_key, | ||
| encrypted_decapsulation_key: key_set.encrypted_decapsulation_key, | ||
| }) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
| use crate::{ | ||
| KeyStore, | ||
| traits::tests::{TestIds, TestSymmKey}, | ||
| }; | ||
|
|
||
| #[test] | ||
| fn test_rotateable_key_set_can_unlock() { | ||
| // generate initial keys | ||
| let upstream_key = SymmetricCryptoKey::make_aes256_cbc_hmac_key(); | ||
| // set up store | ||
| let store: KeyStore<TestIds> = KeyStore::default(); | ||
| let mut ctx = store.context_mut(); | ||
| let original_downstream_key_id = ctx.generate_symmetric_key(); | ||
|
|
||
| // create key set | ||
| let key_set = | ||
| RotateableKeySet::new(&ctx, &upstream_key, original_downstream_key_id).unwrap(); | ||
|
|
||
| // unlock key set | ||
| let unwrapped_downstream_key_id = TestSymmKey::A(1); | ||
| key_set | ||
| .unlock(&mut ctx, &upstream_key, unwrapped_downstream_key_id) | ||
| .unwrap(); | ||
|
|
||
| #[allow(deprecated)] | ||
| let original_downstream_key = ctx | ||
| .dangerous_get_symmetric_key(original_downstream_key_id) | ||
| .unwrap(); | ||
| #[allow(deprecated)] | ||
| let unwrapped_downstream_key = ctx | ||
| .dangerous_get_symmetric_key(unwrapped_downstream_key_id) | ||
| .unwrap(); | ||
| assert_eq!(original_downstream_key, unwrapped_downstream_key); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_rotateable_key_set_rotation() { | ||
| // generate initial keys | ||
| let upstream_key = SymmetricCryptoKey::make_aes256_cbc_hmac_key(); | ||
| // set up store | ||
| let store: KeyStore<TestIds> = KeyStore::default(); | ||
| let mut ctx = store.context_mut(); | ||
| let original_downstream_key_id = ctx.generate_symmetric_key(); | ||
|
|
||
| // create key set | ||
| let key_set = | ||
| RotateableKeySet::new(&ctx, &upstream_key, original_downstream_key_id).unwrap(); | ||
|
|
||
| // rotate | ||
| let new_downstream_key_id = ctx.generate_symmetric_key(); | ||
| let new_key_set = rotate_key_set( | ||
| &ctx, | ||
| key_set, | ||
| original_downstream_key_id, | ||
| new_downstream_key_id, | ||
| ) | ||
| .unwrap(); | ||
|
|
||
| // After rotation, the new key set should be unlocked by the same | ||
| // upstream key and return the new downstream key. | ||
| let unwrapped_downstream_key_id = TestSymmKey::A(2_2); | ||
| new_key_set | ||
| .unlock(&mut ctx, &upstream_key, unwrapped_downstream_key_id) | ||
| .unwrap(); | ||
| #[allow(deprecated)] | ||
| let new_downstream_key = ctx | ||
| .dangerous_get_symmetric_key(new_downstream_key_id) | ||
| .unwrap(); | ||
| #[allow(deprecated)] | ||
| let unwrapped_downstream_key = ctx | ||
| .dangerous_get_symmetric_key(unwrapped_downstream_key_id) | ||
| .unwrap(); | ||
| assert_eq!(new_downstream_key, unwrapped_downstream_key); | ||
| } | ||
| } |
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
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
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.
We should probably mention in the docs that only the first 32 bytes of the PRF output are processed: