General improvements (#250)

* Remove unnecessary constraints on hash

* Remove unnecessary `Result` on `KeyPair::generate_random`

* Fix de-serialization issue on `Ke1State`

* Fix rustfmt

* Remove allocations in `envelope`

* Run Clippy for tests and rustdoc lints too

* Fix `Debug` implementation

* Fix missing constraints on `ClientRegistration`

* Fix de-serialization

* Pin temporary dependency

* Update dependencies

* Replace macro with derive-where

* Remove unnecessary installation of Rust components

* Improve macro naming

* Implement `Copy`, `Debug`, `Ord` and `PartialOrd` for high-level items

* Add `rust-version` field to `Cargo.toml`

* Remove unnecessary allocations

* Fix MSRV

* Fix no_std

* Remove unnecessary allocations

* Remove unnecessary allocations

* Not importing items from voprf helps readability

* Fix rustdoc

* Remove unnecessary allocations

* Remove unnecessary allocations

* Replace `Vec` from `diffie_hellman` with `GenericArray`

* Remove unnecessary allocations

* Remove unnecessary allocations

* Remove `cfg(feature = bench)` guard for `missing_docs`

* Fix documentation

* Remove all remaining allocations from `KeyExchange`

* Improve type-safety

* Remove all remaining allocations in `keypair`

* Remove last remaining allocations except `NonVerifiableClient` input

* Remove base64 encoding in Serde implementation

* Remove unnecessary Serde `alloc` feature

* Make curve25519-dalek optional

* Rename `serialize` crate feature to `serde`

* Switch `KeGroup` implementations to higher-level libraries

- Fixes missing clamping in X25519
- X25519 is now a separate crate feature

* Fix typo
This commit is contained in:
daxpedda
2022-01-03 15:50:40 -08:00
committed by GitHub
parent d59d0b775b
commit 82e4436d39
25 changed files with 3604 additions and 2606 deletions
+151 -27
View File
@@ -6,26 +6,33 @@
// of this source tree.
use crate::errors::ProtocolError;
use alloc::vec::Vec;
use core::marker::PhantomData;
use digest::Update;
use generic_array::{
typenum::{U0, U2},
ArrayLength, GenericArray,
};
use hmac::Mac;
// Corresponds to the I2OSP() function from RFC8017
pub(crate) fn i2osp(input: usize, length: usize) -> Result<alloc::vec::Vec<u8>, ProtocolError> {
let sizeof_usize = core::mem::size_of::<usize>();
pub(crate) fn i2osp<L: ArrayLength<u8>>(
input: usize,
) -> Result<GenericArray<u8, L>, ProtocolError> {
const SIZEOF_USIZE: usize = core::mem::size_of::<usize>();
// Check if input >= 256^length
if (sizeof_usize as u32 - input.leading_zeros() / 8) > length as u32 {
if (SIZEOF_USIZE as u32 - input.leading_zeros() / 8) > L::U32 {
return Err(ProtocolError::SerializationError);
}
if length <= sizeof_usize {
return Ok((&input.to_be_bytes()[sizeof_usize - length..]).to_vec());
if L::USIZE <= SIZEOF_USIZE {
return Ok(GenericArray::clone_from_slice(
&input.to_be_bytes()[SIZEOF_USIZE - L::USIZE..],
));
}
let mut output = alloc::vec![0u8; length];
output.splice(
length - sizeof_usize..length,
input.to_be_bytes().iter().cloned(),
);
let mut output = GenericArray::default();
output[L::USIZE - SIZEOF_USIZE..L::USIZE].copy_from_slice(&input.to_be_bytes());
Ok(output)
}
@@ -40,17 +47,94 @@ pub(crate) fn os2ip(input: &[u8]) -> Result<usize, ProtocolError> {
Ok(usize::from_be_bytes(output_array))
}
// Computes I2OSP(len(input), max_bytes) || input
pub(crate) fn serialize(input: &[u8], max_bytes: usize) -> Result<Vec<u8>, ProtocolError> {
Ok([&i2osp(input.len(), max_bytes)?, input].concat())
/// Computes `I2OSP(len(input), max_bytes) || input` and helps hold output without allocation.
pub(crate) struct Serialize<
'a,
L1: ArrayLength<u8>,
L2: ArrayLength<u8> = U0,
L3: ArrayLength<u8> = U0,
> {
octet: GenericArray<u8, L1>,
input: Input<'a, L2, L3>,
}
enum Input<'a, L1: ArrayLength<u8>, L2: ArrayLength<u8>> {
Owned(GenericArray<u8, L1>),
Borrowed(&'a [u8]),
Label(([&'a [u8]; 2], PhantomData<L2>)),
}
impl<'a, L1: ArrayLength<u8>, L2: ArrayLength<u8>, L3: ArrayLength<u8>> Serialize<'a, L1, L2, L3> {
// Variation of `serialize` that takes a borrowed `input
pub(crate) fn from(input: &'a [u8]) -> Result<Serialize<'a, L1, L2>, ProtocolError> {
Ok(Serialize {
octet: i2osp::<L1>(input.len())?,
input: Input::Borrowed(input),
})
}
// Variation of `serialize` that takes an owned `input`
pub(crate) fn from_owned(
input: GenericArray<u8, L2>,
) -> Result<Serialize<'a, L1, L2>, ProtocolError> {
Ok(Serialize {
octet: i2osp::<L1>(input.len())?,
input: Input::Owned(input),
})
}
// Variation of `serialize` that takes a label
pub(crate) fn from_label(
opaque: &'a [u8],
label: &'a [u8],
) -> Result<Serialize<'a, L1, U0, U2>, ProtocolError> {
Ok(Serialize {
octet: i2osp::<L1>(opaque.len() + label.len())?,
input: Input::Label(([opaque, label], PhantomData)),
})
}
pub(crate) fn iter(&self) -> impl Iterator<Item = &[u8]> {
// Some magic to make it output the same type in all branches.
Some(self.octet.as_slice())
.into_iter()
.chain(match &self.input {
Input::Owned(bytes) => Some(bytes.as_slice()),
Input::Borrowed(bytes) => Some(*bytes),
Input::Label(_) => None,
})
.chain(if let Input::Label((iter, _)) = &self.input {
Some(iter[0]).into_iter().chain(Some(iter[1]).into_iter())
} else {
None.into_iter().chain(None)
})
}
}
impl<'a, L1: ArrayLength<u8>, L2: ArrayLength<u8>> Serialize<'a, L1, L2, U0> {
pub(crate) fn to_array_2(&self) -> [&[u8]; 2] {
let input = match &self.input {
Input::Borrowed(value) => value,
Input::Owned(value) => value.as_slice(),
_ => unreachable!("unexpected `Serialize` constructed with wrong generics"),
};
[self.octet.as_slice(), input]
}
}
impl<'a, L1: ArrayLength<u8>, L2: ArrayLength<u8>> Serialize<'a, L1, L2, U2> {
pub(crate) fn to_array_3(&self) -> [&[u8]; 3] {
match self.input {
Input::Label((label, _)) => [self.octet.as_slice(), label[0], label[1]],
_ => unreachable!("unexpected `Serialize` constructed with wrong generics"),
}
}
}
// Tokenizes an input of the format I2OSP(len(input), max_bytes) || input, outputting
// (input, remainder)
pub(crate) fn tokenize(
input: &[u8],
size_bytes: usize,
) -> Result<(Vec<u8>, Vec<u8>), ProtocolError> {
pub(crate) fn tokenize(input: &[u8], size_bytes: usize) -> Result<(&[u8], &[u8]), ProtocolError> {
if size_bytes > core::mem::size_of::<usize>() || input.len() < size_bytes {
return Err(ProtocolError::SerializationError);
}
@@ -61,29 +145,69 @@ pub(crate) fn tokenize(
}
Ok((
input[size_bytes..size_bytes + size].to_vec(),
input[size_bytes + size..].to_vec(),
&input[size_bytes..size_bytes + size],
&input[size_bytes + size..],
))
}
pub(crate) trait UpdateExt {
fn chain_iter<'a>(self, iter: impl Iterator<Item = &'a [u8]>) -> Self;
}
impl<T: Update> UpdateExt for T {
fn chain_iter<'a>(self, iter: impl Iterator<Item = &'a [u8]>) -> Self {
let mut self_ = self;
for bytes in iter {
self_ = self_.chain(bytes);
}
self_
}
}
pub(crate) trait MacExt {
fn update_iter<'a>(&mut self, iter: impl Iterator<Item = &'a [u8]>);
}
impl<T: Mac> MacExt for T {
fn update_iter<'a>(&mut self, iter: impl Iterator<Item = &'a [u8]>) {
for bytes in iter {
self.update(bytes);
}
}
}
/// The purpose of this macro is to simplify [`concat`](alloc::slice::Concat::concat)ing
/// slices into an [`Iterator`] to avoid allocation
macro_rules! chain {
(
$item1:expr,
$($item2:expr),+$(,)?
) => {
$item1$(.chain($item2))+
};
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod unit_tests {
use super::*;
use generic_array::typenum::{U1, U2};
// Test the error condition for I2OSP
#[test]
fn test_i2osp_err_check() {
assert!(i2osp(0, 1).is_ok());
assert!(i2osp::<U1>(0).is_ok());
assert!(i2osp(255, 1).is_ok());
assert!(i2osp(256, 1).is_err());
assert!(i2osp(257, 1).is_err());
assert!(i2osp::<U1>(255).is_ok());
assert!(i2osp::<U1>(256).is_err());
assert!(i2osp::<U1>(257).is_err());
assert!(i2osp(256 * 256 - 1, 2).is_ok());
assert!(i2osp(256 * 256, 2).is_err());
assert!(i2osp(256 * 256 + 1, 2).is_err());
assert!(i2osp::<U2>(256 * 256 - 1).is_ok());
assert!(i2osp::<U2>(256 * 256).is_err());
assert!(i2osp::<U2>(256 * 256 + 1).is_err());
}
}
Regular → Executable
+494 -285
View File
@@ -7,441 +7,650 @@
use crate::{
ciphersuite::CipherSuite,
envelope::{Envelope, InnerEnvelopeMode},
envelope::{Envelope, EnvelopeLen, InnerEnvelopeMode},
errors::*,
key_exchange::{
group::KeGroup,
traits::{Ke1MessageLen, Ke2MessageLen},
},
key_exchange::{
traits::{FromBytes, KeyExchange, ToBytes},
tripledh::{NonceLen, TripleDH},
},
keypair::KeyPair,
serialization::{i2osp, os2ip, serialize},
messages::CredentialResponseWithoutKeLen,
opaque::MaskedResponseLen,
serialization::{i2osp, os2ip, Serialize},
*,
};
#[cfg(test)]
use alloc::vec;
#[cfg(test)]
use alloc::vec::Vec;
use core::ops::Add;
use curve25519_dalek::ristretto::RistrettoPoint;
use generic_array::typenum::Unsigned;
use digest::FixedOutput;
use generic_array::{
typenum::{Sum, Unsigned, U2},
ArrayLength, GenericArray,
};
use proptest::{collection::vec, prelude::*};
use rand::{rngs::OsRng, RngCore};
use voprf::group::Group;
use sha2::Digest;
struct Default;
impl CipherSuite for Default {
type OprfGroup = RistrettoPoint;
type KeGroup = RistrettoPoint;
#[cfg(feature = "ristretto255")]
struct Ristretto255;
#[cfg(feature = "ristretto255")]
impl CipherSuite for Ristretto255 {
type OprfGroup = curve25519_dalek::ristretto::RistrettoPoint;
type KeGroup = curve25519_dalek::ristretto::RistrettoPoint;
type KeyExchange = TripleDH;
type Hash = sha2::Sha512;
type SlowHash = crate::slow_hash::NoOpHash;
}
const HASH_SIZE: usize = 64; // Because of SHA512
const MAC_SIZE: usize = 64; // Because of SHA512
#[cfg(feature = "p256")]
struct P256;
#[cfg(feature = "p256")]
impl CipherSuite for P256 {
type OprfGroup = p256_::ProjectivePoint;
type KeGroup = p256_::PublicKey;
type KeyExchange = TripleDH;
type Hash = sha2::Sha256;
type SlowHash = crate::slow_hash::NoOpHash;
}
fn random_ristretto_point() -> RistrettoPoint {
fn random_point<CS: CipherSuite>() -> CS::KeGroup {
let mut rng = OsRng;
let mut random_bits = [0u8; 64];
rng.fill_bytes(&mut random_bits);
// This is because RistrettoPoint is on an obsolete sha2 version
let mut bits = [0u8; 64];
let mut hasher = sha2::Sha512::new();
hasher.update(&random_bits[..]);
bits.copy_from_slice(&hasher.finalize());
RistrettoPoint::from_uniform_bytes(&bits)
let sk = CS::KeGroup::random_sk(&mut rng);
CS::KeGroup::public_key(&sk)
}
#[test]
fn client_registration_roundtrip() -> Result<(), ProtocolError> {
let pw = b"hunter2";
let mut rng = OsRng;
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError> {
let pw = b"hunter2";
let mut rng = OsRng;
let blind_result =
&voprf::NonVerifiableClient::<RistrettoPoint, sha2::Sha512>::blind(pw.to_vec(), &mut rng)?;
let blind_result =
&voprf::NonVerifiableClient::<CS::OprfGroup, CS::Hash>::blind(pw.to_vec(), &mut rng)?;
let bytes: Vec<u8> = [
serialize(&blind_result.state.serialize(), 2)?,
serialize(&blind_result.message.serialize(), 2)?,
]
.concat();
let bytes: Vec<u8> = chain!(
Serialize::<U2>::from(&blind_result.state.serialize())?.iter(),
Serialize::<U2>::from(&blind_result.message.serialize())?.iter(),
)
.flatten()
.cloned()
.collect();
let reg = ClientRegistration::<CS>::deserialize(&bytes)?;
let reg_bytes = reg.serialize()?;
assert_eq!(reg_bytes, bytes);
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
let reg = ClientRegistration::<Default>::deserialize(&bytes[..])?;
let reg_bytes = reg.serialize()?;
assert_eq!(reg_bytes, bytes);
Ok(())
}
#[test]
fn server_registration_roundtrip() -> Result<(), ProtocolError> {
// If we don't have envelope and client_pk, the server registration just
// contains the prf key
let mut rng = OsRng;
let mut masking_key = [0u8; HASH_SIZE];
rng.fill_bytes(&mut masking_key);
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError>
where
// Envelope: Nonce + Hash
NonceLen: Add<<CS::Hash as FixedOutput>::OutputSize>,
EnvelopeLen<CS>: ArrayLength<u8>,
// RegistrationUpload: (KePk + Hash) + Envelope
<CS::KeGroup as KeGroup>::PkLen: Add<<CS::Hash as FixedOutput>::OutputSize>,
Sum<<CS::KeGroup as KeGroup>::PkLen, <CS::Hash as FixedOutput>::OutputSize>:
ArrayLength<u8> + Add<EnvelopeLen<CS>>,
RegistrationUploadLen<CS>: ArrayLength<u8>,
// ServerRegistration = RegistrationUpload
{
// If we don't have envelope and client_pk, the server registration just
// contains the prf key
let mut rng = OsRng;
let mut masking_key = GenericArray::<_, <CS::Hash as Digest>::OutputSize>::default();
rng.fill_bytes(&mut masking_key);
// Construct a mock envelope
let mut mock_envelope_bytes = Vec::new();
mock_envelope_bytes.extend_from_slice(&vec![0; NonceLen::USIZE]); // empty nonce
// Construct a mock envelope
let mut mock_envelope_bytes = Vec::new();
mock_envelope_bytes.extend_from_slice(&[0; NonceLen::USIZE]); // empty nonce
// mock_envelope_bytes.extend_from_slice(&ciphertext); // ciphertext which is an encrypted private key
mock_envelope_bytes.extend_from_slice(&[0; MAC_SIZE]); // length-MAC_SIZE hmac
mock_envelope_bytes
.extend_from_slice(&GenericArray::<_, <CS::Hash as Digest>::OutputSize>::default()); // length-MAC_SIZE hmac
let mock_client_kp = KeyPair::<CS::KeGroup>::generate_random(&mut rng);
// serialization order: oprf_key, public key, envelope
let mut bytes = Vec::<u8>::new();
bytes.extend_from_slice(&mock_client_kp.public().to_arr());
bytes.extend_from_slice(&masking_key);
bytes.extend_from_slice(&mock_envelope_bytes);
let reg = ServerRegistration::<CS>::deserialize(&bytes)?;
let reg_bytes = reg.serialize();
assert_eq!(*reg_bytes, bytes);
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
let mock_client_kp = KeyPair::<<Default as CipherSuite>::OprfGroup>::generate_random(&mut rng)?;
// serialization order: oprf_key, public key, envelope
let mut bytes = Vec::<u8>::new();
bytes.extend_from_slice(&mock_client_kp.public().to_arr());
bytes.extend_from_slice(&masking_key);
bytes.extend_from_slice(&mock_envelope_bytes);
let reg = ServerRegistration::<Default>::deserialize(&bytes[..])?;
let reg_bytes = reg.serialize()?;
assert_eq!(reg_bytes, bytes);
Ok(())
}
#[test]
fn registration_request_roundtrip() -> Result<(), ProtocolError> {
let pt = random_ristretto_point();
let pt_bytes = pt.to_arr().to_vec();
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError> {
let pt = random_point::<CS>();
let pt_bytes = pt.to_arr().to_vec();
let mut input = Vec::new();
input.extend_from_slice(pt_bytes.as_slice());
let mut input = Vec::new();
input.extend_from_slice(&pt_bytes);
let r1 = RegistrationRequest::<Default>::deserialize(input.as_slice())?;
let r1_bytes = r1.serialize()?;
assert_eq!(input, r1_bytes);
let r1 = RegistrationRequest::<CS>::deserialize(&input)?;
let r1_bytes = r1.serialize();
assert_eq!(input, *r1_bytes);
// Assert that identity group element is rejected
let identity = RistrettoPoint::identity();
let identity_bytes = identity.to_arr().to_vec();
// Assert that identity group element is rejected
let identity = CS::OprfGroup::identity();
let identity_bytes = identity.to_arr().to_vec();
assert!(
match RegistrationRequest::<Default>::deserialize(identity_bytes.as_slice()) {
assert!(matches!(
RegistrationRequest::<CS>::deserialize(&identity_bytes),
Err(ProtocolError::LibraryError(InternalError::OprfError(
voprf::errors::InternalError::PointError,
))) => true,
_ => false,
}
);
)))
));
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
Ok(())
}
#[test]
fn registration_response_roundtrip() -> Result<(), ProtocolError> {
let pt = random_ristretto_point();
let beta_bytes = pt.to_arr();
let mut rng = OsRng;
let skp = KeyPair::<<Default as CipherSuite>::OprfGroup>::generate_random(&mut rng)?;
let pubkey_bytes = skp.public().to_arr();
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError>
where
// RegistrationResponse: KgPk + KePk
<CS::OprfGroup as Group>::ElemLen: Add<<CS::KeGroup as KeGroup>::PkLen>,
RegistrationResponseLen<CS>: ArrayLength<u8>,
{
let pt = random_point::<CS>();
let beta_bytes = pt.to_arr();
let mut rng = OsRng;
let skp = KeyPair::<CS::KeGroup>::generate_random(&mut rng);
let pubkey_bytes = skp.public().to_arr();
let mut input = Vec::new();
input.extend_from_slice(beta_bytes.as_slice());
input.extend_from_slice(&pubkey_bytes.as_slice());
let mut input = Vec::new();
input.extend_from_slice(&beta_bytes);
input.extend_from_slice(&pubkey_bytes);
let r2 = RegistrationResponse::<Default>::deserialize(input.as_slice())?;
let r2_bytes = r2.serialize()?;
assert_eq!(input, r2_bytes);
let r2 = RegistrationResponse::<CS>::deserialize(&input)?;
let r2_bytes = r2.serialize();
assert_eq!(input, *r2_bytes);
// Assert that identity group element is rejected
let identity = RistrettoPoint::identity();
let identity_bytes = identity.to_arr().to_vec();
// Assert that identity group element is rejected
let identity = CS::OprfGroup::identity();
let identity_bytes = identity.to_arr().to_vec();
assert!(match RegistrationResponse::<Default>::deserialize(
&[identity_bytes, pubkey_bytes.to_vec()].concat()
) {
Err(ProtocolError::LibraryError(InternalError::OprfError(
voprf::errors::InternalError::PointError,
))) => true,
_ => false,
});
assert!(matches!(
RegistrationResponse::<CS>::deserialize(
&[identity_bytes, pubkey_bytes.to_vec()].concat()
),
Err(ProtocolError::LibraryError(InternalError::OprfError(
voprf::errors::InternalError::PointError,
)))
));
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
Ok(())
}
#[test]
fn registration_upload_roundtrip() -> Result<(), ProtocolError> {
let mut rng = OsRng;
let skp = KeyPair::<<Default as CipherSuite>::OprfGroup>::generate_random(&mut rng)?;
let pubkey_bytes = skp.public().to_arr();
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError>
where
// Envelope: Nonce + Hash
NonceLen: Add<<CS::Hash as FixedOutput>::OutputSize>,
EnvelopeLen<CS>: ArrayLength<u8>,
// RegistrationUpload: (KePk + Hash) + Envelope
<CS::KeGroup as KeGroup>::PkLen: Add<<CS::Hash as FixedOutput>::OutputSize>,
Sum<<CS::KeGroup as KeGroup>::PkLen, <CS::Hash as FixedOutput>::OutputSize>:
ArrayLength<u8> + Add<EnvelopeLen<CS>>,
RegistrationUploadLen<CS>: ArrayLength<u8>,
{
let mut rng = OsRng;
let skp = KeyPair::<CS::KeGroup>::generate_random(&mut rng);
let pubkey_bytes = skp.public().to_arr();
let mut key = [0u8; 32];
rng.fill_bytes(&mut key);
let mut nonce = [0u8; 32];
rng.fill_bytes(&mut nonce);
let mut key = [0u8; 32];
rng.fill_bytes(&mut key);
let mut nonce = [0u8; NonceLen::USIZE];
rng.fill_bytes(&mut nonce);
let mut masking_key = vec![0u8; <sha2::Sha512 as Digest>::OutputSize::USIZE];
rng.fill_bytes(&mut masking_key);
let mut masking_key = GenericArray::<_, <CS::Hash as Digest>::OutputSize>::default();
rng.fill_bytes(&mut masking_key);
let randomized_pwd_hasher = hkdf::Hkdf::new(None, &key);
let randomized_pwd_hasher = hkdf::Hkdf::new(None, &key);
let (envelope, _, _) = Envelope::<Default>::seal_raw(
randomized_pwd_hasher,
&nonce,
&pubkey_bytes,
InnerEnvelopeMode::Internal,
)
.unwrap();
let envelope_bytes = envelope.serialize();
let (envelope, _, _) = Envelope::<CS>::seal_raw(
randomized_pwd_hasher,
nonce.into(),
Some(pubkey_bytes.as_slice()).into_iter(),
InnerEnvelopeMode::Internal,
)
.unwrap();
let envelope_bytes = envelope.serialize();
let mut input = Vec::new();
input.extend_from_slice(&pubkey_bytes[..]);
input.extend_from_slice(&masking_key[..]);
input.extend_from_slice(&envelope_bytes);
let mut input = Vec::new();
input.extend_from_slice(&pubkey_bytes);
input.extend_from_slice(&masking_key);
input.extend_from_slice(&envelope_bytes);
let r3 = RegistrationUpload::<Default>::deserialize(&input[..])?;
let r3_bytes = r3.serialize()?;
assert_eq!(input, r3_bytes);
let r3 = RegistrationUpload::<CS>::deserialize(&input)?;
let r3_bytes = r3.serialize();
assert_eq!(input, *r3_bytes);
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
Ok(())
}
#[test]
fn credential_request_roundtrip() -> Result<(), ProtocolError> {
let mut rng = OsRng;
let alpha = random_ristretto_point();
let alpha_bytes = alpha.to_arr().to_vec();
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError>
where
// CredentialRequest: KgPk + Ke1Message
<CS::OprfGroup as Group>::ElemLen: Add<Ke1MessageLen<CS>>,
CredentialRequestLen<CS>: ArrayLength<u8>,
{
let mut rng = OsRng;
let alpha = random_point::<CS>();
let alpha_bytes = alpha.to_arr();
let client_e_kp = KeyPair::<<Default as CipherSuite>::OprfGroup>::generate_random(&mut rng)?;
let mut client_nonce = vec![0u8; NonceLen::USIZE];
rng.fill_bytes(&mut client_nonce);
let client_e_kp = KeyPair::<CS::KeGroup>::generate_random(&mut rng);
let mut client_nonce = [0u8; NonceLen::USIZE];
rng.fill_bytes(&mut client_nonce);
let ke1m: Vec<u8> = [&client_nonce[..], &client_e_kp.public()].concat();
let ke1m: Vec<u8> = [client_nonce.as_ref(), client_e_kp.public()].concat();
let mut input = Vec::new();
input.extend_from_slice(&alpha_bytes);
input.extend_from_slice(&ke1m[..]);
let mut input = Vec::new();
input.extend_from_slice(&alpha_bytes);
input.extend_from_slice(&ke1m);
let l1 = CredentialRequest::<Default>::deserialize(input.as_slice())?;
let l1_bytes = l1.serialize()?;
assert_eq!(input, l1_bytes);
let l1 = CredentialRequest::<CS>::deserialize(&input)?;
let l1_bytes = l1.serialize();
assert_eq!(input, *l1_bytes);
// Assert that identity group element is rejected
let identity = RistrettoPoint::identity();
let identity_bytes = identity.to_arr().to_vec();
// Assert that identity group element is rejected
let identity = CS::OprfGroup::identity();
let identity_bytes = identity.to_arr().to_vec();
assert!(match CredentialRequest::<Default>::deserialize(
&[identity_bytes, ke1m.to_vec()].concat()
) {
Err(ProtocolError::LibraryError(InternalError::OprfError(
voprf::errors::InternalError::PointError,
))) => true,
_ => false,
});
assert!(matches!(
CredentialRequest::<CS>::deserialize(&[identity_bytes, ke1m.to_vec()].concat()),
Err(ProtocolError::LibraryError(InternalError::OprfError(
voprf::errors::InternalError::PointError,
)))
));
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
Ok(())
}
#[test]
fn credential_response_roundtrip() -> Result<(), ProtocolError> {
let pt = random_ristretto_point();
let pt_bytes = pt.to_arr().to_vec();
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError>
where
// CredentialResponseWithoutKeLen: (KgPk + Nonce) + MaskedResponse
<CS::OprfGroup as Group>::ElemLen: Add<NonceLen>,
Sum<<CS::OprfGroup as Group>::ElemLen, NonceLen>:
ArrayLength<u8> + Add<MaskedResponseLen<CS>>,
CredentialResponseWithoutKeLen<CS>: ArrayLength<u8>,
// MaskedResponse: (Nonce + Hash) + KePk
NonceLen: Add<<CS::Hash as FixedOutput>::OutputSize>,
Sum<NonceLen, <CS::Hash as FixedOutput>::OutputSize>:
ArrayLength<u8> + Add<<CS::KeGroup as KeGroup>::PkLen>,
MaskedResponseLen<CS>: ArrayLength<u8>,
// CredentialResponse: CredentialResponseWithoutKeLen + Ke2Message
CredentialResponseWithoutKeLen<CS>: Add<Ke2MessageLen<CS>>,
CredentialResponseLen<CS>: ArrayLength<u8>,
{
let pt = random_point::<CS>();
let pt_bytes = pt.to_arr();
let mut rng = OsRng;
let mut rng = OsRng;
let mut masking_nonce = vec![0u8; 32];
rng.fill_bytes(&mut masking_nonce);
let mut masking_nonce = [0u8; 32];
rng.fill_bytes(&mut masking_nonce);
let mut masked_response =
vec![0u8; <RistrettoPoint as Group>::ElemLen::USIZE + Envelope::<Default>::len()];
rng.fill_bytes(&mut masked_response);
let mut masked_response =
vec![0u8; <CS::OprfGroup as Group>::ElemLen::USIZE + Envelope::<CS>::len()];
rng.fill_bytes(&mut masked_response);
let server_e_kp = KeyPair::<<Default as CipherSuite>::OprfGroup>::generate_random(&mut rng)?;
let mut mac = [0u8; MAC_SIZE];
rng.fill_bytes(&mut mac);
let mut server_nonce = vec![0u8; NonceLen::USIZE];
rng.fill_bytes(&mut server_nonce);
let server_e_kp = KeyPair::<CS::KeGroup>::generate_random(&mut rng);
let mut mac = GenericArray::<_, <CS::Hash as Digest>::OutputSize>::default();
rng.fill_bytes(&mut mac);
let mut server_nonce = [0u8; NonceLen::USIZE];
rng.fill_bytes(&mut server_nonce);
let ke2m: Vec<u8> = [&server_nonce[..], &server_e_kp.public(), &mac[..]].concat();
let ke2m: Vec<u8> = [server_nonce.as_ref(), server_e_kp.public(), &mac].concat();
let mut input = Vec::new();
input.extend_from_slice(pt_bytes.as_slice());
input.extend_from_slice(&masking_nonce);
input.extend_from_slice(&masked_response);
input.extend_from_slice(&ke2m[..]);
let mut input = Vec::new();
input.extend_from_slice(&pt_bytes);
input.extend_from_slice(&masking_nonce);
input.extend_from_slice(&masked_response);
input.extend_from_slice(&ke2m);
let l2 = CredentialResponse::<Default>::deserialize(&input)?;
let l2_bytes = l2.serialize()?;
assert_eq!(input, l2_bytes);
let l2 = CredentialResponse::<CS>::deserialize(&input)?;
let l2_bytes = l2.serialize();
assert_eq!(input, *l2_bytes);
// Assert that identity group element is rejected
let identity = RistrettoPoint::identity();
let identity_bytes = identity.to_arr().to_vec();
// Assert that identity group element is rejected
let identity = CS::OprfGroup::identity();
let identity_bytes = identity.to_arr().to_vec();
assert!(match CredentialResponse::<Default>::deserialize(
&[
identity_bytes,
masking_nonce.to_vec(),
masked_response,
ke2m.to_vec()
]
.concat()
) {
Err(ProtocolError::LibraryError(InternalError::OprfError(
voprf::errors::InternalError::PointError,
))) => true,
_ => false,
});
assert!(matches!(
CredentialResponse::<CS>::deserialize(
&[
identity_bytes,
masking_nonce.to_vec(),
masked_response,
ke2m.to_vec()
]
.concat()
),
Err(ProtocolError::LibraryError(InternalError::OprfError(
voprf::errors::InternalError::PointError,
)))
));
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
Ok(())
}
#[test]
fn credential_finalization_roundtrip() -> Result<(), ProtocolError> {
let mut rng = OsRng;
let mut mac = [0u8; MAC_SIZE];
rng.fill_bytes(&mut mac);
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError> {
let mut rng = OsRng;
let mut mac = GenericArray::<_, <CS::Hash as Digest>::OutputSize>::default();
rng.fill_bytes(&mut mac);
let input: Vec<u8> = [&mac[..]].concat();
let input = mac;
let l3 = CredentialFinalization::<Default>::deserialize(&input)?;
let l3_bytes = l3.serialize()?;
assert_eq!(input, l3_bytes);
let l3 = CredentialFinalization::<CS>::deserialize(&input)?;
let l3_bytes = l3.serialize();
assert_eq!(input.as_slice(), l3_bytes.as_slice());
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
Ok(())
}
#[test]
fn client_login_roundtrip() -> Result<(), ProtocolError> {
let pw = b"hunter2";
let mut rng = OsRng;
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError>
where
// CredentialRequest: KgPk + Ke1Message
<CS::OprfGroup as Group>::ElemLen: Add<Ke1MessageLen<CS>>,
CredentialRequestLen<CS>: ArrayLength<u8>,
{
let pw = b"hunter2";
let mut rng = OsRng;
let client_e_kp = KeyPair::<<Default as CipherSuite>::OprfGroup>::generate_random(&mut rng)?;
let mut client_nonce = vec![0u8; NonceLen::USIZE];
rng.fill_bytes(&mut client_nonce);
let client_e_kp = KeyPair::<CS::KeGroup>::generate_random(&mut rng);
let mut client_nonce = [0; NonceLen::USIZE];
rng.fill_bytes(&mut client_nonce);
let serialized_credential_request = b"serialized credential_request".to_vec();
let l1_data = [client_e_kp.private().to_arr().to_vec(), client_nonce].concat();
let l1_data = [
client_e_kp.private().to_arr().to_vec(),
client_nonce.to_vec(),
]
.concat();
let blind_result =
&voprf::NonVerifiableClient::<RistrettoPoint, sha2::Sha512>::blind(pw.to_vec(), &mut rng)?;
let blind_result =
voprf::NonVerifiableClient::<CS::OprfGroup, CS::Hash>::blind(pw.to_vec(), &mut rng)?;
let credential_request = CredentialRequest::<CS> {
blinded_element: blind_result.message,
ke1_message:
<CS::KeyExchange as KeyExchange<CS::Hash, CS::KeGroup>>::KE1Message::from_bytes(
&[client_nonce.as_ref(), client_e_kp.public()].concat(),
)?,
};
let bytes: Vec<u8> = chain!(
Serialize::<U2>::from(&blind_result.state.serialize())?.iter(),
Serialize::<U2>::from(&credential_request.serialize())?.iter(),
Serialize::<U2>::from(&l1_data)?.iter(),
)
.flatten()
.cloned()
.collect();
let reg = ClientLogin::<CS>::deserialize(&bytes)?;
let reg_bytes = reg.serialize()?;
assert_eq!(reg_bytes, bytes);
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
let bytes: Vec<u8> = [
serialize(&blind_result.state.serialize(), 2)?,
serialize(&serialized_credential_request, 2)?,
serialize(&l1_data, 2)?,
]
.concat();
let reg = ClientLogin::<Default>::deserialize(&bytes[..])?;
let reg_bytes = reg.serialize()?;
assert_eq!(reg_bytes, bytes);
Ok(())
}
#[test]
fn ke1_message_roundtrip() -> Result<(), ProtocolError> {
let mut rng = OsRng;
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError> {
let mut rng = OsRng;
let client_e_kp = KeyPair::<<Default as CipherSuite>::OprfGroup>::generate_random(&mut rng)?;
let mut client_nonce = vec![0u8; NonceLen::USIZE];
rng.fill_bytes(&mut client_nonce);
let client_e_kp = KeyPair::<CS::KeGroup>::generate_random(&mut rng);
let mut client_nonce = vec![0u8; NonceLen::USIZE];
rng.fill_bytes(&mut client_nonce);
let ke1m: Vec<u8> = [&client_nonce[..], &client_e_kp.public()].concat();
let reg = <TripleDH as KeyExchange<sha2::Sha512, RistrettoPoint>>::KE1Message::from_bytes::<
Default,
>(&ke1m[..])?;
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, ke1m);
let ke1m = [client_nonce.as_slice(), client_e_kp.public()].concat();
let reg =
<CS::KeyExchange as KeyExchange<CS::Hash, CS::KeGroup>>::KE1Message::from_bytes(&ke1m)?;
let reg_bytes = reg.to_bytes();
assert_eq!(*reg_bytes, ke1m);
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
Ok(())
}
#[test]
fn ke2_message_roundtrip() -> Result<(), ProtocolError> {
let mut rng = OsRng;
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError> {
let mut rng = OsRng;
let server_e_kp = KeyPair::<<Default as CipherSuite>::OprfGroup>::generate_random(&mut rng)?;
let mut mac = [0u8; MAC_SIZE];
rng.fill_bytes(&mut mac);
let mut server_nonce = vec![0u8; NonceLen::USIZE];
rng.fill_bytes(&mut server_nonce);
let server_e_kp = KeyPair::<CS::KeGroup>::generate_random(&mut rng);
let mut mac = GenericArray::<_, <CS::Hash as Digest>::OutputSize>::default();
rng.fill_bytes(&mut mac);
let mut server_nonce = vec![0u8; NonceLen::USIZE];
rng.fill_bytes(&mut server_nonce);
let ke2m: Vec<u8> = [&server_nonce[..], &server_e_kp.public(), &mac[..]].concat();
let ke2m: Vec<u8> = [server_nonce.as_slice(), server_e_kp.public(), &mac].concat();
let reg = <TripleDH as KeyExchange<sha2::Sha512, RistrettoPoint>>::KE2Message::from_bytes::<
Default,
>(&ke2m[..])?;
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, ke2m);
let reg =
<CS::KeyExchange as KeyExchange<CS::Hash, CS::KeGroup>>::KE2Message::from_bytes(&ke2m)?;
let reg_bytes = reg.to_bytes();
assert_eq!(*reg_bytes, ke2m);
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
Ok(())
}
#[test]
fn ke3_message_roundtrip() -> Result<(), ProtocolError> {
let mut rng = OsRng;
let mut mac = [0u8; MAC_SIZE];
rng.fill_bytes(&mut mac);
fn inner<CS: CipherSuite>() -> Result<(), ProtocolError> {
let mut rng = OsRng;
let mut mac = GenericArray::<_, <CS::Hash as Digest>::OutputSize>::default();
rng.fill_bytes(&mut mac);
let ke3m: Vec<u8> = [&mac[..]].concat();
let ke3m: Vec<u8> = [mac].concat();
let reg = <TripleDH as KeyExchange<sha2::Sha512, RistrettoPoint>>::KE3Message::from_bytes::<
Default,
>(&ke3m[..])?;
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, ke3m);
let reg =
<CS::KeyExchange as KeyExchange<CS::Hash, CS::KeGroup>>::KE3Message::from_bytes(&ke3m)?;
let reg_bytes = reg.to_bytes();
assert_eq!(*reg_bytes, ke3m);
Ok(())
}
#[cfg(feature = "ristretto255")]
inner::<Ristretto255>()?;
#[cfg(feature = "p256")]
inner::<P256>()?;
Ok(())
}
proptest! {
#[test]
fn test_i2osp_os2ip(bytes in vec(any::<u8>(), 0..core::mem::size_of::<usize>())) {
use generic_array::typenum::{U0, U1, U2, U3, U4, U5, U6, U7};
#[test]
fn test_i2osp_os2ip(bytes in vec(any::<u8>(), 0..core::mem::size_of::<usize>())) {
assert_eq!(i2osp(os2ip(&bytes).unwrap(), bytes.len()).unwrap(), bytes);
let input = os2ip(&bytes).unwrap();
let output = match bytes.len() {
0 => i2osp::<U0>(input).unwrap().to_vec(),
1 => i2osp::<U1>(input).unwrap().to_vec(),
2 => i2osp::<U2>(input).unwrap().to_vec(),
3 => i2osp::<U3>(input).unwrap().to_vec(),
4 => i2osp::<U4>(input).unwrap().to_vec(),
5 => i2osp::<U5>(input).unwrap().to_vec(),
6 => i2osp::<U6>(input).unwrap().to_vec(),
7 => i2osp::<U7>(input).unwrap().to_vec(),
_ => unreachable!("unexpected size")
};
assert_eq!(output, bytes);
}
}
#[test]
fn test_nocrash_registration_request(bytes in vec(any::<u8>(), 0..200)) {
RegistrationRequest::<Default>::deserialize(&bytes[..]).map_or(true, |_| true);
macro_rules! test {
($mod:ident, $CS:ty) => {
mod $mod {
use super::*;
proptest! {
#[test]
fn test_nocrash_registration_request(bytes in vec(any::<u8>(), 0..200)) {
RegistrationRequest::<$CS>::deserialize(&bytes).map_or(true, |_| true);
}
#[test]
fn test_nocrash_registration_response(bytes in vec(any::<u8>(), 0..200)) {
RegistrationResponse::<$CS>::deserialize(&bytes).map_or(true, |_| true);
}
#[test]
fn test_nocrash_registration_upload(bytes in vec(any::<u8>(), 0..200)) {
RegistrationUpload::<$CS>::deserialize(&bytes).map_or(true, |_| true);
}
#[test]
fn test_nocrash_credential_request(bytes in vec(any::<u8>(), 0..500)) {
CredentialRequest::<$CS>::deserialize(&bytes).map_or(true, |_| true);
}
#[test]
fn test_nocrash_credential_response(bytes in vec(any::<u8>(), 0..500)) {
CredentialResponse::<$CS>::deserialize(&bytes).map_or(true, |_| true);
}
#[test]
fn test_nocrash_credential_finalization(bytes in vec(any::<u8>(), 0..500)) {
CredentialFinalization::<$CS>::deserialize(&bytes).map_or(true, |_| true);
}
#[test]
fn test_nocrash_client_registration(bytes in vec(any::<u8>(), 0..700)) {
ClientRegistration::<$CS>::deserialize(&bytes).map_or(true, |_| true);
}
#[test]
fn test_nocrash_server_registration(bytes in vec(any::<u8>(), 0..700)) {
ServerRegistration::<$CS>::deserialize(&bytes).map_or(true, |_| true);
}
#[test]
fn test_nocrash_client_login(bytes in vec(any::<u8>(), 0..700)) {
ClientLogin::<$CS>::deserialize(&bytes).map_or(true, |_| true);
}
#[test]
fn test_nocrash_server_login(bytes in vec(any::<u8>(), 0..700)) {
ServerLogin::<$CS>::deserialize(&bytes).map_or(true, |_| true);
}
}
}
};
}
#[test]
fn test_nocrash_registration_response(bytes in vec(any::<u8>(), 0..200)) {
RegistrationResponse::<Default>::deserialize(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_registration_upload(bytes in vec(any::<u8>(), 0..200)) {
RegistrationUpload::<Default>::deserialize(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_credential_request(bytes in vec(any::<u8>(), 0..500)) {
CredentialRequest::<Default>::deserialize(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_credential_response(bytes in vec(any::<u8>(), 0..500)) {
CredentialResponse::<Default>::deserialize(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_credential_finalization(bytes in vec(any::<u8>(), 0..500)) {
CredentialFinalization::<Default>::deserialize(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_client_registration(bytes in vec(any::<u8>(), 0..700)) {
ClientRegistration::<Default>::deserialize(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_server_registration(bytes in vec(any::<u8>(), 0..700)) {
ServerRegistration::<Default>::deserialize(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_client_login(bytes in vec(any::<u8>(), 0..700)) {
ClientLogin::<Default>::deserialize(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_server_login(bytes in vec(any::<u8>(), 0..700)) {
ServerLogin::<Default>::deserialize(&bytes[..]).map_or(true, |_| true);
}
}
#[cfg(feature = "ristretto255")]
test!(ristretto255, Ristretto255);
#[cfg(feature = "p256")]
test!(p256, P256);