Skip to main content

weirdnet_push/
wake.rs

1//! Wake payloads: fixed-size ciphertexts sealed to one device's push key.
2//!
3//! ```text
4//! payload    = 0x01 ‖ E (32) ‖ ChaCha20-Poly1305(key, nonce 0, plaintext (47), aad) (63)   = 96 bytes
5//! key        = HKDF-SHA256(ikm = X25519(e, D), salt = E ‖ D, info = "weirdnet-push/wake/v1")
6//! aad        = "weirdnet-push/wake/v1" ‖ handle
7//! plaintext  = reason (1) ‖ random (16) ‖ unix seconds (8, big-endian) ‖ zeros (22)
8//! ```
9//!
10//! `E` is a fresh X25519 key per payload, so the key is never reused and a zero nonce is
11//! safe. The payload holds only a reason code, a random value and a time: no content, sender,
12//! peer id, address or site name. Everything a push provider, the push service or a relay
13//! sees is the handle (or device token), the time, and these 96 bytes.
14
15use crate::error::{Error, Result};
16use crate::handle::WakeHandle;
17use chacha20poly1305::aead::{Aead, KeyInit, Payload};
18use chacha20poly1305::{ChaCha20Poly1305, Nonce};
19use std::collections::VecDeque;
20use std::time::{Duration, SystemTime, UNIX_EPOCH};
21use weirdnet_keys::exchange::ExchangeSecret;
22use zeroize::Zeroizing;
23
24/// The payload size in bytes.
25pub const PAYLOAD_LEN: usize = 96;
26const VERSION: u8 = 1;
27const INFO: &[u8] = b"weirdnet-push/wake/v1";
28const PLAIN_LEN: usize = 47;
29
30/// Why a device is woken.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32pub enum Reason {
33    /// Sealed messages are waiting on the home relay or a desktop.
34    MessageWaiting,
35    /// A peer asks the device to connect.
36    ConnectionRequested,
37    /// A code this version doesn't know (newer senders).
38    Other(u8),
39}
40
41impl Reason {
42    /// The wire code.
43    pub fn code(self) -> u8 {
44        match self {
45            Reason::MessageWaiting => 1,
46            Reason::ConnectionRequested => 2,
47            Reason::Other(c) => c,
48        }
49    }
50
51    /// From the wire code.
52    pub fn from_code(c: u8) -> Self {
53        match c {
54            1 => Reason::MessageWaiting,
55            2 => Reason::ConnectionRequested,
56            c => Reason::Other(c),
57        }
58    }
59}
60
61/// An opened wake.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub struct Wake {
64    /// Why.
65    pub reason: Reason,
66    /// The sender's random value (for replay checks).
67    pub nonce: [u8; 16],
68    /// When it was sealed (unix seconds, the sender's clock).
69    pub at: u64,
70}
71
72/// A fixed-size wake payload.
73#[derive(Clone, Copy, PartialEq, Eq)]
74pub struct Payload96(pub [u8; PAYLOAD_LEN]);
75
76impl std::fmt::Debug for Payload96 {
77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78        write!(f, "Payload96({}…)", hex::encode(&self.0[..6]))
79    }
80}
81
82impl Payload96 {
83    /// From bytes; they must be exactly [`PAYLOAD_LEN`] long.
84    pub fn from_slice(b: &[u8]) -> Result<Self> {
85        let a: [u8; PAYLOAD_LEN] = b.try_into().map_err(|_| Error::BadPayload)?;
86        if a[0] != VERSION {
87            return Err(Error::BadPayload);
88        }
89        Ok(Self(a))
90    }
91
92    /// Base64url without padding (128 characters), as carried in JSON and push messages.
93    pub fn to_b64(&self) -> String {
94        use base64::Engine;
95        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(self.0)
96    }
97
98    /// From [`Payload96::to_b64`].
99    pub fn from_b64(s: &str) -> Result<Self> {
100        use base64::Engine;
101        let b = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(s).map_err(|_| Error::BadPayload)?;
102        Self::from_slice(&b)
103    }
104}
105
106impl serde::Serialize for Payload96 {
107    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
108        s.serialize_str(&self.to_b64())
109    }
110}
111
112impl<'de> serde::Deserialize<'de> for Payload96 {
113    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
114        let s = String::deserialize(d)?;
115        Payload96::from_b64(&s).map_err(serde::de::Error::custom)
116    }
117}
118
119fn key(shared: &[u8; 32], e: &[u8; 32], d: &[u8; 32]) -> Result<Zeroizing<[u8; 32]>> {
120    let mut k = Zeroizing::new([0u8; 32]);
121    weirdnet_keys::kdf::hkdf_expand(shared, Some(&[&e[..], &d[..]].concat()), INFO, &mut k[..])?;
122    Ok(k)
123}
124
125fn aad(handle: &WakeHandle) -> Vec<u8> {
126    [INFO, handle.as_str().as_bytes()].concat()
127}
128
129fn now() -> u64 {
130    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
131}
132
133/// Seals a wake for the device whose push public key is `device` and whose handle is
134/// `handle`.
135pub fn seal(device: &[u8; 32], handle: &WakeHandle, reason: Reason) -> Result<Payload96> {
136    seal_at(device, handle, reason, now())
137}
138
139/// [`seal`] with a given time (tests).
140pub fn seal_at(device: &[u8; 32], handle: &WakeHandle, reason: Reason, at: u64) -> Result<Payload96> {
141    let e = ExchangeSecret::generate();
142    let epub = e.public();
143    let shared = e.agree(device).ok_or(Error::BadPayload)?;
144    let k = key(&shared, &epub, device)?;
145    let mut plain = Zeroizing::new([0u8; PLAIN_LEN]);
146    plain[0] = reason.code();
147    plain[1..17].copy_from_slice(&weirdnet_keys::random_bytes::<16>()?);
148    plain[17..25].copy_from_slice(&at.to_be_bytes());
149    let ct = ChaCha20Poly1305::new((&*k).into())
150        .encrypt(&Nonce::default(), Payload { msg: &plain[..], aad: &aad(handle) })
151        .map_err(|_| Error::BadPayload)?;
152    let mut out = [0u8; PAYLOAD_LEN];
153    out[0] = VERSION;
154    out[1..33].copy_from_slice(&epub);
155    out[33..].copy_from_slice(&ct);
156    Ok(Payload96(out))
157}
158
159/// A device's push key (X25519). Keep the secret on the device; give the public key to the
160/// home relay and trusted peers with the handle.
161pub struct PushKey(ExchangeSecret);
162
163impl std::fmt::Debug for PushKey {
164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165        f.write_str("PushKey(<redacted>)")
166    }
167}
168
169impl PushKey {
170    /// A new key.
171    pub fn generate() -> Self {
172        Self(ExchangeSecret::generate())
173    }
174
175    /// From stored secret bytes.
176    pub fn from_bytes(b: [u8; 32]) -> Self {
177        Self(ExchangeSecret::from_bytes(b))
178    }
179
180    /// The secret bytes, to store.
181    pub fn to_bytes(&self) -> Zeroizing<[u8; 32]> {
182        self.0.to_bytes()
183    }
184
185    /// The public key.
186    pub fn public(&self) -> [u8; 32] {
187        self.0.public()
188    }
189
190    /// Opens a payload sent to `handle`.
191    pub fn open(&self, handle: &WakeHandle, p: &Payload96) -> Result<Wake> {
192        let mut epub = [0u8; 32];
193        epub.copy_from_slice(&p.0[1..33]);
194        let shared = self.0.agree(&epub).ok_or(Error::BadPayload)?;
195        let k = key(&shared, &epub, &self.public())?;
196        let plain = Zeroizing::new(
197            ChaCha20Poly1305::new((&*k).into())
198                .decrypt(&Nonce::default(), Payload { msg: &p.0[33..], aad: &aad(handle) })
199                .map_err(|_| Error::BadPayload)?,
200        );
201        if plain.len() != PLAIN_LEN || plain[25..].iter().any(|&b| b != 0) {
202            return Err(Error::BadPayload);
203        }
204        let mut nonce = [0u8; 16];
205        nonce.copy_from_slice(&plain[1..17]);
206        Ok(Wake { reason: Reason::from_code(plain[0]), nonce, at: u64::from_be_bytes(plain[17..25].try_into().unwrap()) })
207    }
208}
209
210/// Refuses wakes seen before, older than `window`, or more than `window` ahead.
211#[derive(Debug)]
212pub struct ReplayGuard {
213    window: Duration,
214    seen: VecDeque<(u64, [u8; 16])>,
215    max: usize,
216}
217
218impl ReplayGuard {
219    /// A guard with a window (10 minutes is a good default) remembering up to `max` wakes.
220    pub fn new(window: Duration, max: usize) -> Self {
221        Self { window, seen: VecDeque::new(), max: max.max(1) }
222    }
223
224    /// Checks and remembers a wake at the device's time `now` (unix seconds).
225    pub fn check(&mut self, w: &Wake, now: u64) -> Result<()> {
226        let win = self.window.as_secs();
227        if w.at + win < now || w.at > now + win {
228            return Err(Error::Replay);
229        }
230        while self.seen.front().is_some_and(|(t, _)| t + win < now) {
231            self.seen.pop_front();
232        }
233        if self.seen.iter().any(|(_, n)| n == &w.nonce) {
234            return Err(Error::Replay);
235        }
236        if self.seen.len() >= self.max {
237            self.seen.pop_front();
238        }
239        self.seen.push_back((w.at, w.nonce));
240        Ok(())
241    }
242
243    /// [`ReplayGuard::check`] with the system clock.
244    pub fn check_now(&mut self, w: &Wake) -> Result<()> {
245        self.check(w, now())
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252
253    #[test]
254    fn seal_open_fixed_size_and_bound_to_handle_and_key() {
255        let k = PushKey::generate();
256        let h = WakeHandle::generate();
257        let p = seal(&k.public(), &h, Reason::MessageWaiting).unwrap();
258        assert_eq!(p.0.len(), PAYLOAD_LEN);
259        assert_eq!(p.to_b64().len(), 128);
260        let w = k.open(&h, &p).unwrap();
261        assert_eq!(w.reason, Reason::MessageWaiting);
262        // Two payloads for the same wake differ entirely after the version byte.
263        let q = seal(&k.public(), &h, Reason::MessageWaiting).unwrap();
264        assert_ne!(p.0[1..], q.0[1..]);
265        assert!(matches!(k.open(&WakeHandle::generate(), &p), Err(Error::BadPayload)));
266        assert!(matches!(PushKey::generate().open(&h, &p), Err(Error::BadPayload)));
267        for i in [0usize, 1, 40, 95] {
268            let mut bad = p;
269            bad.0[i] ^= 1;
270            let r = Payload96::from_slice(&bad.0).and_then(|b| k.open(&h, &b));
271            assert!(r.is_err(), "byte {i}");
272        }
273        assert!(Payload96::from_slice(&p.0[..95]).is_err());
274        assert_eq!(Payload96::from_b64(&p.to_b64()).unwrap(), p);
275        let json = serde_json::to_string(&p).unwrap();
276        assert_eq!(serde_json::from_str::<Payload96>(&json).unwrap(), p);
277        assert_eq!(Reason::from_code(Reason::ConnectionRequested.code()), Reason::ConnectionRequested);
278        assert_eq!(Reason::from_code(9), Reason::Other(9));
279    }
280
281    #[test]
282    fn replays_and_stale_wakes_are_refused() {
283        let k = PushKey::generate();
284        let h = WakeHandle::generate();
285        let mut g = ReplayGuard::new(Duration::from_secs(600), 100);
286        let p = seal_at(&k.public(), &h, Reason::ConnectionRequested, 10_000).unwrap();
287        let w = k.open(&h, &p).unwrap();
288        assert_eq!(w.at, 10_000);
289        g.check(&w, 10_010).unwrap();
290        assert!(matches!(g.check(&w, 10_011), Err(Error::Replay)));
291        let old = k.open(&h, &seal_at(&k.public(), &h, Reason::MessageWaiting, 9_000).unwrap()).unwrap();
292        assert!(matches!(g.check(&old, 10_010), Err(Error::Replay)));
293        let ahead = k.open(&h, &seal_at(&k.public(), &h, Reason::MessageWaiting, 11_000).unwrap()).unwrap();
294        assert!(matches!(g.check(&ahead, 10_010), Err(Error::Replay)));
295    }
296}