bitwarden_fido/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
4use bitwarden_core::key_management::KeyIds;
5use bitwarden_crypto::KeyStoreContext;
6use bitwarden_vault::{
7    CipherError, CipherView, Fido2CredentialFullView, Fido2CredentialNewView, Fido2CredentialView,
8};
9use crypto::{CoseKeyToPkcs8Error, PrivateKeyFromSecretKeyError};
10use passkey::types::{ctap2::Aaguid, Passkey};
11
12#[cfg(feature = "uniffi")]
13uniffi::setup_scaffolding!();
14#[cfg(feature = "uniffi")]
15mod uniffi_support;
16
17mod authenticator;
18mod client;
19mod client_fido;
20mod crypto;
21mod traits;
22mod types;
23pub use authenticator::{
24    CredentialsForAutofillError, Fido2Authenticator, GetAssertionError, MakeCredentialError,
25    SilentlyDiscoverCredentialsError,
26};
27pub use client::{Fido2Client, Fido2ClientError};
28pub use client_fido::{ClientFido2, ClientFido2Ext, DecryptFido2AutofillCredentialsError};
29pub use passkey::authenticator::UIHint;
30use thiserror::Error;
31pub use traits::{
32    CheckUserOptions, CheckUserResult, Fido2CallbackError, Fido2CredentialStore,
33    Fido2UserInterface, Verification,
34};
35pub use types::{
36    AuthenticatorAssertionResponse, AuthenticatorAttestationResponse, ClientData,
37    Fido2CredentialAutofillView, Fido2CredentialAutofillViewError, GetAssertionRequest,
38    GetAssertionResult, MakeCredentialRequest, MakeCredentialResult, Options, Origin,
39    PublicKeyCredentialAuthenticatorAssertionResponse,
40    PublicKeyCredentialAuthenticatorAttestationResponse, PublicKeyCredentialRpEntity,
41    PublicKeyCredentialUserEntity, UnverifiedAssetLink,
42};
43
44use self::crypto::{cose_key_to_pkcs8, pkcs8_to_cose_key};
45
46// This is the AAGUID for the Bitwarden Passkey provider (d548826e-79b4-db40-a3d8-11116f7e8349)
47// It is used for the Relaying Parties to identify the authenticator during registration
48const AAGUID: Aaguid = Aaguid([
49    0xd5, 0x48, 0x82, 0x6e, 0x79, 0xb4, 0xdb, 0x40, 0xa3, 0xd8, 0x11, 0x11, 0x6f, 0x7e, 0x83, 0x49,
50]);
51
52#[allow(dead_code, missing_docs)]
53#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
54pub struct SelectedCredential {
55    cipher: CipherView,
56    credential: Fido2CredentialView,
57}
58
59// This container is needed so we can properly implement the TryFrom trait for Passkey
60// Otherwise we need to decrypt the Fido2 credentials every time we create a CipherView
61#[derive(Clone)]
62pub(crate) struct CipherViewContainer {
63    cipher: CipherView,
64    fido2_credentials: Vec<Fido2CredentialFullView>,
65}
66
67impl CipherViewContainer {
68    fn new(cipher: CipherView, ctx: &mut KeyStoreContext<KeyIds>) -> Result<Self, CipherError> {
69        let fido2_credentials = cipher.get_fido2_credentials(ctx)?;
70        Ok(Self {
71            cipher,
72            fido2_credentials,
73        })
74    }
75}
76
77#[allow(missing_docs)]
78#[derive(Debug, Error)]
79pub enum Fido2Error {
80    #[error(transparent)]
81    DecodeError(#[from] base64::DecodeError),
82
83    #[error(transparent)]
84    UnknownEnum(#[from] UnknownEnum),
85
86    #[error(transparent)]
87    InvalidGuid(#[from] InvalidGuid),
88
89    #[error(transparent)]
90    PrivateKeyFromSecretKeyError(#[from] PrivateKeyFromSecretKeyError),
91
92    #[error("No Fido2 credentials found")]
93    NoFido2CredentialsFound,
94}
95
96impl TryFrom<CipherViewContainer> for Passkey {
97    type Error = Fido2Error;
98
99    fn try_from(value: CipherViewContainer) -> Result<Self, Self::Error> {
100        let cred = value
101            .fido2_credentials
102            .first()
103            .ok_or(Fido2Error::NoFido2CredentialsFound)?;
104
105        try_from_credential_full_view(cred.clone())
106    }
107}
108
109fn try_from_credential_full_view(value: Fido2CredentialFullView) -> Result<Passkey, Fido2Error> {
110    let counter: u32 = value.counter.parse().expect("Invalid counter");
111    let counter = (counter != 0).then_some(counter);
112    let key_value = URL_SAFE_NO_PAD.decode(value.key_value)?;
113    let user_handle = value
114        .user_handle
115        .map(|u| URL_SAFE_NO_PAD.decode(u))
116        .transpose()?;
117
118    let key = pkcs8_to_cose_key(&key_value)?;
119
120    Ok(Passkey {
121        key,
122        credential_id: string_to_guid_bytes(&value.credential_id)?.into(),
123        rp_id: value.rp_id.clone(),
124        user_handle: user_handle.map(|u| u.into()),
125        counter,
126    })
127}
128
129#[allow(missing_docs)]
130#[derive(Debug, Error)]
131pub enum FillCredentialError {
132    #[error(transparent)]
133    InvalidInputLength(#[from] InvalidInputLength),
134    #[error(transparent)]
135    CoseKeyToPkcs8Error(#[from] CoseKeyToPkcs8Error),
136}
137
138#[allow(missing_docs)]
139pub fn fill_with_credential(
140    view: &Fido2CredentialView,
141    value: Passkey,
142) -> Result<Fido2CredentialFullView, FillCredentialError> {
143    let cred_id: Vec<u8> = value.credential_id.into();
144    let user_handle = value
145        .user_handle
146        .map(|u| URL_SAFE_NO_PAD.encode(u.to_vec()));
147    let key_value = URL_SAFE_NO_PAD.encode(cose_key_to_pkcs8(&value.key)?);
148
149    Ok(Fido2CredentialFullView {
150        credential_id: guid_bytes_to_string(&cred_id)?,
151        key_type: "public-key".to_owned(),
152        key_algorithm: "ECDSA".to_owned(),
153        key_curve: "P-256".to_owned(),
154        key_value,
155        rp_id: value.rp_id,
156        rp_name: view.rp_name.clone(),
157        user_handle,
158
159        counter: value.counter.unwrap_or(0).to_string(),
160        user_name: view.user_name.clone(),
161        user_display_name: view.user_display_name.clone(),
162        discoverable: "true".to_owned(),
163        creation_date: chrono::offset::Utc::now(),
164    })
165}
166
167pub(crate) fn try_from_credential_new_view(
168    user: &passkey::types::ctap2::make_credential::PublicKeyCredentialUserEntity,
169    rp: &passkey::types::ctap2::make_credential::PublicKeyCredentialRpEntity,
170) -> Result<Fido2CredentialNewView, InvalidInputLength> {
171    let cred_id: Vec<u8> = vec![0; 16];
172    let user_handle = URL_SAFE_NO_PAD.encode(user.id.to_vec());
173
174    Ok(Fido2CredentialNewView {
175        // TODO: Why do we have a credential id here?
176        credential_id: guid_bytes_to_string(&cred_id)?,
177        key_type: "public-key".to_owned(),
178        key_algorithm: "ECDSA".to_owned(),
179        key_curve: "P-256".to_owned(),
180        rp_id: rp.id.clone(),
181        rp_name: rp.name.clone(),
182        user_handle: Some(user_handle),
183
184        counter: 0.to_string(),
185        user_name: user.name.clone(),
186        user_display_name: user.display_name.clone(),
187        creation_date: chrono::offset::Utc::now(),
188    })
189}
190
191pub(crate) fn try_from_credential_full(
192    value: Passkey,
193    user: passkey::types::ctap2::make_credential::PublicKeyCredentialUserEntity,
194    rp: passkey::types::ctap2::make_credential::PublicKeyCredentialRpEntity,
195    options: passkey::types::ctap2::get_assertion::Options,
196) -> Result<Fido2CredentialFullView, FillCredentialError> {
197    let cred_id: Vec<u8> = value.credential_id.into();
198    let key_value = URL_SAFE_NO_PAD.encode(cose_key_to_pkcs8(&value.key)?);
199    let user_handle = URL_SAFE_NO_PAD.encode(user.id.to_vec());
200
201    Ok(Fido2CredentialFullView {
202        credential_id: guid_bytes_to_string(&cred_id)?,
203        key_type: "public-key".to_owned(),
204        key_algorithm: "ECDSA".to_owned(),
205        key_curve: "P-256".to_owned(),
206        key_value,
207        rp_id: value.rp_id,
208        rp_name: rp.name,
209        user_handle: Some(user_handle),
210
211        counter: value.counter.unwrap_or(0).to_string(),
212        user_name: user.name,
213        user_display_name: user.display_name,
214        discoverable: options.rk.to_string(),
215        creation_date: chrono::offset::Utc::now(),
216    })
217}
218
219#[allow(missing_docs)]
220#[derive(Debug, Error)]
221#[error("Input should be a 16 byte array")]
222pub struct InvalidInputLength;
223
224#[allow(missing_docs)]
225pub fn guid_bytes_to_string(source: &[u8]) -> Result<String, InvalidInputLength> {
226    if source.len() != 16 {
227        return Err(InvalidInputLength);
228    }
229    Ok(uuid::Uuid::from_bytes(source.try_into().expect("Invalid length")).to_string())
230}
231
232#[allow(missing_docs)]
233#[derive(Debug, Error)]
234#[error("Invalid GUID")]
235pub struct InvalidGuid;
236
237#[allow(missing_docs)]
238pub fn string_to_guid_bytes(source: &str) -> Result<Vec<u8>, InvalidGuid> {
239    if source.starts_with("b64.") {
240        let bytes = URL_SAFE_NO_PAD
241            .decode(source.trim_start_matches("b64."))
242            .map_err(|_| InvalidGuid)?;
243        Ok(bytes)
244    } else {
245        let Ok(uuid) = uuid::Uuid::try_parse(source) else {
246            return Err(InvalidGuid);
247        };
248        Ok(uuid.as_bytes().to_vec())
249    }
250}
251
252#[allow(missing_docs)]
253#[derive(Debug, Error)]
254#[error("Unknown enum value")]
255pub struct UnknownEnum;
256
257// Some utilities to convert back and forth between enums and strings
258fn get_enum_from_string_name<T: serde::de::DeserializeOwned>(s: &str) -> Result<T, UnknownEnum> {
259    let serialized = format!(r#""{}""#, s);
260    let deserialized: T = serde_json::from_str(&serialized).map_err(|_| UnknownEnum)?;
261    Ok(deserialized)
262}
263
264fn get_string_name_from_enum(s: impl serde::Serialize) -> Result<String, serde_json::Error> {
265    let serialized = serde_json::to_string(&s)?;
266    let deserialized: String = serde_json::from_str(&serialized)?;
267    Ok(deserialized)
268}
269
270#[cfg(test)]
271mod tests {
272    use passkey::types::webauthn::AuthenticatorAttachment;
273
274    use super::{get_enum_from_string_name, get_string_name_from_enum};
275
276    #[test]
277    fn test_enum_string_conversion_works_as_expected() {
278        assert_eq!(
279            get_string_name_from_enum(AuthenticatorAttachment::CrossPlatform).unwrap(),
280            "cross-platform"
281        );
282
283        assert_eq!(
284            get_enum_from_string_name::<AuthenticatorAttachment>("cross-platform").unwrap(),
285            AuthenticatorAttachment::CrossPlatform
286        );
287    }
288
289    #[test]
290    fn string_to_guid_with_uuid_works() {
291        let uuid = "d548826e-79b4-db40-a3d8-11116f7e8349";
292        let bytes = super::string_to_guid_bytes(uuid).unwrap();
293        assert_eq!(
294            bytes,
295            vec![213, 72, 130, 110, 121, 180, 219, 64, 163, 216, 17, 17, 111, 126, 131, 73]
296        );
297    }
298
299    #[test]
300    fn string_to_guid_with_b64_works() {
301        let b64 = "b64.1UiCbnm020Cj2BERb36DSQ";
302        let bytes = super::string_to_guid_bytes(b64).unwrap();
303        assert_eq!(
304            bytes,
305            vec![213, 72, 130, 110, 121, 180, 219, 64, 163, 216, 17, 17, 111, 126, 131, 73]
306        );
307    }
308}