1use std::collections::HashSet;
2use std::io::{Cursor, Read};
3
4use crate::FramingError;
5
6const TAG_UNENCRYPTED: u8 = 0;
7const TAG_SYMMETRIC: u8 = 1;
8const TAG_PASSWORD: u8 = 2;
9const TAG_RECIPIENTS: u8 = 3;
10const TAG_PASSWORD_AND_RECIPIENTS: u8 = 4;
11const TAG_ARGON2ID: u8 = 1;
12const TAG_AES_256_GCM: u8 = 1;
13const TAG_CHACHA20_POLY1305: u8 = 2;
14const TAG_HPKE_X25519_HKDF_SHA256_AES128GCM: u8 = 1;
15const TAG_EXTENSIONS: u8 = 0x80;
16const MAX_RECIPIENTS: usize = 1024;
17const MIN_RECIPIENT_ID_SIZE: usize = 1;
18const MAX_RECIPIENT_ID_SIZE: usize = 256;
19const MAX_HPKE_ENC_SIZE: usize = 1024;
20const MAX_WRAPPED_DEK_SIZE: usize = 4096;
21pub const PASSWORD_SALT_SIZE: usize = 16;
22pub const AEAD_NONCE_SIZE: usize = 12;
23pub const DEK_SIZE: usize = 32;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[repr(u8)]
27pub enum EncryptionScope {
28 Header = 1,
29 Data = 2,
30 HeaderAndData = 3,
31}
32
33impl EncryptionScope {
34 fn from_tag(tag: u8) -> Result<Self, FramingError> {
35 match tag {
36 1 => Ok(Self::Header),
37 2 => Ok(Self::Data),
38 3 => Ok(Self::HeaderAndData),
39 _ => Err(FramingError::InvalidDescriptor),
40 }
41 }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45#[repr(u8)]
46pub enum ContentAead {
47 Aes256Gcm = TAG_AES_256_GCM,
48 ChaCha20Poly1305 = TAG_CHACHA20_POLY1305,
49}
50
51impl ContentAead {
52 fn from_tag(tag: u8) -> Result<Self, FramingError> {
53 match tag {
54 TAG_AES_256_GCM => Ok(Self::Aes256Gcm),
55 TAG_CHACHA20_POLY1305 => Ok(Self::ChaCha20Poly1305),
56 _ => Err(FramingError::InvalidDescriptor),
57 }
58 }
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62#[repr(u8)]
63pub enum HpkeSuite {
64 X25519HkdfSha256Aes128Gcm = TAG_HPKE_X25519_HKDF_SHA256_AES128GCM,
65}
66
67impl HpkeSuite {
68 fn from_tag(tag: u8) -> Result<Self, FramingError> {
69 match tag {
70 TAG_HPKE_X25519_HKDF_SHA256_AES128GCM => Ok(Self::X25519HkdfSha256Aes128Gcm),
71 _ => Err(FramingError::InvalidDescriptor),
72 }
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct PasswordKeyWrap {
78 pub algorithm: ContentAead,
79 pub salt: [u8; PASSWORD_SALT_SIZE],
80 pub memory_kib: u32,
81 pub iterations: u32,
82 pub parallelism: u32,
83 pub wrap_nonce: [u8; AEAD_NONCE_SIZE],
84 pub wrapped_dek: Vec<u8>,
85}
86
87impl PasswordKeyWrap {
88 pub fn validate(&self) -> Result<(), FramingError> {
89 if !(65_536..=1_048_576).contains(&self.memory_kib)
90 || !(2..=10).contains(&self.iterations)
91 || !(1..=16).contains(&self.parallelism)
92 || !(DEK_SIZE + 16..=MAX_WRAPPED_DEK_SIZE).contains(&self.wrapped_dek.len())
93 {
94 return Err(FramingError::InvalidDescriptor);
95 }
96 Ok(())
97 }
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct RecipientKeyWrap {
102 pub recipient_id: Vec<u8>,
103 pub suite: HpkeSuite,
104 pub enc: Vec<u8>,
105 pub wrapped_dek: Vec<u8>,
106}
107
108impl RecipientKeyWrap {
109 pub fn validate(&self) -> Result<(), FramingError> {
110 if !(MIN_RECIPIENT_ID_SIZE..=MAX_RECIPIENT_ID_SIZE).contains(&self.recipient_id.len())
111 || self.enc.is_empty()
112 || self.enc.len() > MAX_HPKE_ENC_SIZE
113 || !(DEK_SIZE + 16..=MAX_WRAPPED_DEK_SIZE).contains(&self.wrapped_dek.len())
114 {
115 return Err(FramingError::InvalidDescriptor);
116 }
117 Ok(())
118 }
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct DescriptorExtension {
123 pub tag: u8,
124 pub value: Vec<u8>,
125}
126
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub enum EncryptionDescriptor {
129 Unencrypted,
130 Symmetric {
131 scope: EncryptionScope,
132 algorithm: ContentAead,
133 nonce: [u8; AEAD_NONCE_SIZE],
134 },
135 Password {
136 scope: EncryptionScope,
137 algorithm: ContentAead,
138 nonce: [u8; AEAD_NONCE_SIZE],
139 key_wrap: PasswordKeyWrap,
140 },
141 Recipients {
142 scope: EncryptionScope,
143 algorithm: ContentAead,
144 nonce: [u8; AEAD_NONCE_SIZE],
145 recipients: Vec<RecipientKeyWrap>,
146 },
147 PasswordAndRecipients {
148 scope: EncryptionScope,
149 algorithm: ContentAead,
150 nonce: [u8; AEAD_NONCE_SIZE],
151 password: PasswordKeyWrap,
152 recipients: Vec<RecipientKeyWrap>,
153 },
154}
155
156impl EncryptionDescriptor {
157 pub fn is_header_encrypted(&self) -> bool {
158 matches!(
159 self,
160 Self::Symmetric {
161 scope: EncryptionScope::Header | EncryptionScope::HeaderAndData,
162 ..
163 } | Self::Password {
164 scope: EncryptionScope::Header | EncryptionScope::HeaderAndData,
165 ..
166 } | Self::Recipients {
167 scope: EncryptionScope::Header | EncryptionScope::HeaderAndData,
168 ..
169 } | Self::PasswordAndRecipients {
170 scope: EncryptionScope::Header | EncryptionScope::HeaderAndData,
171 ..
172 }
173 )
174 }
175
176 pub fn is_data_encrypted(&self) -> bool {
177 matches!(
178 self,
179 Self::Symmetric {
180 scope: EncryptionScope::Data | EncryptionScope::HeaderAndData,
181 ..
182 } | Self::Password {
183 scope: EncryptionScope::Data | EncryptionScope::HeaderAndData,
184 ..
185 } | Self::Recipients {
186 scope: EncryptionScope::Data | EncryptionScope::HeaderAndData,
187 ..
188 } | Self::PasswordAndRecipients {
189 scope: EncryptionScope::Data | EncryptionScope::HeaderAndData,
190 ..
191 }
192 )
193 }
194
195 pub fn encode(&self) -> Result<Vec<u8>, FramingError> {
196 self.encode_with_extensions(&[])
197 }
198
199 pub fn encode_with_extensions(
200 &self,
201 extensions: &[DescriptorExtension],
202 ) -> Result<Vec<u8>, FramingError> {
203 let mut output = Vec::new();
204 match self {
205 Self::Unencrypted => output.push(TAG_UNENCRYPTED),
206 Self::Symmetric {
207 scope,
208 algorithm,
209 nonce,
210 } => {
211 output.extend_from_slice(&[TAG_SYMMETRIC, *scope as u8, *algorithm as u8]);
212 output.extend_from_slice(nonce);
213 }
214 Self::Password {
215 scope,
216 algorithm,
217 nonce,
218 key_wrap,
219 } => {
220 output.extend_from_slice(&[TAG_PASSWORD, *scope as u8, *algorithm as u8]);
221 output.extend_from_slice(nonce);
222 encode_password_wrap(&mut output, key_wrap)?;
223 }
224 Self::Recipients {
225 scope,
226 algorithm,
227 nonce,
228 recipients,
229 } => {
230 output.extend_from_slice(&[TAG_RECIPIENTS, *scope as u8, *algorithm as u8]);
231 output.extend_from_slice(nonce);
232 encode_recipients(&mut output, recipients)?;
233 }
234 Self::PasswordAndRecipients {
235 scope,
236 algorithm,
237 nonce,
238 password,
239 recipients,
240 } => {
241 output.extend_from_slice(&[
242 TAG_PASSWORD_AND_RECIPIENTS,
243 *scope as u8,
244 *algorithm as u8,
245 ]);
246 output.extend_from_slice(nonce);
247 encode_password_wrap(&mut output, password)?;
248 encode_recipients(&mut output, recipients)?;
249 }
250 }
251 for extension in extensions {
252 if extension.tag < TAG_EXTENSIONS {
253 return Err(FramingError::InvalidDescriptor);
254 }
255 output.push(extension.tag);
256 write_bytes(&mut output, &extension.value)?;
257 }
258 if output.len() > crate::MAX_ENCRYPTION_DESCRIPTOR_SIZE {
259 return Err(FramingError::InvalidDescriptor);
260 }
261 Ok(output)
262 }
263
264 pub fn decode(bytes: &[u8]) -> Result<(Self, Vec<DescriptorExtension>), FramingError> {
265 if bytes.is_empty() || bytes.len() > crate::MAX_ENCRYPTION_DESCRIPTOR_SIZE {
266 return Err(FramingError::InvalidDescriptor);
267 }
268 let mut cursor = Cursor::new(bytes);
269 let mode = read_u8(&mut cursor)?;
270 let descriptor = match mode {
271 TAG_UNENCRYPTED => Self::Unencrypted,
272 TAG_SYMMETRIC | TAG_PASSWORD | TAG_RECIPIENTS | TAG_PASSWORD_AND_RECIPIENTS => {
273 let scope = EncryptionScope::from_tag(read_u8(&mut cursor)?)?;
274 let algorithm = ContentAead::from_tag(read_u8(&mut cursor)?)?;
275 let nonce = read_array(&mut cursor)?;
276 match mode {
277 TAG_SYMMETRIC => Self::Symmetric {
278 scope,
279 algorithm,
280 nonce,
281 },
282 TAG_PASSWORD => Self::Password {
283 scope,
284 algorithm,
285 nonce,
286 key_wrap: decode_password_wrap(&mut cursor)?,
287 },
288 TAG_RECIPIENTS => Self::Recipients {
289 scope,
290 algorithm,
291 nonce,
292 recipients: decode_recipients(&mut cursor)?,
293 },
294 _ => Self::PasswordAndRecipients {
295 scope,
296 algorithm,
297 nonce,
298 password: decode_password_wrap(&mut cursor)?,
299 recipients: decode_recipients(&mut cursor)?,
300 },
301 }
302 }
303 _ => return Err(FramingError::InvalidDescriptor),
304 };
305
306 let mut extensions = Vec::new();
307 while (cursor.position() as usize) < bytes.len() {
308 let tag = read_u8(&mut cursor)?;
309 if tag < TAG_EXTENSIONS {
310 return Err(FramingError::InvalidDescriptor);
311 }
312 let value = read_bytes(&mut cursor, crate::MAX_ENCRYPTION_DESCRIPTOR_SIZE)?;
313 extensions.push(DescriptorExtension { tag, value });
314 }
315 Ok((descriptor, extensions))
316 }
317}
318
319fn encode_password_wrap(output: &mut Vec<u8>, wrap: &PasswordKeyWrap) -> Result<(), FramingError> {
320 wrap.validate()?;
321 output.extend_from_slice(&[TAG_ARGON2ID, wrap.algorithm as u8]);
322 output.extend_from_slice(&wrap.salt);
323 output.extend_from_slice(&wrap.memory_kib.to_le_bytes());
324 output.extend_from_slice(&wrap.iterations.to_le_bytes());
325 output.extend_from_slice(&wrap.parallelism.to_le_bytes());
326 output.extend_from_slice(&wrap.wrap_nonce);
327 write_bytes(output, &wrap.wrapped_dek)
328}
329
330fn decode_password_wrap(reader: &mut Cursor<&[u8]>) -> Result<PasswordKeyWrap, FramingError> {
331 if read_u8(reader)? != TAG_ARGON2ID {
332 return Err(FramingError::InvalidDescriptor);
333 }
334 let wrap = PasswordKeyWrap {
335 algorithm: ContentAead::from_tag(read_u8(reader)?)?,
336 salt: read_array(reader)?,
337 memory_kib: read_u32(reader)?,
338 iterations: read_u32(reader)?,
339 parallelism: read_u32(reader)?,
340 wrap_nonce: read_array(reader)?,
341 wrapped_dek: read_bytes(reader, MAX_WRAPPED_DEK_SIZE)?,
342 };
343 wrap.validate()?;
344 Ok(wrap)
345}
346
347fn encode_recipients(
348 output: &mut Vec<u8>,
349 recipients: &[RecipientKeyWrap],
350) -> Result<(), FramingError> {
351 if recipients.is_empty() || recipients.len() > MAX_RECIPIENTS {
352 return Err(FramingError::InvalidDescriptor);
353 }
354 write_u32(output, recipients.len())?;
355 let mut ids = HashSet::with_capacity(recipients.len());
356 for recipient in recipients {
357 recipient.validate()?;
358 if !ids.insert(recipient.recipient_id.as_slice()) {
359 return Err(FramingError::InvalidDescriptor);
360 }
361 write_bytes(output, &recipient.recipient_id)?;
362 output.push(recipient.suite as u8);
363 write_bytes(output, &recipient.enc)?;
364 write_bytes(output, &recipient.wrapped_dek)?;
365 }
366 Ok(())
367}
368
369fn decode_recipients(reader: &mut Cursor<&[u8]>) -> Result<Vec<RecipientKeyWrap>, FramingError> {
370 let count = read_u32(reader)? as usize;
371 if count == 0 || count > MAX_RECIPIENTS {
372 return Err(FramingError::InvalidDescriptor);
373 }
374 let mut recipients = Vec::with_capacity(count);
375 let mut ids = HashSet::with_capacity(count);
376 for _ in 0..count {
377 let recipient_id = read_bytes(reader, MAX_RECIPIENT_ID_SIZE)?;
378 let suite = HpkeSuite::from_tag(read_u8(reader)?)?;
379 let enc = read_bytes(reader, MAX_HPKE_ENC_SIZE)?;
380 let wrapped_dek = read_bytes(reader, MAX_WRAPPED_DEK_SIZE)?;
381 let recipient = RecipientKeyWrap {
382 recipient_id,
383 suite,
384 enc,
385 wrapped_dek,
386 };
387 recipient.validate()?;
388 if !ids.insert(recipient.recipient_id.clone()) {
389 return Err(FramingError::InvalidDescriptor);
390 }
391 recipients.push(recipient);
392 }
393 Ok(recipients)
394}
395
396fn write_bytes(output: &mut Vec<u8>, bytes: &[u8]) -> Result<(), FramingError> {
397 let length = u32::try_from(bytes.len()).map_err(|_| FramingError::InvalidDescriptor)?;
398 output.extend_from_slice(&length.to_le_bytes());
399 output.extend_from_slice(bytes);
400 Ok(())
401}
402
403fn write_u32(output: &mut Vec<u8>, value: usize) -> Result<(), FramingError> {
404 let value = u32::try_from(value).map_err(|_| FramingError::InvalidDescriptor)?;
405 output.extend_from_slice(&value.to_le_bytes());
406 Ok(())
407}
408
409fn read_u8(reader: &mut Cursor<&[u8]>) -> Result<u8, FramingError> {
410 let mut value = [0];
411 reader.read_exact(&mut value)?;
412 Ok(value[0])
413}
414
415fn read_u32(reader: &mut Cursor<&[u8]>) -> Result<u32, FramingError> {
416 let mut bytes = [0; 4];
417 reader.read_exact(&mut bytes)?;
418 Ok(u32::from_le_bytes(bytes))
419}
420
421fn read_array<const N: usize>(reader: &mut Cursor<&[u8]>) -> Result<[u8; N], FramingError> {
422 let mut bytes = [0; N];
423 reader.read_exact(&mut bytes)?;
424 Ok(bytes)
425}
426
427fn read_bytes(reader: &mut Cursor<&[u8]>, max_len: usize) -> Result<Vec<u8>, FramingError> {
428 let length = read_u32(reader)? as usize;
429 if length > max_len {
430 return Err(FramingError::InvalidDescriptor);
431 }
432 let mut bytes = vec![0; length];
433 reader.read_exact(&mut bytes)?;
434 Ok(bytes)
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440
441 fn password_wrap() -> PasswordKeyWrap {
442 PasswordKeyWrap {
443 algorithm: ContentAead::Aes256Gcm,
444 salt: [1; PASSWORD_SALT_SIZE],
445 memory_kib: 65_536,
446 iterations: 3,
447 parallelism: 1,
448 wrap_nonce: [2; AEAD_NONCE_SIZE],
449 wrapped_dek: vec![3; DEK_SIZE + 16],
450 }
451 }
452
453 fn recipient(id: &[u8]) -> RecipientKeyWrap {
454 RecipientKeyWrap {
455 recipient_id: id.to_vec(),
456 suite: HpkeSuite::X25519HkdfSha256Aes128Gcm,
457 enc: vec![4; 32],
458 wrapped_dek: vec![5; DEK_SIZE + 16],
459 }
460 }
461
462 #[test]
463 fn unencrypted_descriptor_has_stable_wire_tag() {
464 let bytes = EncryptionDescriptor::Unencrypted.encode().unwrap();
465 assert_eq!(bytes, [0]);
466 assert_eq!(
467 EncryptionDescriptor::decode(&bytes).unwrap(),
468 (EncryptionDescriptor::Unencrypted, vec![])
469 );
470 }
471
472 #[test]
473 fn password_and_recipients_round_trip() {
474 let descriptor = EncryptionDescriptor::PasswordAndRecipients {
475 scope: EncryptionScope::HeaderAndData,
476 algorithm: ContentAead::ChaCha20Poly1305,
477 nonce: [6; AEAD_NONCE_SIZE],
478 password: password_wrap(),
479 recipients: vec![recipient(b"key-a"), recipient(b"key-b")],
480 };
481 let encoded = descriptor.encode().unwrap();
482 let (decoded, extensions) = EncryptionDescriptor::decode(&encoded).unwrap();
483 assert_eq!(decoded, descriptor);
484 assert!(extensions.is_empty());
485 }
486
487 #[test]
488 fn descriptor_rejects_bad_parameters_duplicates_and_trailing_mandatory_data() {
489 let mut wrap = password_wrap();
490 wrap.memory_kib = 1024;
491 assert_eq!(wrap.validate(), Err(FramingError::InvalidDescriptor));
492
493 let descriptor = EncryptionDescriptor::Recipients {
494 scope: EncryptionScope::Data,
495 algorithm: ContentAead::Aes256Gcm,
496 nonce: [0; AEAD_NONCE_SIZE],
497 recipients: vec![recipient(b"same"), recipient(b"same")],
498 };
499 assert_eq!(descriptor.encode(), Err(FramingError::InvalidDescriptor));
500
501 let mut encoded = EncryptionDescriptor::Unencrypted.encode().unwrap();
502 encoded.push(1);
503 assert_eq!(
504 EncryptionDescriptor::decode(&encoded),
505 Err(FramingError::InvalidDescriptor)
506 );
507 }
508
509 #[test]
510 fn descriptor_skips_optional_tlvs_and_rejects_unknown_mandatory_tags() {
511 let descriptor = EncryptionDescriptor::Symmetric {
512 scope: EncryptionScope::Header,
513 algorithm: ContentAead::Aes256Gcm,
514 nonce: [7; AEAD_NONCE_SIZE],
515 };
516 let encoded = descriptor
517 .encode_with_extensions(&[DescriptorExtension {
518 tag: 0x80,
519 value: vec![8, 9],
520 }])
521 .unwrap();
522 let (decoded, extensions) = EncryptionDescriptor::decode(&encoded).unwrap();
523 assert_eq!(decoded, descriptor);
524 assert_eq!(
525 extensions,
526 vec![DescriptorExtension {
527 tag: 0x80,
528 value: vec![8, 9]
529 }]
530 );
531 assert_eq!(
532 EncryptionDescriptor::decode(&[0x7f]),
533 Err(FramingError::InvalidDescriptor)
534 );
535 }
536}