Skip to content

Feature/update to draft 03 #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 28, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -10,7 +10,7 @@ authors = [
"Richard Haehne <[email protected]>",
]

description = "pure rust implementation of SFrame draft-ietf-sframe-enc-01"
description = "pure rust implementation of SFrame draft-ietf-sframe-enc-03"
repository = "https://github.com/goto-opensource/sframe-rs"
documentation = "https://docs.rs/sframe/"
readme = "README.md"
@@ -45,6 +45,7 @@ rand = "0.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
strum_macros = "0.25"
test-case = "3.1.0"

[features]
default = ["ring"]
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -8,29 +8,29 @@ Secure Frame (SFrame)
![maintenance](https://img.shields.io/maintenance/yes/2023)


This library is an implementation of [draft-ietf-sframe-enc-latest](https://sframe-wg.github.io/sframe/draft-ietf-sframe-enc.html) and provides and end-to-end encryption mechanism for media frames that is suited for WebRTC conferences.
This library is an implementation of [draft-ietf-sframe-enc-03](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-03) and provides and end-to-end encryption mechanism for media frames that is suited for WebRTC conferences.
It is in it's current form a subset of the specification.
There is an alternative implementation under [goto-opensource/secure-frame-ts](https://github.com/goto-opensource/secure-frame-ts)

## Differences from the sframe draft
* ratcheting is not implemented
* keyIds are used as senderIds
* no metadata authentication
* no metadata authentication

## Supported crypto libraries
Currently two crypto libraries are supported:
- [ring](https://crates.io/crates/ring)
- [ring](https://crates.io/crates/ring)
- is enabled per default with the feature `ring`
- supports compilation to Wasm32
- Aes-CTR mode ciphers are not supported
- [openssl](https://crates.io/crates/openssl)
- is enabled with the feature `openssl`
- To build e.g. use `cargo build --features openssl --no-default-features`
- uses rust bindings to OpenSSL.
- Per default the OpenSSL library is locally compiled and then statically linked. The build process requires a C compiler, `perl` (and `perl-core`), and `make`. For further options see the [openssl crate documentation](https://docs.rs/openssl/0.10.55/openssl/).
- Per default the OpenSSL library is locally compiled and then statically linked. The build process requires a C compiler, `perl` (and `perl-core`), and `make`. For further options see the [openssl crate documentation](https://docs.rs/openssl/0.10.55/openssl/).
- Compilation to Wasm32 is [not yet supported](https://github.com/sfackler/rust-openssl/issues/1016)

Both cannot be enabled at the same time, thus on conflict `sframe` issues a compiler error.
Both cannot be enabled at the same time, thus on conflict `sframe` issues a compiler error.
## License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.

@@ -39,4 +39,4 @@ Unless you explicitly state otherwise, any contribution intentionally submitted
## Contribution
Any help in form of descriptive and friendly issues or comprehensive pull requests are welcome!

The Changelog of this library is generated from its commit log, there any commit message must conform with https://www.conventionalcommits.org/en/v1.0.0/. For simplicity you could make your commits with convco.
The Changelog of this library is generated from its commit log, there any commit message must conform with https://www.conventionalcommits.org/en/v1.0.0/. For simplicity you could make your commits with convco.
6 changes: 6 additions & 0 deletions benches/crypto.rs
Original file line number Diff line number Diff line change
@@ -108,6 +108,12 @@ fn crypto_benches(c: &mut Criterion) {
for variant in [
CipherSuiteVariant::AesGcm128Sha256,
CipherSuiteVariant::AesGcm256Sha512,
#[cfg(feature = "openssl")]
CipherSuiteVariant::AesCtr128HmacSha256_80,
#[cfg(feature = "openssl")]
CipherSuiteVariant::AesCtr128HmacSha256_64,
#[cfg(feature = "openssl")]
CipherSuiteVariant::AesCtr128HmacSha256_32,
] {
let mut ctx = CryptoBenches::from(variant);
ctx.run_benches(c);
248 changes: 99 additions & 149 deletions src/crypto/aead.rs
Original file line number Diff line number Diff line change
@@ -34,167 +34,117 @@ pub trait AeadDecrypt {
#[cfg(test)]
mod test {

mod aes_gcm {
use crate::{
crypto::{
aead::AeadEncrypt,
cipher_suite::{CipherSuite, CipherSuiteVariant},
key_expansion::KeyExpansion,
secret::Secret,
},
header::{Header, HeaderFields},
};
use rand::{thread_rng, Rng};
const KEY_MATERIAL: &str = "THIS_IS_RANDOM";

#[test]
fn encrypt_random_frame() {
let mut data = vec![0u8; 1024];
thread_rng().fill(data.as_mut_slice());
let header = Header::default();
let cipher_suite = CipherSuite::from(CipherSuiteVariant::AesGcm256Sha512);
let secret = Secret::expand_from(&cipher_suite, KEY_MATERIAL.as_bytes()).unwrap();

let _tag = cipher_suite
.encrypt(
&mut data,
&secret,
&Vec::from(&header),
header.frame_count(),
)
.unwrap();
}
use crate::crypto::key_derivation::KeyDerivation;
use crate::header::{FrameCount, KeyId};
use crate::test_vectors::{get_sframe_test_vector, SframeTest};
use crate::util::test::assert_bytes_eq;
use crate::{
crypto::{
aead::AeadDecrypt,
aead::AeadEncrypt,
cipher_suite::{CipherSuite, CipherSuiteVariant},
secret::Secret,
},
header::{Header, HeaderFields},
};

use test_case::test_case;

use rand::{thread_rng, Rng};

const KEY_MATERIAL: &str = "THIS_IS_RANDOM";

#[test]
fn encrypt_random_frame() {
let mut data = vec![0u8; 1024];
thread_rng().fill(data.as_mut_slice());
let header = Header::default();
let cipher_suite = CipherSuite::from(CipherSuiteVariant::AesGcm256Sha512);
let secret =
Secret::expand_from(&cipher_suite, KEY_MATERIAL.as_bytes(), KeyId::default()).unwrap();

let _tag = cipher_suite
.encrypt(
&mut data,
&secret,
&Vec::from(&header),
header.frame_count(),
)
.unwrap();
}

mod test_vectors {

use crate::crypto::key_expansion::KeyExpansion;
use crate::test_vectors::{get_test_vector, TestVector};

use crate::{
crypto::{
aead::{AeadDecrypt, AeadEncrypt},
cipher_suite::{CipherSuite, CipherSuiteVariant},
secret::Secret,
},
header::{FrameCount, Header, HeaderFields, KeyId},
util::test::assert_bytes_eq,
};

fn encrypt_test_vector(variant: CipherSuiteVariant) {
let test_vector = get_test_vector(&variant.to_string());
let cipher_suite = CipherSuite::from(variant);

let secret = prepare_secret(&cipher_suite, test_vector);

for enc in &test_vector.encryptions {
let mut data = test_vector.plain_text.clone();
let header = Header::with_frame_count(
KeyId::from(enc.key_id),
FrameCount::from(enc.frame_count),
);
let header_buffer = Vec::from(&header);
let tag = cipher_suite
.encrypt(&mut data, &secret, &header_buffer, header.frame_count())
.unwrap();
let full_frame: Vec<u8> = header_buffer
.into_iter()
.chain(data.into_iter())
.chain(tag.as_ref().iter().cloned())
.collect();

assert_bytes_eq(&full_frame, &enc.cipher_text);
}
}
#[test_case(CipherSuiteVariant::AesGcm128Sha256; "AesGcm128Sha256")]
#[test_case(CipherSuiteVariant::AesGcm256Sha512; "AesGcm256Sha512")]
#[cfg_attr(feature = "openssl", test_case(CipherSuiteVariant::AesCtr128HmacSha256_80; "AesCtr128HmacSha256_80"))]
#[cfg_attr(feature = "openssl", test_case(CipherSuiteVariant::AesCtr128HmacSha256_64; "AesCtr128HmacSha256_64"))]
#[cfg_attr(feature = "openssl", test_case(CipherSuiteVariant::AesCtr128HmacSha256_32; "AesCtr128HmacSha256_32"))]
fn encrypt_test_vector(variant: CipherSuiteVariant) {
let test_vec = get_sframe_test_vector(&variant.to_string());
let cipher_suite = CipherSuite::from(variant);

fn decrypt_test_vector(variant: CipherSuiteVariant) {
let test_vector = get_test_vector(&variant.to_string());
let cipher_suite = CipherSuite::from(variant);
let secret = prepare_secret(&cipher_suite, test_vec);

let secret = prepare_secret(&cipher_suite, test_vector);
let mut data_buffer = test_vec.plain_text.clone();

for enc in &test_vector.encryptions {
let header = Header::with_frame_count(
KeyId::from(enc.key_id),
FrameCount::from(enc.frame_count),
);
let header_buffer = Vec::from(&header);
let mut data = Vec::from(&enc.cipher_text[header.size()..]);
let header = Header::with_frame_count(
KeyId::from(test_vec.key_id),
FrameCount::from(test_vec.frame_count),
);
let header_buffer = Vec::from(&header);

let decrypted = cipher_suite
.decrypt(&mut data, &secret, &header_buffer, header.frame_count())
.unwrap();
let aad_buffer = [header_buffer.as_slice(), test_vec.metadata.as_slice()].concat();

assert_bytes_eq(decrypted, &test_vector.plain_text);
}
}
let tag = cipher_suite
.encrypt(&mut data_buffer, &secret, &aad_buffer, header.frame_count())
.unwrap();

fn prepare_secret(cipher_suite: &CipherSuite, test_vector: &TestVector) -> Secret {
if cipher_suite.is_ctr_mode() {
Secret::expand_from(cipher_suite, &test_vector.key_material).unwrap()
} else {
Secret::from_test_vector(test_vector)
}
}
let full_frame: Vec<u8> = header_buffer
.into_iter()
.chain(data_buffer)
.chain(tag.as_ref().iter().cloned())
.collect();

#[test]
fn encrypt_test_vector_aes_gcm_128_sha256() {
encrypt_test_vector(CipherSuiteVariant::AesGcm128Sha256);
}
assert_bytes_eq(&aad_buffer, &test_vec.aad);
assert_bytes_eq(&full_frame, &test_vec.cipher_text);
}

#[test]
fn should_decrypt_test_vector_aes_gcm_128_sha256() {
decrypt_test_vector(CipherSuiteVariant::AesGcm128Sha256);
}
#[test_case(CipherSuiteVariant::AesGcm128Sha256; "AesGcm128Sha256")]
#[test_case(CipherSuiteVariant::AesGcm256Sha512; "AesGcm256Sha512")]
#[cfg_attr(feature = "openssl", test_case(CipherSuiteVariant::AesCtr128HmacSha256_80; "AesCtr128HmacSha256_80"))]
#[cfg_attr(feature = "openssl", test_case(CipherSuiteVariant::AesCtr128HmacSha256_64; "AesCtr128HmacSha256_64"))]
#[cfg_attr(feature = "openssl", test_case(CipherSuiteVariant::AesCtr128HmacSha256_32; "AesCtr128HmacSha256_32"))]
fn decrypt_test_vector(variant: CipherSuiteVariant) {
let test_vec = get_sframe_test_vector(&variant.to_string());
let cipher_suite = CipherSuite::from(variant);

#[test]
fn encrypt_test_vectors_aes_gcm_256_sha512() {
encrypt_test_vector(CipherSuiteVariant::AesGcm256Sha512);
}
let secret = prepare_secret(&cipher_suite, test_vec);
let header = Header::with_frame_count(
KeyId::from(test_vec.key_id),
FrameCount::from(test_vec.frame_count),
);
let header_buffer = Vec::from(&header);

#[test]
fn should_decrypt_test_vectors_aes_gcm_256_sha512() {
decrypt_test_vector(CipherSuiteVariant::AesGcm256Sha512);
}
let aad_buffer = [header_buffer.as_slice(), test_vec.metadata.as_slice()].concat();
assert_bytes_eq(&aad_buffer, &test_vec.aad);

let mut data = Vec::from(&test_vec.cipher_text[header.size()..]);

let decrypted = cipher_suite
.decrypt(&mut data, &secret, &aad_buffer, header.frame_count())
.unwrap();

assert_bytes_eq(decrypted, &test_vec.plain_text);
}

#[cfg(feature = "openssl")]
mod aes_ctr {
use crate::CipherSuiteVariant;

use super::{decrypt_test_vector, encrypt_test_vector};

#[test]
fn should_encrypt_test_vectors_aes_ctr_64_hmac_sha256_64() {
encrypt_test_vector(CipherSuiteVariant::AesCtr128HmacSha256_64);
}

#[test]
fn should_decrypt_test_vectors_aes_ctr_64_hmac_sha256_64() {
decrypt_test_vector(CipherSuiteVariant::AesCtr128HmacSha256_64);
}

#[test]
fn should_encrypt_test_vectors_aes_ctr_64_hmac_sha256_32() {
encrypt_test_vector(CipherSuiteVariant::AesCtr128HmacSha256_32);
}

#[test]
fn should_decrypt_test_vectors_aes_ctr_64_hmac_sha256_32() {
decrypt_test_vector(CipherSuiteVariant::AesCtr128HmacSha256_32);
}

#[test]
// AesCtr128HmacSha256_80 is not available in the test vectors
#[ignore]
fn should_encrypt_test_vectors_aes_ctr_64_hmac_sha256_80() {
encrypt_test_vector(CipherSuiteVariant::AesCtr128HmacSha256_32);
}

#[test]
// AesCtr128HmacSha256_80 is not available in the test vectors
#[ignore]
fn should_decrypt_test_vectors_aes_ctr_64_hmac_sha256_80() {
decrypt_test_vector(CipherSuiteVariant::AesCtr128HmacSha256_32);
}
fn prepare_secret(cipher_suite: &CipherSuite, test_vec: &SframeTest) -> Secret {
if cipher_suite.is_ctr_mode() {
// the test vectors do not provide the auth key, so we have to expand here
Secret::expand_from(cipher_suite, &test_vec.key_material, test_vec.key_id).unwrap()
} else {
Secret {
key: test_vec.sframe_key.clone(),
salt: test_vec.sframe_salt.clone(),
auth: None,
}
}
}
2 changes: 1 addition & 1 deletion src/crypto/cipher_suite.rs
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@

/// Depicts which AEAD algorithm is used for encryption
/// and which hashing function is used for the key expansion,
/// see [sframe draft 00 4.4](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-01#name-ciphersuites)
/// see [sframe draft 03 4.4](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-03#name-cipher-suites)
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(test, derive(strum_macros::Display))]
pub enum CipherSuiteVariant {
114 changes: 114 additions & 0 deletions src/crypto/key_derivation.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Copyright (c) 2023 GoTo Group, Inc
// SPDX-License-Identifier: Apache-2.0 AND MIT

use super::{cipher_suite::CipherSuite, secret::Secret};
use crate::error::Result;

pub trait KeyDerivation {
fn expand_from<M, K>(cipher_suite: &CipherSuite, key_material: M, key_id: K) -> Result<Secret>
where
M: AsRef<[u8]>,
K: Into<u64>;
}

pub fn get_hkdf_key_expand_info(key_id: u64) -> Vec<u8> {
[
SFRAME_LABEL,
SFRAME_HKDF_KEY_EXPAND_INFO,
&key_id.to_be_bytes(),
]
.concat()
}

pub fn get_hkdf_salt_expand_info(key_id: u64) -> Vec<u8> {
[
SFRAME_LABEL,
SFRAME_HDKF_SALT_EXPAND_INFO,
&key_id.to_be_bytes(),
]
.concat()
}

const SFRAME_LABEL: &[u8] = b"SFrame 1.0 ";

const SFRAME_HKDF_KEY_EXPAND_INFO: &[u8] = b"Secret key ";
const SFRAME_HDKF_SALT_EXPAND_INFO: &[u8] = b"Secret salt ";

cfg_if::cfg_if! {
if #[cfg(feature = "openssl")] {
pub fn get_hkdf_aead_label(tag_len: usize) -> Vec<u8> {
// for current platforms there is no issue casting from usize to u64
[SFRAME_HDKF_SUB_AEAD_LABEL, &(tag_len).to_be_bytes()].concat()
}

pub const SFRAME_HDKF_SUB_AEAD_LABEL: &[u8] = b"SFrame 1.0 AES CTR AEAD ";
pub const SFRAME_HKDF_SUB_ENC_EXPAND_INFO: &[u8] = b"enc";
pub const SFRAME_HDKF_SUB_AUTH_EXPAND_INFO: &[u8] = b"auth";
}
}

#[cfg(test)]
mod test {
use super::KeyDerivation;
use crate::crypto::cipher_suite::CipherSuite;
use crate::crypto::secret::Secret;
use crate::test_vectors::get_sframe_test_vector;
use crate::{crypto::cipher_suite::CipherSuiteVariant, util::test::assert_bytes_eq};

mod aes_gcm {
use crate::crypto::key_derivation::{get_hkdf_key_expand_info, get_hkdf_salt_expand_info};

use super::*;

use test_case::test_case;

#[test_case(CipherSuiteVariant::AesGcm128Sha256; "AesGcm128Sha256")]
#[test_case(CipherSuiteVariant::AesGcm256Sha512; "AesGcm256Sha512")]

fn derive_correct_base_keys(variant: CipherSuiteVariant) {
let test_vec = get_sframe_test_vector(&variant.to_string());

assert_bytes_eq(
&get_hkdf_key_expand_info(test_vec.key_id),
&test_vec.sframe_key_label,
);
assert_bytes_eq(
&get_hkdf_salt_expand_info(test_vec.key_id),
&test_vec.sframe_salt_label,
);

let secret = Secret::expand_from(
&CipherSuite::from(variant),
&test_vec.key_material,
test_vec.key_id,
)
.unwrap();

assert_bytes_eq(&secret.key, &test_vec.sframe_key);
assert_bytes_eq(&secret.salt, &test_vec.sframe_salt);
}
}

#[cfg(feature = "openssl")]
mod aes_ctr {
use super::*;
use test_case::test_case;

#[test_case(CipherSuiteVariant::AesCtr128HmacSha256_80; "AesCtr128HmacSha256_80")]
#[test_case(CipherSuiteVariant::AesCtr128HmacSha256_64; "AesCtr128HmacSha256_64")]
#[test_case(CipherSuiteVariant::AesCtr128HmacSha256_32; "AesCtr128HmacSha256_32")]
fn derive_correct_sub_keys(variant: CipherSuiteVariant) {
let test_vec = get_sframe_test_vector(&variant.to_string());
let cipher_suite = CipherSuite::from(variant);

let secret =
Secret::expand_from(&cipher_suite, &test_vec.key_material, test_vec.key_id)
.unwrap();

assert_bytes_eq(&secret.salt, &test_vec.sframe_salt);
// the subkeys stored in secret.key and secret.auth are not included in the test vectors
assert_eq!(secret.auth.unwrap().len(), cipher_suite.hash_len);
assert_eq!(secret.key.len(), cipher_suite.key_len);
}
}
}
85 changes: 0 additions & 85 deletions src/crypto/key_expansion.rs

This file was deleted.

2 changes: 1 addition & 1 deletion src/crypto/mod.rs
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@

pub mod aead;
pub mod cipher_suite;
pub mod key_expansion;
pub mod key_derivation;
pub mod secret;

cfg_if::cfg_if! {
12 changes: 7 additions & 5 deletions src/crypto/openssl/aead.rs
Original file line number Diff line number Diff line change
@@ -190,11 +190,13 @@ impl CipherSuite {
let mut signer = openssl::sign::Signer::new(openssl::hash::MessageDigest::sha256(), &key)?;

// for current platforms there is no issue casting from usize to u64
let aad_len = (aad.len() as u64).to_be_bytes();
let ct_len = (encrypted.len() as u64).to_be_bytes();
for buf in [&aad_len, &ct_len, nonce, aad, encrypted] {
signer.update(buf)?;
}
signer.update(&(aad.len() as u64).to_be_bytes())?;
signer.update(&(encrypted.len() as u64).to_be_bytes())?;
signer.update(&(self.auth_tag_len as u64).to_be_bytes())?;
signer.update(nonce)?;
signer.update(aad)?;
signer.update(encrypted)?;

let mut tag = signer.sign_to_vec()?;
tag.resize(self.auth_tag_len, 0);

Original file line number Diff line number Diff line change
@@ -4,23 +4,24 @@
use crate::{
crypto::{
cipher_suite::{CipherSuite, CipherSuiteVariant},
key_expansion::{
KeyExpansion, SFRAME_HDKF_SALT_EXPAND_INFO, SFRAME_HDKF_SUB_AUTH_EXPAND_INFO,
SFRAME_HKDF_KEY_EXPAND_INFO, SFRAME_HKDF_SALT, SFRAME_HKDF_SUB_ENC_EXPAND_INFO,
SFRAME_HKDF_SUB_SALT,
key_derivation::{
get_hkdf_aead_label, get_hkdf_key_expand_info, get_hkdf_salt_expand_info,
KeyDerivation, SFRAME_HDKF_SUB_AUTH_EXPAND_INFO, SFRAME_HKDF_SUB_ENC_EXPAND_INFO,
},
secret::Secret,
},
error::{Result, SframeError},
};

impl KeyExpansion for Secret {
fn expand_from<T>(cipher_suite: &CipherSuite, key_material: T) -> Result<Secret>
impl KeyDerivation for Secret {
fn expand_from<M, K>(cipher_suite: &CipherSuite, key_material: M, key_id: K) -> Result<Secret>
where
T: AsRef<[u8]>,
M: AsRef<[u8]>,
K: Into<u64>,
{
let try_expand = || {
let (base_key, salt) = expand_secret(cipher_suite, key_material.as_ref())?;
let (base_key, salt) =
expand_secret(cipher_suite, key_material.as_ref(), key_id.into())?;
let (key, auth) = if cipher_suite.is_ctr_mode() {
let (key, auth) = expand_subsecret(cipher_suite, &base_key)?;
(key, Some(auth))
@@ -31,25 +32,27 @@ impl KeyExpansion for Secret {
Ok(Secret { key, salt, auth })
};

try_expand().map_err(|_: openssl::error::ErrorStack| SframeError::KeyExpansion)
try_expand().map_err(|_: openssl::error::ErrorStack| SframeError::KeyDerivation)
}
}

fn expand_secret(
cipher_suite: &CipherSuite,
key_material: &[u8],
key_id: u64,
) -> std::result::Result<(Vec<u8>, Vec<u8>), openssl::error::ErrorStack> {
let prk = extract_prk(cipher_suite, key_material, SFRAME_HKDF_SALT)?;
// No salt used for the extraction: https://www.ietf.org/archive/id/draft-ietf-sframe-enc-03.html#name-key-derivation
let prk = extract_pseudo_random_key(cipher_suite, key_material, b"")?;
let key = expand_key(
cipher_suite,
&prk,
SFRAME_HKDF_KEY_EXPAND_INFO,
&get_hkdf_key_expand_info(key_id),
cipher_suite.key_len,
)?;
let salt = expand_key(
cipher_suite,
&prk,
SFRAME_HDKF_SALT_EXPAND_INFO,
&get_hkdf_salt_expand_info(key_id),
cipher_suite.nonce_len,
)?;

@@ -60,7 +63,8 @@ fn expand_subsecret(
cipher_suite: &CipherSuite,
key: &[u8],
) -> std::result::Result<(Vec<u8>, Vec<u8>), openssl::error::ErrorStack> {
let prk = extract_prk(cipher_suite, key, SFRAME_HKDF_SUB_SALT)?;
let salt = get_hkdf_aead_label(cipher_suite.auth_tag_len);
let prk = extract_pseudo_random_key(cipher_suite, key, &salt)?;
let key = expand_key(
cipher_suite,
&prk,
@@ -77,7 +81,7 @@ fn expand_subsecret(
Ok((key, auth))
}

fn extract_prk(
fn extract_pseudo_random_key(
cipher_suite: &CipherSuite,
key_material: &[u8],
salt: &[u8],
@@ -135,3 +139,29 @@ impl From<CipherSuiteVariant> for &'static openssl::md::MdRef {
}
}
}
#[cfg(test)]
mod test {

use super::*;
use crate::{test_vectors::get_aes_ctr_test_vector, util::test::assert_bytes_eq};

use test_case::test_case;

#[test_case(CipherSuiteVariant::AesCtr128HmacSha256_80; "AesCtr128HmacSha256_80")]
#[test_case(CipherSuiteVariant::AesCtr128HmacSha256_64; "AesCtr128HmacSha256_64")]
#[test_case(CipherSuiteVariant::AesCtr128HmacSha256_32; "AesCtr128HmacSha256_32")]
fn derive_correct_sub_keys(variant: CipherSuiteVariant) {
let test_vec = get_aes_ctr_test_vector(&variant.to_string());
let cipher_suite = CipherSuite::from(variant);

let aead_salt = get_hkdf_aead_label(cipher_suite.auth_tag_len);
assert_bytes_eq(&aead_salt, &test_vec.aead_label);

let prk = extract_pseudo_random_key(&cipher_suite, &test_vec.base_key, &aead_salt).unwrap();
assert_bytes_eq(&prk, &test_vec.aead_secret);

let (key, auth) = expand_subsecret(&cipher_suite, &test_vec.base_key).unwrap();
assert_bytes_eq(&key, &test_vec.enc_key);
assert_bytes_eq(&auth, &test_vec.auth_key);
}
}
2 changes: 1 addition & 1 deletion src/crypto/openssl/mod.rs
Original file line number Diff line number Diff line change
@@ -2,5 +2,5 @@
// SPDX-License-Identifier: Apache-2.0 AND MIT

pub mod aead;
pub mod key_expansion;
pub mod key_derivation;
pub mod tag;
2 changes: 1 addition & 1 deletion src/crypto/ring/aead.rs
Original file line number Diff line number Diff line change
@@ -47,7 +47,7 @@ impl From<CipherSuiteVariant> for &'static ring::aead::Algorithm {
impl CipherSuite {
fn unbound_encryption_key(&self, secret: &Secret) -> Result<ring::aead::UnboundKey> {
ring::aead::UnboundKey::new(self.variant.into(), secret.key.as_slice())
.map_err(|_| SframeError::KeyExpansion)
.map_err(|_| SframeError::KeyDerivation)
}
}

Original file line number Diff line number Diff line change
@@ -4,25 +4,34 @@
use crate::{
crypto::{
cipher_suite::{CipherSuite, CipherSuiteVariant},
key_expansion::{
KeyExpansion, SFRAME_HDKF_SALT_EXPAND_INFO, SFRAME_HKDF_KEY_EXPAND_INFO,
SFRAME_HKDF_SALT,
},
key_derivation::{get_hkdf_key_expand_info, get_hkdf_salt_expand_info, KeyDerivation},
secret::Secret,
},
error::{Result, SframeError},
};

impl KeyExpansion for Secret {
fn expand_from<T>(cipher_suite: &CipherSuite, key_material: T) -> Result<Secret>
impl KeyDerivation for Secret {
fn expand_from<M, K>(cipher_suite: &CipherSuite, key_material: M, key_id: K) -> Result<Secret>
where
T: AsRef<[u8]>,
M: AsRef<[u8]>,
K: Into<u64>,
{
let key_id = key_id.into();
let algorithm = cipher_suite.variant.into();
let prk = ring::hkdf::Salt::new(algorithm, SFRAME_HKDF_SALT).extract(key_material.as_ref());
// No salt used for the extraction: https://www.ietf.org/archive/id/draft-ietf-sframe-enc-03.html#name-key-derivation
let pseudo_random_key =
ring::hkdf::Salt::new(algorithm, b"").extract(key_material.as_ref());

let key = expand_key(&prk, SFRAME_HKDF_KEY_EXPAND_INFO, cipher_suite.key_len)?;
let salt = expand_key(&prk, SFRAME_HDKF_SALT_EXPAND_INFO, cipher_suite.nonce_len)?;
let key = expand_key(
&pseudo_random_key,
&get_hkdf_key_expand_info(key_id),
cipher_suite.key_len,
)?;
let salt = expand_key(
&pseudo_random_key,
&get_hkdf_salt_expand_info(key_id),
cipher_suite.nonce_len,
)?;

Ok(Secret {
key,
@@ -54,7 +63,7 @@ fn expand_key(prk: &ring::hkdf::Prk, info: &[u8], key_len: usize) -> Result<Vec<

prk.expand(&[info], OkmKeyLength(key_len))
.and_then(|okm| okm.fill(sframe_key.as_mut_slice()))
.map_err(|_| SframeError::KeyExpansion)?;
.map_err(|_| SframeError::KeyDerivation)?;

Ok(sframe_key)
}
2 changes: 1 addition & 1 deletion src/crypto/ring/mod.rs
Original file line number Diff line number Diff line change
@@ -2,4 +2,4 @@
// SPDX-License-Identifier: Apache-2.0 AND MIT

pub mod aead;
pub mod key_expansion;
pub mod key_derivation;
48 changes: 17 additions & 31 deletions src/crypto/secret.rs
Original file line number Diff line number Diff line change
@@ -20,48 +20,34 @@ impl Secret {

iv
}

#[cfg(test)]
pub(crate) fn from_test_vector(test_vector: &crate::test_vectors::TestVector) -> Secret {
Secret {
key: test_vector.key.clone(),
salt: test_vector.salt.clone(),
auth: None,
}
}
}

#[cfg(test)]
mod test {
use crate::crypto::cipher_suite::CipherSuite;
use crate::crypto::key_expansion::KeyExpansion;
use crate::test_vectors::get_test_vector;

use crate::test_vectors::get_sframe_test_vector;
use crate::{
crypto::cipher_suite::CipherSuiteVariant, header::FrameCount, util::test::assert_bytes_eq,
};

use super::Secret;

use test_case::test_case;
const NONCE_LEN: usize = 12;

fn test_nonce(variant: CipherSuiteVariant) {
let tv = get_test_vector(&variant.to_string());

for enc in &tv.encryptions {
let secret =
Secret::expand_from(&CipherSuite::from(variant), &tv.key_material).unwrap();
let nonce: [u8; NONCE_LEN] = secret.create_nonce(&FrameCount::from(enc.frame_count));
assert_bytes_eq(&nonce, &enc.nonce);
}
}
#[test_case(CipherSuiteVariant::AesGcm128Sha256; "AesGcm128Sha256")]
#[test_case(CipherSuiteVariant::AesGcm256Sha512; "AesGcm256Sha512")]
#[cfg_attr(feature = "openssl", test_case(CipherSuiteVariant::AesCtr128HmacSha256_80; "AesCtr128HmacSha256_80"))]
#[cfg_attr(feature = "openssl", test_case(CipherSuiteVariant::AesCtr128HmacSha256_64; "AesCtr128HmacSha256_64"))]
#[cfg_attr(feature = "openssl", test_case(CipherSuiteVariant::AesCtr128HmacSha256_32; "AesCtr128HmacSha256_32"))]
fn create_correct_nonce(variant: CipherSuiteVariant) {
let test_vec = get_sframe_test_vector(&variant.to_string());

let secret = Secret {
key: test_vec.sframe_key.clone(),
salt: test_vec.sframe_salt.clone(),
auth: None,
};

#[test]
fn create_correct_nonce_aes_gcm_128_sha256() {
test_nonce(CipherSuiteVariant::AesGcm128Sha256);
}
#[test]
fn create_correct_nonce_aes_gcm_256_sha512() {
test_nonce(CipherSuiteVariant::AesGcm256Sha512);
let nonce: [u8; NONCE_LEN] = secret.create_nonce(&FrameCount::from(test_vec.frame_count));
assert_bytes_eq(&nonce, &test_vec.nonce);
}
}
2 changes: 1 addition & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
@@ -27,7 +27,7 @@ pub enum SframeError {

/// Could not expand encryption key for [`Sender`] or decryption key for [`Receiver`] with HKDF
#[error("Unable to create unbound encryption key")]
KeyExpansion,
KeyDerivation,

/// frame validation failed in the [`Receiver`] before decryption
#[error("{0}")]
2 changes: 1 addition & 1 deletion src/header/basic_header.rs
Original file line number Diff line number Diff line change
@@ -11,7 +11,7 @@ use super::{
};

bitfield! {
/// Modeled after [sframe draft 00 4.2](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-01#name-sframe-header)
/// Modeled after [sframe draft 03 4.3](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-03#name-sframe-header)
/// ```txt
/// 0 1 2 3 4 5 6 7
/// +-+-+-+-+-+-+-+-+---------------------------------+
2 changes: 1 addition & 1 deletion src/header/extended_header.rs
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ use super::{
};

bitfield! {
/// Modeled after [sframe draft 00 4.2](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-01#name-sframe-header)
/// Modeled after [sframe draft 03 4.3](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-03#name-sframe-header)
/// ```txt
/// 0 1 2 3 4 5 6 7
/// +-+-+-+-+-+-+-+-+---------------------------+---------------------------+
17 changes: 7 additions & 10 deletions src/header/mod.rs
Original file line number Diff line number Diff line change
@@ -44,7 +44,7 @@ pub trait HeaderFields {
}

/// Sframe header with a KID with a length of up to 3bits
/// modeled after [sframe draft 00 4.2](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-01#name-sframe-header)
/// modeled after [sframe draft 03 4.3](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-03#name-sframe-header)
/// ```txt
/// 0 1 2 3 4 5 6 7
/// +-+-+-+-+-+-+-+-+---------------------------------+
@@ -73,7 +73,7 @@ impl BasicHeader {
}
}
/// Extended sframe header with a KID with a length of up to 8 bytes
/// modeled after [sframe draft 00 4.2](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-01#name-sframe-header)
/// modeled after [sframe draft 03 4.3](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-03#name-sframe-header)
/// ```txt
/// 0 1 2 3 4 5 6 7
/// +-+-+-+-+-+-+-+-+---------------------------+---------------------------+
@@ -102,7 +102,7 @@ impl ExtendedHeader {
}

#[derive(Copy, Clone, Debug)]
/// Represents an Sframe header modeled after [sframe draft 00 4.2](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-01#name-sframe-header)
/// Represents an Sframe header modeled after [sframe draft 03 4.3](https://datatracker.ietf.org/doc/html/draft-ietf-sframe-enc-03#name-sframe-header)
/// containing the key id of the sender (KID) and the current frame count (CTR).
/// There are two variants, either with a KID represented by 3 bits (Basic) and an extended version with a KID of up to 8 bytes (Extended).
/// The CTR field has a variable length of up to 8 bytes where the size is represented with LEN. Here LEN=0 represents a length of 1.
@@ -218,7 +218,6 @@ mod test {
use super::{frame_count::FrameCount, keyid::KeyId, Header};
use crate::header::{Deserialization, HeaderFields};
use crate::util::test::assert_bytes_eq;
use crate::CipherSuiteVariant::{AesGcm128Sha256, AesGcm256Sha512};

use pretty_assertions::assert_eq;

@@ -254,25 +253,23 @@ mod test {

#[test]
fn serialize_test_vectors() {
crate::test_vectors::get_test_vector(&AesGcm128Sha256.to_string())
.encryptions
crate::test_vectors::get_header_test_vectors()
.iter()
.for_each(|test_vector| {
let header = Header::with_frame_count(
KeyId::from(test_vector.key_id),
FrameCount::from(test_vector.frame_count),
);
assert_bytes_eq(Vec::from(&header).as_slice(), &test_vector.header);
assert_bytes_eq(Vec::from(&header).as_slice(), &test_vector.encoded);
});
}

#[test]
fn deserialize_test_vectors() {
crate::test_vectors::get_test_vector(&AesGcm256Sha512.to_string())
.encryptions
crate::test_vectors::get_header_test_vectors()
.iter()
.for_each(|test_vector| {
let header = Header::deserialize(&test_vector.header).unwrap();
let header = Header::deserialize(&test_vector.encoded).unwrap();
assert_eq!(header.key_id(), KeyId::from(test_vector.key_id));
assert_eq!(header.frame_count(), test_vector.frame_count);
});
7 changes: 4 additions & 3 deletions src/receiver.rs
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ use crate::{
crypto::{
aead::AeadDecrypt,
cipher_suite::{CipherSuite, CipherSuiteVariant},
key_expansion::KeyExpansion,
key_derivation::KeyDerivation,
secret::Secret,
},
error::{Result, SframeError},
@@ -107,9 +107,10 @@ impl Receiver {
Id: Into<KeyId>,
KeyMaterial: AsRef<[u8]> + ?Sized,
{
let key_id = key_id.into();
self.secrets.insert(
key_id.into(),
Secret::expand_from(&self.options.cipher_suite, key_material)?,
key_id,
Secret::expand_from(&self.options.cipher_suite, key_material, key_id)?,
);
Ok(())
}
71 changes: 6 additions & 65 deletions src/sender.rs
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@ use crate::{
crypto::{
aead::AeadEncrypt,
cipher_suite::{CipherSuite, CipherSuiteVariant},
key_expansion::KeyExpansion,
key_derivation::KeyDerivation,
secret::Secret,
},
error::{Result, SframeError},
@@ -108,74 +108,15 @@ impl Sender {
where
KeyMaterial: AsRef<[u8]> + ?Sized,
{
self.secret = Some(Secret::expand_from(&self.cipher_suite, key_material)?);
self.secret = Some(Secret::expand_from(
&self.cipher_suite,
key_material,
self.key_id,
)?);
Ok(())
}
}

#[cfg(test)]
mod test_on_wire_format {
use super::*;
use crate::receiver::Receiver;

fn hex(hex_str: &str) -> Vec<u8> {
hex::decode(hex_str).unwrap()
}

const KEY_ID: u8 = 0;

#[test]
fn deadbeef_decrypt() {
let material = hex("1234567890123456789012345678901212345678901234567890123456789012");
let mut sender = Sender::new(KEY_ID);
let mut receiver = Receiver::default();

sender.set_encryption_key(&material).unwrap();
receiver.set_encryption_key(KEY_ID, &material).unwrap();

let encrypted = sender.encrypt(&hex("deadbeafcacadebaca00"), 4).unwrap();
let decrypted = receiver.decrypt(encrypted, 4).unwrap();

assert_eq!(decrypted, hex("deadbeafcacadebaca00"));
}

#[test]
fn deadbeef_on_wire() {
let material = hex("1234567890123456789012345678901212345678901234567890123456789012");
let mut sender = Sender::new(KEY_ID);
let mut receiver = Receiver::default();

sender.set_encryption_key(&material).unwrap();
receiver.set_encryption_key(KEY_ID, &material).unwrap();

let encrypted = sender.encrypt(&hex("deadbeafcacadebaca00"), 4).unwrap();

assert_eq!(
hex::encode(encrypted),
"deadbeaf0000a160a9176ba4ce7ca128df74907d422e5064d1c23529"
);
}

#[test]
fn deadbeef_on_wire_long() {
let material = hex("1234567890123456789012345678901212345678901234567890123456789012");
let mut sender = Sender::new(KEY_ID);
let mut receiver = Receiver::default();

sender.set_encryption_key(&material).unwrap();
receiver.set_encryption_key(KEY_ID, &material).unwrap();

let encrypted = sender
.encrypt(&hex("deadbeafcacadebacacacadebacacacadebaca00"), 4)
.unwrap();

assert_eq!(
hex::encode(encrypted),
"deadbeaf0000a160a9176b6ebe53f594a64faa1f48a5246b202d13416bf671b3edae7704a862"
);
}
}

#[cfg(test)]
mod test {
use super::*;
131 changes: 112 additions & 19 deletions src/test_vectors/mod.rs
Original file line number Diff line number Diff line change
@@ -5,63 +5,140 @@
extern crate serde;
use phf::phf_map;

pub fn get_test_vector(cipher_suite_variant: &str) -> &'static TestVector {
#[derive(serde::Deserialize, Debug, Clone)]
pub struct TestVectors {
pub header: Vec<HeaderTest>,
pub aes_ctr_hmac: Vec<AesCtrHmacTest>,
pub sframe: Vec<SframeTest>,
}

pub fn get_header_test_vectors() -> &'static Vec<HeaderTest> {
&TEST_VECTORS.header
}

pub fn get_aes_ctr_test_vector(cipher_suite_variant: &str) -> &'static AesCtrHmacTest {
TEST_VECTORS
.aes_ctr_hmac
.iter()
.find(|v| v.cipher_suite_variant == cipher_suite_variant)
.unwrap()
}

pub fn get_sframe_test_vector(cipher_suite_variant: &str) -> &'static SframeTest {
TEST_VECTORS
.sframe
.iter()
.find(|v| v.cipher_suite_variant == cipher_suite_variant)
.unwrap()
}

const TEST_VECTORS_STR: &str = std::include_str!("test-vectors.json");
lazy_static::lazy_static! {
static ref TEST_VECTORS: Vec<TestVector> = {
static ref TEST_VECTORS: TestVectors = {
parse_test_vectors()
};
}

const CIPHER_SUITE_NAME_FROM_ID: phf::Map<u8, &str> = phf_map! {
// AesCtr128HmacSha256_80 is not included in the test vectors
1u8 => "AesCtr128HmacSha256_32",
1u8 => "AesCtr128HmacSha256_80",
2u8 => "AesCtr128HmacSha256_64",
3u8 => "AesGcm128Sha256",
4u8 => "AesGcm256Sha512",
3u8 => "AesCtr128HmacSha256_32",
4u8 => "AesGcm128Sha256",
5u8 => "AesGcm256Sha512",
};

#[derive(serde::Deserialize, Debug, Clone)]
pub struct EncryptionTestCase {
pub struct HeaderTest {
#[serde(rename = "kid")]
pub key_id: u64,
#[serde(rename = "ctr")]
pub frame_count: u64,
#[serde(deserialize_with = "vec_from_hex_str")]
pub header: Vec<u8>,
pub encoded: Vec<u8>,
}

#[derive(serde::Deserialize, Debug, Clone)]
pub struct AesCtrHmacTest {
#[serde(
rename = "cipher_suite",
deserialize_with = "cipher_suite_name_from_id"
)]
pub cipher_suite_variant: String,

#[serde(rename = "key", deserialize_with = "vec_from_hex_str")]
pub base_key: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub aead_label: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub aead_secret: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub enc_key: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub auth_key: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub nonce: Vec<u8>,
#[serde(rename = "ciphertext", deserialize_with = "vec_from_hex_str")]

#[serde(deserialize_with = "vec_from_hex_str")]
pub aad: Vec<u8>,

#[serde(rename = "pt", deserialize_with = "vec_from_hex_str")]
pub plain_text: Vec<u8>,

#[serde(rename = "ct", deserialize_with = "vec_from_hex_str")]
pub cipher_text: Vec<u8>,
}

#[derive(serde::Deserialize, Debug, Clone)]
pub struct TestVector {
pub struct SframeTest {
#[serde(
rename = "cipher_suite",
deserialize_with = "cipher_suite_name_from_id"
)]
pub cipher_suite_variant: String,

#[serde(rename = "kid")]
pub key_id: u64,

#[serde(rename = "ctr")]
pub frame_count: u64,

#[serde(rename = "base_key", deserialize_with = "vec_from_hex_str")]
pub key_material: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub key: Vec<u8>,
pub sframe_key_label: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub sframe_salt_label: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub sframe_secret: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub sframe_key: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub salt: Vec<u8>,
pub sframe_salt: Vec<u8>,

#[serde(rename = "plaintext", deserialize_with = "vec_from_hex_str")]
#[serde(deserialize_with = "vec_from_hex_str")]
pub metadata: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub nonce: Vec<u8>,

#[serde(deserialize_with = "vec_from_hex_str")]
pub aad: Vec<u8>,

#[serde(rename = "pt", deserialize_with = "vec_from_hex_str")]
pub plain_text: Vec<u8>,

pub encryptions: Vec<EncryptionTestCase>,
#[serde(rename = "ct", deserialize_with = "vec_from_hex_str")]
pub cipher_text: Vec<u8>,
}

fn vec_from_hex_str<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
@@ -88,20 +165,36 @@ where
}
}

fn parse_test_vectors() -> Vec<TestVector> {
fn parse_test_vectors() -> TestVectors {
serde_json::from_str(TEST_VECTORS_STR).unwrap()
}

#[cfg(test)]
mod test {
use super::{get_test_vector, CIPHER_SUITE_NAME_FROM_ID};
use crate::test_vectors::{get_aes_ctr_test_vector, get_sframe_test_vector};

use super::{get_header_test_vectors, CIPHER_SUITE_NAME_FROM_ID};

#[test]
fn should_parse_header_test_vectors() {
let header_tests = get_header_test_vectors();
assert_ne!(header_tests.len(), 0);
}
#[test]
fn should_parse_test_vectors() {
fn should_parse_sframe_test_vectors() {
let valid_cipher_suite_variants = CIPHER_SUITE_NAME_FROM_ID.values();
for &variant in valid_cipher_suite_variants {
let vector = get_test_vector(variant);
assert_eq!(vector.cipher_suite_variant, variant);
let sframe_test = get_sframe_test_vector(variant);
assert_eq!(sframe_test.cipher_suite_variant, variant);
}
}

#[test]
fn should_parse_aes_test_vectors() {
for cipher_suite_id in 1..=3u8 {
let &variant = CIPHER_SUITE_NAME_FROM_ID.get(&cipher_suite_id).unwrap();
let aes_ctr_test = get_aes_ctr_test_vector(variant);
assert_eq!(aes_ctr_test.cipher_suite_variant, variant);
}
}
}
1,803 changes: 1,569 additions & 234 deletions src/test_vectors/test-vectors.json

Large diffs are not rendered by default.