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    #[error("Invalid counter")]
96    InvalidCounter,
97}
98
99impl TryFrom<CipherViewContainer> for Passkey {
100    type Error = Fido2Error;
101
102    fn try_from(value: CipherViewContainer) -> Result<Self, Self::Error> {
103        let cred = value
104            .fido2_credentials
105            .first()
106            .ok_or(Fido2Error::NoFido2CredentialsFound)?;
107
108        try_from_credential_full_view(cred.clone())
109    }
110}
111
112fn try_from_credential_full_view(value: Fido2CredentialFullView) -> Result<Passkey, Fido2Error> {
113    let counter: u32 = value
114        .counter
115        .parse()
116        .map_err(|_| Fido2Error::InvalidCounter)?;
117    let counter = (counter != 0).then_some(counter);
118    let key_value = URL_SAFE_NO_PAD.decode(value.key_value)?;
119    let user_handle = value
120        .user_handle
121        .map(|u| URL_SAFE_NO_PAD.decode(u))
122        .transpose()?;
123
124    let key = pkcs8_to_cose_key(&key_value)?;
125
126    Ok(Passkey {
127        key,
128        credential_id: string_to_guid_bytes(&value.credential_id)?.into(),
129        rp_id: value.rp_id.clone(),
130        user_handle: user_handle.map(|u| u.into()),
131        counter,
132    })
133}
134
135#[allow(missing_docs)]
136#[derive(Debug, Error)]
137pub enum FillCredentialError {
138    #[error(transparent)]
139    InvalidInputLength(#[from] InvalidInputLength),
140    #[error(transparent)]
141    CoseKeyToPkcs8Error(#[from] CoseKeyToPkcs8Error),
142}
143
144#[allow(missing_docs)]
145pub fn fill_with_credential(
146    view: &Fido2CredentialView,
147    value: Passkey,
148) -> Result<Fido2CredentialFullView, FillCredentialError> {
149    let cred_id: Vec<u8> = value.credential_id.into();
150    let user_handle = value
151        .user_handle
152        .map(|u| URL_SAFE_NO_PAD.encode(u.to_vec()));
153    let key_value = URL_SAFE_NO_PAD.encode(cose_key_to_pkcs8(&value.key)?);
154
155    Ok(Fido2CredentialFullView {
156        credential_id: guid_bytes_to_string(&cred_id)?,
157        key_type: "public-key".to_owned(),
158        key_algorithm: "ECDSA".to_owned(),
159        key_curve: "P-256".to_owned(),
160        key_value,
161        rp_id: value.rp_id,
162        rp_name: view.rp_name.clone(),
163        user_handle,
164
165        counter: value.counter.unwrap_or(0).to_string(),
166        user_name: view.user_name.clone(),
167        user_display_name: view.user_display_name.clone(),
168        discoverable: "true".to_owned(),
169        creation_date: chrono::offset::Utc::now(),
170    })
171}
172
173pub(crate) fn try_from_credential_new_view(
174    user: &passkey::types::ctap2::make_credential::PublicKeyCredentialUserEntity,
175    rp: &passkey::types::ctap2::make_credential::PublicKeyCredentialRpEntity,
176) -> Result<Fido2CredentialNewView, InvalidInputLength> {
177    let cred_id: Vec<u8> = vec![0; 16];
178    let user_handle = URL_SAFE_NO_PAD.encode(user.id.to_vec());
179
180    Ok(Fido2CredentialNewView {
181        // TODO: Why do we have a credential id here?
182        credential_id: guid_bytes_to_string(&cred_id)?,
183        key_type: "public-key".to_owned(),
184        key_algorithm: "ECDSA".to_owned(),
185        key_curve: "P-256".to_owned(),
186        rp_id: rp.id.clone(),
187        rp_name: rp.name.clone(),
188        user_handle: Some(user_handle),
189
190        counter: 0.to_string(),
191        user_name: user.name.clone(),
192        user_display_name: user.display_name.clone(),
193        creation_date: chrono::offset::Utc::now(),
194    })
195}
196
197pub(crate) fn try_from_credential_full(
198    value: Passkey,
199    user: passkey::types::ctap2::make_credential::PublicKeyCredentialUserEntity,
200    rp: passkey::types::ctap2::make_credential::PublicKeyCredentialRpEntity,
201    options: passkey::types::ctap2::get_assertion::Options,
202) -> Result<Fido2CredentialFullView, FillCredentialError> {
203    let cred_id: Vec<u8> = value.credential_id.into();
204    let key_value = URL_SAFE_NO_PAD.encode(cose_key_to_pkcs8(&value.key)?);
205    let user_handle = URL_SAFE_NO_PAD.encode(user.id.to_vec());
206
207    Ok(Fido2CredentialFullView {
208        credential_id: guid_bytes_to_string(&cred_id)?,
209        key_type: "public-key".to_owned(),
210        key_algorithm: "ECDSA".to_owned(),
211        key_curve: "P-256".to_owned(),
212        key_value,
213        rp_id: value.rp_id,
214        rp_name: rp.name,
215        user_handle: Some(user_handle),
216
217        counter: value.counter.unwrap_or(0).to_string(),
218        user_name: user.name,
219        user_display_name: user.display_name,
220        discoverable: options.rk.to_string(),
221        creation_date: chrono::offset::Utc::now(),
222    })
223}
224
225#[allow(missing_docs)]
226#[derive(Debug, Error)]
227#[error("Input should be a 16 byte array")]
228pub struct InvalidInputLength;
229
230#[allow(missing_docs)]
231pub fn guid_bytes_to_string(source: &[u8]) -> Result<String, InvalidInputLength> {
232    if source.len() != 16 {
233        return Err(InvalidInputLength);
234    }
235    Ok(uuid::Uuid::from_bytes(source.try_into().expect("Invalid length")).to_string())
236}
237
238#[allow(missing_docs)]
239#[derive(Debug, Error)]
240#[error("Invalid GUID")]
241pub struct InvalidGuid;
242
243#[allow(missing_docs)]
244pub fn string_to_guid_bytes(source: &str) -> Result<Vec<u8>, InvalidGuid> {
245    if source.starts_with("b64.") {
246        let bytes = URL_SAFE_NO_PAD
247            .decode(source.trim_start_matches("b64."))
248            .map_err(|_| InvalidGuid)?;
249        Ok(bytes)
250    } else {
251        let Ok(uuid) = uuid::Uuid::try_parse(source) else {
252            return Err(InvalidGuid);
253        };
254        Ok(uuid.as_bytes().to_vec())
255    }
256}
257
258#[allow(missing_docs)]
259#[derive(Debug, Error)]
260#[error("Unknown enum value")]
261pub struct UnknownEnum;
262
263// Some utilities to convert back and forth between enums and strings
264fn get_enum_from_string_name<T: serde::de::DeserializeOwned>(s: &str) -> Result<T, UnknownEnum> {
265    let serialized = format!(r#""{s}""#);
266    let deserialized: T = serde_json::from_str(&serialized).map_err(|_| UnknownEnum)?;
267    Ok(deserialized)
268}
269
270fn get_string_name_from_enum(s: impl serde::Serialize) -> Result<String, serde_json::Error> {
271    let serialized = serde_json::to_string(&s)?;
272    let deserialized: String = serde_json::from_str(&serialized)?;
273    Ok(deserialized)
274}
275
276#[cfg(test)]
277mod tests {
278    use passkey::types::webauthn::AuthenticatorAttachment;
279
280    use super::{get_enum_from_string_name, get_string_name_from_enum};
281
282    #[test]
283    fn test_enum_string_conversion_works_as_expected() {
284        assert_eq!(
285            get_string_name_from_enum(AuthenticatorAttachment::CrossPlatform).unwrap(),
286            "cross-platform"
287        );
288
289        assert_eq!(
290            get_enum_from_string_name::<AuthenticatorAttachment>("cross-platform").unwrap(),
291            AuthenticatorAttachment::CrossPlatform
292        );
293    }
294
295    #[test]
296    fn string_to_guid_with_uuid_works() {
297        let uuid = "d548826e-79b4-db40-a3d8-11116f7e8349";
298        let bytes = super::string_to_guid_bytes(uuid).unwrap();
299        assert_eq!(
300            bytes,
301            vec![213, 72, 130, 110, 121, 180, 219, 64, 163, 216, 17, 17, 111, 126, 131, 73]
302        );
303    }
304
305    #[test]
306    fn string_to_guid_with_b64_works() {
307        let b64 = "b64.1UiCbnm020Cj2BERb36DSQ";
308        let bytes = super::string_to_guid_bytes(b64).unwrap();
309        assert_eq!(
310            bytes,
311            vec![213, 72, 130, 110, 121, 180, 219, 64, 163, 216, 17, 17, 111, 126, 131, 73]
312        );
313    }
314}