1use crate::config;
19use labstream_proto::features;
20use std::io::{self, Write};
21use std::sync::{Mutex, OnceLock};
22
23pub const MAX_FRAME_PLAIN: usize = 65536;
25
26pub const TAG_LEN: usize = 16;
28
29pub const MAX_FRAME_CIPHER: usize = MAX_FRAME_PLAIN + TAG_LEN;
31
32#[derive(Debug, Clone, Default, PartialEq, Eq)]
34pub struct EncryptionPolicy {
35 pub enabled: bool,
37 pub required: bool,
39 pub psk: Option<String>,
41}
42
43impl EncryptionPolicy {
44 pub fn off() -> Self {
46 EncryptionPolicy::default()
47 }
48
49 pub fn opportunistic(psk: Option<String>) -> Self {
52 EncryptionPolicy {
53 enabled: true,
54 required: false,
55 psk,
56 }
57 }
58
59 pub fn required(psk: Option<String>) -> Self {
62 EncryptionPolicy {
63 enabled: true,
64 required: true,
65 psk,
66 }
67 }
68}
69
70static RUNTIME_POLICY: OnceLock<Mutex<Option<EncryptionPolicy>>> = OnceLock::new();
71
72fn policy_lock() -> &'static Mutex<Option<EncryptionPolicy>> {
73 RUNTIME_POLICY.get_or_init(|| Mutex::new(None))
74}
75
76pub fn set_runtime_policy(policy: Option<EncryptionPolicy>) {
79 *policy_lock().lock().unwrap() = policy;
80}
81
82pub fn effective_policy() -> EncryptionPolicy {
84 if let Some(p) = policy_lock().lock().unwrap().clone() {
85 return p;
86 }
87 let cfg = config::get();
88 let enabled = cfg.require_encryption || cfg.features.iter().any(|f| f == features::ENC);
89 EncryptionPolicy {
90 enabled,
91 required: cfg.require_encryption,
92 psk: cfg.encryption_key.clone(),
93 }
94}
95
96pub const fn compiled_in() -> bool {
98 cfg!(feature = "encryption")
99}
100
101#[cfg(feature = "encryption")]
102mod imp {
103 use super::*;
104 use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, CHACHA20_POLY1305};
105 use ring::agreement::{self, EphemeralPrivateKey, UnparsedPublicKey, X25519};
106 use ring::digest::{Context, SHA256};
107 use ring::hkdf::{Salt, HKDF_SHA256};
108 use ring::rand::SystemRandom;
109
110 pub struct EphemeralKey {
112 private: EphemeralPrivateKey,
113 public: [u8; 32],
114 }
115
116 impl EphemeralKey {
117 pub fn generate() -> io::Result<Self> {
119 let rng = SystemRandom::new();
120 let private = EphemeralPrivateKey::generate(&X25519, &rng)
121 .map_err(|_| io::Error::other("X25519 key generation failed"))?;
122 let pub_bytes = private
123 .compute_public_key()
124 .map_err(|_| io::Error::other("X25519 public key computation failed"))?;
125 let mut public = [0u8; 32];
126 public.copy_from_slice(pub_bytes.as_ref());
127 Ok(EphemeralKey { private, public })
128 }
129
130 pub fn public_bytes(&self) -> [u8; 32] {
132 self.public
133 }
134
135 pub fn derive_feed_key(
142 self,
143 peer_pk: [u8; 32],
144 is_outlet: bool,
145 psk: Option<&str>,
146 ) -> io::Result<[u8; 32]> {
147 let (inlet_pk, outlet_pk) = if is_outlet {
148 (peer_pk, self.public)
149 } else {
150 (self.public, peer_pk)
151 };
152 let peer = UnparsedPublicKey::new(&X25519, peer_pk);
153 agreement::agree_ephemeral(self.private, &peer, |shared| {
154 let mut salt_ctx = Context::new(&SHA256);
155 salt_ctx.update(b"labstream-enc-v1");
156 salt_ctx.update(&inlet_pk);
157 salt_ctx.update(&outlet_pk);
158 if let Some(secret) = psk {
159 salt_ctx.update(b"|psk|");
160 salt_ctx.update(secret.as_bytes());
161 }
162 let salt_digest = salt_ctx.finish();
163 let salt = Salt::new(HKDF_SHA256, salt_digest.as_ref());
164 let prk = salt.extract(shared);
165 let okm = prk
166 .expand(&[b"labstream-enc-v1-o2i"], HKDF_SHA256)
167 .map_err(|_| ())?;
168 let mut key = [0u8; 32];
169 okm.fill(&mut key).map_err(|_| ())?;
170 Ok::<[u8; 32], ()>(key)
171 })
172 .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "X25519 key agreement failed"))?
173 .map_err(|_| io::Error::other("HKDF-SHA256 key derivation failed"))
174 }
175 }
176
177 fn make_nonce(seq: u64) -> Nonce {
178 let mut n = [0u8; 12];
179 n[4..12].copy_from_slice(&seq.to_le_bytes());
180 Nonce::assume_unique_for_key(n)
181 }
182
183 fn make_key(raw: &[u8; 32]) -> io::Result<LessSafeKey> {
184 let unbound = UnboundKey::new(&CHACHA20_POLY1305, raw)
185 .map_err(|_| io::Error::other("invalid ChaCha20-Poly1305 key"))?;
186 Ok(LessSafeKey::new(unbound))
187 }
188
189 pub struct EncWriter<W: Write> {
191 inner: W,
192 key: LessSafeKey,
193 seq: u64,
194 buf: Vec<u8>,
195 }
196
197 impl<W: Write> EncWriter<W> {
198 pub fn new(inner: W, key: &[u8; 32]) -> io::Result<Self> {
200 Ok(EncWriter {
201 inner,
202 key: make_key(key)?,
203 seq: 0,
204 buf: Vec::with_capacity(4096),
205 })
206 }
207
208 pub fn write_frame(&mut self, plain: &[u8]) -> io::Result<()> {
211 if self.seq == u64::MAX {
212 return Err(io::Error::other("encryption nonce space exhausted"));
213 }
214 let ct_len = plain.len() + TAG_LEN;
215 let len_bytes = (ct_len as u32).to_le_bytes();
216 self.buf.clear();
217 self.buf.extend_from_slice(&len_bytes);
218 self.buf.extend_from_slice(plain);
219 let nonce = make_nonce(self.seq);
220 self.seq += 1;
221 let tag = self
222 .key
223 .seal_in_place_separate_tag(nonce, Aad::from(len_bytes), &mut self.buf[4..])
224 .map_err(|_| io::Error::other("ChaCha20-Poly1305 encryption failed"))?;
225 self.buf.extend_from_slice(tag.as_ref());
226 self.inner.write_all(&self.buf)
227 }
228 }
229
230 impl<W: Write> Write for EncWriter<W> {
231 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
232 if buf.is_empty() {
233 return Ok(0);
234 }
235 for chunk in buf.chunks(MAX_FRAME_PLAIN) {
236 self.write_frame(chunk)?;
237 }
238 Ok(buf.len())
239 }
240
241 fn flush(&mut self) -> io::Result<()> {
242 self.inner.flush()
243 }
244 }
245
246 pub struct EncReader {
249 key: LessSafeKey,
250 seq: u64,
251 cipher_carry: Vec<u8>,
252 }
253
254 impl EncReader {
255 pub fn new(key: &[u8; 32]) -> io::Result<Self> {
257 Ok(EncReader {
258 key: make_key(key)?,
259 seq: 0,
260 cipher_carry: Vec::with_capacity(4096),
261 })
262 }
263
264 pub fn decrypt_into(&mut self, raw: &[u8], plain_out: &mut Vec<u8>) -> io::Result<()> {
267 self.cipher_carry.extend_from_slice(raw);
268 let mut pos = 0usize;
269 while self.cipher_carry.len() - pos >= 4 {
270 let len_bytes: [u8; 4] = self.cipher_carry[pos..pos + 4].try_into().unwrap();
271 let ct_len = u32::from_le_bytes(len_bytes) as usize;
272 if !(TAG_LEN..=MAX_FRAME_CIPHER).contains(&ct_len) {
273 return Err(io::Error::new(
274 io::ErrorKind::InvalidData,
275 "invalid encrypted frame length",
276 ));
277 }
278 if self.cipher_carry.len() - pos < 4 + ct_len {
279 break;
280 }
281 if self.seq == u64::MAX {
282 return Err(io::Error::new(
283 io::ErrorKind::InvalidData,
284 "encryption nonce space exhausted",
285 ));
286 }
287 let nonce = make_nonce(self.seq);
288 self.seq += 1;
289 let frame = &mut self.cipher_carry[pos + 4..pos + 4 + ct_len];
290 let plain = self
291 .key
292 .open_in_place(nonce, Aad::from(len_bytes), frame)
293 .map_err(|_| {
294 io::Error::new(
295 io::ErrorKind::InvalidData,
296 "encrypted frame authentication failed (wrong key or tampered data)",
297 )
298 })?;
299 plain_out.extend_from_slice(plain);
300 pos += 4 + ct_len;
301 }
302 if pos > 0 {
303 self.cipher_carry.drain(..pos);
304 }
305 Ok(())
306 }
307 }
308}
309
310#[cfg(not(feature = "encryption"))]
311mod imp {
312 use super::*;
313
314 pub struct EphemeralKey;
316
317 impl EphemeralKey {
318 pub fn generate() -> io::Result<Self> {
320 Err(io::Error::new(
321 io::ErrorKind::Unsupported,
322 "labstream was built without the encryption feature",
323 ))
324 }
325
326 pub fn public_bytes(&self) -> [u8; 32] {
328 [0u8; 32]
329 }
330
331 pub fn derive_feed_key(
333 self,
334 _peer_pk: [u8; 32],
335 _is_outlet: bool,
336 _psk: Option<&str>,
337 ) -> io::Result<[u8; 32]> {
338 Err(io::Error::new(
339 io::ErrorKind::Unsupported,
340 "labstream was built without the encryption feature",
341 ))
342 }
343 }
344
345 pub struct EncWriter<W: Write>(W);
347
348 impl<W: Write> EncWriter<W> {
349 pub fn new(_inner: W, _key: &[u8; 32]) -> io::Result<Self> {
351 Err(io::Error::new(
352 io::ErrorKind::Unsupported,
353 "labstream was built without the encryption feature",
354 ))
355 }
356
357 pub fn write_frame(&mut self, _plain: &[u8]) -> io::Result<()> {
359 Err(io::Error::new(
360 io::ErrorKind::Unsupported,
361 "labstream was built without the encryption feature",
362 ))
363 }
364 }
365
366 impl<W: Write> Write for EncWriter<W> {
367 fn write(&mut self, _buf: &[u8]) -> io::Result<usize> {
368 Err(io::Error::new(
369 io::ErrorKind::Unsupported,
370 "labstream was built without the encryption feature",
371 ))
372 }
373
374 fn flush(&mut self) -> io::Result<()> {
375 self.0.flush()
376 }
377 }
378
379 pub struct EncReader;
381
382 impl EncReader {
383 pub fn new(_key: &[u8; 32]) -> io::Result<Self> {
385 Err(io::Error::new(
386 io::ErrorKind::Unsupported,
387 "labstream was built without the encryption feature",
388 ))
389 }
390
391 pub fn decrypt_into(&mut self, _raw: &[u8], _plain_out: &mut Vec<u8>) -> io::Result<()> {
393 Err(io::Error::new(
394 io::ErrorKind::Unsupported,
395 "labstream was built without the encryption feature",
396 ))
397 }
398 }
399}
400
401pub use imp::{EncReader, EncWriter, EphemeralKey};
402
403#[cfg(all(test, feature = "encryption"))]
404mod tests {
405 use super::*;
406
407 #[test]
408 fn x25519_hkdf_chacha20_round_trip_hides_plaintext_and_detects_tampering() {
409 let in_kp = EphemeralKey::generate().unwrap();
410 let out_kp = EphemeralKey::generate().unwrap();
411 let in_pk = in_kp.public_bytes();
412 let out_pk = out_kp.public_bytes();
413
414 let k_out = out_kp
415 .derive_feed_key(in_pk, true, Some("lab-secret-42"))
416 .unwrap();
417 let k_in = in_kp
418 .derive_feed_key(out_pk, false, Some("lab-secret-42"))
419 .unwrap();
420 assert_eq!(k_out, k_in);
421
422 let plaintext = b"SECRET_EEG_SAMPLE_MARKER_0123456789";
423 let mut wire = Vec::new();
424 {
425 let mut w = EncWriter::new(&mut wire, &k_out).unwrap();
426 w.write_all(plaintext).unwrap();
427 w.flush().unwrap();
428 }
429 assert!(
431 !wire.windows(plaintext.len()).any(|w| w == plaintext),
432 "plaintext leaked onto wire"
433 );
434
435 let mut r = EncReader::new(&k_in).unwrap();
437 let mut recovered = Vec::new();
438 for chunk in wire.chunks(7) {
439 r.decrypt_into(chunk, &mut recovered).unwrap();
440 }
441 assert_eq!(recovered, plaintext);
442
443 let mut tampered = wire.clone();
445 tampered[10] ^= 0x01;
446 let mut r_bad = EncReader::new(&k_in).unwrap();
447 assert!(r_bad.decrypt_into(&tampered, &mut Vec::new()).is_err());
448
449 let in_kp2 = EphemeralKey::generate().unwrap();
451 let out_kp2 = EphemeralKey::generate().unwrap();
452 let in_pk2 = in_kp2.public_bytes();
453 let out_pk2 = out_kp2.public_bytes();
454 let k_out2 = out_kp2
455 .derive_feed_key(in_pk2, true, Some("key-A"))
456 .unwrap();
457 let k_in2 = in_kp2
458 .derive_feed_key(out_pk2, false, Some("key-B"))
459 .unwrap();
460 assert_ne!(k_out2, k_in2);
461 let mut wire2 = Vec::new();
462 EncWriter::new(&mut wire2, &k_out2)
463 .unwrap()
464 .write_frame(b"hello")
465 .unwrap();
466 assert!(EncReader::new(&k_in2)
467 .unwrap()
468 .decrypt_into(&wire2, &mut Vec::new())
469 .is_err());
470 }
471}