Skip to main content

weirdnet_net/
exchange.rs

1//! Key exchanges: authenticated X25519 Diffie-Hellman between two node identities, and the
2//! invitation tokens and links that carry them.
3//!
4//! The offerer signs an *offer* (its node key, a fresh X25519 public key, where to reach it,
5//! the scope and an expiry) with its Ed25519 node identity. The answerer checks the
6//! signature, signs an *answer* bound to the offer's hash with its own fresh X25519 key,
7//! and both compute the same secret:
8//!
9//! ```text
10//! transcript = SHA-256(TRANSCRIPT ‖ OFFER ‖ 0 ‖ offer ‖ ANSWER ‖ 0 ‖ answer)   (both signed)
11//! key        = HKDF-SHA256(ikm = X25519(a, B), salt = transcript, info = KEY)
12//! short code = HKDF(..., info = SAS) as ten digits, 12345-67890
13//! ```
14//!
15//! The labels come from the [`Profile`]; the agreement and the derivations are done by
16//! `weirdnet-keys`. Both people compare the short code (or the fingerprint) out of band to
17//! rule out a man in the middle. Tokens are the profile's prefix and base64url JSON, safe
18//! to paste anywhere: they hold only public keys and signatures.
19use crate::error::{NetError, Result};
20use crate::profile::Profile;
21use base64::Engine;
22use libp2p::PeerId;
23use libp2p::identity::{Keypair, PublicKey};
24use serde::{Deserialize, Serialize};
25use sha2::Digest;
26use weirdnet_keys::exchange::{self as kx, ExchangeSecret};
27use weirdnet_keys::{Key32, Sealed};
28use zeroize::Zeroizing;
29
30/// Offers are good for a week unless asked otherwise (never less than a minute).
31pub const DEFAULT_TTL_MS: i64 = 7 * 24 * 3600 * 1000;
32const MIN_TTL_MS: i64 = 60_000;
33
34/// A signed offer (an invitation to exchange keys).
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
36pub struct Offer {
37    pub v: u8,
38    /// The exchange id (the same on both sides).
39    pub id: String,
40    pub peer: String,
41    /// The offerer's node public key (protobuf, base64url).
42    pub key: String,
43    /// Its fresh X25519 public key (hex).
44    pub eph: String,
45    pub addrs: Vec<String>,
46    pub label: String,
47    pub scope: serde_json::Value,
48    pub created: i64,
49    pub expires: i64,
50    #[serde(default)]
51    pub sig: String,
52}
53
54/// A signed answer to an offer.
55#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
56pub struct Answer {
57    pub v: u8,
58    /// The offer's exchange id.
59    pub offer: String,
60    /// SHA-256 of the signed offer (hex).
61    pub offer_hash: String,
62    pub peer: String,
63    pub key: String,
64    pub eph: String,
65    pub addrs: Vec<String>,
66    pub label: String,
67    pub created: i64,
68    #[serde(default)]
69    pub sig: String,
70}
71
72/// What both sides derive.
73pub struct Derived {
74    pub key: Key32,
75    /// `12345-67890`.
76    pub short_code: String,
77    /// The transcript's first 8 bytes, grouped: `ab12 cd34 ef56 7890`.
78    pub fingerprint: String,
79}
80
81/// A pasted token.
82#[derive(Debug, Clone)]
83pub enum Token {
84    Offer(Offer),
85    Answer(Answer),
86}
87
88fn b64() -> base64::engine::GeneralPurpose {
89    base64::engine::general_purpose::URL_SAFE_NO_PAD
90}
91
92fn signed_bytes<T: Serialize>(domain: &str, t: &T) -> Result<Vec<u8>> {
93    let mut v = domain.as_bytes().to_vec();
94    v.push(0);
95    v.extend(serde_json::to_vec(t)?);
96    Ok(v)
97}
98
99fn public_key(b64key: &str, peer: &str) -> Result<PublicKey> {
100    let raw = b64().decode(b64key).map_err(|_| NetError::invalid("exchange", "bad node key"))?;
101    let pk = PublicKey::try_decode_protobuf(&raw).map_err(|_| NetError::invalid("exchange", "bad node key"))?;
102    if pk.to_peer_id().to_string() != peer {
103        return Err(NetError::invalid("exchange", "the node key does not match the peer id"));
104    }
105    Ok(pk)
106}
107
108fn x_public(hexkey: &str) -> Result<[u8; 32]> {
109    hex::decode(hexkey).ok().and_then(|v| v.try_into().ok()).ok_or_else(|| NetError::invalid("exchange", "bad exchange key"))
110}
111
112impl Offer {
113    /// The offerer's node key (checked against its peer id).
114    pub fn public_key(&self) -> Result<PublicKey> {
115        public_key(&self.key, &self.peer)
116    }
117}
118
119impl Answer {
120    /// The answerer's node key (checked against its peer id).
121    pub fn public_key(&self) -> Result<PublicKey> {
122        public_key(&self.key, &self.peer)
123    }
124}
125
126/// Normalize a typed short code (`1234567890`, `12345 67890`) to `12345-67890`.
127pub fn normalize_code(s: &str) -> String {
128    let d: String = s.chars().filter(|c| c.is_ascii_digit()).collect();
129    if d.len() == 10 { format!("{}-{}", &d[..5], &d[5..]) } else { s.trim().to_string() }
130}
131
132impl Profile {
133    /// A new offer and its X25519 secret (kept until the answer arrives).
134    pub fn offer(
135        &self,
136        kp: &Keypair,
137        label: &str,
138        addrs: Vec<String>,
139        scope: serde_json::Value,
140        now: i64,
141        ttl_ms: i64,
142    ) -> Result<(Offer, Zeroizing<[u8; 32]>)> {
143        (self.scopes)(&scope)?;
144        let secret = ExchangeSecret::generate();
145        let mut o = Offer {
146            v: 1,
147            id: uuid::Uuid::new_v4().simple().to_string(),
148            peer: kp.public().to_peer_id().to_string(),
149            key: b64().encode(kp.public().encode_protobuf()),
150            eph: hex::encode(secret.public()),
151            addrs,
152            label: label.to_string(),
153            scope,
154            created: now,
155            expires: now + ttl_ms.max(MIN_TTL_MS),
156            sig: String::new(),
157        };
158        let sig = kp.sign(&signed_bytes(self.offer_domain, &o)?).map_err(|e| NetError::Crypto(e.to_string()))?;
159        o.sig = b64().encode(sig);
160        Ok((o, secret.to_bytes()))
161    }
162
163    /// Check an offer's version, scope, key, signature and expiry; returns the offerer.
164    pub fn verify_offer(&self, o: &Offer, now: i64) -> Result<PeerId> {
165        if o.v != 1 {
166            return Err(NetError::invalid("exchange", format!("offer version {} is not supported", o.v)));
167        }
168        (self.scopes)(&o.scope)?;
169        let pk = public_key(&o.key, &o.peer)?;
170        let sig = b64().decode(&o.sig).map_err(|_| NetError::invalid("exchange", "bad signature"))?;
171        let unsigned = Offer { sig: String::new(), ..o.clone() };
172        if !pk.verify(&signed_bytes(self.offer_domain, &unsigned)?, &sig) {
173            return Err(NetError::invalid("exchange", "the offer's signature does not verify"));
174        }
175        if now > o.expires {
176            return Err(NetError::invalid("exchange", "the offer has expired; ask for a new one"));
177        }
178        Ok(pk.to_peer_id())
179    }
180
181    /// SHA-256 of the signed offer (hex).
182    pub fn offer_hash(&self, o: &Offer) -> Result<String> {
183        Ok(hex::encode(sha2::Sha256::digest(signed_bytes(self.offer_domain, o)?)))
184    }
185
186    pub fn offer_token(&self, o: &Offer) -> Result<String> {
187        Ok(format!("{}{}", self.offer_prefix, b64().encode(serde_json::to_vec(o)?)))
188    }
189
190    /// Answer an offer (after [`Profile::verify_offer`]): the answer and the derived key.
191    pub fn answer(&self, kp: &Keypair, offer: &Offer, label: &str, addrs: Vec<String>, now: i64) -> Result<(Answer, Derived)> {
192        if offer.peer == kp.public().to_peer_id().to_string() {
193            return Err(NetError::invalid("exchange", "this is this node's own offer; it is answered on the other node"));
194        }
195        let secret = ExchangeSecret::generate();
196        let mut a = Answer {
197            v: 1,
198            offer: offer.id.clone(),
199            offer_hash: self.offer_hash(offer)?,
200            peer: kp.public().to_peer_id().to_string(),
201            key: b64().encode(kp.public().encode_protobuf()),
202            eph: hex::encode(secret.public()),
203            addrs,
204            label: label.to_string(),
205            created: now,
206            sig: String::new(),
207        };
208        let sig = kp.sign(&signed_bytes(self.answer_domain, &a)?).map_err(|e| NetError::Crypto(e.to_string()))?;
209        a.sig = b64().encode(sig);
210        let shared = secret.agree(&x_public(&offer.eph)?).ok_or_else(|| NetError::invalid("exchange", "the offer's exchange key is invalid"))?;
211        let d = self.derive(&shared, offer, &a)?;
212        Ok((a, d))
213    }
214
215    /// Check an answer against our offer; returns the answerer.
216    pub fn verify_answer(&self, a: &Answer, offer: &Offer) -> Result<PeerId> {
217        if a.v != 1 {
218            return Err(NetError::invalid("exchange", format!("answer version {} is not supported", a.v)));
219        }
220        if a.offer != offer.id || a.offer_hash != self.offer_hash(offer)? {
221            return Err(NetError::invalid("exchange", "the answer is for a different offer"));
222        }
223        let pk = public_key(&a.key, &a.peer)?;
224        let sig = b64().decode(&a.sig).map_err(|_| NetError::invalid("exchange", "bad signature"))?;
225        let unsigned = Answer { sig: String::new(), ..a.clone() };
226        if !pk.verify(&signed_bytes(self.answer_domain, &unsigned)?, &sig) {
227            return Err(NetError::invalid("exchange", "the answer's signature does not verify"));
228        }
229        if a.peer == offer.peer {
230            return Err(NetError::invalid("exchange", "an offer cannot be answered by the node that made it"));
231        }
232        Ok(pk.to_peer_id())
233    }
234
235    /// The offerer's side: the key from its kept secret and the answer.
236    pub fn complete(&self, a: &Answer, offer: &Offer, secret: &[u8]) -> Result<Derived> {
237        self.verify_answer(a, offer)?;
238        let s: [u8; 32] = secret.try_into().map_err(|_| NetError::Crypto("bad exchange secret".into()))?;
239        let secret = ExchangeSecret::from_bytes(s);
240        let shared = secret.agree(&x_public(&a.eph)?).ok_or_else(|| NetError::invalid("exchange", "the answer's exchange key is invalid"))?;
241        self.derive(&shared, offer, a)
242    }
243
244    pub fn answer_token(&self, a: &Answer) -> Result<String> {
245        Ok(format!("{}{}", self.answer_prefix, b64().encode(serde_json::to_vec(a)?)))
246    }
247
248    fn derive(&self, dh: &[u8; 32], offer: &Offer, answer: &Answer) -> Result<Derived> {
249        let mut t = sha2::Sha256::new();
250        t.update(self.transcript_domain.as_bytes());
251        t.update(signed_bytes(self.offer_domain, offer)?);
252        t.update(signed_bytes(self.answer_domain, answer)?);
253        let transcript = t.finalize();
254        let (key, sas) = kx::derive(dh, &transcript, self.key_info.as_bytes(), self.sas_info.as_bytes())?;
255        let n = u64::from_be_bytes(sas) % 10_000_000_000;
256        let code = format!("{:05}-{:05}", n / 100_000, n % 100_000);
257        Ok(Derived { key, short_code: code, fingerprint: crate::identity::group(&hex::encode(&transcript[..8])) })
258    }
259
260    /// Read an offer or answer token, or its link (whitespace and line breaks ignored).
261    pub fn parse_token(&self, s: &str) -> Result<Token> {
262        let s: String = self.unlink(s);
263        let (body, offer) = if let Some(b) = s.strip_prefix(self.offer_prefix) {
264            (b, true)
265        } else if let Some(b) = s.strip_prefix(self.answer_prefix) {
266            (b, false)
267        } else {
268            return Err(NetError::invalid(
269                "token",
270                format!("not an exchange token (they start with `{}` or `{}`)", self.offer_prefix, self.answer_prefix),
271            ));
272        };
273        let raw = b64().decode(body).map_err(|_| NetError::invalid("token", "damaged (base64)"))?;
274        Ok(if offer {
275            Token::Offer(serde_json::from_slice(&raw).map_err(|e| NetError::invalid("token", format!("damaged ({e})")))?)
276        } else {
277            Token::Answer(serde_json::from_slice(&raw).map_err(|e| NetError::invalid("token", format!("damaged ({e})")))?)
278        })
279    }
280
281    fn msg_aad(&self, exchange: &str, from: &PeerId, to: &PeerId) -> Vec<u8> {
282        format!("{}|{exchange}|{from}|{to}", self.msg_aad).into_bytes()
283    }
284
285    /// Seal a message for the other side of an exchange (XChaCha20-Poly1305 under the
286    /// exchange key, by `weirdnet-keys`; the exchange and both peer ids are bound as
287    /// associated data, so a message can't be replayed into another exchange or direction).
288    pub fn seal_msg(&self, key: &Key32, exchange: &str, from: &PeerId, to: &PeerId, plaintext: &[u8]) -> Result<Sealed> {
289        Ok(weirdnet_keys::seal(key, plaintext, &self.msg_aad(exchange, from, to))?)
290    }
291
292    /// Open a message sealed by [`Profile::seal_msg`]; every failure reads the same.
293    pub fn open_msg(&self, key: &Key32, exchange: &str, from: &PeerId, to: &PeerId, s: &Sealed) -> Result<Zeroizing<Vec<u8>>> {
294        weirdnet_keys::open(key, s, &self.msg_aad(exchange, from, to)).map_err(|_| NetError::Crypto("a message failed to authenticate".into()))
295    }
296}