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

Modern-Apps.git / third_party / betocore / np_adv / src / lib.rs

lib.rs213 lines · 7.5 KiBRaw
1// Copyright 2022 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//! Serialization and deserialization for v0 (legacy) and v1 (extended) Nearby Presence
16//! advertisements.
17//!
18//! See `tests/examples_v0.rs` and `tests/examples_v1.rs` for some tests that show common
19//! deserialization scenarios.
20
21#![no_std]
22#![allow(clippy::expect_used, clippy::indexing_slicing, clippy::panic)]
23
24#[cfg(any(test, feature = "alloc"))]
25extern crate alloc;
26
27#[cfg(feature = "std")]
28extern crate std;
29
30use core::fmt;
31pub use strum;
32pub use tinyvec::ArrayVec;
33
34use crate::credential::matched::MatchedCredential;
35use crate::extended::deserialize::{deser_decrypt_v1, V1AdvertisementContents};
36use crate::{
37 credential::book::CredentialBook,
38 header::NpVersionHeader,
39 legacy::{deser_decrypt_v0, V0AdvertisementContents},
40};
41use core::fmt::Debug;
42use crypto_provider::CryptoProvider;
43use deserialization_arena::DeserializationArena;
44use legacy::data_elements::DataElementDeserializeError;
45
46#[cfg(test)]
47mod tests;
48
49mod array_vec;
50pub mod credential;
51pub mod deserialization_arena;
52pub mod extended;
53pub mod filter;
54mod header;
55mod helpers;
56pub mod legacy;
57pub mod shared_data;
58
59/// Canonical form of NP's service UUID.
60///
61/// Note that UUIDs are encoded in BT frames in little-endian order, so these bytes may need to be
62/// reversed depending on the host BT API.
63pub const NP_SVC_UUID: [u8; 2] = [0xFC, 0xF1];
64
65/// Parse, deserialize, decrypt, and validate a complete NP advertisement (the entire contents of
66/// the service data for the NP UUID).
67pub fn deserialize_advertisement<'adv, 'cred, B, P>(
68 arena: DeserializationArena<'adv>,
69 adv: &'adv [u8],
70 cred_book: &'cred B,
71) -> Result<DeserializedAdvertisement<'adv, B::Matched>, AdvDeserializationError>
72where
73 B: CredentialBook<'cred>,
74 P: CryptoProvider,
75{
76 let (remaining, header) = NpVersionHeader::parse(adv)
77 .map_err(|_e| AdvDeserializationError::VersionHeaderParseError)?;
78 match header {
79 NpVersionHeader::V0(encoding) => deser_decrypt_v0::<B, P>(encoding, cred_book, remaining)
80 .map(DeserializedAdvertisement::V0),
81 NpVersionHeader::V1(header) => {
82 deser_decrypt_v1::<B, P>(arena, cred_book, remaining, header)
83 .map(DeserializedAdvertisement::V1)
84 }
85 }
86}
87
88/// An NP advertisement with its header parsed.
89#[allow(clippy::large_enum_variant)]
90#[derive(Debug, PartialEq, Eq)]
91pub enum DeserializedAdvertisement<'adv, M: MatchedCredential> {
92 /// V0 header has all reserved bits, so there is no data to represent other than the version
93 /// itself.
94 V0(V0AdvertisementContents<'adv, M>),
95 /// V1 advertisement
96 V1(V1AdvertisementContents<'adv, M>),
97}
98
99impl<'adv, M: MatchedCredential> DeserializedAdvertisement<'adv, M> {
100 /// Attempts to cast this deserialized advertisement into the `V0AdvertisementContents`
101 /// variant. If the underlying advertisement is not V0, this will instead return `None`.
102 pub fn into_v0(self) -> Option<V0AdvertisementContents<'adv, M>> {
103 match self {
104 Self::V0(x) => Some(x),
105 _ => None,
106 }
107 }
108 /// Attempts to cast this deserialized advertisement into the `V1AdvertisementContents`
109 /// variant. If the underlying advertisement is not V1, this will instead return `None`.
110 pub fn into_v1(self) -> Option<V1AdvertisementContents<'adv, M>> {
111 match self {
112 Self::V1(x) => Some(x),
113 _ => None,
114 }
115 }
116}
117
118/// Errors that can occur during advertisement deserialization.
119#[derive(PartialEq)]
120pub enum AdvDeserializationError {
121 /// The advertisement header could not be parsed
122 VersionHeaderParseError,
123 /// The advertisement content could not be parsed
124 ParseError {
125 /// Potentially hazardous details about deserialization errors. Read the documentation for
126 /// [AdvDeserializationErrorDetailsHazmat] before using this field.
127 details_hazmat: AdvDeserializationErrorDetailsHazmat,
128 },
129}
130
131impl Debug for AdvDeserializationError {
132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 match self {
134 AdvDeserializationError::VersionHeaderParseError => {
135 write!(f, "VersionHeaderParseError")
136 }
137 AdvDeserializationError::ParseError { .. } => write!(f, "ParseError"),
138 }
139 }
140}
141
142impl fmt::Display for AdvDeserializationError {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 match self {
145 AdvDeserializationError::VersionHeaderParseError => {
146 write!(f, "VersionHeaderParseError")
147 }
148 AdvDeserializationError::ParseError { .. } => write!(f, "ParseError"),
149 }
150 }
151}
152
153#[cfg(feature = "std")]
154impl std::error::Error for AdvDeserializationError {}
155
156/// Potentially hazardous details about deserialization errors. These error information can
157/// potentially expose side-channel information about the plaintext of the advertisements and/or
158/// the keys used to decrypt them. For any place that you avoid exposing the keys directly
159/// (e.g. across FFIs, print to log, etc), avoid exposing these error details as well.
160#[derive(PartialEq)]
161pub enum AdvDeserializationErrorDetailsHazmat {
162 /// Parsing the overall advertisement or DE structure failed
163 AdvertisementDeserializeError,
164 /// Deserializing an individual DE from its DE contents failed
165 V0DataElementDeserializeError(DataElementDeserializeError),
166 /// Non-identity DE contents must not be empty
167 NoPublicDataElements,
168}
169
170impl From<legacy::deserialize::AdvDeserializeError> for AdvDeserializationError {
171 fn from(err: legacy::deserialize::AdvDeserializeError) -> Self {
172 match err {
173 legacy::deserialize::AdvDeserializeError::NoDataElements => {
174 AdvDeserializationError::ParseError {
175 details_hazmat: AdvDeserializationErrorDetailsHazmat::NoPublicDataElements,
176 }
177 }
178 legacy::deserialize::AdvDeserializeError::InvalidStructure => {
179 AdvDeserializationError::ParseError {
180 details_hazmat:
181 AdvDeserializationErrorDetailsHazmat::AdvertisementDeserializeError,
182 }
183 }
184 }
185 }
186}
187
188// trivial Debug/Display that won't leak anything
189impl Debug for AdvDeserializationErrorDetailsHazmat {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 write!(f, "AdvDeserializationErrorDetailsHazmat")
192 }
193}
194
195impl fmt::Display for AdvDeserializationErrorDetailsHazmat {
196 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197 write!(f, "AdvDeserializationErrorDetailsHazmat")
198 }
199}
200
201#[cfg(feature = "std")]
202impl std::error::Error for AdvDeserializationErrorDetailsHazmat {}
203
204/// DE length is out of range (e.g. > 4 bits for encoded V0, > max DE size for actual V0, >127 for
205/// V1) or invalid for the relevant DE type.
206#[derive(Debug, PartialEq, Eq)]
207pub struct DeLengthOutOfRange;
208
209pub(crate) mod private {
210 /// A marker trait to prevent other crates from implementing traits that
211 /// are intended to be only implemented internally.
212 pub trait Sealed {}
213}