Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / third_party / betocore / np_adv / src / credential / matched.rs

matched.rs349 lines · 13.4 KiBRaw
1// Copyright 2024 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Contains matched credential structs and traits which contain information about the credential
16//! which is passed back to the caller upon a successful decrypt and credential match.
17
18#[cfg(any(test, feature = "alloc"))]
19use alloc::vec::Vec;
20#[cfg(any(test, feature = "alloc"))]
21use crypto_provider::CryptoProvider;
22
23#[cfg(any(test, feature = "alloc"))]
24use crate::credential::metadata::{decrypt_metadata_with_nonce, encrypt_metadata};
25use crate::credential::{v0::V0, v1::V1, ProtocolVersion};
26use core::{convert::Infallible, fmt::Debug};
27use ldt_np_adv::V0IdentityToken;
28
29/// The portion of a credential's data to be bundled with the advertisement content it was used to
30/// decrypt. At a minimum, this includes any encrypted identity-specific metadata.
31///
32/// As it is `Debug` and `Eq`, implementors should not hold any cryptographic secrets to avoid
33/// accidental logging, timing side channels on comparison, etc, or should use custom impls of
34/// those traits rather than deriving them.
35///
36/// Instances of `MatchedCredential` may be cloned whenever advertisement content is
37/// successfully associated with a credential (see [`WithMatchedCredential`]). As a
38/// result, it's recommended to use matched-credentials which reference
39/// some underlying match-data, but don't necessarily own it.
40/// See [`ReferencedMatchedCredential`] for the most common case of shared references.
41pub trait MatchedCredential: Debug + PartialEq + Eq + Clone {
42 /// The type returned for successful calls to [`Self::fetch_encrypted_metadata`].
43 type EncryptedMetadata: AsRef<[u8]>;
44
45 /// The type of errors for [`Self::fetch_encrypted_metadata`].
46 type EncryptedMetadataFetchError: Debug;
47
48 /// Attempts to obtain the (AES-GCM)-encrypted metadata bytes for the credential,
49 /// with possible failure based on the availability of the underlying data (i.e:
50 /// failing disk reads.)
51 ///
52 /// If your implementation does not maintain any encrypted metadata for each credential,
53 /// you may simply return an empty byte-array from this method.
54 ///
55 /// If your method for obtaining metadata cannot fail, use
56 /// the `core::convert::Infallible` type for the error type
57 /// [`Self::EncryptedMetadataFetchError`].
58 fn fetch_encrypted_metadata(
59 &self,
60 ) -> Result<Self::EncryptedMetadata, Self::EncryptedMetadataFetchError>;
61}
62
63/// [`MatchedCredential`] wrapper around a shared reference to a [`MatchedCredential`].
64/// This is done instead of providing a blanket impl of [`MatchedCredential`] for
65/// reference types to allow for downstream crates to impl [`MatchedCredential`] on
66/// specific reference types.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub struct ReferencedMatchedCredential<'a, M: MatchedCredential> {
69 wrapped: &'a M,
70}
71
72impl<'a, M: MatchedCredential> From<&'a M> for ReferencedMatchedCredential<'a, M> {
73 fn from(wrapped: &'a M) -> Self {
74 Self { wrapped }
75 }
76}
77
78impl<M: MatchedCredential> AsRef<M> for ReferencedMatchedCredential<'_, M> {
79 fn as_ref(&self) -> &M {
80 self.wrapped
81 }
82}
83
84impl<M: MatchedCredential> MatchedCredential for ReferencedMatchedCredential<'_, M> {
85 type EncryptedMetadata = <M as MatchedCredential>::EncryptedMetadata;
86 type EncryptedMetadataFetchError = <M as MatchedCredential>::EncryptedMetadataFetchError;
87 fn fetch_encrypted_metadata(
88 &self,
89 ) -> Result<Self::EncryptedMetadata, Self::EncryptedMetadataFetchError> {
90 self.wrapped.fetch_encrypted_metadata()
91 }
92}
93
94/// A simple implementation of [`MatchedCredential`] where all match-data
95/// is contained in the encrypted metadata byte-field.
96#[derive(Debug, PartialEq, Eq, Clone)]
97pub struct MetadataMatchedCredential<A: AsRef<[u8]> + Clone + Debug + PartialEq + Eq> {
98 encrypted_metadata: A,
99}
100
101#[cfg(any(test, feature = "alloc"))]
102impl MetadataMatchedCredential<Vec<u8>> {
103 /// Builds a [`MetadataMatchedCredential`] whose contents are given
104 /// as plaintext to be encrypted using AES-GCM against the given
105 /// broadcast crypto-material.
106 pub fn encrypt_from_plaintext<V, C>(
107 hkdf: &np_hkdf::NpKeySeedHkdf<C>,
108 identity_token: V::IdentityToken,
109 plaintext_metadata: &[u8],
110 ) -> Self
111 where
112 V: ProtocolVersion,
113 C: CryptoProvider,
114 {
115 // TODO move this to identity provider
116 let encrypted_metadata = encrypt_metadata::<C, V>(hkdf, identity_token, plaintext_metadata);
117 Self { encrypted_metadata }
118 }
119}
120
121impl<A: AsRef<[u8]> + Clone + Debug + PartialEq + Eq> MetadataMatchedCredential<A> {
122 /// Builds a new [`MetadataMatchedCredential`] with the given
123 /// encrypted metadata.
124 pub fn new(encrypted_metadata: A) -> Self {
125 Self { encrypted_metadata }
126 }
127}
128
129impl<A: AsRef<[u8]> + Clone + Debug + PartialEq + Eq> MatchedCredential
130 for MetadataMatchedCredential<A>
131{
132 type EncryptedMetadata = A;
133 type EncryptedMetadataFetchError = Infallible;
134 fn fetch_encrypted_metadata(&self) -> Result<Self::EncryptedMetadata, Infallible> {
135 Ok(self.encrypted_metadata.clone())
136 }
137}
138
139/// A simple implementation of [`MatchedCredential`] where all match-data
140/// is contained in the encrypted metadata byte-field.
141#[derive(Debug, PartialEq, Eq, Clone)]
142pub struct MatchedCredentialWithId<A: AsRef<[u8]> + Clone + Debug + PartialEq + Eq> {
143 encrypted_metadata: A,
144 id: i64,
145}
146
147impl<A: AsRef<[u8]> + Clone + Debug + PartialEq + Eq> MatchedCredentialWithId<A> {
148 /// Builds a new [`MatchedCredentialWithId`] with the given
149 /// encrypted metadata.
150 pub fn new(encrypted_metadata: A, id: i64) -> Self {
151 Self { encrypted_metadata, id }
152 }
153
154 /// Returns the unique ID of the matched credential.
155 pub fn id(&self) -> i64 {
156 self.id
157 }
158}
159
160impl<A: AsRef<[u8]> + Clone + Debug + PartialEq + Eq> MatchedCredential
161 for MatchedCredentialWithId<A>
162{
163 type EncryptedMetadata = A;
164 type EncryptedMetadataFetchError = Infallible;
165 fn fetch_encrypted_metadata(&self) -> Result<Self::EncryptedMetadata, Infallible> {
166 Ok(self.encrypted_metadata.clone())
167 }
168}
169
170/// Trivial implementation of [`MatchedCredential`] which consists of no match-data.
171/// Suitable for usage scenarios where the decoded advertisement contents matter,
172/// but not necessarily which devices generated the contents.
173///
174/// Attempting to obtain the encrypted metadata from this type of credential
175/// will always yield an empty byte-array.
176#[derive(Default, Debug, PartialEq, Eq, Clone)]
177pub struct EmptyMatchedCredential;
178
179impl MatchedCredential for EmptyMatchedCredential {
180 type EncryptedMetadata = [u8; 0];
181 type EncryptedMetadataFetchError = Infallible;
182 fn fetch_encrypted_metadata(
183 &self,
184 ) -> Result<Self::EncryptedMetadata, Self::EncryptedMetadataFetchError> {
185 Ok([0u8; 0])
186 }
187}
188
189#[cfg(any(test, feature = "devtools"))]
190/// A [`MatchedCredential`] which consists only of the `key_seed` in the crypto-material
191/// for the credential. Note that this is unique per-credential by construction,
192/// and so this provides natural match-data for credentials in settings where
193/// there may not be any other information available.
194///
195/// Since this matched-credential type contains cryptographic information mirroring
196/// a credential's crypto-material, this structure is not suitable for production
197/// usage outside of unit tests and dev-tools.
198///
199/// Additionally, note that the metadata on this particular kind of matched credential
200/// is deliberately made inaccessible. This is done because a key-seed representation
201/// is only suitable in very limited circumstances where no other meaningful
202/// identifying information is available, such as that which is contained in metadata.
203/// Attempting to obtain the encrypted metadata from this type of matched credential
204/// will always yield an empty byte-array.
205#[derive(Default, Debug, PartialEq, Eq, Clone)]
206pub struct KeySeedMatchedCredential {
207 key_seed: [u8; 32],
208}
209
210#[cfg(any(test, feature = "devtools"))]
211impl From<[u8; 32]> for KeySeedMatchedCredential {
212 fn from(key_seed: [u8; 32]) -> Self {
213 Self { key_seed }
214 }
215}
216#[cfg(any(test, feature = "devtools"))]
217impl From<KeySeedMatchedCredential> for [u8; 32] {
218 fn from(matched: KeySeedMatchedCredential) -> Self {
219 matched.key_seed
220 }
221}
222
223#[cfg(any(test, feature = "devtools"))]
224impl MatchedCredential for KeySeedMatchedCredential {
225 type EncryptedMetadata = [u8; 0];
226 type EncryptedMetadataFetchError = Infallible;
227 fn fetch_encrypted_metadata(
228 &self,
229 ) -> Result<Self::EncryptedMetadata, Self::EncryptedMetadataFetchError> {
230 Ok([0u8; 0])
231 }
232}
233
234/// Common trait to deserialized, decrypted V0 advs and V1 sections which
235/// exposes relevant data about matched identities.
236pub trait HasIdentityMatch {
237 /// The protocol version for which this advertisement
238 /// content has an identity-match.
239 type Version: ProtocolVersion;
240
241 /// Gets the decrypted plaintext version-specific
242 /// metadata key for the associated identity.
243 fn identity_token(&self) -> <Self::Version as ProtocolVersion>::IdentityToken;
244}
245
246impl HasIdentityMatch for V0IdentityToken {
247 type Version = V0;
248 fn identity_token(&self) -> Self {
249 *self
250 }
251}
252
253impl HasIdentityMatch for crate::extended::V1IdentityToken {
254 type Version = V1;
255 fn identity_token(&self) -> Self {
256 *self
257 }
258}
259
260#[cfg(any(test, feature = "alloc"))]
261/// Type for errors from [`WithMatchedCredential#decrypt_metadata`]
262#[derive(Debug)]
263pub enum MatchedMetadataDecryptionError<M: MatchedCredential> {
264 /// Retrieving the encrypted metadata failed for one reason
265 /// or another, so we didn't get a chance to try decryption.
266 RetrievalFailed(<M as MatchedCredential>::EncryptedMetadataFetchError),
267 /// The encrypted metadata could be retrieved, but it did
268 /// not successfully decrypt against the matched identity.
269 /// This could be an indication of data corruption or
270 /// of malformed crypto on the sender-side.
271 DecryptionFailed,
272}
273
274/// Decrypted advertisement content with the [MatchedCredential] from the credential that decrypted
275/// it, along with any other information which is relevant to the identity-match.
276#[derive(Debug, PartialEq, Eq)]
277pub struct WithMatchedCredential<M: MatchedCredential, T: HasIdentityMatch> {
278 matched: M,
279 /// The 12-byte metadata nonce as derived from the key-seed HKDF
280 /// to be used for decrypting the encrypted metadata in the attached
281 /// matched-credential.
282 metadata_nonce: [u8; 12],
283 contents: T,
284}
285
286impl<M: MatchedCredential + Clone, T: HasIdentityMatch>
287 WithMatchedCredential<ReferencedMatchedCredential<'_, M>, T>
288{
289 /// Clones the referenced match-data to update this container
290 /// so that the match-data is owned, rather than borrowed.
291 pub fn clone_match_data(self) -> WithMatchedCredential<M, T> {
292 let matched = self.matched.as_ref().clone();
293 let metadata_nonce = self.metadata_nonce;
294 let contents = self.contents;
295
296 WithMatchedCredential { matched, metadata_nonce, contents }
297 }
298}
299
300impl<M: MatchedCredential, T: HasIdentityMatch> WithMatchedCredential<M, T> {
301 pub(crate) fn new(matched: M, metadata_nonce: [u8; 12], contents: T) -> Self {
302 Self { matched, metadata_nonce, contents }
303 }
304 /// Applies the given function to the wrapped contents, yielding
305 /// a new instance with the same matched-credential.
306 pub fn map<R: HasIdentityMatch>(
307 self,
308 mapping: impl FnOnce(T) -> R,
309 ) -> WithMatchedCredential<M, R> {
310 let contents = mapping(self.contents);
311 let matched = self.matched;
312 let metadata_nonce = self.metadata_nonce;
313 WithMatchedCredential { matched, metadata_nonce, contents }
314 }
315 /// Credential data for the credential that decrypted the content.
316 pub fn matched_credential(&self) -> &M {
317 &self.matched
318 }
319 /// The decrypted advertisement content.
320 pub fn contents(&self) -> &T {
321 &self.contents
322 }
323
324 #[cfg(any(test, feature = "alloc"))]
325 fn decrypt_metadata_from_fetch<C: CryptoProvider>(
326 &self,
327 encrypted_metadata: &[u8],
328 ) -> Result<Vec<u8>, MatchedMetadataDecryptionError<M>> {
329 decrypt_metadata_with_nonce::<C, T::Version>(
330 self.metadata_nonce,
331 self.contents.identity_token(),
332 encrypted_metadata,
333 )
334 .map_err(|_| MatchedMetadataDecryptionError::DecryptionFailed)
335 }
336
337 #[cfg(any(test, feature = "alloc"))]
338 /// Attempts to decrypt the encrypted metadata
339 /// associated with the matched credential
340 /// based on the details of the identity-match.
341 pub fn decrypt_metadata<C: CryptoProvider>(
342 &self,
343 ) -> Result<Vec<u8>, MatchedMetadataDecryptionError<M>> {
344 self.matched
345 .fetch_encrypted_metadata()
346 .map_err(|e| MatchedMetadataDecryptionError::RetrievalFailed(e))
347 .and_then(|x| Self::decrypt_metadata_from_fetch::<C>(self, x.as_ref()))
348 }
349}