Skip to main content

bluetooth_host/
keys.rs

1//! Bonds (the keys pairing leaves behind), our own identity, and resolving
2//! private addresses to the identities they hide.
3//!
4//! Kept as two JSON files in the data directory, written whole to a
5//! temporary file and renamed, mode 0600: `identity.json` (our IRK and
6//! static random address) and `bonds.json`.
7
8use std::collections::HashMap;
9use std::fs;
10use std::io::Write;
11use std::path::{Path, PathBuf};
12use std::sync::Mutex;
13
14use serde::{Deserialize, Serialize};
15
16use crate::address::Address;
17use crate::crypto;
18use crate::error::Result;
19
20/// A long-term key and how to find it again.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
22pub struct LongTermKey {
23    /// The key.
24    #[serde(with = "hex_u128")]
25    pub key: u128,
26    /// Encrypted Diversifier (0 for Secure Connections).
27    pub ediv: u16,
28    /// Random number (0 for Secure Connections).
29    pub rand: u64,
30    /// Key size, octets.
31    pub key_size: u8,
32}
33
34/// What we keep about a bonded (or otherwise known) device.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub struct Bond {
37    /// The device's identity address.
38    pub identity: Address,
39    /// The key to encrypt with: the Secure Connections LTK, or under legacy
40    /// pairing the one the peer distributed (used when we are central).
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub ltk: Option<LongTermKey>,
43    /// Under legacy pairing, the LTK we distributed (used when we are peripheral).
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub local_ltk: Option<LongTermKey>,
46    /// The device's Identity Resolving Key.
47    #[serde(
48        default,
49        skip_serializing_if = "Option::is_none",
50        with = "hex_u128_opt"
51    )]
52    pub irk: Option<u128>,
53    /// The device's Connection Signature Resolving Key.
54    #[serde(
55        default,
56        skip_serializing_if = "Option::is_none",
57        with = "hex_u128_opt"
58    )]
59    pub csrk: Option<u128>,
60    /// The pairing had MITM protection.
61    #[serde(default)]
62    pub authenticated: bool,
63    /// The pairing used Secure Connections.
64    #[serde(default)]
65    pub secure_connections: bool,
66    /// Its GATT client configuration on our server: (value handle, bits).
67    #[serde(default, skip_serializing_if = "Vec::is_empty")]
68    pub cccd: Vec<(u16, u16)>,
69    /// A label, for IRKs entered by hand (tags whose IRK is known without pairing).
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub label: Option<String>,
72    /// Other (non-resolvable) addresses the device paired from: some
73    /// devices distribute a public identity but connect from a static random
74    /// address.
75    #[serde(default, skip_serializing_if = "Vec::is_empty")]
76    pub aliases: Vec<Address>,
77}
78
79impl Bond {
80    /// A bond with nothing in it yet.
81    pub fn new(identity: Address) -> Self {
82        Bond {
83            identity,
84            ltk: None,
85            local_ltk: None,
86            irk: None,
87            csrk: None,
88            authenticated: false,
89            secure_connections: false,
90            cccd: Vec::new(),
91            label: None,
92            aliases: Vec::new(),
93        }
94    }
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize)]
98struct Identity {
99    #[serde(with = "hex_u128")]
100    irk: u128,
101    address: Address,
102}
103
104/// Bonds and our identity.
105pub struct Keys {
106    dir: Option<PathBuf>,
107    identity: Identity,
108    bonds: Mutex<Vec<Bond>>,
109    cache: Mutex<HashMap<[u8; 6], Option<Address>>>,
110}
111
112/// Resolved (and unresolvable) private addresses remembered, so a busy site
113/// does not run AES for every advertisement.
114const CACHE_LIMIT: usize = 4096;
115
116impl Keys {
117    /// Opens (or creates) the key files in `dir`; `None` keeps everything in memory.
118    pub fn open(dir: Option<&Path>) -> Result<Keys> {
119        let identity = match dir.map(|d| d.join("identity.json")) {
120            Some(p) if p.exists() => serde_json::from_slice(&fs::read(&p)?)
121                .map_err(|e| crate::Error::Protocol(format!("{}: {e}", p.display())))?,
122            _ => {
123                let id = Identity {
124                    irk: crypto::random_u128(),
125                    address: Address::new_static_random(),
126                };
127                if let Some(d) = dir {
128                    fs::create_dir_all(d)?;
129                    write_private(
130                        &d.join("identity.json"),
131                        &serde_json::to_vec_pretty(&id).unwrap_or_default(),
132                    )?;
133                }
134                id
135            }
136        };
137        let bonds = match dir.map(|d| d.join("bonds.json")) {
138            Some(p) if p.exists() => serde_json::from_slice(&fs::read(&p)?)
139                .map_err(|e| crate::Error::Protocol(format!("{}: {e}", p.display())))?,
140            _ => Vec::new(),
141        };
142        Ok(Keys {
143            dir: dir.map(Path::to_path_buf),
144            identity,
145            bonds: Mutex::new(bonds),
146            cache: Mutex::new(HashMap::new()),
147        })
148    }
149
150    /// Our static random address (used when the controller has no public one).
151    pub fn local_static_address(&self) -> Address {
152        self.identity.address
153    }
154
155    /// Our Identity Resolving Key, distributed when pairing.
156    pub fn local_irk(&self) -> u128 {
157        self.identity.irk
158    }
159
160    /// Every bond.
161    pub fn bonds(&self) -> Vec<Bond> {
162        self.bonds.lock().unwrap_or_else(|e| e.into_inner()).clone()
163    }
164
165    /// The bond with a device, by identity address.
166    pub fn bond(&self, identity: &Address) -> Option<Bond> {
167        self.bonds
168            .lock()
169            .unwrap_or_else(|e| e.into_inner())
170            .iter()
171            .find(|b| b.identity == *identity)
172            .cloned()
173    }
174
175    /// Stores (or replaces) a bond.
176    pub fn store(&self, bond: Bond) -> Result<()> {
177        let mut b = self.bonds.lock().unwrap_or_else(|e| e.into_inner());
178        b.retain(|x| x.identity != bond.identity);
179        b.push(bond);
180        self.cache.lock().unwrap_or_else(|e| e.into_inner()).clear();
181        self.save(&b)
182    }
183
184    /// Updates a bond in place, if there is one.
185    pub fn update(&self, identity: &Address, f: impl FnOnce(&mut Bond)) -> Result<bool> {
186        let mut b = self.bonds.lock().unwrap_or_else(|e| e.into_inner());
187        let Some(x) = b.iter_mut().find(|x| x.identity == *identity) else {
188            return Ok(false);
189        };
190        f(x);
191        self.save(&b)?;
192        Ok(true)
193    }
194
195    /// Forgets a device. Returns whether there was a bond.
196    pub fn remove(&self, identity: &Address) -> Result<bool> {
197        let mut b = self.bonds.lock().unwrap_or_else(|e| e.into_inner());
198        let before = b.len();
199        b.retain(|x| x.identity != *identity);
200        self.cache.lock().unwrap_or_else(|e| e.into_inner()).clear();
201        let removed = b.len() != before;
202        self.save(&b)?;
203        Ok(removed)
204    }
205
206    /// Records an IRK known without pairing (some tags print theirs), so the
207    /// device's private addresses resolve to `identity`.
208    pub fn add_irk(&self, identity: Address, irk: u128, label: Option<String>) -> Result<()> {
209        let mut bond = self.bond(&identity).unwrap_or_else(|| Bond::new(identity));
210        bond.irk = Some(irk);
211        if label.is_some() {
212            bond.label = label;
213        }
214        self.store(bond)
215    }
216
217    /// The identity a device uses this address for: resolved from an IRK
218    /// for a private address, or a bond's identity or alias.
219    pub fn identity_of(&self, addr: &Address) -> Option<Address> {
220        if addr.is_resolvable() {
221            return self.resolve(addr);
222        }
223        self.bonds
224            .lock()
225            .unwrap_or_else(|e| e.into_inner())
226            .iter()
227            .find(|b| b.identity == *addr || b.aliases.contains(addr))
228            .map(|b| b.identity)
229    }
230
231    /// The identity behind a resolvable private address, from the stored IRKs.
232    pub fn resolve(&self, addr: &Address) -> Option<Address> {
233        if !addr.is_resolvable() {
234            return None;
235        }
236        if let Some(hit) = self
237            .cache
238            .lock()
239            .unwrap_or_else(|e| e.into_inner())
240            .get(&addr.bytes)
241        {
242            return *hit;
243        }
244        let found = self
245            .bonds
246            .lock()
247            .unwrap_or_else(|e| e.into_inner())
248            .iter()
249            .find(|b| b.irk.is_some_and(|irk| crypto::resolves(irk, &addr.bytes)))
250            .map(|b| b.identity);
251        let mut c = self.cache.lock().unwrap_or_else(|e| e.into_inner());
252        if c.len() >= CACHE_LIMIT {
253            c.clear();
254        }
255        c.insert(addr.bytes, found);
256        found
257    }
258
259    /// The bond whose local (legacy) LTK has this EDIV and Rand.
260    pub(crate) fn by_ediv_rand(&self, ediv: u16, rand: u64) -> Option<Bond> {
261        self.bonds
262            .lock()
263            .unwrap_or_else(|e| e.into_inner())
264            .iter()
265            .find(|b| {
266                b.local_ltk
267                    .is_some_and(|k| k.ediv == ediv && k.rand == rand)
268            })
269            .cloned()
270    }
271
272    fn save(&self, bonds: &[Bond]) -> Result<()> {
273        if let Some(d) = &self.dir {
274            write_private(
275                &d.join("bonds.json"),
276                &serde_json::to_vec_pretty(bonds).unwrap_or_default(),
277            )?;
278        }
279        Ok(())
280    }
281}
282
283/// Writes a file readable only by its owner, atomically.
284fn write_private(path: &Path, data: &[u8]) -> std::io::Result<()> {
285    let tmp = path.with_extension("tmp");
286    let mut o = fs::OpenOptions::new();
287    o.write(true).create(true).truncate(true);
288    #[cfg(unix)]
289    {
290        use std::os::unix::fs::OpenOptionsExt;
291        o.mode(0o600);
292    }
293    let mut f = o.open(&tmp)?;
294    f.write_all(data)?;
295    f.sync_all()?;
296    drop(f);
297    fs::rename(&tmp, path)
298}
299
300mod hex_u128 {
301    pub fn serialize<S: serde::Serializer>(v: &u128, s: S) -> Result<S::Ok, S::Error> {
302        s.serialize_str(&format!("{v:032x}"))
303    }
304    pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result<u128, D::Error> {
305        let s = <String as serde::Deserialize>::deserialize(d)?;
306        u128::from_str_radix(s.trim(), 16).map_err(serde::de::Error::custom)
307    }
308}
309
310mod hex_u128_opt {
311    pub fn serialize<S: serde::Serializer>(v: &Option<u128>, s: S) -> Result<S::Ok, S::Error> {
312        match v {
313            Some(v) => s.serialize_str(&format!("{v:032x}")),
314            None => s.serialize_none(),
315        }
316    }
317    pub fn deserialize<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u128>, D::Error> {
318        let s = <Option<String> as serde::Deserialize>::deserialize(d)?;
319        s.map(|s| u128::from_str_radix(s.trim(), 16).map_err(serde::de::Error::custom))
320            .transpose()
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    #[test]
329    fn persists_and_resolves() {
330        let dir = tempfile::tempdir().unwrap();
331        let k = Keys::open(Some(dir.path())).unwrap();
332        let me = k.local_static_address();
333        let irk = 0x1234_5678_9abc_def0_1122_3344_5566_7788u128;
334        let id: Address = "11:22:33:44:55:66".parse().unwrap();
335        k.add_irk(id, irk, Some("tag".into())).unwrap();
336        let rpa = Address::random(crypto::new_rpa(irk));
337        assert_eq!(k.resolve(&rpa), Some(id));
338        assert_eq!(k.resolve(&Address::random(crypto::new_rpa(irk ^ 1))), None);
339
340        let k2 = Keys::open(Some(dir.path())).unwrap();
341        assert_eq!(k2.local_static_address(), me);
342        assert_eq!(k2.bond(&id).unwrap().irk, Some(irk));
343        assert!(k2.remove(&id).unwrap());
344        assert!(Keys::open(Some(dir.path())).unwrap().bonds().is_empty());
345        #[cfg(unix)]
346        {
347            use std::os::unix::fs::PermissionsExt;
348            let mode = fs::metadata(dir.path().join("bonds.json"))
349                .unwrap()
350                .permissions()
351                .mode();
352            assert_eq!(mode & 0o777, 0o600);
353        }
354    }
355}