1use crate::crypto::{aes128_ecb, aes128_ofb, cbc_mac};
9use crate::{random_bytes, Error, NetworkKey};
10use std::collections::HashMap;
11use std::time::{Duration, Instant};
12
13pub const CC_SECURITY: u8 = 0x98;
15
16pub mod cmd {
18 pub const COMMANDS_SUPPORTED_GET: u8 = 0x02;
20 pub const COMMANDS_SUPPORTED_REPORT: u8 = 0x03;
22 pub const SCHEME_GET: u8 = 0x04;
24 pub const SCHEME_REPORT: u8 = 0x05;
26 pub const NETWORK_KEY_SET: u8 = 0x06;
28 pub const NETWORK_KEY_VERIFY: u8 = 0x07;
30 pub const SCHEME_INHERIT: u8 = 0x08;
32 pub const NONCE_GET: u8 = 0x40;
34 pub const NONCE_REPORT: u8 = 0x80;
36 pub const MESSAGE_ENCAPSULATION: u8 = 0x81;
38 pub const MESSAGE_ENCAPSULATION_NONCE_GET: u8 = 0xc1;
40}
41
42pub const NONCE_LIFETIME: Duration = Duration::from_secs(10);
44pub const MAX_OWN_NONCES: usize = 64;
46pub const MAX_PAYLOAD: usize = 26;
48
49#[derive(Clone, zeroize::Zeroize, zeroize::ZeroizeOnDrop)]
51struct Keys {
52 auth: [u8; 16],
53 enc: [u8; 16],
54}
55
56impl Keys {
57 fn new(network_key: &NetworkKey) -> Self {
58 Keys {
59 auth: aes128_ecb(network_key, &[0x55; 16]),
60 enc: aes128_ecb(network_key, &[0xaa; 16]),
61 }
62 }
63}
64
65pub const TEMP_KEY: NetworkKey = [0; 16];
67
68#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum S0Payload {
71 Complete(Vec<u8>),
73 FirstHalf,
75}
76
77pub struct S0Manager {
79 own_node: u16,
80 keys: Keys,
81 temp: Keys,
82 own_nonces: HashMap<u8, ([u8; 8], u16, Instant)>,
83 peer_nonces: HashMap<u16, ([u8; 8], Instant)>,
84 halves: HashMap<(u16, u8), (Vec<u8>, Instant)>,
85 seq: u8,
86}
87
88impl std::fmt::Debug for S0Manager {
89 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90 f.debug_struct("S0Manager")
91 .field("own_node", &self.own_node)
92 .finish()
93 }
94}
95
96fn frame_control(sequenced: bool, second: bool, counter: u8) -> u8 {
98 (if sequenced { 0x10 } else { 0 }) | (if second { 0x20 } else { 0 }) | (counter & 0x0f)
99}
100
101impl S0Manager {
102 pub fn new(own_node: u16, network_key: &NetworkKey) -> Self {
104 S0Manager {
105 own_node,
106 keys: Keys::new(network_key),
107 temp: Keys::new(&TEMP_KEY),
108 own_nonces: HashMap::new(),
109 peer_nonces: HashMap::new(),
110 halves: HashMap::new(),
111 seq: 0,
112 }
113 }
114
115 pub fn set_own_node(&mut self, own_node: u16) {
117 self.own_node = own_node;
118 }
119
120 pub fn set_network_key(&mut self, key: &NetworkKey) {
122 self.keys = Keys::new(key);
123 }
124
125 fn expire(&mut self, now: Instant) {
126 self.own_nonces
127 .retain(|_, (_, _, t)| now.duration_since(*t) < NONCE_LIFETIME);
128 self.peer_nonces
129 .retain(|_, (_, t)| now.duration_since(*t) < NONCE_LIFETIME);
130 self.halves
131 .retain(|_, (_, t)| now.duration_since(*t) < NONCE_LIFETIME);
132 }
133
134 pub fn nonce_get() -> Vec<u8> {
136 vec![CC_SECURITY, cmd::NONCE_GET]
137 }
138
139 pub fn nonce_report(&mut self, peer: u16) -> Result<Vec<u8>, Error> {
141 let now = Instant::now();
142 self.expire(now);
143 if self.own_nonces.len() >= MAX_OWN_NONCES {
144 if let Some(oldest) = self
146 .own_nonces
147 .iter()
148 .min_by_key(|(_, (_, _, t))| *t)
149 .map(|(k, _)| *k)
150 {
151 self.own_nonces.remove(&oldest);
152 }
153 }
154 let nonce = loop {
155 let n = random_bytes::<8>()?;
156 if !self.own_nonces.contains_key(&n[0]) {
158 break n;
159 }
160 };
161 self.own_nonces.insert(nonce[0], (nonce, peer, now));
162 let mut v = vec![CC_SECURITY, cmd::NONCE_REPORT];
163 v.extend_from_slice(&nonce);
164 Ok(v)
165 }
166
167 pub fn handle_nonce_report(&mut self, peer: u16, frame: &[u8]) -> Result<(), Error> {
169 if frame.len() != 10 || frame[0] != CC_SECURITY || frame[1] != cmd::NONCE_REPORT {
170 return Err(Error::Malformed("not an S0 nonce report"));
171 }
172 let n: [u8; 8] = frame[2..10].try_into().expect("8 bytes");
173 self.peer_nonces.insert(peer, (n, Instant::now()));
174 Ok(())
175 }
176
177 pub fn has_peer_nonce(&self, peer: u16) -> bool {
179 self.peer_nonces
180 .get(&peer)
181 .is_some_and(|(_, t)| t.elapsed() < NONCE_LIFETIME)
182 }
183
184 pub fn encapsulate(
190 &mut self,
191 peer: u16,
192 command: &[u8],
193 temp_key: bool,
194 ) -> Result<Vec<u8>, Error> {
195 if command.len() > MAX_PAYLOAD {
196 return Err(Error::Malformed("S0 command too long for one frame"));
197 }
198 self.encapsulate_part(
199 peer,
200 command,
201 frame_control(false, false, 0),
202 temp_key,
203 false,
204 )
205 }
206
207 pub fn split(&mut self, command: &[u8]) -> Option<[(Vec<u8>, u8); 2]> {
209 if command.len() <= MAX_PAYLOAD || command.len() > 2 * MAX_PAYLOAD {
210 return None;
211 }
212 self.seq = (self.seq + 1) & 0x0f;
213 let (a, b) = command.split_at(MAX_PAYLOAD);
214 Some([
215 (a.to_vec(), frame_control(true, false, self.seq)),
216 (b.to_vec(), frame_control(true, true, self.seq)),
217 ])
218 }
219
220 pub fn encapsulate_part(
223 &mut self,
224 peer: u16,
225 part: &[u8],
226 control: u8,
227 temp_key: bool,
228 nonce_get: bool,
229 ) -> Result<Vec<u8>, Error> {
230 let now = Instant::now();
231 self.expire(now);
232 let (receiver_nonce, _) = self.peer_nonces.remove(&peer).ok_or(Error::NoNonce)?;
233 let sender_nonce = random_bytes::<8>()?;
234 let keys = if temp_key { &self.temp } else { &self.keys };
235 let mut iv = [0u8; 16];
236 iv[..8].copy_from_slice(&sender_nonce);
237 iv[8..].copy_from_slice(&receiver_nonce);
238 let mut plain = Vec::with_capacity(part.len() + 1);
239 plain.push(control);
240 plain.extend_from_slice(part);
241 let ct = aes128_ofb(&keys.enc, &iv, &plain);
242 let command = if nonce_get {
243 cmd::MESSAGE_ENCAPSULATION_NONCE_GET
244 } else {
245 cmd::MESSAGE_ENCAPSULATION
246 };
247 let mac = Self::mac(&keys.auth, &iv, command, self.own_node, peer, &ct);
248 let mut out = Vec::with_capacity(2 + 8 + ct.len() + 9);
249 out.extend_from_slice(&[CC_SECURITY, command]);
250 out.extend_from_slice(&sender_nonce);
251 out.extend_from_slice(&ct);
252 out.push(receiver_nonce[0]);
253 out.extend_from_slice(&mac);
254 Ok(out)
255 }
256
257 fn mac(
258 auth: &[u8; 16],
259 iv: &[u8; 16],
260 command: u8,
261 sender: u16,
262 receiver: u16,
263 ct: &[u8],
264 ) -> [u8; 8] {
265 let mut data = Vec::with_capacity(20 + ct.len());
266 data.extend_from_slice(iv);
267 data.extend_from_slice(&[command, sender as u8, receiver as u8, ct.len() as u8]);
268 data.extend_from_slice(ct);
269 let full = cbc_mac(auth, &data);
270 full[..8].try_into().expect("8 bytes")
271 }
272
273 pub fn decapsulate(
278 &mut self,
279 peer: u16,
280 frame: &[u8],
281 temp_key: bool,
282 ) -> Result<S0Payload, Error> {
283 if frame.len() < 2 + 8 + 1 + 1 + 8
284 || frame[0] != CC_SECURITY
285 || !matches!(
286 frame[1],
287 cmd::MESSAGE_ENCAPSULATION | cmd::MESSAGE_ENCAPSULATION_NONCE_GET
288 )
289 {
290 return Err(Error::Malformed("not an S0 encapsulation"));
291 }
292 let now = Instant::now();
293 self.expire(now);
294 let sender_nonce = &frame[2..10];
295 let ct = &frame[10..frame.len() - 9];
296 let nonce_id = frame[frame.len() - 9];
297 let mac = &frame[frame.len() - 8..];
298 let (receiver_nonce, issued_to, _) =
299 self.own_nonces.remove(&nonce_id).ok_or(Error::NoNonce)?;
300 if issued_to != peer {
301 return Err(Error::NoNonce);
302 }
303 let keys = if temp_key { &self.temp } else { &self.keys };
304 let mut iv = [0u8; 16];
305 iv[..8].copy_from_slice(sender_nonce);
306 iv[8..].copy_from_slice(&receiver_nonce);
307 let want = Self::mac(&keys.auth, &iv, frame[1], peer, self.own_node, ct);
308 if want.as_slice() != mac {
309 return Err(Error::DecryptFailed);
310 }
311 let plain = aes128_ofb(&keys.enc, &iv, ct);
312 let control = plain[0];
313 let body = plain[1..].to_vec();
314 let sequenced = control & 0x10 != 0;
315 let second = control & 0x20 != 0;
316 let counter = control & 0x0f;
317 if !sequenced {
318 return Ok(S0Payload::Complete(body));
319 }
320 if !second {
321 self.halves.insert((peer, counter), (body, now));
322 return Ok(S0Payload::FirstHalf);
323 }
324 let (mut first, _) = self
325 .halves
326 .remove(&(peer, counter))
327 .ok_or(Error::Malformed("S0 second half without first"))?;
328 first.extend_from_slice(&body);
329 Ok(S0Payload::Complete(first))
330 }
331}
332
333#[cfg(test)]
334mod tests {
335 use super::*;
336
337 #[test]
338 fn roundtrip() {
339 let key = [7u8; 16];
340 let mut c = S0Manager::new(1, &key);
341 let mut n = S0Manager::new(9, &key);
342 assert_eq!(c.encapsulate(9, &[0x25, 0x02], false), Err(Error::NoNonce));
343 let report = n.nonce_report(1).unwrap();
344 c.handle_nonce_report(9, &report).unwrap();
345 let f = c.encapsulate(9, &[0x25, 0x01, 0xff], false).unwrap();
346 assert_eq!(
347 n.decapsulate(1, &f, false).unwrap(),
348 S0Payload::Complete(vec![0x25, 0x01, 0xff])
349 );
350 assert_eq!(n.decapsulate(1, &f, false), Err(Error::NoNonce));
352 }
353
354 #[test]
355 fn mac_and_key_are_checked() {
356 let mut c = S0Manager::new(1, &[7; 16]);
357 let mut n = S0Manager::new(9, &[8; 16]);
358 let r = n.nonce_report(1).unwrap();
359 c.handle_nonce_report(9, &r).unwrap();
360 let f = c.encapsulate(9, &[0x25, 0x02], false).unwrap();
361 assert_eq!(n.decapsulate(1, &f, false), Err(Error::DecryptFailed));
362 let r = n.nonce_report(1).unwrap();
364 c.handle_nonce_report(9, &r).unwrap();
365 let mut set = vec![CC_SECURITY, cmd::NETWORK_KEY_SET];
366 set.extend_from_slice(&[7; 16]);
367 let f = c.encapsulate(9, &set, true).unwrap();
368 assert_eq!(
369 n.decapsulate(1, &f, true).unwrap(),
370 S0Payload::Complete(set)
371 );
372 }
373
374 #[test]
375 fn nonce_from_another_peer_is_refused() {
376 let key = [7u8; 16];
377 let mut c = S0Manager::new(1, &key);
378 let mut n = S0Manager::new(9, &key);
379 let r = n.nonce_report(2).unwrap();
380 c.handle_nonce_report(9, &r).unwrap();
381 let f = c.encapsulate(9, &[0x20, 0x02], false).unwrap();
382 assert_eq!(n.decapsulate(1, &f, false), Err(Error::NoNonce));
383 }
384
385 #[test]
386 fn two_part_commands() {
387 let key = [7u8; 16];
388 let mut c = S0Manager::new(1, &key);
389 let mut n = S0Manager::new(9, &key);
390 let long: Vec<u8> = (0..40).collect();
391 let parts = c.split(&long).unwrap();
392 for (i, (part, control)) in parts.iter().enumerate() {
393 let r = n.nonce_report(1).unwrap();
394 c.handle_nonce_report(9, &r).unwrap();
395 let f = c
396 .encapsulate_part(9, part, *control, false, i == 0)
397 .unwrap();
398 let out = n.decapsulate(1, &f, false).unwrap();
399 if i == 0 {
400 assert_eq!(out, S0Payload::FirstHalf);
401 } else {
402 assert_eq!(out, S0Payload::Complete(long.clone()));
403 }
404 }
405 }
406
407 #[test]
408 fn nonce_table_is_bounded() {
409 let mut n = S0Manager::new(9, &[0; 16]);
410 for _ in 0..500 {
411 n.nonce_report(1).unwrap();
412 }
413 assert!(n.own_nonces.len() <= MAX_OWN_NONCES);
414 }
415}