| 1 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 2 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 4 |
// option. This file may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
use std::mem; |
| 8 |
|
| 9 |
use neqo_common::{hex, qinfo, qtrace, Encoder}; |
| 10 |
|
| 11 |
use crate::{ |
| 12 |
constants::{Cipher, Version}, |
| 13 |
err::{Error, Res}, |
| 14 |
hkdf, |
| 15 |
p11::{random, SymKey}, |
| 16 |
Aead, |
| 17 |
}; |
| 18 |
|
| 19 |
#[derive(Debug)] |
| 20 |
pub struct SelfEncrypt { |
| 21 |
version: Version, |
| 22 |
cipher: Cipher, |
| 23 |
key_id: u8, |
| 24 |
key: SymKey, |
| 25 |
old_key: Option<SymKey>, |
| 26 |
} |
| 27 |
|
| 28 |
impl SelfEncrypt { |
| 29 |
const VERSION: u8 = 1; |
| 30 |
const SALT_LENGTH: usize = 16; |
| 31 |
|
| 32 |
/// # Errors |
| 33 |
/// |
| 34 |
/// Failure to generate a new HKDF key using NSS results in an error. |
| 35 |
pub fn new(version: Version, cipher: Cipher) -> Res<Self> { |
| 36 |
let key = hkdf::generate_key(version, cipher)?; |
| 37 |
Ok(Self { |
| 38 |
version, |
| 39 |
cipher, |
| 40 |
key_id: 0, |
| 41 |
key, |
| 42 |
old_key: None, |
| 43 |
}) |
| 44 |
} |
| 45 |
|
| 46 |
fn make_aead(&self, k: &SymKey, salt: &[u8]) -> Res<Aead> { |
| 47 |
debug_assert_eq!(salt.len(), Self::SALT_LENGTH); |
| 48 |
let salt = hkdf::import_key(self.version, salt)?; |
| 49 |
let secret = hkdf::extract(self.version, self.cipher, Some(&salt), k)?; |
| 50 |
Aead::new(self.version, self.cipher, &secret, "neqo self") |
| 51 |
} |
| 52 |
|
| 53 |
/// Rotate keys. This causes any previous key that is being held to be replaced by the current |
| 54 |
/// key. |
| 55 |
/// |
| 56 |
/// # Errors |
| 57 |
/// |
| 58 |
/// Failure to generate a new HKDF key using NSS results in an error. |
| 59 |
pub fn rotate(&mut self) -> Res<()> { |
| 60 |
let new_key = hkdf::generate_key(self.version, self.cipher)?; |
| 61 |
self.old_key = Some(mem::replace(&mut self.key, new_key)); |
| 62 |
let (kid, _) = self.key_id.overflowing_add(1); |
| 63 |
self.key_id = kid; |
| 64 |
qinfo!("[SelfEncrypt] Rotated keys to {}", self.key_id); |
| 65 |
Ok(()) |
| 66 |
} |
| 67 |
|
| 68 |
/// Seal an item using the underlying key. This produces a single buffer that contains |
| 69 |
/// the encrypted `plaintext`, plus a version number and salt. |
| 70 |
/// `aad` is only used as input to the AEAD, it is not included in the output; the |
| 71 |
/// caller is responsible for carrying the AAD as appropriate. |
| 72 |
/// |
| 73 |
/// # Errors |
| 74 |
/// |
| 75 |
/// Failure to protect using NSS AEAD APIs produces an error. |
| 76 |
pub fn seal(&self, aad: &[u8], plaintext: &[u8]) -> Res<Vec<u8>> { |
| 77 |
// Format is: |
| 78 |
// struct { |
| 79 |
// uint8 version; |
| 80 |
// uint8 key_id; |
| 81 |
// uint8 salt[16]; |
| 82 |
// opaque aead_encrypted(plaintext)[length as expanded]; |
| 83 |
// }; |
| 84 |
// AAD covers the entire header, plus the value of the AAD parameter that is provided. |
| 85 |
let salt = random::<{ Self::SALT_LENGTH }>(); |
| 86 |
let cipher = self.make_aead(&self.key, &salt)?; |
| 87 |
let encoded_len = 2 + salt.len() + plaintext.len() + cipher.expansion(); |
| 88 |
|
| 89 |
let mut enc = Encoder::with_capacity(encoded_len); |
| 90 |
enc.encode_byte(Self::VERSION); |
| 91 |
enc.encode_byte(self.key_id); |
| 92 |
enc.encode(&salt); |
| 93 |
|
| 94 |
let mut extended_aad = enc.clone(); |
| 95 |
extended_aad.encode(aad); |
| 96 |
|
| 97 |
let offset = enc.len(); |
| 98 |
let mut output: Vec<u8> = enc.into(); |
| 99 |
output.resize(encoded_len, 0); |
| 100 |
cipher.encrypt(0, extended_aad.as_ref(), plaintext, &mut output[offset..])?; |
| 101 |
qtrace!( |
| 102 |
"[SelfEncrypt] seal {} {} -> {}", |
| 103 |
hex(aad), |
| 104 |
hex(plaintext), |
| 105 |
hex(&output) |
| 106 |
); |
| 107 |
Ok(output) |
| 108 |
} |
| 109 |
|
| 110 |
const fn select_key(&self, kid: u8) -> Option<&SymKey> { |
| 111 |
if kid == self.key_id { |
| 112 |
Some(&self.key) |
| 113 |
} else { |
| 114 |
let (prev_key_id, _) = self.key_id.overflowing_sub(1); |
| 115 |
if kid == prev_key_id { |
| 116 |
self.old_key.as_ref() |
| 117 |
} else { |
| 118 |
None |
| 119 |
} |
| 120 |
} |
| 121 |
} |
| 122 |
|
| 123 |
/// Open the protected `ciphertext`. |
| 124 |
/// |
| 125 |
/// # Errors |
| 126 |
/// |
| 127 |
/// Returns an error when the self-encrypted object is invalid; |
| 128 |
/// when the keys have been rotated; or when NSS fails. |
| 129 |
#[expect(clippy::similar_names, reason = "aad is similar to aead.")] |
| 130 |
pub fn open(&self, aad: &[u8], ciphertext: &[u8]) -> Res<Vec<u8>> { |
| 131 |
if ciphertext[0] != Self::VERSION { |
| 132 |
return Err(Error::SelfEncryptFailure); |
| 133 |
} |
| 134 |
let Some(key) = self.select_key(ciphertext[1]) else { |
| 135 |
return Err(Error::SelfEncryptFailure); |
| 136 |
}; |
| 137 |
let offset = 2 + Self::SALT_LENGTH; |
| 138 |
|
| 139 |
let mut extended_aad = Encoder::with_capacity(offset + aad.len()); |
| 140 |
extended_aad.encode(&ciphertext[0..offset]); |
| 141 |
extended_aad.encode(aad); |
| 142 |
|
| 143 |
let aead = self.make_aead(key, &ciphertext[2..offset])?; |
| 144 |
// NSS insists on having extra space available for decryption. |
| 145 |
let padded_len = ciphertext.len() - offset; |
| 146 |
let mut output = vec![0; padded_len]; |
| 147 |
let decrypted = |
| 148 |
aead.decrypt(0, extended_aad.as_ref(), &ciphertext[offset..], &mut output)?; |
| 149 |
let final_len = decrypted.len(); |
| 150 |
output.truncate(final_len); |
| 151 |
qtrace!( |
| 152 |
"[SelfEncrypt] open {} {} -> {}", |
| 153 |
hex(aad), |
| 154 |
hex(ciphertext), |
| 155 |
hex(&output) |
| 156 |
); |
| 157 |
Ok(output) |
| 158 |
} |
| 159 |
} |