use aws_lc_rs::{aead, error, test, test_file};
use aws_lc_rs::aead::{Nonce, NONCE_LEN};
use core::ops::RangeFrom;
use mirai_annotations::unrecoverable;
#[test]
fn aead_aes_gcm_128() {
test_aead(
&aead::AES_128_GCM,
seal_with_key,
open_with_key,
test_file!("data/aead_aes_128_gcm_tests.txt"),
);
test_aead(
&aead::AES_128_GCM,
seal_with_less_safe_key,
open_with_less_safe_key,
test_file!("data/aead_aes_128_gcm_tests.txt"),
);
}
#[test]
fn aead_aes_gcm_256() {
test_aead(
&aead::AES_256_GCM,
seal_with_key,
open_with_key,
test_file!("data/aead_aes_256_gcm_tests.txt"),
);
test_aead(
&aead::AES_256_GCM,
seal_with_less_safe_key,
open_with_less_safe_key,
test_file!("data/aead_aes_256_gcm_tests.txt"),
);
}
#[test]
fn aead_chacha20_poly1305() {
test_aead(
&aead::CHACHA20_POLY1305,
seal_with_key,
open_with_key,
test_file!("data/aead_chacha20_poly1305_tests.txt"),
);
test_aead(
&aead::CHACHA20_POLY1305,
seal_with_less_safe_key,
open_with_less_safe_key,
test_file!("data/aead_chacha20_poly1305_tests.txt"),
);
}
#[allow(clippy::too_many_lines)]
fn test_aead<Seal, Open>(
aead_alg: &'static aead::Algorithm,
seal: Seal,
open: Open,
test_file: test::File,
) where
Seal: Fn(
&'static aead::Algorithm,
&[u8],
Nonce,
aead::Aad<&[u8]>,
&mut Vec<u8>,
) -> Result<(), error::Unspecified>,
Open: for<'a> Fn(
&'static aead::Algorithm,
&[u8],
Nonce,
aead::Aad<&[u8]>,
&'a mut [u8],
RangeFrom<usize>,
) -> Result<&'a mut [u8], error::Unspecified>,
{
static MINIMAL_IN_PREFIX_LENS: [usize; 36] = [
0,
1,
2,
5,
8,
5 + 8,
15, 16, 17, 31, 32, 33, 47, 48, 49, 63, 64, 65, 79, 80, 81, 95, 96, 97, 111, 112, 113, 127, 128, 129, 143, 144, 145, 255, 256, 257, ];
test_aead_key_sizes(aead_alg);
test::run(test_file, |section, test_case| {
assert_eq!(section, "");
let key_bytes = test_case.consume_bytes("KEY");
let nonce_bytes = test_case.consume_bytes("NONCE");
let plaintext = test_case.consume_bytes("IN");
let aad = test_case.consume_bytes("AD");
let mut ct = test_case.consume_bytes("CT");
let tag = test_case.consume_bytes("TAG");
let error = test_case.consume_optional_string("FAILS");
match &error {
Some(err) if err == "WRONG_NONCE_LENGTH" => {
assert!(aead::Nonce::try_assume_unique_for_key(&nonce_bytes).is_err());
return Ok(());
}
_ => (),
};
let mut s_in_out = plaintext.clone();
let nonce = aead::Nonce::try_assume_unique_for_key(&nonce_bytes).unwrap();
let s_result = seal(
aead_alg,
&key_bytes[..],
nonce,
aead::Aad::from(&aad[..]),
&mut s_in_out,
);
ct.extend(tag);
if s_result.is_ok() {
assert_eq!(&ct, &s_in_out);
}
let mut more_comprehensive_in_prefix_lengths = [0; 4096];
let in_prefix_lengths = if cfg!(debug_assertions) {
&MINIMAL_IN_PREFIX_LENS[..]
} else {
#[allow(clippy::needless_range_loop)]
for b in 0..more_comprehensive_in_prefix_lengths.len() {
more_comprehensive_in_prefix_lengths[b] = b;
}
&more_comprehensive_in_prefix_lengths[..]
};
let mut o_in_out = vec![123u8; 4096];
for &in_prefix_len in in_prefix_lengths.iter() {
o_in_out.truncate(0);
o_in_out.resize(in_prefix_len, 123);
o_in_out.extend_from_slice(&ct[..]);
let o_in_out_clone = o_in_out.clone();
let nonce = aead::Nonce::try_assume_unique_for_key(&nonce_bytes).unwrap();
let o_result = open(
aead_alg,
&key_bytes,
nonce,
aead::Aad::from(&aad[..]),
&mut o_in_out,
in_prefix_len..,
);
match error {
None => {
assert!(s_result.is_ok());
assert!(o_result.is_ok(), "Not ok: {o_result:?}");
let result = o_result.unwrap();
assert_eq!(&plaintext[..], result);
for bad_func in [aead_open_bad_tag, aead_open_bad_nonce, aead_open_bad_aad] {
bad_func(
aead_alg,
&key_bytes,
&nonce_bytes,
aad.as_slice(),
&o_in_out_clone,
in_prefix_len,
&open,
);
}
}
Some(ref error) if error == "WRONG_NONCE_LENGTH" => {
assert_eq!(Err(error::Unspecified), s_result);
assert_eq!(Err(error::Unspecified), o_result);
}
Some(error) => {
unrecoverable!("Unexpected error test case: {}", error);
}
};
}
Ok(())
});
}
fn aead_open_bad_tag<Open>(
aead_alg: &'static aead::Algorithm,
key_bytes: &[u8],
nonce_bytes: &[u8],
aad_bytes: &[u8],
in_out: &[u8],
in_prefix_len: usize,
open: Open,
) where
Open: for<'a> Fn(
&'static aead::Algorithm,
&[u8],
Nonce,
aead::Aad<&[u8]>,
&'a mut [u8],
RangeFrom<usize>,
) -> Result<&'a mut [u8], error::Unspecified>,
{
let mut in_out = Vec::from(in_out);
let in_out_len = in_out.len();
in_out[in_out_len - 1] ^= 0x08;
let nonce_bytes = Vec::from(nonce_bytes);
let aad_bytes = Vec::from(aad_bytes);
let nonce = Nonce::try_assume_unique_for_key(&nonce_bytes).unwrap();
let aad = aead::Aad::from(aad_bytes.as_slice());
let err_result = open(
aead_alg,
key_bytes,
nonce,
aad,
&mut in_out,
in_prefix_len..,
);
assert!(err_result.is_err());
}
fn aead_open_bad_nonce<Open>(
aead_alg: &'static aead::Algorithm,
key_bytes: &[u8],
nonce_bytes: &[u8],
aad_bytes: &[u8],
in_out: &[u8],
in_prefix_len: usize,
open: Open,
) where
Open: for<'a> Fn(
&'static aead::Algorithm,
&[u8],
Nonce,
aead::Aad<&[u8]>,
&'a mut [u8],
RangeFrom<usize>,
) -> Result<&'a mut [u8], error::Unspecified>,
{
let mut in_out = Vec::from(in_out);
let mut nonce_bytes = Vec::from(nonce_bytes);
nonce_bytes[NONCE_LEN - 1] ^= 0x80;
let aad_bytes = Vec::from(aad_bytes);
let nonce = Nonce::try_assume_unique_for_key(&nonce_bytes).unwrap();
let aad = aead::Aad::from(aad_bytes.as_slice());
let err_result = open(
aead_alg,
key_bytes,
nonce,
aad,
&mut in_out,
in_prefix_len..,
);
assert!(err_result.is_err());
}
fn aead_open_bad_aad<Open>(
aead_alg: &'static aead::Algorithm,
key_bytes: &[u8],
nonce_bytes: &[u8],
aad_bytes: &[u8],
in_out: &[u8],
in_prefix_len: usize,
open: Open,
) where
Open: for<'a> Fn(
&'static aead::Algorithm,
&[u8],
Nonce,
aead::Aad<&[u8]>,
&'a mut [u8],
RangeFrom<usize>,
) -> Result<&'a mut [u8], error::Unspecified>,
{
let mut in_out = Vec::from(in_out);
let nonce_bytes = Vec::from(nonce_bytes);
let mut aad_bytes = Vec::from(aad_bytes);
let aad_len = aad_bytes.len();
if aad_len == 0 {
aad_bytes.push(0x08);
} else {
aad_bytes[aad_len - 1] ^= 0x08;
}
let nonce = Nonce::try_assume_unique_for_key(&nonce_bytes).unwrap();
let aad = aead::Aad::from(aad_bytes.as_slice());
let err_result = open(
aead_alg,
key_bytes,
nonce,
aad,
&mut in_out,
in_prefix_len..,
);
assert!(err_result.is_err());
}
fn seal_with_key(
algorithm: &'static aead::Algorithm,
key: &[u8],
nonce: aead::Nonce,
aad: aead::Aad<&[u8]>,
in_out: &mut Vec<u8>,
) -> Result<(), error::Unspecified> {
let mut s_key: aead::SealingKey<OneNonceSequence> = make_key(algorithm, key, nonce);
s_key.seal_in_place_append_tag(aad, in_out)
}
fn open_with_key<'a>(
algorithm: &'static aead::Algorithm,
key: &[u8],
nonce: Nonce,
aad: aead::Aad<&[u8]>,
in_out: &'a mut [u8],
ciphertext_and_tag: RangeFrom<usize>,
) -> Result<&'a mut [u8], error::Unspecified> {
let mut o_key: aead::OpeningKey<OneNonceSequence> = make_key(algorithm, key, nonce);
o_key.open_within(aad, in_out, ciphertext_and_tag)
}
fn seal_with_less_safe_key(
algorithm: &'static aead::Algorithm,
key: &[u8],
nonce: Nonce,
aad: aead::Aad<&[u8]>,
in_out: &mut Vec<u8>,
) -> Result<(), error::Unspecified> {
let key = make_less_safe_key(algorithm, key);
key.seal_in_place_append_tag(nonce, aad, in_out)
}
fn open_with_less_safe_key<'a>(
algorithm: &'static aead::Algorithm,
key: &[u8],
nonce: aead::Nonce,
aad: aead::Aad<&[u8]>,
in_out: &'a mut [u8],
ciphertext_and_tag: RangeFrom<usize>,
) -> Result<&'a mut [u8], error::Unspecified> {
let key = make_less_safe_key(algorithm, key);
key.open_within(nonce, aad, in_out, ciphertext_and_tag)
}
#[allow(clippy::range_plus_one)]
fn test_aead_key_sizes(aead_alg: &'static aead::Algorithm) {
let key_len = aead_alg.key_len();
let key_data = vec![1u8; key_len * 2];
assert!(aead::UnboundKey::new(aead_alg, &key_data[..key_len]).is_ok());
assert!(aead::UnboundKey::new(aead_alg, &key_data[..(key_len - 1)]).is_err());
assert!(aead::UnboundKey::new(aead_alg, &key_data[..(key_len + 1)]).is_err());
assert!(aead::UnboundKey::new(aead_alg, &key_data[..(key_len / 2)]).is_err());
assert!(aead::UnboundKey::new(aead_alg, &key_data[..(key_len * 2)]).is_err());
assert!(aead::UnboundKey::new(aead_alg, &[]).is_err());
assert!(aead::UnboundKey::new(aead_alg, &[0]).is_err());
}
#[allow(clippy::range_plus_one)]
#[test]
fn test_aead_nonce_sizes() {
let nonce_len = aead::NONCE_LEN;
let nonce = vec![0u8; nonce_len * 2];
assert!(aead::Nonce::try_assume_unique_for_key(&nonce[..nonce_len]).is_ok());
assert!(aead::Nonce::try_assume_unique_for_key(&nonce[..(nonce_len - 1)]).is_err());
assert!(aead::Nonce::try_assume_unique_for_key(&nonce[..(nonce_len + 1)]).is_err());
assert!(aead::Nonce::try_assume_unique_for_key(&nonce[..(nonce_len / 2)]).is_err());
assert!(aead::Nonce::try_assume_unique_for_key(&nonce[..(nonce_len * 2)]).is_err());
assert!(aead::Nonce::try_assume_unique_for_key(&[]).is_err());
assert!(aead::Nonce::try_assume_unique_for_key(&nonce[..1]).is_err());
assert!(aead::Nonce::try_assume_unique_for_key(&nonce[..16]).is_err()); }
#[allow(clippy::range_plus_one, clippy::cast_possible_truncation)]
#[test]
fn aead_chacha20_poly1305_openssh() {
test::run(
test_file!("data/aead_chacha20_poly1305_openssh_tests.txt"),
|section, test_case| {
assert_eq!(section, "");
let key_bytes = {
let as_vec = test_case.consume_bytes("KEY");
let mut as_array = [0u8; aead::chacha20_poly1305_openssh::KEY_LEN];
as_array.copy_from_slice(&as_vec);
as_array
};
let sequence_number = test_case.consume_usize("SEQUENCE_NUMBER");
assert_eq!(sequence_number as u32 as usize, sequence_number);
let sequence_num = sequence_number as u32;
let plaintext = test_case.consume_bytes("IN");
let ct = test_case.consume_bytes("CT");
let expected_tag = test_case.consume_bytes("TAG");
let mut tag = [0u8; aead::chacha20_poly1305_openssh::TAG_LEN];
let mut s_in_out = plaintext.clone();
let s_key = aead::chacha20_poly1305_openssh::SealingKey::new(&key_bytes);
s_key.seal_in_place(sequence_num, &mut s_in_out[..], &mut tag);
assert_eq!(&ct, &s_in_out);
assert_eq!(&expected_tag, &tag);
let o_key = aead::chacha20_poly1305_openssh::OpeningKey::new(&key_bytes);
{
let mut cipher_text_clone = Vec::from(&s_in_out[..]);
let mut tag_clone = [0u8; aead::chacha20_poly1305_openssh::TAG_LEN];
tag_clone.copy_from_slice(&tag);
tag_clone[0] = 1;
let o_result =
o_key.open_in_place(sequence_num, &mut cipher_text_clone[..], &tag_clone);
assert!(o_result.is_err());
}
{
let mut cipher_text_clone = Vec::from(&s_in_out[..]);
let o_result = o_key.open_in_place(
sequence_num.checked_add(1).unwrap(),
&mut cipher_text_clone[..],
&tag,
);
assert!(o_result.is_err());
}
{
let o_result = o_key.open_in_place(sequence_num, &mut s_in_out[..], &tag);
assert_eq!(o_result, Ok(&plaintext[4..]));
}
assert_eq!(&s_in_out[..4], &ct[..4]);
assert_eq!(&s_in_out[4..], &plaintext[4..]);
Ok(())
},
);
}
#[test]
fn test_aead_traits() {
test::compile_time_assert_send::<aead::Tag>();
test::compile_time_assert_sync::<aead::Tag>();
test::compile_time_assert_send::<aead::UnboundKey>();
test::compile_time_assert_sync::<aead::UnboundKey>();
test::compile_time_assert_send::<aead::LessSafeKey>();
test::compile_time_assert_sync::<aead::LessSafeKey>();
}
#[test]
fn test_aead_thread_safeness() {
lazy_static::lazy_static! {
static ref SECRET_KEY: aead::LessSafeKey = aead::LessSafeKey::new(
aead::UnboundKey::new(&aead::AES_128_GCM, b"this is a test! ").unwrap(),
);
}
use std::thread;
let tag = SECRET_KEY
.seal_in_place_separate_tag(
aead::Nonce::try_assume_unique_for_key(&[0; aead::NONCE_LEN]).unwrap(),
aead::Aad::empty(),
&mut [],
)
.unwrap();
let mut join_handles = Vec::new();
for _ in 1..100 {
let join_handle = thread::spawn(|| {
SECRET_KEY
.seal_in_place_separate_tag(
aead::Nonce::try_assume_unique_for_key(&[0; aead::NONCE_LEN]).unwrap(),
aead::Aad::empty(),
&mut [],
)
.unwrap()
});
join_handles.push(join_handle);
}
for handle in join_handles {
let thread_tag = handle.join().unwrap();
assert_eq!(thread_tag.as_ref(), tag.as_ref());
}
}
#[test]
fn test_aead_key_debug() {
let key_bytes = [0; 32];
let nonce = [0; aead::NONCE_LEN];
let key = aead::UnboundKey::new(&aead::AES_256_GCM, &key_bytes).unwrap();
assert_eq!("UnboundKey { algorithm: AES_256_GCM }", format!("{key:?}"));
let sealing_key: aead::SealingKey<OneNonceSequence> = make_key(
&aead::AES_256_GCM,
&key_bytes,
aead::Nonce::try_assume_unique_for_key(&nonce).unwrap(),
);
assert_eq!(
"SealingKey { algorithm: AES_256_GCM }",
format!("{sealing_key:?}")
);
let opening_key: aead::OpeningKey<OneNonceSequence> = make_key(
&aead::AES_256_GCM,
&key_bytes,
aead::Nonce::try_assume_unique_for_key(&nonce).unwrap(),
);
assert_eq!(
"OpeningKey { algorithm: AES_256_GCM }",
format!("{opening_key:?}")
);
let key: aead::LessSafeKey = make_less_safe_key(&aead::AES_256_GCM, &key_bytes);
assert_eq!("LessSafeKey { algorithm: AES_256_GCM }", format!("{key:?}"));
}
#[test]
#[allow(clippy::unit_cmp)]
fn rustls_bug() {
const KEY: &[u8] = &[
239, 90, 253, 140, 117, 97, 1, 139, 56, 128, 152, 217, 106, 97, 87, 101, 79, 81, 29, 233,
96, 98, 201, 110, 206, 250, 122, 166, 21, 134, 58, 249,
];
const NONCE: [u8; 12] = [43, 177, 114, 110, 129, 186, 1, 92, 12, 167, 248, 103];
const AAD: &[u8] = &[0, 0, 0, 0, 0, 0, 0, 0, 22, 3, 3, 0, 16];
const DATA: &[u8; 16] = &[
20, 0, 0, 12, 92, 94, 146, 70, 164, 130, 7, 112, 227, 239, 243, 228,
];
fn append(v: &mut Vec<u8>, extra: &[u8], data: &[u8], tag: &[u8]) {
v.extend_from_slice(extra);
v.extend_from_slice(data);
v.extend_from_slice(tag);
}
let uk = aead::UnboundKey::new(&aead::AES_256_GCM, KEY).unwrap();
let ring_uk = ring::aead::UnboundKey::new(&ring::aead::AES_256_GCM, KEY).unwrap();
let lsk = aead::LessSafeKey::new(uk);
let ring_lsk = ring::aead::LessSafeKey::new(ring_uk);
let mut enc_data: Vec<u8> = vec![];
enc_data.extend_from_slice(&DATA[..]);
let tag = lsk
.seal_in_place_separate_tag(
aead::Nonce::assume_unique_for_key(NONCE),
aead::Aad::from(AAD),
&mut enc_data,
)
.unwrap();
let mut ring_enc_data: Vec<u8> = vec![];
ring_enc_data.extend_from_slice(&DATA[..]);
let ring_tag = ring_lsk
.seal_in_place_separate_tag(
ring::aead::Nonce::assume_unique_for_key(NONCE),
ring::aead::Aad::from(AAD),
&mut ring_enc_data,
)
.unwrap();
assert_eq!(ring_tag.as_ref(), tag.as_ref());
assert_eq!(ring_enc_data.as_slice(), enc_data.as_slice());
let prefix_bytes: &[u8] = &NONCE[4..];
let mut enc_data_tag_vec: Vec<u8> = vec![];
append(&mut enc_data_tag_vec, prefix_bytes, &enc_data, tag.as_ref());
let mut ring_enc_data_tag_vec: Vec<u8> = vec![];
append(
&mut ring_enc_data_tag_vec,
prefix_bytes,
&ring_enc_data,
ring_tag.as_ref(),
);
assert_eq!(ring_enc_data_tag_vec, enc_data_tag_vec);
let len = lsk
.open_within(
aead::Nonce::assume_unique_for_key(NONCE),
aead::Aad::from(AAD),
&mut enc_data_tag_vec[..],
prefix_bytes.len()..,
)
.unwrap()
.len();
let ring_len = ring_lsk
.open_within(
ring::aead::Nonce::assume_unique_for_key(NONCE),
ring::aead::Aad::from(AAD),
&mut ring_enc_data_tag_vec[..],
prefix_bytes.len()..,
)
.unwrap()
.len();
assert_eq!(
ring_enc_data_tag_vec.truncate(ring_len),
enc_data_tag_vec.truncate(len)
);
}
fn make_key<K: aead::BoundKey<OneNonceSequence>>(
algorithm: &'static aead::Algorithm,
key: &[u8],
nonce: aead::Nonce,
) -> K {
let key = aead::UnboundKey::new(algorithm, key).unwrap();
let nonce_sequence = OneNonceSequence::new(nonce);
K::new(key, nonce_sequence)
}
fn make_less_safe_key(algorithm: &'static aead::Algorithm, key: &[u8]) -> aead::LessSafeKey {
let key = aead::UnboundKey::new(algorithm, key).unwrap();
aead::LessSafeKey::new(key)
}
struct OneNonceSequence(Option<aead::Nonce>);
impl OneNonceSequence {
fn new(nonce: aead::Nonce) -> Self {
Self(Some(nonce))
}
}
impl aead::NonceSequence for OneNonceSequence {
fn advance(&mut self) -> Result<aead::Nonce, error::Unspecified> {
self.0.take().ok_or(error::Unspecified)
}
}