Updating opaque interfaces to include ids from the internet draft (#56)

This commit is contained in:
Kevin Lewi
2020-11-02 20:15:06 -05:00
committed by François Garillot
parent 7cc1c0992a
commit 0fc3448777
7 changed files with 625 additions and 456 deletions
+146 -24
View File
@@ -4,9 +4,9 @@
// LICENSE file in the root directory of this source tree.
use crate::{
errors::{InternalPakeError, ProtocolError},
errors::{InternalPakeError, PakeError, ProtocolError},
hash::Hash,
serialization::{serialize, tokenize},
serialization::{serialize, tokenize, u8_to_credential_type, CredentialType},
};
use digest::Digest;
use generic_array::{
@@ -16,6 +16,7 @@ use generic_array::{
use hkdf::Hkdf;
use hmac::{Hmac, Mac, NewMac};
use rand_core::{CryptoRng, RngCore};
use std::collections::HashMap;
// Constant string used as salt for HKDF computation
const STR_ENVU: &[u8] = b"EnvU";
@@ -39,14 +40,59 @@ const NONCE_LEN: usize = 32;
pub(crate) struct Envelope<D: Hash> {
nonce: Vec<u8>,
ciphertext: Vec<u8>,
auth_data: Vec<u8>,
hmac: GenericArray<u8, <D as Digest>::OutputSize>,
}
pub(crate) struct OpenedEnvelopeECF {
pub(crate) credentials_map: HashMap<CredentialType, Vec<u8>>,
pub(crate) export_key: GenericArray<u8, ExportKeySize>,
}
pub(crate) struct OpenedEnvelope {
pub(crate) plaintext: Vec<u8>,
pub(crate) export_key: GenericArray<u8, ExportKeySize>,
}
/// Representation for the format of the envelope
pub struct EnvelopeCredentialsFormat {
pub(crate) secret_credentials: Vec<CredentialType>,
pub(crate) cleartext_credentials: Vec<CredentialType>,
}
impl EnvelopeCredentialsFormat {
/// Creates a new envelope credentials format with validity checking
/// An ECF is valid if:
/// - skU is a secret credential
/// - pkS is either a secret or cleartext credential
pub fn new(
secret_credentials: Vec<CredentialType>,
cleartext_credentials: Vec<CredentialType>,
) -> Result<Self, ProtocolError> {
if !secret_credentials.iter().any(|&v| v == CredentialType::SkU) {
// No skU found in secret credentials
return Err(ProtocolError::ServerInvalidEnvelopeCredentialsFormatError);
}
if !secret_credentials.iter().any(|&v| v == CredentialType::PkS)
&& !cleartext_credentials
.iter()
.any(|&v| v == CredentialType::PkS)
{
// No pkS found in either secret credentials or cleartext_credentials
return Err(ProtocolError::ServerInvalidEnvelopeCredentialsFormatError);
}
Ok(Self {
secret_credentials,
cleartext_credentials,
})
}
/// Uses the default setting for the envelope credentials format
pub fn default() -> Result<Self, ProtocolError> {
Self::new(vec![CredentialType::SkU], vec![CredentialType::PkS])
}
}
impl<D: Hash> Envelope<D> {
/// The additional number of bytes added to the plaintext
pub(crate) fn additional_size() -> usize {
@@ -57,10 +103,6 @@ impl<D: Hash> Envelope<D> {
<D as Digest>::OutputSize::to_usize()
}
fn hmac_size() -> usize {
<D as Digest>::OutputSize::to_usize()
}
fn export_key_size() -> usize {
ExportKeySize::to_usize()
}
@@ -68,11 +110,13 @@ impl<D: Hash> Envelope<D> {
pub(crate) fn new(
nonce: Vec<u8>,
ciphertext: Vec<u8>,
auth_data: Vec<u8>,
hmac: GenericArray<u8, <D as Digest>::OutputSize>,
) -> Self {
Self {
nonce,
ciphertext,
auth_data,
hmac,
}
}
@@ -81,48 +125,98 @@ impl<D: Hash> Envelope<D> {
/// nonce | ciphertext | hmac
/// nonce_size bytes | variable length | hmac_size bytes
pub(crate) fn from_bytes(bytes: &[u8]) -> Result<Self, InternalPakeError> {
let ciphertext_start = NONCE_LEN;
let ciphertext_end = bytes.len() - Self::hmac_size();
Ok(Self::new(
bytes[..ciphertext_start].to_vec(),
bytes[ciphertext_start..ciphertext_end].to_vec(),
GenericArray::clone_from_slice(&bytes[ciphertext_end..]),
))
let (result, remainder) = Self::deserialize(bytes)
.map_err(|_| InternalPakeError::IncompatibleEnvelopeCredentialsError)?;
if !remainder.is_empty() {
return Err(InternalPakeError::IncompatibleEnvelopeCredentialsError);
}
Ok(result)
}
pub(crate) fn to_bytes(&self) -> Vec<u8> {
[&self.nonce[..], &self.ciphertext[..], &self.hmac[..]].concat()
self.serialize()
}
pub(crate) fn serialize(&self) -> Vec<u8> {
[
&self.nonce[..],
&serialize((&self.ciphertext).to_vec(), 2)[..],
&serialize(vec![], 2)[..],
&serialize((&self.hmac).to_vec(), 2)[..],
&serialize(&self.ciphertext, 2)[..],
&serialize(&self.auth_data, 2)[..],
&serialize(&self.hmac, 2)[..],
]
.concat()
}
pub(crate) fn deserialize(input: &[u8]) -> Result<(Self, Vec<u8>), ProtocolError> {
if input.len() < NONCE_LEN {
return Err(ProtocolError::VerificationError(
PakeError::SerializationError,
));
}
let nonce = &input[..NONCE_LEN];
let (ciphertext, remainder) = tokenize(input[NONCE_LEN..].to_vec(), 2)?;
let (_, remainder) = tokenize(remainder, 2)?;
let (auth_data, remainder) = tokenize(remainder, 2)?;
let (hmac, remainder) = tokenize(remainder, 2)?;
Ok((
Self::new(
nonce.to_vec(),
ciphertext,
auth_data,
GenericArray::clone_from_slice(&hmac[..]),
),
remainder,
))
}
fn serialize_extensions(
cred_format: Vec<CredentialType>,
credentials: &HashMap<CredentialType, Vec<u8>>,
) -> Result<Vec<u8>, InternalPakeError> {
let mut ret = Vec::new();
for index_type in cred_format {
match &credentials.get(&index_type) {
Some(v) => {
ret.push(index_type as u8 + 1);
ret.extend(serialize(&v, 2));
}
None => return Err(InternalPakeError::IncompatibleEnvelopeCredentialsError),
}
}
Ok(ret)
}
fn deserialize_extensions(
bytes: &[u8],
) -> Result<HashMap<CredentialType, Vec<u8>>, InternalPakeError> {
let mut credentials: HashMap<CredentialType, Vec<u8>> = HashMap::new();
let mut bytes_copy: Vec<u8> = Vec::new();
bytes_copy.extend_from_slice(&bytes);
while !bytes_copy.is_empty() {
let t = u8_to_credential_type(bytes_copy[0])
.ok_or(InternalPakeError::IncompatibleEnvelopeCredentialsError)?;
let (cred, remainder) = tokenize(bytes_copy[1..].to_vec(), 2)
.map_err(|_| InternalPakeError::IncompatibleEnvelopeCredentialsError)?;
bytes_copy = remainder;
credentials.insert(t, cred);
}
Ok(credentials)
}
pub(crate) fn seal<R: RngCore + CryptoRng>(
key: &[u8],
ecf: EnvelopeCredentialsFormat,
credentials: HashMap<CredentialType, Vec<u8>>,
rng: &mut R,
) -> Result<(Self, GenericArray<u8, ExportKeySize>), InternalPakeError> {
let plaintext = Self::serialize_extensions(ecf.secret_credentials, &credentials)?;
let aad = Self::serialize_extensions(ecf.cleartext_credentials, &credentials)?;
Self::seal_raw(key, &plaintext, &aad, rng)
}
/// Uses a key to convert the plaintext into an envelope, authenticated by the aad field.
/// Note that a new nonce is sampled for each call to seal.
pub(crate) fn seal<R: RngCore + CryptoRng>(
pub(crate) fn seal_raw<R: RngCore + CryptoRng>(
key: &[u8],
plaintext: &[u8],
aad: &[u8],
@@ -152,14 +246,42 @@ impl<D: Hash> Envelope<D> {
hmac.update(&aad);
Ok((
Self::new(nonce, ciphertext.to_vec(), hmac.finalize().into_bytes()),
Self::new(
nonce,
ciphertext.to_vec(),
aad.to_vec(),
hmac.finalize().into_bytes(),
),
*GenericArray::from_slice(&export_key),
))
}
pub(crate) fn open(&self, key: &[u8]) -> Result<OpenedEnvelopeECF, InternalPakeError> {
let mut credentials_map = Self::deserialize_extensions(&self.auth_data)?;
let opened = self.open_raw(key, &self.auth_data)?;
let plaintext_map = Self::deserialize_extensions(&opened.plaintext)?;
for (i, plaintext) in plaintext_map {
if credentials_map.contains_key(&i) {
// Trying to set a credential that was already provided in the aad
return Err(InternalPakeError::IncompatibleEnvelopeCredentialsError);
}
credentials_map.insert(i, plaintext);
}
Ok(OpenedEnvelopeECF {
credentials_map,
export_key: opened.export_key,
})
}
/// Attempts to decrypt the envelope using a key, which is successful only if the key and
/// aad used to construct the envelope are the same.
pub(crate) fn open(&self, key: &[u8], aad: &[u8]) -> Result<OpenedEnvelope, InternalPakeError> {
pub(crate) fn open_raw(
&self,
key: &[u8],
aad: &[u8],
) -> Result<OpenedEnvelope, InternalPakeError> {
let h = Hkdf::<D>::new(Some(&self.nonce), &key);
let mut okm =
vec![0u8; self.ciphertext.len() + Self::hmac_key_size() + Self::export_key_size()];
@@ -205,8 +327,8 @@ mod tests {
rng.fill_bytes(&mut msg);
let (envelope, export_key_1) =
Envelope::<sha2::Sha256>::seal(&key, &msg, b"aad", &mut rng).unwrap();
let opened_envelope = envelope.open(&key, b"aad").unwrap();
Envelope::<sha2::Sha256>::seal_raw(&key, &msg, b"aad", &mut rng).unwrap();
let opened_envelope = envelope.open_raw(&key, b"aad").unwrap();
assert_eq!(&msg.to_vec(), &opened_envelope.plaintext);
assert_eq!(&export_key_1.to_vec(), &opened_envelope.export_key.to_vec());
}
+21
View File
@@ -40,6 +40,9 @@ pub enum InternalPakeError {
/// This error occurs when the envelope seal open hmac check fails
/// HMAC check in seal open failed.
SealOpenHmacError,
/// This error occurs when the envelope cannot be constructed properly
/// based on the credentials that were specified to be required.
IncompatibleEnvelopeCredentialsError,
}
/// Represents an error in password checking
@@ -80,6 +83,9 @@ pub enum ProtocolError {
/// This error occurs when the server answer cannot be handled
/// Server response cannot be handled.
ServerError,
/// This error occurs when the server specifies an envelope credentials
/// format that is invalid
ServerInvalidEnvelopeCredentialsFormatError,
/// This error occurs when the client request cannot be handled
/// Client request cannot be handled.
ClientError,
@@ -127,4 +133,19 @@ pub(crate) mod utils {
}
Ok(slice)
}
pub fn check_slice_size_atleast<'a>(
slice: &'a [u8],
expected_len: usize,
arg_name: &'static str,
) -> Result<&'a [u8], InternalPakeError> {
if slice.len() < expected_len {
return Err(InternalPakeError::SizeError {
name: arg_name,
len: expected_len,
actual_len: slice.len(),
});
}
Ok(slice)
}
}
+304 -126
View File
@@ -7,19 +7,25 @@
use crate::{
ciphersuite::CipherSuite,
envelope::{Envelope, ExportKeySize},
errors::{utils::check_slice_size, InternalPakeError, PakeError, ProtocolError},
envelope::{Envelope, EnvelopeCredentialsFormat, ExportKeySize},
errors::{
utils::{check_slice_size, check_slice_size_atleast},
InternalPakeError, PakeError, ProtocolError,
},
group::Group,
hash::Hash,
key_exchange::traits::{KeyExchange, ToBytes},
keypair::{KeyPair, SizedBytes},
oprf,
oprf::OprfClientBytes,
serialization::{serialize, tokenize, CredentialType, ProtocolMessageType},
serialization::{
serialize, tokenize, u8_to_credential_type, CredentialType, ProtocolMessageType,
},
slow_hash::SlowHash,
};
use generic_array::{typenum::Unsigned, GenericArray};
use rand_core::{CryptoRng, RngCore};
use std::collections::HashMap;
use std::{convert::TryFrom, marker::PhantomData};
use zeroize::Zeroize;
@@ -28,6 +34,8 @@ use zeroize::Zeroize;
/// The message sent by the client to the server, to initiate registration
pub struct RegisterFirstMessage<Grp> {
/// User identity
id_u: Vec<u8>,
/// blinded password information
alpha: Grp,
}
@@ -35,42 +43,44 @@ pub struct RegisterFirstMessage<Grp> {
impl<Grp: Group> TryFrom<&[u8]> for RegisterFirstMessage<Grp> {
type Error = ProtocolError;
fn try_from(first_message_bytes: &[u8]) -> Result<Self, Self::Error> {
let checked_slice = check_slice_size(
first_message_bytes,
Grp::ElemLen::to_usize(),
"first_message_bytes",
)?;
let elem_len = Grp::ElemLen::to_usize();
let checked_slice =
check_slice_size_atleast(first_message_bytes, elem_len, "first_message_bytes")?;
let id_u = checked_slice[..checked_slice.len() - elem_len].to_vec();
// Check that the message is actually containing an element of the
// correct subgroup
let arr = GenericArray::from_slice(checked_slice);
let arr = GenericArray::from_slice(&checked_slice[checked_slice.len() - elem_len..]);
let alpha = Grp::from_element_slice(arr)?;
Ok(Self { alpha })
Ok(Self { id_u, alpha })
}
}
impl<Grp: Group> RegisterFirstMessage<Grp> {
/// byte representation for the registration request
fn to_bytes(&self) -> GenericArray<u8, Grp::ElemLen> {
self.alpha.to_arr()
/// Byte representation for the registration request
pub fn to_bytes(&self) -> Vec<u8> {
[&self.id_u[..], &self.alpha.to_arr().to_vec()[..]].concat()
}
}
impl<Grp: Group> RegisterFirstMessage<Grp> {
/// Serialization into bytes
pub fn serialize(&self) -> Vec<u8> {
let mut registration_request: Vec<u8> = Vec::new();
registration_request.extend_from_slice(&serialize(Vec::new(), 2));
registration_request.extend_from_slice(&serialize((&self.to_bytes()).to_vec(), 2));
registration_request.extend_from_slice(&serialize(&self.id_u, 2));
registration_request.extend_from_slice(&serialize(&self.alpha.to_arr(), 2));
let mut output: Vec<u8> = Vec::new();
output.push(ProtocolMessageType::from(self) as u8 + 1);
output.extend_from_slice(&serialize(registration_request, 3));
output.extend_from_slice(&serialize(&registration_request, 3));
output
}
/// Deserialization from bytes
pub fn deserialize(input: &[u8]) -> Result<Self, ProtocolError> {
if input[0] != ProtocolMessageType::RegistrationRequest as u8 + 1 {
if input.is_empty()
|| input.is_empty()
|| input[0] != ProtocolMessageType::RegistrationRequest as u8 + 1
{
return Err(PakeError::SerializationError.into());
}
@@ -79,14 +89,23 @@ impl<Grp: Group> RegisterFirstMessage<Grp> {
return Err(PakeError::SerializationError.into());
}
let (_, remainder) = tokenize(data, 2)?;
let (id_u, remainder) = tokenize(data, 2)?;
let (alpha_bytes, remainder) = tokenize(remainder, 2)?;
if !remainder.is_empty() {
return Err(PakeError::SerializationError.into());
}
Self::try_from(&alpha_bytes[..])
let checked_slice = check_slice_size(
&alpha_bytes,
Grp::ElemLen::to_usize(),
"first_message_bytes",
)?;
// Check that the message is actually containing an element of the
// correct subgroup
let arr = GenericArray::from_slice(checked_slice);
let alpha = Grp::from_element_slice(arr)?;
Ok(Self { id_u, alpha })
}
}
@@ -95,6 +114,10 @@ impl<Grp: Group> RegisterFirstMessage<Grp> {
pub struct RegisterSecondMessage<Grp> {
/// The server's oprf output
beta: Grp,
/// Server's static public key
server_s_pk: Vec<u8>,
/// Envelope credentials format
ecf: EnvelopeCredentialsFormat,
}
impl<Grp> TryFrom<&[u8]> for RegisterSecondMessage<Grp>
@@ -103,17 +126,25 @@ where
{
type Error = ProtocolError;
fn try_from(second_message_bytes: &[u8]) -> Result<Self, Self::Error> {
let checked_slice = check_slice_size(
second_message_bytes,
Grp::ElemLen::to_usize(),
"second_message_bytes",
)?;
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
let elem_len = Grp::ElemLen::to_usize();
let checked_slice = check_slice_size_atleast(bytes, elem_len, "second_message_bytes")?;
// Check that the message is actually containing an element of the
// correct subgroup
let arr = GenericArray::from_slice(&checked_slice);
let arr = GenericArray::from_slice(&checked_slice[..elem_len]);
let beta = Grp::from_element_slice(arr)?;
Ok(Self { beta })
let server_s_pk = checked_slice[elem_len..].to_vec();
// Note that we use a default envelope credentials format here, since it
// is not included in the byte representation
let ecf = EnvelopeCredentialsFormat::default()?;
Ok(Self {
beta,
server_s_pk,
ecf,
})
}
}
@@ -121,30 +152,47 @@ impl<Grp> RegisterSecondMessage<Grp>
where
Grp: Group,
{
/// byte representation for the registration response message
fn to_bytes(&self) -> Vec<u8> {
self.beta.to_arr().to_vec()
/// Byte representation for the registration response message. This does not
/// include the envelope credentials format
pub fn to_bytes(&self) -> Vec<u8> {
[&self.beta.to_arr().to_vec()[..], &self.server_s_pk[..]].concat()
}
/// Serialization into bytes
pub fn serialize(&self) -> Vec<u8> {
let mut registration_response: Vec<u8> = Vec::new();
registration_response.extend_from_slice(&serialize((&self.to_bytes()).to_vec(), 2));
registration_response.extend_from_slice(&serialize(Vec::new(), 2));
registration_response.extend_from_slice(&serialize(&self.beta.to_arr(), 2));
registration_response.extend_from_slice(&serialize(&self.server_s_pk, 2));
// TODO: The following should not be hardcoded, but instead be customizable
registration_response.extend_from_slice(&[1u8, CredentialType::SkU as u8 + 1]);
registration_response.extend_from_slice(&[1u8, CredentialType::PkS as u8 + 1]);
// Handle ecf serialization
let secret_credentials: Vec<u8> = self
.ecf
.secret_credentials
.iter()
.map(|&x| x as u8 + 1)
.collect();
let cleartext_credentials: Vec<u8> = self
.ecf
.cleartext_credentials
.iter()
.map(|&x| x as u8 + 1)
.collect();
let ecf_serialized = [
serialize(&secret_credentials, 1),
serialize(&cleartext_credentials, 1),
]
.concat();
registration_response.extend_from_slice(&ecf_serialized);
let mut output: Vec<u8> = Vec::new();
output.push(ProtocolMessageType::from(self) as u8 + 1);
output.extend_from_slice(&serialize(registration_response, 3));
output.extend_from_slice(&serialize(&registration_response, 3));
output
}
/// Deserialization from bytes
pub fn deserialize(input: &[u8]) -> Result<Self, ProtocolError> {
if input[0] != ProtocolMessageType::RegistrationResponse as u8 + 1 {
if input.is_empty() || input[0] != ProtocolMessageType::RegistrationResponse as u8 + 1 {
return Err(PakeError::SerializationError.into());
}
@@ -154,18 +202,39 @@ where
}
let (beta_bytes, remainder) = tokenize(data, 2)?;
let (_, remainder) = tokenize(remainder, 2)?;
let (server_s_pk, remainder) = tokenize(remainder, 2)?;
// TODO: The following should affect what is placed in the envelope rather than
// being ignored
let (_, remainder) = tokenize(remainder, 1)?;
let (_, remainder) = tokenize(remainder, 1)?;
// Handle ecf deserialization
let (secret_credentials, remainder) = tokenize(remainder, 1)?;
let (cleartext_credentials, remainder) = tokenize(remainder, 1)?;
let sc = secret_credentials
.iter()
.map(|x| u8_to_credential_type(*x).ok_or(PakeError::SerializationError))
.collect::<Result<Vec<CredentialType>, _>>()?;
let cc = cleartext_credentials
.iter()
.map(|x| u8_to_credential_type(*x).ok_or(PakeError::SerializationError))
.collect::<Result<Vec<CredentialType>, _>>()?;
let ecf = EnvelopeCredentialsFormat::new(sc, cc)?;
if !remainder.is_empty() {
return Err(PakeError::SerializationError.into());
}
Self::try_from(&beta_bytes[..])
let checked_slice = check_slice_size(
&beta_bytes,
Grp::ElemLen::to_usize(),
"second_message_bytes",
)?;
// Check that the message is actually containing an element of the
// correct subgroup
let arr = GenericArray::from_slice(&checked_slice);
let beta = Grp::from_element_slice(arr)?;
Ok(Self {
ecf,
server_s_pk,
beta,
})
}
}
@@ -213,17 +282,17 @@ where
pub fn serialize(&self) -> Vec<u8> {
let mut registration_upload: Vec<u8> = Vec::new();
registration_upload.extend_from_slice(&self.envelope.serialize());
registration_upload.extend_from_slice(&serialize(self.client_s_pk.to_arr().to_vec(), 2));
registration_upload.extend_from_slice(&serialize(&self.client_s_pk.to_arr(), 2));
let mut output: Vec<u8> = Vec::new();
output.push(ProtocolMessageType::from(self) as u8 + 1);
output.extend_from_slice(&serialize(registration_upload, 3));
output.extend_from_slice(&serialize(&registration_upload, 3));
output
}
/// Deserialization from bytes
pub fn deserialize(input: &[u8]) -> Result<Self, ProtocolError> {
if input[0] != ProtocolMessageType::RegistrationUpload as u8 + 1 {
if input.is_empty() || input[0] != ProtocolMessageType::RegistrationUpload as u8 + 1 {
return Err(PakeError::SerializationError.into());
}
@@ -248,6 +317,8 @@ where
/// The message sent by the user to the server, to initiate registration
pub struct LoginFirstMessage<CS: CipherSuite> {
/// User identity
id_u: Vec<u8>,
/// blinded password information
alpha: CS::Group,
ke1_message: <CS::KeyExchange as KeyExchange<CS::Hash, CS::KeyFormat>>::KE1Message,
@@ -256,27 +327,7 @@ pub struct LoginFirstMessage<CS: CipherSuite> {
impl<CS: CipherSuite> TryFrom<&[u8]> for LoginFirstMessage<CS> {
type Error = ProtocolError;
fn try_from(first_message_bytes: &[u8]) -> Result<Self, Self::Error> {
let min_expected_len = <CS::Group as Group>::ElemLen::to_usize();
let checked_slice = (if first_message_bytes.len() <= min_expected_len {
Err(InternalPakeError::SizeError {
name: "first_message_bytes",
len: min_expected_len,
actual_len: first_message_bytes.len(),
})
} else {
Ok(first_message_bytes)
})?;
// Check that the message is actually containing an element of the
// correct subgroup
let elem_len = <CS::Group as Group>::ElemLen::to_usize();
let arr = GenericArray::from_slice(&checked_slice[..elem_len]);
let alpha = CS::Group::from_element_slice(arr)?;
let ke1_message =
<CS::KeyExchange as KeyExchange<CS::Hash, CS::KeyFormat>>::KE1Message::try_from(
&checked_slice[elem_len..],
)?;
Ok(Self { alpha, ke1_message })
Self::deserialize(first_message_bytes)
}
}
@@ -289,33 +340,46 @@ impl<CS: CipherSuite> LoginFirstMessage<CS> {
/// Serialization into bytes
pub fn serialize(&self) -> Vec<u8> {
let mut credential_request: Vec<u8> = Vec::new();
credential_request.extend_from_slice(&serialize(Vec::new(), 2));
credential_request.extend_from_slice(&serialize((&self.alpha.to_arr()).to_vec(), 2));
credential_request.extend_from_slice(&serialize(&self.id_u, 2));
credential_request.extend_from_slice(&serialize(&self.alpha.to_arr(), 2));
let mut output: Vec<u8> = Vec::new();
output.push(ProtocolMessageType::from(self) as u8 + 1);
output.extend_from_slice(&serialize(credential_request, 3));
output.extend_from_slice(&serialize(&credential_request, 3));
output.extend_from_slice(&self.ke1_message.to_bytes());
output
}
/// Deserialization from bytes
pub fn deserialize(input: &[u8]) -> Result<Self, ProtocolError> {
if input[0] != ProtocolMessageType::CredentialRequest as u8 + 1 {
if input.is_empty() || input[0] != ProtocolMessageType::CredentialRequest as u8 + 1 {
return Err(PakeError::SerializationError.into());
}
let (data, ke1m) = tokenize(input[1..].to_vec(), 3)?;
let (_, remainder) = tokenize(data, 2)?;
let (id_u, remainder) = tokenize(data, 2)?;
let (alpha_bytes, remainder) = tokenize(remainder, 2)?;
if !remainder.is_empty() {
return Err(PakeError::SerializationError.into());
}
let concatenated = [&alpha_bytes[..], &ke1m[..]].concat();
Self::try_from(&concatenated[..])
let elem_len = <CS::Group as Group>::ElemLen::to_usize();
let checked_slice = check_slice_size(&alpha_bytes, elem_len, "login_first_message_bytes")?;
let arr = GenericArray::from_slice(&checked_slice[..elem_len]);
let alpha = <CS::Group as Group>::from_element_slice(arr)?;
let ke1_message =
<CS::KeyExchange as KeyExchange<CS::Hash, CS::KeyFormat>>::KE1Message::try_from(
&ke1m[..],
)?;
Ok(Self {
id_u,
alpha,
ke1_message,
})
}
}
@@ -333,28 +397,25 @@ impl<CS: CipherSuite> LoginSecondMessage<CS> {
/// Serialization into bytes
pub fn serialize(&self) -> Vec<u8> {
let mut credential_response: Vec<u8> = Vec::new();
credential_response.extend_from_slice(&serialize((&self.beta.to_arr()).to_vec(), 2));
credential_response.extend_from_slice(&serialize((&self.envelope.to_bytes()).to_vec(), 2));
credential_response.extend_from_slice(&serialize(Vec::new(), 2));
credential_response.extend_from_slice(&serialize(&self.beta.to_arr(), 2));
credential_response.extend_from_slice(&serialize(&self.envelope.to_bytes(), 2));
let mut output: Vec<u8> = Vec::new();
output.push(ProtocolMessageType::from(self) as u8 + 1);
output.extend_from_slice(&serialize(credential_response, 3));
output.extend_from_slice(&serialize(&credential_response, 3));
output.extend_from_slice(&self.ke2_message.to_bytes());
output
}
/// Deserialization from bytes
pub fn deserialize(input: &[u8]) -> Result<Self, ProtocolError> {
if input[0] != ProtocolMessageType::CredentialResponse as u8 + 1 {
if input.is_empty() || input[0] != ProtocolMessageType::CredentialResponse as u8 + 1 {
return Err(PakeError::SerializationError.into());
}
let (data, ke2m) = tokenize(input[1..].to_vec(), 3)?;
let (beta_bytes, remainder) = tokenize(data, 2)?;
let (envelope_bytes, remainder) = tokenize(remainder, 2)?;
let (_, remainder) = tokenize(remainder, 2)?;
if !remainder.is_empty() {
return Err(PakeError::SerializationError.into());
@@ -368,15 +429,9 @@ impl<CS: CipherSuite> LoginSecondMessage<CS> {
impl<CS: CipherSuite> TryFrom<&[u8]> for LoginSecondMessage<CS> {
type Error = ProtocolError;
fn try_from(second_message_bytes: &[u8]) -> Result<Self, Self::Error> {
let key_len = <<CS::KeyFormat as KeyPair>::Repr as SizedBytes>::Len::to_usize();
let envelope_size = key_len + Envelope::<CS::Hash>::additional_size();
let elem_len = <CS::Group as Group>::ElemLen::to_usize();
let ke2_message_size = CS::KeyExchange::ke2_message_size();
let checked_slice = check_slice_size(
second_message_bytes,
elem_len + envelope_size + ke2_message_size,
"login_second_message_bytes",
)?;
let checked_slice =
check_slice_size_atleast(second_message_bytes, elem_len, "login_second_message_bytes")?;
// Check that the message is actually containing an element of the
// correct subgroup
@@ -384,12 +439,14 @@ impl<CS: CipherSuite> TryFrom<&[u8]> for LoginSecondMessage<CS> {
let arr = GenericArray::from_slice(beta_bytes);
let beta = CS::Group::from_element_slice(arr)?;
let envelope =
Envelope::<CS::Hash>::from_bytes(&checked_slice[elem_len..elem_len + envelope_size])?;
let (envelope, remainder) = Envelope::<CS::Hash>::deserialize(&checked_slice[elem_len..])?;
let ke2_message_size = CS::KeyExchange::ke2_message_size();
let checked_remainder =
check_slice_size_atleast(&remainder, ke2_message_size, "login_second_message_bytes")?;
let ke2_message =
<CS::KeyExchange as KeyExchange<CS::Hash, CS::KeyFormat>>::KE2Message::try_from(
&checked_slice[elem_len + envelope_size..],
&checked_remainder,
)?;
Ok(Self {
@@ -417,6 +474,14 @@ impl<CS: CipherSuite> TryFrom<&[u8]> for LoginThirdMessage<CS> {
}
impl<CS: CipherSuite> LoginThirdMessage<CS> {
/// Serialization into bytes
pub fn serialize(&self) -> Vec<u8> {
let mut output: Vec<u8> = Vec::new();
output.push(ProtocolMessageType::from(self) as u8 + 1);
output.extend_from_slice(&self.ke3_message.to_bytes());
output
}
/// byte representation for the login finalization
pub fn to_bytes(&self) -> Vec<u8> {
self.ke3_message.to_bytes()
@@ -428,6 +493,10 @@ impl<CS: CipherSuite> LoginThirdMessage<CS> {
/// The state elements the client holds to register itself
pub struct ClientRegistration<CS: CipherSuite> {
/// User identity
id_u: Vec<u8>,
/// Server identity
id_s: Vec<u8>,
/// a blinding factor
pub(crate) blinding_factor: <CS::Group as Group>::Scalar,
/// the client's password
@@ -436,7 +505,10 @@ pub struct ClientRegistration<CS: CipherSuite> {
impl<CS: CipherSuite> TryFrom<&[u8]> for ClientRegistration<CS> {
type Error = ProtocolError;
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
fn try_from(input: &[u8]) -> Result<Self, Self::Error> {
let (id_u, bytes) = tokenize(input.to_vec(), 2)?;
let (id_s, bytes) = tokenize(bytes.to_vec(), 2)?;
let min_expected_len = <CS::Group as Group>::ScalarLen::to_usize();
let checked_slice = (if bytes.len() <= min_expected_len {
Err(InternalPakeError::SizeError {
@@ -455,6 +527,8 @@ impl<CS: CipherSuite> TryFrom<&[u8]> for ClientRegistration<CS> {
let blinding_factor = CS::Group::from_scalar_slice(blinding_factor_bytes)?;
let password = checked_slice[scalar_len..].to_vec();
Ok(Self {
id_u,
id_s,
blinding_factor,
password,
})
@@ -465,6 +539,8 @@ impl<CS: CipherSuite> ClientRegistration<CS> {
/// byte representation for the client's registration state
pub fn to_bytes(&self) -> Vec<u8> {
let output: Vec<u8> = [
&serialize(&self.id_u, 2),
&serialize(&self.id_s, 2),
&CS::Group::scalar_as_bytes(&self.blinding_factor)[..],
&self.password,
]
@@ -502,6 +578,23 @@ impl<CS: CipherSuite> ClientRegistration<CS> {
password: &[u8],
pepper: Option<&[u8]>,
blinding_factor_rng: &mut R,
) -> Result<(RegisterFirstMessage<CS::Group>, Self), ProtocolError> {
Self::start_with_user_and_server_name(
&Vec::new(),
&Vec::new(),
password,
pepper,
blinding_factor_rng,
)
}
/// Same as ClientRegistration::start, but also accepts a username and server name as input
pub fn start_with_user_and_server_name<R: RngCore + CryptoRng>(
user_name: &[u8],
server_name: &[u8],
password: &[u8],
pepper: Option<&[u8]>,
blinding_factor_rng: &mut R,
) -> Result<(RegisterFirstMessage<CS::Group>, Self), ProtocolError> {
let OprfClientBytes {
alpha,
@@ -509,8 +602,13 @@ impl<CS: CipherSuite> ClientRegistration<CS> {
} = oprf::generate_oprf1::<R, CS::Group>(&password, pepper, blinding_factor_rng)?;
Ok((
RegisterFirstMessage::<CS::Group> { alpha },
RegisterFirstMessage::<CS::Group> {
id_u: user_name.to_vec(),
alpha,
},
Self {
id_u: user_name.to_vec(),
id_s: server_name.to_vec(),
blinding_factor,
password: password.to_vec(),
},
@@ -561,6 +659,17 @@ impl<CS: CipherSuite> ClientRegistration<CS> {
r2: RegisterSecondMessage<CS::Group>,
server_s_pk: &<CS::KeyFormat as KeyPair>::Repr,
rng: &mut R,
) -> Result<ClientRegistrationFinishResult<CS::KeyFormat, CS::Hash>, ProtocolError> {
let mut r2_cloned = r2;
r2_cloned.server_s_pk = server_s_pk.to_arr().to_vec();
self.finish_using_transmitted_server_public_key(r2_cloned, rng)
}
/// Same as finish, but without the server public key check
pub fn finish_using_transmitted_server_public_key<R: CryptoRng + RngCore>(
self,
r2: RegisterSecondMessage<CS::Group>,
rng: &mut R,
) -> Result<ClientRegistrationFinishResult<CS::KeyFormat, CS::Hash>, ProtocolError> {
let client_static_keypair = CS::KeyFormat::generate_random(rng)?;
@@ -570,12 +679,21 @@ impl<CS: CipherSuite> ClientRegistration<CS> {
&self.blinding_factor,
)?;
let (envelope, export_key) = Envelope::<CS::Hash>::seal(
&password_derived_key,
&client_static_keypair.private().to_arr(),
&server_s_pk.to_arr(),
rng,
)?;
let mut credentials_map: HashMap<CredentialType, Vec<u8>> = HashMap::new();
credentials_map.insert(
CredentialType::SkU,
client_static_keypair.private().to_arr().to_vec(),
);
credentials_map.insert(
CredentialType::PkU,
client_static_keypair.public().to_arr().to_vec(),
);
credentials_map.insert(CredentialType::PkS, r2.server_s_pk);
credentials_map.insert(CredentialType::IdU, self.id_u.clone());
credentials_map.insert(CredentialType::IdS, self.id_s.clone());
let (envelope, export_key) =
Envelope::<CS::Hash>::seal(&password_derived_key, r2.ecf, credentials_map, rng)?;
Ok((
RegisterThirdMessage {
@@ -632,36 +750,36 @@ where
>: generic_array::ArrayLength<u8>,
{
type Error = ProtocolError;
fn try_from(server_registration_bytes: &[u8]) -> Result<Self, Self::Error> {
let key_len = <<CS::KeyFormat as KeyPair>::Repr as SizedBytes>::Len::to_usize();
let scalar_len = <CS::Group as Group>::ScalarLen::to_usize();
let envelope_size = key_len + Envelope::<CS::Hash>::additional_size();
if server_registration_bytes.len() == scalar_len {
/// The format of a serialized ServerRegistration object:
/// oprf_key | client_s_pk | envelope
fn try_from(input: &[u8]) -> Result<Self, Self::Error> {
let scalar_len = <CS::Group as Group>::ScalarLen::to_usize();
if input.len() == scalar_len {
return Ok(Self {
oprf_key: CS::Group::from_scalar_slice(GenericArray::from_slice(
server_registration_bytes,
))?,
oprf_key: CS::Group::from_scalar_slice(GenericArray::from_slice(input))?,
client_s_pk: None,
envelope: None,
});
}
let checked_bytes = check_slice_size(
server_registration_bytes,
envelope_size + key_len + scalar_len,
"server_registration_bytes",
)?;
// Need to do this check manually because envelope is variable-size
let key_len = <<CS::KeyFormat as KeyPair>::Repr as SizedBytes>::Len::to_usize();
let checked_bytes =
check_slice_size_atleast(&input, scalar_len + key_len, "server_registration_bytes")?;
let oprf_key_bytes = GenericArray::from_slice(&checked_bytes[..scalar_len]);
let oprf_key = CS::Group::from_scalar_slice(oprf_key_bytes)?;
let unchecked_client_s_pk = <CS::KeyFormat as KeyPair>::Repr::from_bytes(
&checked_bytes[scalar_len..scalar_len + key_len],
)?;
let client_s_pk = CS::KeyFormat::check_public_key(unchecked_client_s_pk)?;
let envelope = Envelope::<CS::Hash>::from_bytes(&checked_bytes[scalar_len + key_len..])?;
Ok(Self {
envelope: Some(Envelope::<CS::Hash>::from_bytes(
&checked_bytes[checked_bytes.len() - envelope_size..],
)?),
envelope: Some(envelope),
client_s_pk: Some(client_s_pk),
oprf_key,
})
@@ -720,6 +838,30 @@ where
pub fn start<R: RngCore + CryptoRng>(
message: RegisterFirstMessage<CS::Group>,
rng: &mut R,
) -> Result<(RegisterSecondMessage<CS::Group>, Self), ProtocolError> {
Self::start_with_server_pk(message, &Vec::new(), rng)
}
/// Same as start, but with the ability to supply a server_s_pk as input
pub fn start_with_server_pk<R: RngCore + CryptoRng>(
message: RegisterFirstMessage<CS::Group>,
server_s_pk: &[u8],
rng: &mut R,
) -> Result<(RegisterSecondMessage<CS::Group>, Self), ProtocolError> {
Self::start_with_server_pk_and_ecf(
message,
server_s_pk,
EnvelopeCredentialsFormat::default()?,
rng,
)
}
/// Same as start, but with the ability to supply a server_s_pk as input and envelope credentials format
pub fn start_with_server_pk_and_ecf<R: RngCore + CryptoRng>(
message: RegisterFirstMessage<CS::Group>,
server_s_pk: &[u8],
ecf: EnvelopeCredentialsFormat,
rng: &mut R,
) -> Result<(RegisterSecondMessage<CS::Group>, Self), ProtocolError> {
// RFC: generate oprf_key (salt) and v_u = g^oprf_key
let oprf_key = CS::Group::random_scalar(rng);
@@ -728,7 +870,11 @@ where
let beta = oprf::generate_oprf2::<CS::Group>(message.alpha, &oprf_key)?;
Ok((
RegisterSecondMessage { beta },
RegisterSecondMessage {
beta,
server_s_pk: server_s_pk.to_vec(),
ecf,
},
Self {
envelope: None,
client_s_pk: None,
@@ -786,6 +932,10 @@ where
/// The state elements the client holds to perform a login
pub struct ClientLogin<CS: CipherSuite> {
/// User identity
id_u: Vec<u8>,
/// Server identity
id_s: Vec<u8>,
/// A blinding factor, which is used to mask (and unmask) secret
/// information before transmission
blinding_factor: <CS::Group as Group>::Scalar,
@@ -796,7 +946,10 @@ pub struct ClientLogin<CS: CipherSuite> {
impl<CS: CipherSuite> TryFrom<&[u8]> for ClientLogin<CS> {
type Error = ProtocolError;
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
fn try_from(input: &[u8]) -> Result<Self, Self::Error> {
let (id_u, bytes) = tokenize(input.to_vec(), 2)?;
let (id_s, bytes) = tokenize(bytes.to_vec(), 2)?;
let scalar_len = <CS::Group as Group>::ScalarLen::to_usize();
let ke1_state_size =
<CS::KeyExchange as KeyExchange<CS::Hash, CS::KeyFormat>>::ke1_state_size();
@@ -809,7 +962,7 @@ impl<CS: CipherSuite> TryFrom<&[u8]> for ClientLogin<CS> {
actual_len: bytes.len(),
})
} else {
Ok(bytes)
Ok(bytes.clone())
})?;
let blinding_factor_bytes = GenericArray::from_slice(&checked_slice[..scalar_len]);
@@ -820,6 +973,8 @@ impl<CS: CipherSuite> TryFrom<&[u8]> for ClientLogin<CS> {
)?;
let password = bytes[scalar_len + ke1_state_size..].to_vec();
Ok(Self {
id_u,
id_s,
blinding_factor,
password,
ke1_state,
@@ -831,6 +986,8 @@ impl<CS: CipherSuite> ClientLogin<CS> {
/// byte representation for the client's login state
pub fn to_bytes(&self) -> Vec<u8> {
let output: Vec<u8> = [
&serialize(&self.id_u, 2),
&serialize(&self.id_s, 2),
&CS::Group::scalar_as_bytes(&self.blinding_factor)[..],
&self.ke1_state.to_bytes(),
&self.password,
@@ -875,6 +1032,17 @@ impl<CS: CipherSuite> ClientLogin<CS> {
password: &[u8],
pepper: Option<&[u8]>,
rng: &mut R,
) -> Result<(LoginFirstMessage<CS>, Self), ProtocolError> {
Self::start_with_user_and_server_name(&Vec::new(), &Vec::new(), password, pepper, rng)
}
/// Same as start, but allows the user to supply a username and server name
pub fn start_with_user_and_server_name<R: RngCore + CryptoRng>(
user_name: &[u8],
server_name: &[u8],
password: &[u8],
pepper: Option<&[u8]>,
rng: &mut R,
) -> Result<(LoginFirstMessage<CS>, Self), ProtocolError> {
let OprfClientBytes {
alpha,
@@ -883,11 +1051,17 @@ impl<CS: CipherSuite> ClientLogin<CS> {
let (ke1_state, ke1_message) = CS::KeyExchange::generate_ke1(alpha.to_arr().to_vec(), rng)?;
let l1 = LoginFirstMessage { alpha, ke1_message };
let l1 = LoginFirstMessage {
id_u: user_name.to_vec(),
alpha,
ke1_message,
};
Ok((
l1,
Self {
id_u: user_name.to_vec(),
id_s: server_name.to_vec(),
blinding_factor,
password: password.to_vec(),
ke1_state,
@@ -933,7 +1107,7 @@ impl<CS: CipherSuite> ClientLogin<CS> {
pub fn finish<R: RngCore + CryptoRng>(
self,
l2: LoginSecondMessage<CS>,
server_s_pk: &<<CS as CipherSuite>::KeyFormat as KeyPair>::Repr,
_server_s_pk: &<<CS as CipherSuite>::KeyFormat as KeyPair>::Repr,
_client_e_sk_rng: &mut R,
) -> Result<ClientLoginFinishResult<CS>, ProtocolError> {
let l2_bytes: Vec<u8> = [&l2.beta.to_arr()[..], &l2.envelope.to_bytes()].concat();
@@ -946,7 +1120,7 @@ impl<CS: CipherSuite> ClientLogin<CS> {
let opened_envelope = &l2
.envelope
.open(&password_derived_key, &server_s_pk.to_arr())
.open(&password_derived_key)
.map_err(|e| match e {
InternalPakeError::SealOpenHmacError => PakeError::InvalidLoginError,
err => PakeError::from(err),
@@ -956,8 +1130,12 @@ impl<CS: CipherSuite> ClientLogin<CS> {
l2_bytes,
l2.ke2_message,
&self.ke1_state,
server_s_pk.clone(),
<CS::KeyFormat as KeyPair>::Repr::from_bytes(&opened_envelope.plaintext)?,
<CS::KeyFormat as KeyPair>::Repr::from_bytes(
&opened_envelope.credentials_map[&CredentialType::PkS],
)?,
<CS::KeyFormat as KeyPair>::Repr::from_bytes(
&opened_envelope.credentials_map[&CredentialType::SkU],
)?,
)?;
Ok((
+24 -5
View File
@@ -2,6 +2,7 @@
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use crate::errors::PakeError;
use crate::{
@@ -9,8 +10,8 @@ use crate::{
hash::Hash,
keypair::KeyPair,
opaque::{
LoginFirstMessage, LoginSecondMessage, RegisterFirstMessage, RegisterSecondMessage,
RegisterThirdMessage,
LoginFirstMessage, LoginSecondMessage, LoginThirdMessage, RegisterFirstMessage,
RegisterSecondMessage, RegisterThirdMessage,
},
};
@@ -20,9 +21,10 @@ pub enum ProtocolMessageType {
RegistrationUpload,
CredentialRequest,
CredentialResponse,
KeyExchange,
}
#[allow(dead_code)]
#[derive(Copy, Clone, Eq, Hash, PartialEq)]
pub enum CredentialType {
SkU,
PkU,
@@ -31,6 +33,17 @@ pub enum CredentialType {
IdS,
}
pub(crate) fn u8_to_credential_type(x: u8) -> Option<CredentialType> {
match x {
1 => Some(CredentialType::SkU),
2 => Some(CredentialType::PkU),
3 => Some(CredentialType::PkS),
4 => Some(CredentialType::IdU),
5 => Some(CredentialType::IdS),
_ => None,
}
}
impl<T> From<&RegisterFirstMessage<T>> for ProtocolMessageType {
fn from(_mt: &RegisterFirstMessage<T>) -> Self {
ProtocolMessageType::RegistrationRequest
@@ -61,7 +74,13 @@ impl<T: CipherSuite> From<&LoginSecondMessage<T>> for ProtocolMessageType {
}
}
pub(crate) fn serialize(input: Vec<u8>, max_bytes: usize) -> Vec<u8> {
impl<T: CipherSuite> From<&LoginThirdMessage<T>> for ProtocolMessageType {
fn from(_mt: &LoginThirdMessage<T>) -> Self {
ProtocolMessageType::KeyExchange
}
}
pub(crate) fn serialize(input: &[u8], max_bytes: usize) -> Vec<u8> {
let mut output: Vec<u8> = Vec::new();
output.extend_from_slice(&input.len().to_be_bytes()[8 - max_bytes..]);
output.extend_from_slice(&input[..]);
@@ -69,7 +88,7 @@ pub(crate) fn serialize(input: Vec<u8>, max_bytes: usize) -> Vec<u8> {
}
pub(crate) fn tokenize(input: Vec<u8>, size_bytes: usize) -> Result<(Vec<u8>, Vec<u8>), PakeError> {
if size_bytes > 8 {
if size_bytes > 8 || input.len() < size_bytes {
return Err(PakeError::SerializationError);
}
+103 -44
View File
@@ -2,6 +2,7 @@
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use crate::{
ciphersuite::CipherSuite,
envelope::Envelope,
@@ -12,10 +13,10 @@ use crate::{
},
keypair::{KeyPair, SizedBytes, X25519KeyPair},
opaque::*,
serialization::{serialize, ProtocolMessageType},
};
use curve25519_dalek::ristretto::RistrettoPoint;
use generic_array::typenum::Unsigned;
use proptest::{collection::vec, prelude::*};
use rand_core::{OsRng, RngCore};
@@ -31,6 +32,8 @@ impl CipherSuite for Default {
type SlowHash = crate::slow_hash::NoOpHash;
}
const MAX_ID_LENGTH: usize = 10;
fn random_ristretto_point() -> RistrettoPoint {
let mut rng = OsRng;
let mut random_bits = [0u8; 64];
@@ -50,8 +53,21 @@ fn client_registration_roundtrip() {
let pw = b"hunter2";
let mut rng = OsRng;
let sc = <RistrettoPoint as Group>::random_scalar(&mut rng);
// serialization order: scalar, password
let bytes: Vec<u8> = [&sc.as_bytes()[..], &pw[..]].concat();
let id_u_length: usize = rng.gen_range(0, MAX_ID_LENGTH);
let id_s_length: usize = rng.gen_range(0, MAX_ID_LENGTH);
let mut id_u = [0u8; MAX_ID_LENGTH];
rng.fill_bytes(&mut id_u);
let mut id_s = [0u8; MAX_ID_LENGTH];
rng.fill_bytes(&mut id_s);
// serialization order: id_u, id_s, scalar, password
let bytes: Vec<u8> = [
&serialize(&id_u[..id_u_length], 2)[..],
&serialize(&id_s[..id_s_length], 2)[..],
&sc.as_bytes()[..],
&pw[..],
]
.concat();
let reg = ClientRegistration::<Default>::try_from(&bytes[..]).unwrap();
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, bytes);
@@ -62,24 +78,28 @@ fn server_registration_roundtrip() {
// If we don't have envelope and client_pk, the server registration just
// contains the prf key
let mut rng = OsRng;
let sc = <RistrettoPoint as Group>::random_scalar(&mut rng);
let oprf_key = <RistrettoPoint as Group>::random_scalar(&mut rng);
let mut oprf_bytes: Vec<u8> = vec![];
oprf_bytes.extend_from_slice(sc.as_bytes());
oprf_bytes.extend_from_slice(oprf_key.as_bytes());
let reg = ServerRegistration::<Default>::try_from(&oprf_bytes[..]).unwrap();
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, oprf_bytes);
// If we do have envelope and client pk, the server registration contains
// the whole kit
let key_len =
<<<Default as CipherSuite>::KeyFormat as KeyPair>::Repr as SizedBytes>::Len::to_usize();
let envelope_size = key_len + Envelope::<sha2::Sha256>::additional_size();
let mut mock_envelope_bytes = vec![0u8; envelope_size];
rng.fill_bytes(&mut mock_envelope_bytes);
println!("{}", mock_envelope_bytes.len());
// Construct a mock envelope
let mut mock_envelope_bytes = Vec::new();
mock_envelope_bytes.extend_from_slice(&[0; NONCE_LEN]); // empty nonce
mock_envelope_bytes.extend_from_slice(&[0, 0]); // empty ciphertext
mock_envelope_bytes.extend_from_slice(&[0, 0]); // empty auth_data
// length-32 hmac
mock_envelope_bytes.extend_from_slice(&[0, 32]);
mock_envelope_bytes.extend_from_slice(&[0; 32]);
let mock_client_kp = Default::generate_random_keypair(&mut rng).unwrap();
// serialization order: scalar, public key, envelope
// serialization order: oprf_key, public key, envelope
let mut bytes = Vec::<u8>::new();
bytes.extend_from_slice(sc.as_bytes());
bytes.extend_from_slice(oprf_key.as_bytes());
bytes.extend_from_slice(&mock_client_kp.public().to_arr());
bytes.extend_from_slice(&mock_envelope_bytes);
let reg = ServerRegistration::<Default>::try_from(&bytes[..]).unwrap();
@@ -91,10 +111,21 @@ fn server_registration_roundtrip() {
fn register_first_message_roundtrip() {
let pt = random_ristretto_point();
let pt_bytes = pt.to_arr().to_vec();
let header = [1, 0, 0, 36, 0, 0, 0, 32];
let mut rng = OsRng;
let id_length: usize = rng.gen_range(0, MAX_ID_LENGTH);
let mut id = [0u8; MAX_ID_LENGTH];
rng.fill_bytes(&mut id);
let alpha_length: usize = 32;
let total_length: usize = alpha_length + id_length + 4;
let mut input = Vec::new();
input.extend_from_slice(&header);
input.extend_from_slice(&[ProtocolMessageType::RegistrationRequest as u8 + 1]);
input.extend_from_slice(&total_length.to_be_bytes()[8 - 3..]);
input.extend_from_slice(&id_length.to_be_bytes()[8 - 2..]);
input.extend_from_slice(&id[..id_length]);
input.extend_from_slice(&alpha_length.to_be_bytes()[8 - 2..]);
input.extend_from_slice(pt_bytes.as_slice());
let r1 = RegisterFirstMessage::<RistrettoPoint>::deserialize(input.as_slice()).unwrap();
@@ -105,14 +136,24 @@ fn register_first_message_roundtrip() {
#[test]
fn register_second_message_roundtrip() {
let pt = random_ristretto_point();
let pt_bytes = pt.to_arr();
let header = [2, 0, 0, 40, 0, 32];
let tail = [0, 0, 1, 1, 1, 3];
let beta_bytes = pt.to_arr();
let mut rng = OsRng;
let skp = Default::generate_random_keypair(&mut rng).unwrap();
let pubkey_bytes = skp.public().to_arr();
let credential_types = [1, 1, 1, 3];
let beta_length: usize = beta_bytes.len();
let pubkey_length: usize = pubkey_bytes.len();
let total_length: usize = beta_length + pubkey_length + credential_types.len() + 4;
let mut input = Vec::new();
input.extend_from_slice(&header);
input.extend_from_slice(pt_bytes.as_slice());
input.extend_from_slice(&tail);
input.extend_from_slice(&[ProtocolMessageType::RegistrationResponse as u8 + 1]);
input.extend_from_slice(&total_length.to_be_bytes()[8 - 3..]);
input.extend_from_slice(&beta_length.to_be_bytes()[8 - 2..]);
input.extend_from_slice(beta_bytes.as_slice());
input.extend_from_slice(&pubkey_length.to_be_bytes()[8 - 2..]);
input.extend_from_slice(&pubkey_bytes.as_slice());
input.extend_from_slice(&credential_types);
let r2 = RegisterSecondMessage::<RistrettoPoint>::deserialize(input.as_slice()).unwrap();
let r2_bytes = r2.serialize();
@@ -125,9 +166,6 @@ fn register_third_message_roundtrip() {
let skp = Default::generate_random_keypair(&mut rng).unwrap();
let pubkey_bytes = skp.public().to_arr();
let header = [3, 0, 0, 136];
let intermediate = [0, 32];
let mut key = [0u8; 32];
rng.fill_bytes(&mut key);
@@ -135,12 +173,17 @@ fn register_third_message_roundtrip() {
rng.fill_bytes(&mut msg);
let (envelope, _) =
Envelope::<sha2::Sha256>::seal(&key, &msg, &pubkey_bytes, &mut rng).unwrap();
Envelope::<sha2::Sha256>::seal_raw(&key, &msg, &pubkey_bytes, &mut rng).unwrap();
let envelope_bytes = envelope.serialize();
let pubkey_length: usize = pubkey_bytes.len();
let total_length: usize = pubkey_length + envelope_bytes.len() + 2;
let mut input = Vec::new();
input.extend_from_slice(&header);
input.extend_from_slice(&envelope.serialize());
input.extend_from_slice(&intermediate);
input.extend_from_slice(&[ProtocolMessageType::RegistrationUpload as u8 + 1]);
input.extend_from_slice(&total_length.to_be_bytes()[8 - 3..]);
input.extend_from_slice(&envelope_bytes);
input.extend_from_slice(&pubkey_length.to_be_bytes()[8 - 2..]);
input.extend_from_slice(&pubkey_bytes[..]);
let r3 = RegisterThirdMessage::<X25519KeyPair, sha2::Sha256>::deserialize(&input[..]).unwrap();
@@ -150,11 +193,12 @@ fn register_third_message_roundtrip() {
#[test]
fn login_first_message_roundtrip() {
let pt = random_ristretto_point();
let pt_bytes = pt.to_arr().to_vec();
let header = [4, 0, 0, 36, 0, 0, 0, 32];
let mut rng = OsRng;
let alpha = random_ristretto_point();
let alpha_bytes = alpha.to_arr().to_vec();
let id_length: usize = rng.gen_range(0, MAX_ID_LENGTH);
let mut id = [0u8; MAX_ID_LENGTH];
rng.fill_bytes(&mut id);
let client_e_kp = Default::generate_random_keypair(&mut rng).unwrap();
let mut client_nonce = [0u8; NONCE_LEN];
@@ -162,9 +206,16 @@ fn login_first_message_roundtrip() {
let ke1m: Vec<u8> = [&client_nonce[..], &client_e_kp.public()].concat();
let alpha_length = alpha_bytes.len();
let total_length_without_ke1m: usize = id_length + alpha_length + 4;
let mut input = Vec::new();
input.extend_from_slice(&header);
input.extend_from_slice(pt_bytes.as_slice());
input.extend_from_slice(&[ProtocolMessageType::CredentialRequest as u8 + 1]);
input.extend_from_slice(&total_length_without_ke1m.to_be_bytes()[8 - 3..]);
input.extend_from_slice(&id_length.to_be_bytes()[8 - 2..]);
input.extend_from_slice(&id[..id_length]);
input.extend_from_slice(&alpha_length.to_be_bytes()[8 - 2..]);
input.extend_from_slice(&alpha_bytes);
input.extend_from_slice(&ke1m[..]);
let l1 = LoginFirstMessage::<Default>::deserialize(input.as_slice()).unwrap();
@@ -176,15 +227,11 @@ fn login_first_message_roundtrip() {
fn login_second_message_roundtrip() {
let pt = random_ristretto_point();
let pt_bytes = pt.to_arr().to_vec();
let header = [5, 0, 0, 134, 0, 32];
let mut rng = OsRng;
let skp = Default::generate_random_keypair(&mut rng).unwrap();
let pubkey_bytes = skp.public().to_arr();
let intermediate1 = [0, 96];
let intermediate2 = [0, 0];
let mut key = [0u8; 32];
rng.fill_bytes(&mut key);
@@ -192,7 +239,7 @@ fn login_second_message_roundtrip() {
rng.fill_bytes(&mut msg);
let (envelope, _) =
Envelope::<sha2::Sha256>::seal(&key, &msg, &pubkey_bytes, &mut rng).unwrap();
Envelope::<sha2::Sha256>::seal_raw(&key, &msg, &pubkey_bytes, &mut rng).unwrap();
let server_e_kp = Default::generate_random_keypair(&mut rng).unwrap();
let mut mac = [0u8; 32];
@@ -202,15 +249,18 @@ fn login_second_message_roundtrip() {
let ke2m: Vec<u8> = [&server_nonce[..], &server_e_kp.public(), &mac[..]].concat();
let total_length_without_ke2m: usize = pt_bytes.len() + envelope.to_bytes().len() + 4;
let mut input = Vec::new();
input.extend_from_slice(&header);
input.extend_from_slice(&[ProtocolMessageType::CredentialResponse as u8 + 1]);
input.extend_from_slice(&total_length_without_ke2m.to_be_bytes()[8 - 3..]);
input.extend_from_slice(&pt_bytes.len().to_be_bytes()[8 - 2..]);
input.extend_from_slice(pt_bytes.as_slice());
input.extend_from_slice(&intermediate1[..]);
input.extend_from_slice(&envelope.to_bytes().len().to_be_bytes()[8 - 2..]);
input.extend_from_slice(&envelope.to_bytes());
input.extend_from_slice(&intermediate2[..]);
input.extend_from_slice(&ke2m[..]);
let l2 = LoginSecondMessage::<Default>::deserialize(input.as_slice()).unwrap();
let l2 = LoginSecondMessage::<Default>::deserialize(&input).unwrap();
let l2_bytes = l2.serialize();
assert_eq!(input, l2_bytes);
}
@@ -219,6 +269,13 @@ fn login_second_message_roundtrip() {
fn client_login_roundtrip() {
let pw = b"hunter2";
let mut rng = OsRng;
let id_u_length: usize = rng.gen_range(0, MAX_ID_LENGTH);
let id_s_length: usize = rng.gen_range(0, MAX_ID_LENGTH);
let mut id_u = [0u8; MAX_ID_LENGTH];
rng.fill_bytes(&mut id_u);
let mut id_s = [0u8; MAX_ID_LENGTH];
rng.fill_bytes(&mut id_s);
let sc = <RistrettoPoint as Group>::random_scalar(&mut rng);
let client_e_kp = Default::generate_random_keypair(&mut rng).unwrap();
@@ -230,8 +287,10 @@ fn client_login_roundtrip() {
hasher.update(l1_data);
let hashed_l1 = hasher.finalize();
// serialization order: scalar, password, ke1_state
// serialization order: id_u, id_s, scalar, password, ke1_state
let bytes: Vec<u8> = [
&serialize(&id_u[..id_u_length], 2)[..],
&serialize(&id_s[..id_s_length], 2)[..],
&sc.as_bytes()[..],
&pw[..],
client_e_kp.public(),
+27 -27
View File
@@ -64,35 +64,35 @@ pub struct TestVectorParameters {
static TEST_VECTOR: &str = r#"
{
"client_s_pk": "b2341df425f90244c72d8e19b249ca0d6d1a3a3dfe6ee1773e1b782a81efef29",
"client_s_sk": "701e8cd1263abd2f2a22d4dc94b1d5fe3c9cb14030e7e7c154745825b059fd7f",
"client_e_pk": "97cb1eb93a69542597517b110ccca457d5ce8d8bfcbfb2a9258bb7b4bd7f716e",
"client_e_sk": "80616968ed8daae02c02d3ba41a70104ed0deecd2276e058994d601a1351b359",
"server_s_pk": "e12d737e520eaf8504fbf302c2945011bff360bdf02ee102f2ebd6a883c80e02",
"server_s_sk": "9075d3d3c5b6bc2f6218e7672c0532c619ce09dddf196006c5ffdaf628a3d760",
"server_e_pk": "f73d27d7ca78ded52209bc3bae000f9d95b147360edac1e97c148a3a7396a279",
"server_e_sk": "a0e59a07908fc793c590fd83343003a54330e24af908ed31c921e6e6504c3248",
"client_s_pk": "db67c19dde3ff9df4226c638056bf740811d6136b41d81a9995a29d8ae4da74a",
"client_s_sk": "c0580c0dcfba5b38e3bf7dd110bd5025c319678b30c8baecaf9c2ef3c959f253",
"client_e_pk": "c3a4413191704cbe3ee1cc8293a565e260a3cbadfdb091bc00e953b33883c363",
"client_e_sk": "18be455fafb4cbe97a7531c2fc4ff2ce9b7bfc0119b0fcd7660443ddd0ec4068",
"server_s_pk": "2d3e373aaa1b3fb0df397789b671ca33f1b880bcc5ebc89b9e390b5ebb720e1d",
"server_s_sk": "48bb316e50d6c93a6d4a95eba0652ab147eb422c7207bc780ebd47f952a8f164",
"server_e_pk": "6bcb8d80d0fcf242e4ed4d414375d66a696d1bfe220af29681c89835444b9d7b",
"server_e_sk": "b88df6767ae031eb77be76b66ad467bea6ff26a41db963ff3b4db81ed6c72452",
"password": "70617373776f7264",
"blinding_factor_raw": "ca2d8ae51794579bd0f46044d7daccf222b4590053536b48575bc169f7478fd0a0b580fb0aae948c26ba403a2e7b98f563e434a0aad93f4105419c474453c34e",
"blinding_factor": "5a9a073b1a1efedebdb404bc073ae74b316920d68ab628bed0c500cae95d6e02",
"blinding_factor_raw": "7235ed80e9335579c8fbda9e61e8c92358b53267f33d14002cf1ee8e4a452190706c642cda5611d54aba2d8aebe91c20d230ce350d6bc76ccde2bbe3c3b38af3",
"blinding_factor": "ccfacfd5e65693b9ea7b1bbe8c61d83e20bc67a54465d0659573f2801a474b0a",
"pepper": "706570706572",
"oprf_key": "203fabe2af9c8dc668b81db1ece9c2412c94c276495f33202479886de1b12907",
"envelope_nonce": "b0076712e01fecdb12301d5d7da92236e47f20494e68defb32084f1ab6c3d4f8",
"client_nonce": "b9f09e9b0606fa88c4194011d5c204861b73c43cbf1ea0d08c03ec2fd6d05572",
"server_nonce": "a213c02274e7f20fc3b571d25e98854c5dae2cfde6c9bf228a66bf3eff3e2a97",
"r1": "01000024000000207e2c67a156ab27490f20008fcae9e9f722d8a9f4eeac373a711259981ca05dd5",
"r2": "020000280020710fdd19883e869e784c84f2864fa0bfc227662404b77cc8a54d79ae7fb931ea000001010103",
"r3": "03000088b0076712e01fecdb12301d5d7da92236e47f20494e68defb32084f1ab6c3d4f80020923b1d26cac4e3d91cec445b3322f4cc69a727f184353cb4dfe6d55a4c7d2bb400000020b77fbd41eacb8434f102c8c29cd4831e708046d38615df566675421ae8eb49330020b2341df425f90244c72d8e19b249ca0d6d1a3a3dfe6ee1773e1b782a81efef29",
"l1": "04000024000000207e2c67a156ab27490f20008fcae9e9f722d8a9f4eeac373a711259981ca05dd5b9f09e9b0606fa88c4194011d5c204861b73c43cbf1ea0d08c03ec2fd6d0557297cb1eb93a69542597517b110ccca457d5ce8d8bfcbfb2a9258bb7b4bd7f716e",
"l2": "050000860020710fdd19883e869e784c84f2864fa0bfc227662404b77cc8a54d79ae7fb931ea0060b0076712e01fecdb12301d5d7da92236e47f20494e68defb32084f1ab6c3d4f8923b1d26cac4e3d91cec445b3322f4cc69a727f184353cb4dfe6d55a4c7d2bb4b77fbd41eacb8434f102c8c29cd4831e708046d38615df566675421ae8eb49330000a0e59a07908fc793c590fd83343003a54330e24af908ed31c921e6e6504c3248f73d27d7ca78ded52209bc3bae000f9d95b147360edac1e97c148a3a7396a27939ccf2a17a5b281068665b4865e6c6331533461a8e10a4ceffc4c6a6609c326a",
"l3": "127144e6469e001d56237a58c8c869a8173e042bf2ff19d8331441d36ada9c3f",
"client_registration_state": "5a9a073b1a1efedebdb404bc073ae74b316920d68ab628bed0c500cae95d6e0270617373776f7264",
"client_login_state": "5a9a073b1a1efedebdb404bc073ae74b316920d68ab628bed0c500cae95d6e0280616968ed8daae02c02d3ba41a70104ed0deecd2276e058994d601a1351b359b9f09e9b0606fa88c4194011d5c204861b73c43cbf1ea0d08c03ec2fd6d05572f258311568d792d6ebecee225c0fde4512139e29a435e9f9a0b82dc3809a83ab70617373776f7264",
"server_registration_state": "203fabe2af9c8dc668b81db1ece9c2412c94c276495f33202479886de1b12907",
"server_login_state": "ebc0953924d55ad66aa801a7c85f47f35889b90002451a04fb7134b8a2a5a33cd69098c0a81ce06f58cbe4fd6ba23c9c1404ad6f639ba64d5f0f7bf0a041fc5872b17f13bd41cbfbdfa8d74bc94ec1abcc77b9a3da8fbad918ca0a5f84a81443",
"password_file": "203fabe2af9c8dc668b81db1ece9c2412c94c276495f33202479886de1b12907b2341df425f90244c72d8e19b249ca0d6d1a3a3dfe6ee1773e1b782a81efef29b0076712e01fecdb12301d5d7da92236e47f20494e68defb32084f1ab6c3d4f8923b1d26cac4e3d91cec445b3322f4cc69a727f184353cb4dfe6d55a4c7d2bb4b77fbd41eacb8434f102c8c29cd4831e708046d38615df566675421ae8eb4933",
"export_key": "da3a52148a58168c9f804df5e216e3d3f16e935d4d70a5eb249433d88e02ae4c",
"shared_secret": "72b17f13bd41cbfbdfa8d74bc94ec1abcc77b9a3da8fbad918ca0a5f84a81443"
"oprf_key": "44f6b4ad762943517e400ce878e0c1409573ee98d96c14e5a507e601788c2207",
"envelope_nonce": "ed0eb006204e163097595826da4f4e8df648fdcb54feef22cefbbdd1c9e85038",
"client_nonce": "774cd501736601475cea7a382cb1d38b34c574baab82c0e87cbe3dcf9de3d0a6",
"server_nonce": "a627d3525b162594be0c134ccf5fd4cab719e37ec945e70a128d66abb3bb58c4",
"r1": "010000240000002060ebaf93d439cd229e8fd843b9cd2656d40cba15981f04464c9842f98557f30b",
"r2": "020000280020ab7af6fd8628eded06289ccf85ad8e2f4bc8d584129b923cdc6a2865300a8f6a000001010103",
"r3": "030000aeed0eb006204e163097595826da4f4e8df648fdcb54feef22cefbbdd1c9e85038002358a913a1bcdee339dde801af723f204f5cdc9335e0256eed49a4b36a226a1a062ddc9500230300202d3e373aaa1b3fb0df397789b671ca33f1b880bcc5ebc89b9e390b5ebb720e1d0020a2eb1b19e25b90e0089e543dd391ca362f05d01fa6d521d00c35312755c665f00020db67c19dde3ff9df4226c638056bf740811d6136b41d81a9995a29d8ae4da74a",
"l1": "040000240000002060ebaf93d439cd229e8fd843b9cd2656d40cba15981f04464c9842f98557f30b774cd501736601475cea7a382cb1d38b34c574baab82c0e87cbe3dcf9de3d0a6c3a4413191704cbe3ee1cc8293a565e260a3cbadfdb091bc00e953b33883c363",
"l2": "050000b00020ab7af6fd8628eded06289ccf85ad8e2f4bc8d584129b923cdc6a2865300a8f6a008ced0eb006204e163097595826da4f4e8df648fdcb54feef22cefbbdd1c9e85038002358a913a1bcdee339dde801af723f204f5cdc9335e0256eed49a4b36a226a1a062ddc9500230300202d3e373aaa1b3fb0df397789b671ca33f1b880bcc5ebc89b9e390b5ebb720e1d0020a2eb1b19e25b90e0089e543dd391ca362f05d01fa6d521d00c35312755c665f0b88df6767ae031eb77be76b66ad467bea6ff26a41db963ff3b4db81ed6c724526bcb8d80d0fcf242e4ed4d414375d66a696d1bfe220af29681c89835444b9d7b3a1f7e046c1460ed3a47fff7be87b5670d568a1bab2ae7f5b7ee70ff99c3d21d",
"l3": "28b18759b0f5977c607170b7ceb1b5d75bffbc185991ae001c0fded87f826d89",
"client_registration_state": "00000000ccfacfd5e65693b9ea7b1bbe8c61d83e20bc67a54465d0659573f2801a474b0a70617373776f7264",
"client_login_state": "00000000ccfacfd5e65693b9ea7b1bbe8c61d83e20bc67a54465d0659573f2801a474b0a18be455fafb4cbe97a7531c2fc4ff2ce9b7bfc0119b0fcd7660443ddd0ec4068774cd501736601475cea7a382cb1d38b34c574baab82c0e87cbe3dcf9de3d0a68d5a62ba390f1ee0419616e1a135e609ad248c7a3ee7edf4fb90f575148758d070617373776f7264",
"server_registration_state": "44f6b4ad762943517e400ce878e0c1409573ee98d96c14e5a507e601788c2207",
"server_login_state": "14e5fe977591bb71f1e2bcd0542d26023c818048a257781fe276a3e8f9e0be4d58075843e2050013c815c6ef3d015a4ef1294543225832281adec71e1a92fa32a783f8c52f881f276f1c780f21b3fcb4eb36b75daea84b3bb9f7ce0699842864",
"password_file": "44f6b4ad762943517e400ce878e0c1409573ee98d96c14e5a507e601788c2207db67c19dde3ff9df4226c638056bf740811d6136b41d81a9995a29d8ae4da74aed0eb006204e163097595826da4f4e8df648fdcb54feef22cefbbdd1c9e85038002358a913a1bcdee339dde801af723f204f5cdc9335e0256eed49a4b36a226a1a062ddc9500230300202d3e373aaa1b3fb0df397789b671ca33f1b880bcc5ebc89b9e390b5ebb720e1d0020a2eb1b19e25b90e0089e543dd391ca362f05d01fa6d521d00c35312755c665f0",
"export_key": "48e39aeec42923ada9a239b231ff290efb1d4d01ccec8cd820a42dde10ff0d09",
"shared_secret": "a783f8c52f881f276f1c780f21b3fcb4eb36b75daea84b3bb9f7ce0699842864"
}
"#;
-230
View File
@@ -1,230 +0,0 @@
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
use crate::{
ciphersuite::CipherSuite,
envelope::Envelope,
group::Group,
key_exchange::{
traits::{KeyExchange, ToBytes},
tripledh::{TripleDH, NONCE_LEN},
},
keypair::{KeyPair, SizedBytes, X25519KeyPair},
opaque::*,
};
use curve25519_dalek::ristretto::RistrettoPoint;
use generic_array::typenum::Unsigned;
use proptest::{collection::vec, prelude::*};
use rand_core::{OsRng, RngCore};
use sha2::{Digest, Sha256};
use std::convert::TryFrom;
struct Default;
impl CipherSuite for Default {
type Group = RistrettoPoint;
type KeyFormat = crate::keypair::X25519KeyPair;
type KeyExchange = TripleDH;
type Hash = sha2::Sha256;
type SlowHash = crate::slow_hash::NoOpHash;
}
fn random_ristretto_point() -> RistrettoPoint {
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)
}
#[test]
fn client_registration_roundtrip() {
let pw = b"hunter2";
let mut rng = OsRng;
let sc = <RistrettoPoint as Group>::random_scalar(&mut rng);
// serialization order: scalar, password
let bytes: Vec<u8> = [&sc.as_bytes()[..], &pw[..]].concat();
let reg = ClientRegistration::<Default>::try_from(&bytes[..]).unwrap();
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, bytes);
}
#[test]
fn server_registration_roundtrip() {
// If we don't have envelope and client_pk, the server registration just
// contains the prf key
let mut rng = OsRng;
let sc = <RistrettoPoint as Group>::random_scalar(&mut rng);
let mut oprf_bytes: Vec<u8> = vec![];
oprf_bytes.extend_from_slice(sc.as_bytes());
let reg = ServerRegistration::<Default>::try_from(&oprf_bytes[..]).unwrap();
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, oprf_bytes);
// If we do have envelope and client pk, the server registration contains
// the whole kit
let key_len =
<<<Default as CipherSuite>::KeyFormat as KeyPair>::Repr as SizedBytes>::Len::to_usize();
let envelope_size = key_len + Envelope::<sha2::Sha256>::additional_size();
let mut mock_envelope_bytes = vec![0u8; envelope_size];
rng.fill_bytes(&mut mock_envelope_bytes);
println!("{}", mock_envelope_bytes.len());
let mock_client_kp = Default::generate_random_keypair(&mut rng).unwrap();
// serialization order: scalar, public key, envelope
let mut bytes = Vec::<u8>::new();
bytes.extend_from_slice(sc.as_bytes());
bytes.extend_from_slice(&mock_client_kp.public().to_arr());
bytes.extend_from_slice(&mock_envelope_bytes);
let reg = ServerRegistration::<Default>::try_from(&bytes[..]).unwrap();
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, bytes);
}
#[test]
fn register_first_message_roundtrip() {
let pt = random_ristretto_point();
let pt_bytes = pt.to_arr();
let r1 = RegisterFirstMessage::<RistrettoPoint>::try_from(pt_bytes.as_slice()).unwrap();
let r1_bytes = r1.to_bytes();
assert_eq!(pt_bytes, r1_bytes);
}
#[test]
fn register_second_message_roundtrip() {
let pt = random_ristretto_point();
let pt_bytes = pt.to_arr();
let message = pt_bytes.to_vec();
let r2 = RegisterSecondMessage::<RistrettoPoint>::try_from(&message[..]).unwrap();
let r2_bytes = r2.to_bytes();
assert_eq!(message, r2_bytes);
}
#[test]
fn register_third_message_roundtrip() {
let mut rng = OsRng;
let skp = Default::generate_random_keypair(&mut rng).unwrap();
let pubkey_bytes = skp.public().to_arr();
let mut key = [0u8; 32];
rng.fill_bytes(&mut key);
let mut msg = [0u8; 32];
rng.fill_bytes(&mut msg);
let (ciphertext, _) =
Envelope::<sha2::Sha256>::seal(&key, &msg, &pubkey_bytes, &mut rng).unwrap();
let message: Vec<u8> = [&ciphertext.to_bytes(), &pubkey_bytes[..]].concat();
let r3 = RegisterThirdMessage::<X25519KeyPair, sha2::Sha256>::try_from(&message[..]).unwrap();
let r3_bytes = r3.to_bytes();
assert_eq!(message, r3_bytes);
}
#[test]
fn client_login_roundtrip() {
let pw = b"hunter2";
let mut rng = OsRng;
let sc = <RistrettoPoint as Group>::random_scalar(&mut rng);
let client_e_kp = Default::generate_random_keypair(&mut rng).unwrap();
let mut client_nonce = [0u8; NONCE_LEN];
rng.fill_bytes(&mut client_nonce);
let l1_data = [&sc.to_bytes()[..], &client_nonce, client_e_kp.public()].concat();
let mut hasher = Sha256::new();
hasher.update(l1_data);
let hashed_l1 = hasher.finalize();
// serialization order: scalar, password, ke1_state
let bytes: Vec<u8> = [
&sc.as_bytes()[..],
&pw[..],
client_e_kp.public(),
&client_nonce,
hashed_l1.as_slice(),
]
.concat();
let reg = ClientLogin::<Default>::try_from(&bytes[..]).unwrap();
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, bytes);
}
#[test]
fn login_first_message_roundtrip() {
let mut rng = OsRng;
let client_e_kp = Default::generate_random_keypair(&mut rng).unwrap();
let mut client_nonce = [0u8; NONCE_LEN];
rng.fill_bytes(&mut client_nonce);
let ke1m: Vec<u8> = [&client_nonce[..], &client_e_kp.public()].concat();
let reg = <TripleDH as KeyExchange<sha2::Sha256, crate::keypair::X25519KeyPair>>::KE1Message::try_from(
&ke1m[..],
)
.unwrap();
let reg_bytes = reg.to_bytes();
assert_eq!(reg_bytes, ke1m);
}
proptest! {
#[test]
fn test_nocrash_register_first_message(bytes in vec(any::<u8>(), 0..200)) {
RegisterFirstMessage::<RistrettoPoint>::try_from(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_register_second_message(bytes in vec(any::<u8>(), 0..200)) {
RegisterSecondMessage::<RistrettoPoint>::try_from(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_register_third_message(bytes in vec(any::<u8>(), 0..200)) {
RegisterThirdMessage::<crate::keypair::X25519KeyPair, sha2::Sha512>::try_from(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_login_first_message(bytes in vec(any::<u8>(), 0..500)) {
LoginFirstMessage::<Default>::try_from(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_login_second_message(bytes in vec(any::<u8>(), 0..500)) {
LoginSecondMessage::<Default>::try_from(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_login_third_message(bytes in vec(any::<u8>(), 0..500)) {
LoginThirdMessage::<Default>::try_from(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_client_registration(bytes in vec(any::<u8>(), 0..700)) {
ClientRegistration::<Default>::try_from(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_server_registration(bytes in vec(any::<u8>(), 0..700)) {
ServerRegistration::<Default>::try_from(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_client_login(bytes in vec(any::<u8>(), 0..700)) {
ClientLogin::<Default>::try_from(&bytes[..]).map_or(true, |_| true);
}
#[test]
fn test_nocrash_server_login(bytes in vec(any::<u8>(), 0..700)) {
ServerLogin::<Default>::try_from(&bytes[..]).map_or(true, |_| true);
}
}