-
Notifications
You must be signed in to change notification settings - Fork 20
[PM-26177] 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
base: main
Are you sure you want to change the base?
Changes from all commits
32ca764
4b8b249
eabb6cf
748f6d6
f986b43
0dce15e
b9bb1f0
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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') { | ||
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() | ||
} | ||
} |
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. Note: I'd recommend moving RotateableKeySet into it's own file, since it is a different cryptographic construction. (As a KM note, |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,10 @@ | ||
use serde::{Deserialize, Serialize}; | ||
|
||
use crate::{ | ||
CoseKeyBytes, CoseSerializable, CryptoError, EncString, KeyEncryptable, KeyIds, | ||
KeyStoreContext, SignedPublicKey, SignedPublicKeyMessage, SpkiPublicKeyBytes, | ||
SymmetricCryptoKey, | ||
AsymmetricCryptoKey, AsymmetricPublicCryptoKey, CoseKeyBytes, CoseSerializable, CryptoError, | ||
EncString, KeyDecryptable, KeyEncryptable, KeyIds, KeyStoreContext, Pkcs8PrivateKeyBytes, | ||
SignedPublicKey, SignedPublicKeyMessage, SpkiPublicKeyBytes, SymmetricCryptoKey, | ||
UnsignedSharedKey, | ||
}; | ||
|
||
/// Rotated set of account keys | ||
|
@@ -45,6 +48,122 @@ pub fn dangerous_get_v2_rotated_account_keys<Ids: KeyIds>( | |
}) | ||
} | ||
|
||
/// 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 { | ||
quexten marked this conversation as resolved.
Show resolved
Hide resolved
|
||
/// `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>( | ||
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. This method is currently unused since we don't yet have plans to use the rotateable key set on mobile, only to create them. However, it implements functionality that is currently done in TypeScript that could be moved to the SDK. I can remove it until we decide to either migrate the browser apps to this SDK method or start using it in the mobile apps. |
||
&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::*; | ||
|
@@ -137,4 +256,79 @@ mod tests { | |
.unwrap() | ||
); | ||
} | ||
|
||
#[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 = TestSymmKey::A(0); | ||
ctx.generate_symmetric_key(original_downstream_key_id) | ||
.unwrap(); | ||
|
||
// 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 = TestSymmKey::A(1); | ||
ctx.generate_symmetric_key(original_downstream_key_id) | ||
.unwrap(); | ||
|
||
// create key set | ||
let key_set = | ||
RotateableKeySet::new(&ctx, &upstream_key, original_downstream_key_id).unwrap(); | ||
|
||
// rotate | ||
let new_downstream_key_id = TestSymmKey::A(2_1); | ||
ctx.generate_symmetric_key(new_downstream_key_id).unwrap(); | ||
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); | ||
} | ||
} |
Uh oh!
There was an error while loading. Please reload this page.