Skip to content

Commit 38b8958

Browse files
committed
Typed byte arrays
1 parent 6d8bb8f commit 38b8958

File tree

42 files changed

+526
-282
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+526
-282
lines changed

bitwarden_license/bitwarden-sm/src/projects/create.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use bitwarden_api_api::models::ProjectCreateRequestModel;
22
use bitwarden_core::{key_management::SymmetricKeyId, Client};
3-
use bitwarden_crypto::PrimitiveEncryptableWithContentType;
3+
use bitwarden_crypto::PrimitiveEncryptable;
44
use schemars::JsonSchema;
55
use serde::{Deserialize, Serialize};
66
use uuid::Uuid;

bitwarden_license/bitwarden-sm/src/projects/update.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use bitwarden_api_api::models::ProjectUpdateRequestModel;
22
use bitwarden_core::{key_management::SymmetricKeyId, Client};
3-
use bitwarden_crypto::PrimitiveEncryptableWithContentType;
3+
use bitwarden_crypto::PrimitiveEncryptable;
44
use schemars::JsonSchema;
55
use serde::{Deserialize, Serialize};
66
use uuid::Uuid;

bitwarden_license/bitwarden-sm/src/secrets/create.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use bitwarden_api_api::models::SecretCreateRequestModel;
22
use bitwarden_core::{key_management::SymmetricKeyId, Client};
3-
use bitwarden_crypto::PrimitiveEncryptableWithContentType;
3+
use bitwarden_crypto::PrimitiveEncryptable;
44
use schemars::JsonSchema;
55
use serde::{Deserialize, Serialize};
66
use uuid::Uuid;

bitwarden_license/bitwarden-sm/src/secrets/update.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use bitwarden_api_api::models::SecretUpdateRequestModel;
22
use bitwarden_core::{key_management::SymmetricKeyId, Client};
3-
use bitwarden_crypto::PrimitiveEncryptableWithContentType;
3+
use bitwarden_crypto::PrimitiveEncryptable;
44
use schemars::JsonSchema;
55
use serde::{Deserialize, Serialize};
66
use uuid::Uuid;

crates/bitwarden-core/src/auth/auth_request.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ pub(crate) fn auth_request_decrypt_user_key(
5252
private_key: String,
5353
user_key: UnsignedSharedKey,
5454
) -> Result<SymmetricCryptoKey, EncryptionSettingsError> {
55-
let key = AsymmetricCryptoKey::from_der(&STANDARD.decode(private_key)?)?;
55+
let key = AsymmetricCryptoKey::from_der(&STANDARD.decode(private_key)?.into())?;
5656
let key: SymmetricCryptoKey = user_key.decapsulate_key_unsigned(&key)?;
5757
Ok(key)
5858
}
@@ -66,7 +66,7 @@ pub(crate) fn auth_request_decrypt_master_key(
6666
) -> Result<SymmetricCryptoKey, EncryptionSettingsError> {
6767
use bitwarden_crypto::MasterKey;
6868

69-
let key = AsymmetricCryptoKey::from_der(&STANDARD.decode(private_key)?)?;
69+
let key = AsymmetricCryptoKey::from_der(&STANDARD.decode(private_key)?.into())?;
7070
let master_key: SymmetricCryptoKey = master_key.decapsulate_key_unsigned(&key)?;
7171
let master_key = MasterKey::try_from(&master_key)?;
7272

@@ -118,7 +118,8 @@ fn test_auth_request() {
118118
];
119119

120120
let private_key =
121-
AsymmetricCryptoKey::from_der(&STANDARD.decode(&request.private_key).unwrap()).unwrap();
121+
AsymmetricCryptoKey::from_der(&STANDARD.decode(&request.private_key).unwrap().into())
122+
.unwrap();
122123

123124
let encrypted = UnsignedSharedKey::encapsulate_key_unsigned(
124125
&SymmetricCryptoKey::try_from(secret.clone()).unwrap(),
@@ -135,7 +136,7 @@ fn test_auth_request() {
135136
mod tests {
136137
use std::num::NonZeroU32;
137138

138-
use bitwarden_crypto::{Kdf, MasterKey};
139+
use bitwarden_crypto::{Kdf, MasterKey, SerializedBytes, SpkiPublicKeyDerContentFormat};
139140

140141
use super::*;
141142
use crate::key_management::{
@@ -166,8 +167,9 @@ mod tests {
166167
let public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvyLRDUwXB4BfQ507D4meFPmwn5zwy3IqTPJO4plrrhnclWahXa240BzyFW9gHgYu+Jrgms5xBfRTBMcEsqqNm7+JpB6C1B6yvnik0DpJgWQw1rwvy4SUYidpR/AWbQi47n/hvnmzI/sQxGddVfvWu1iTKOlf5blbKYAXnUE5DZBGnrWfacNXwRRdtP06tFB0LwDgw+91CeLSJ9py6dm1qX5JIxoO8StJOQl65goLCdrTWlox+0Jh4xFUfCkb+s3px+OhSCzJbvG/hlrSRcUz5GnwlCEyF3v5lfUtV96MJD+78d8pmH6CfFAp2wxKRAbGdk+JccJYO6y6oIXd3Fm7twIDAQAB";
167168

168169
// Verify fingerprint
169-
let pbkey = STANDARD.decode(public_key).unwrap();
170-
let fingerprint = fingerprint("[email protected]", &pbkey).unwrap();
170+
let pubkey = STANDARD.decode(public_key).unwrap();
171+
let pubkey = SerializedBytes::<SpkiPublicKeyDerContentFormat>::from(pubkey.clone());
172+
let fingerprint = fingerprint("[email protected]", &pubkey).unwrap();
171173
assert_eq!(fingerprint, "childless-unfair-prowler-dropbox-designate");
172174

173175
approve_auth_request(&client, public_key.to_owned()).unwrap();

crates/bitwarden-core/src/client/encryption_settings.rs

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -49,16 +49,16 @@ impl EncryptionSettings {
4949
signing_key: Option<EncString>,
5050
store: &KeyStore<KeyIds>,
5151
) -> Result<(), EncryptionSettingsError> {
52-
use bitwarden_crypto::{
53-
AsymmetricCryptoKey, CoseSerializable, CryptoError, KeyDecryptable, SigningKey,
54-
};
52+
use bitwarden_crypto::{AsymmetricCryptoKey, CoseSerializable, KeyDecryptable, SigningKey};
5553
use log::warn;
5654

5755
use crate::key_management::{AsymmetricKeyId, SigningKeyId, SymmetricKeyId};
5856

5957
let private_key = {
60-
let dec: Vec<u8> = private_key.decrypt_with_key(&user_key)?;
58+
use bitwarden_crypto::{Pkcs8PrivateKeyDerContentFormat, SerializedBytes};
6159

60+
let dec: Vec<u8> = private_key.decrypt_with_key(&user_key)?;
61+
let dec: SerializedBytes<Pkcs8PrivateKeyDerContentFormat> = SerializedBytes::from(dec);
6262
// FIXME: [PM-11690] - Temporarily ignore invalid private keys until we have a recovery
6363
// process in place.
6464
AsymmetricCryptoKey::from_der(&dec)
@@ -72,12 +72,13 @@ impl EncryptionSettings {
7272
// .map_err(|_| EncryptionSettingsError::InvalidPrivateKey)?,
7373
// )
7474
};
75-
let signing_key = signing_key
76-
.map(|key| {
77-
let dec: Vec<u8> = key.decrypt_with_key(&user_key)?;
78-
SigningKey::from_cose(dec.as_slice()).map_err(Into::<CryptoError>::into)
79-
})
80-
.transpose()?;
75+
let signing_key = signing_key.map(|key| {
76+
use bitwarden_crypto::{CoseKeyContentFormat, SerializedBytes};
77+
78+
let dec: Vec<u8> = key.decrypt_with_key(&user_key).unwrap();
79+
let dec: SerializedBytes<CoseKeyContentFormat> = SerializedBytes::from(dec);
80+
SigningKey::from_cose(&dec).unwrap()
81+
});
8182

8283
// FIXME: [PM-18098] When this is part of crypto we won't need to use deprecated methods
8384
#[allow(deprecated)]

crates/bitwarden-core/src/key_management/crypto.rs

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@ use std::collections::HashMap;
88

99
use base64::{engine::general_purpose::STANDARD, Engine};
1010
use bitwarden_crypto::{
11-
AsymmetricCryptoKey, ContentFormat, CoseSerializable, CryptoError, EncString, Kdf,
12-
KeyDecryptable, KeyEncryptable, MasterKey, PrimitiveEncryptable, SignatureAlgorithm,
13-
SignedPublicKey, SigningKey, SymmetricCryptoKey, UnsignedSharedKey, UserKey,
11+
AsymmetricCryptoKey, CoseSerializable, CryptoError, EncString, Kdf, KeyDecryptable,
12+
KeyEncryptable, MasterKey, Pkcs8PrivateKeyDerContentFormat, PrimitiveEncryptable,
13+
SerializedBytes, SignatureAlgorithm, SignedPublicKey, SigningKey, SymmetricCryptoKey,
14+
UnsignedSharedKey, UserKey,
1415
};
1516
use bitwarden_error::bitwarden_error;
1617
use schemars::JsonSchema;
@@ -351,7 +352,7 @@ pub(super) fn derive_pin_key(
351352

352353
Ok(DerivePinKeyResponse {
353354
pin_protected_user_key,
354-
encrypted_pin: pin.encrypt_with_key(user_key, ContentFormat::Utf8)?,
355+
encrypted_pin: pin.encrypt_with_key(user_key)?,
355356
})
356357
}
357358

@@ -536,6 +537,8 @@ pub(super) fn verify_asymmetric_keys(
536537
.decrypt_with_key(user_key)
537538
.map_err(VerifyError::DecryptFailed)?;
538539

540+
let decrypted_private_key: SerializedBytes<Pkcs8PrivateKeyDerContentFormat> =
541+
SerializedBytes::from(decrypted_private_key);
539542
let private_key = AsymmetricCryptoKey::from_der(&decrypted_private_key)
540543
.map_err(VerifyError::ParseFailed)?;
541544

@@ -602,13 +605,9 @@ pub fn make_user_signing_keys_for_enrollment(
602605

603606
Ok(MakeUserSigningKeysResponse {
604607
verifying_key: STANDARD.encode(signature_keypair.to_verifying_key().to_cose()),
605-
// This needs to be changed to use the correct COSE content format before rolling out to
606-
// users: https://bitwarden.atlassian.net/browse/PM-22189
607-
signing_key: signature_keypair.to_cose().encrypt(
608-
&mut ctx,
609-
SymmetricKeyId::User,
610-
ContentFormat::CoseKey,
611-
)?,
608+
signing_key: signature_keypair
609+
.to_cose()
610+
.encrypt(&mut ctx, SymmetricKeyId::User)?,
612611
signed_public_key,
613612
})
614613
}
@@ -844,8 +843,9 @@ mod tests {
844843
let encrypted = enroll_admin_password_reset(&client, public_key.to_owned()).unwrap();
845844

846845
let private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCzLtEUdxfcLxDj84yaGFsVF5hZ8Hjlb08NMQDy1RnBma06I3ZESshLYzVz4r/gegMn9OOltfV/Yxlyvida8oW6qdlfJ7AVz6Oa8pV7BiL40C7b76+oqraQpyYw2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JAregvXxfopxO+/7BAoGARicvEtDp7WWnSc1OPoj6N14VIxgYcI7SyrzE0d/1x3ffKzB5e7qomNpxKzvqrVP8DzG7ydh8jaKPmv1MfF8tpYRy3AhmN3/GYwCnPqT75YYrhcrWcVdax5gmQVqHkFtIQkRSCIftzPLlpMGKha/YBV8c1fvC4LD0NPh/Ynv0gtECgYEAyOZg95/kte0jpgUEgwuMrzkhY/AaUJULFuR5MkyvReEbtSBQwV5tx60+T95PHNiFooWWVXiLMsAgyI2IbkxVR1Pzdri3gWK5CTfqb7kLuaj/B7SGvBa2Sxo478KS5K8tBBBWkITqo+wLC0mn3uZi1dyMWO1zopTA+KtEGF2dtGQ=";
847-
let private_key =
848-
AsymmetricCryptoKey::from_der(&STANDARD.decode(private_key).unwrap()).unwrap();
846+
let private_key = STANDARD.decode(private_key).unwrap();
847+
let private_key = SerializedBytes::<Pkcs8PrivateKeyDerContentFormat>::from(private_key);
848+
let private_key = AsymmetricCryptoKey::from_der(&private_key).unwrap();
849849
let decrypted: SymmetricCryptoKey =
850850
encrypted.decapsulate_key_unsigned(&private_key).unwrap();
851851

@@ -937,11 +937,7 @@ mod tests {
937937
fn test_verify_asymmetric_keys_parse_failed() {
938938
let (user_key, key_pair) = setup_asymmetric_keys_test();
939939

940-
let invalid_private_key = "bad_key"
941-
.to_string()
942-
.into_bytes()
943-
.encrypt_with_key(&user_key.0, ContentFormat::Utf8)
944-
.unwrap();
940+
let invalid_private_key = "bad_key".to_string().encrypt_with_key(&user_key.0).unwrap();
945941

946942
let request = VerifyAsymmetricKeysRequest {
947943
user_key: user_key.0.to_base64(),

crates/bitwarden-core/src/platform/generate_fingerprint.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
//! This module contains the logic for generating fingerprints.
44
55
use base64::{engine::general_purpose::STANDARD, Engine};
6-
use bitwarden_crypto::fingerprint;
6+
use bitwarden_crypto::{fingerprint, SerializedBytes, SpkiPublicKeyDerContentFormat};
77
use serde::{Deserialize, Serialize};
88
use thiserror::Error;
99

@@ -42,7 +42,7 @@ pub enum FingerprintError {
4242

4343
pub(crate) fn generate_fingerprint(input: &FingerprintRequest) -> Result<String, FingerprintError> {
4444
let key = STANDARD.decode(&input.public_key)?;
45-
45+
let key = SerializedBytes::<SpkiPublicKeyDerContentFormat>::from(key);
4646
Ok(fingerprint(&input.fingerprint_material, &key)?)
4747
}
4848

crates/bitwarden-core/src/secrets_manager/state.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
66
use std::{fmt::Debug, path::Path};
77

8-
use bitwarden_crypto::{ContentFormat, EncString, KeyDecryptable, KeyEncryptable};
8+
use bitwarden_crypto::{EncString, KeyDecryptable, KeyEncryptable};
99
use serde::{Deserialize, Serialize};
1010

1111
use crate::auth::AccessToken;
@@ -73,7 +73,7 @@ pub(crate) fn set(
7373
) -> Result<(), StateFileError> {
7474
let serialized_state: String = serde_json::to_string(&state)?;
7575
let encrypted_state: EncString =
76-
serialized_state.encrypt_with_key(&access_token.encryption_key, ContentFormat::Utf8)?;
76+
serialized_state.encrypt_with_key(&access_token.encryption_key)?;
7777
let state_string: String = encrypted_state.to_string();
7878

7979
Ok(std::fs::write(state_file, state_string)?)

crates/bitwarden-crypto/examples/signature.rs

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
//! This example demonstrates how to create signatures and countersignatures for a message, and how
22
//! to verify them.
33
4-
use bitwarden_crypto::{CoseSerializable, SigningNamespace};
4+
use bitwarden_crypto::{
5+
CoseSerializable, CoseSign1ContentFormat, SerializedBytes, SigningNamespace,
6+
};
57
use serde::{Deserialize, Serialize};
68

79
const EXAMPLE_NAMESPACE: &SigningNamespace = &SigningNamespace::SignedPublicKey;
@@ -38,16 +40,18 @@ fn main() {
3840
.expect("Failed to sign message");
3941

4042
// Alice sends the signed object to Bob
41-
mock_server.upload("signature", signature.to_cose());
43+
mock_server.upload("signature", signature.to_cose().as_ref().to_vec());
4244
mock_server.upload("serialized_message", serialized_message.as_bytes().to_vec());
4345

4446
// Bob retrieves the signed object from the server
45-
let retrieved_signature = bitwarden_crypto::Signature::from_cose(
46-
mock_server
47-
.download("signature")
48-
.expect("Failed to download signature"),
49-
)
50-
.expect("Failed to deserialize signature");
47+
let retrieved_signature =
48+
bitwarden_crypto::Signature::from_cose(&SerializedBytes::<CoseSign1ContentFormat>::from(
49+
mock_server
50+
.download("signature")
51+
.expect("Failed to download signature")
52+
.clone(),
53+
))
54+
.expect("Failed to deserialize signature");
5155
let retrieved_serialized_message = bitwarden_crypto::SerializedMessage::from_bytes(
5256
mock_server
5357
.download("serialized_message")
@@ -76,7 +80,7 @@ fn main() {
7680
)
7781
.expect("Failed to counter sign message");
7882
// Bob sends the counter signature to Charlie
79-
mock_server.upload("bobs_signature", bobs_signature.to_cose());
83+
mock_server.upload("bobs_signature", bobs_signature.to_cose().as_ref().to_vec());
8084

8185
// Charlie retrieves the signatures, and the message
8286
let retrieved_serialized_message = bitwarden_crypto::SerializedMessage::from_bytes(
@@ -88,18 +92,22 @@ fn main() {
8892
.content_type()
8993
.expect("Failed to get content type from signature"),
9094
);
91-
let retrieved_alice_signature = bitwarden_crypto::Signature::from_cose(
92-
mock_server
93-
.download("signature")
94-
.expect("Failed to download Alice's signature"),
95-
)
96-
.expect("Failed to deserialize Alice's signature");
97-
let retrieved_bobs_signature = bitwarden_crypto::Signature::from_cose(
98-
mock_server
99-
.download("bobs_signature")
100-
.expect("Failed to download Bob's signature"),
101-
)
102-
.expect("Failed to deserialize Bob's signature");
95+
let retrieved_alice_signature =
96+
bitwarden_crypto::Signature::from_cose(&SerializedBytes::<CoseSign1ContentFormat>::from(
97+
mock_server
98+
.download("signature")
99+
.expect("Failed to download Alice's signature")
100+
.clone(),
101+
))
102+
.expect("Failed to deserialize Alice's signature");
103+
let retrieved_bobs_signature =
104+
bitwarden_crypto::Signature::from_cose(&SerializedBytes::<CoseSign1ContentFormat>::from(
105+
mock_server
106+
.download("bobs_signature")
107+
.expect("Failed to download Bob's signature")
108+
.clone(),
109+
))
110+
.expect("Failed to deserialize Bob's signature");
103111

104112
// Charlie verifies Alice's signature
105113
if !retrieved_alice_signature.verify(

0 commit comments

Comments
 (0)