Files
opaque-vx/src/opaque.rs
T

1168 lines
41 KiB
Rust
Raw Normal View History

2023-05-22 23:04:26 -07:00
// Copyright (c) Meta Platforms, Inc. and affiliates.
2020-06-05 09:35:14 -07:00
//
2023-05-22 23:04:26 -07:00
// This source code is dual-licensed under either the MIT license found in the
// LICENSE-MIT file in the root directory of this source tree or the Apache
2021-12-03 14:38:11 -08:00
// License, Version 2.0 found in the LICENSE-APACHE file in the root directory
2023-05-22 23:04:26 -07:00
// of this source tree. You may select, at your option, one of the above-listed
// licenses.
2020-06-05 09:35:14 -07:00
//! Provides the main OPAQUE API
use core::ops::Add;
2022-02-25 07:13:22 +01:00
use derive_where::derive_where;
2025-05-19 22:56:25 +02:00
use digest::Output;
use generic_array::typenum::{Sum, Unsigned};
2022-01-06 06:19:02 +01:00
use generic_array::{ArrayLength, GenericArray};
use hkdf::Hkdf;
use hkdf::SimpleHkdfExtract as HkdfExtract;
use rand::{CryptoRng, Rng};
2025-04-28 21:47:39 +02:00
use subtle::{Choice, ConstantTimeEq, CtOption};
2025-05-19 22:56:25 +02:00
use voprf::{BlindedElement, Group as _, OprfClient, OprfClientLen};
use zeroize::Zeroizing;
2020-06-05 09:35:14 -07:00
2025-05-19 22:56:25 +02:00
use crate::ciphersuite::{CipherSuite, KeGroup, KeHash, OprfGroup, OprfHash};
2022-01-06 06:19:02 +01:00
use crate::envelope::{Envelope, EnvelopeLen};
use crate::errors::{InternalError, ProtocolError};
2025-04-15 22:31:37 +02:00
use crate::hash::OutputSize;
2025-05-19 22:56:25 +02:00
use crate::key_exchange::group::Group;
use crate::key_exchange::shared::NonceLen;
2025-06-25 00:17:29 +02:00
use crate::key_exchange::{
Deserialize, Ke1MessageLen, Ke1StateLen, Ke2StateLen, KeyExchange, Serialize,
SerializedContext, SerializedCredentialResponse, SerializedIdentifiers,
2025-05-19 22:56:25 +02:00
};
use crate::keypair::{
KeyPair, OprfSeed, OprfSeedSerialization, PrivateKey, PrivateKeySerialization, PublicKey,
2022-01-06 06:19:02 +01:00
};
2022-04-02 01:10:00 +02:00
use crate::ksf::Ksf;
2022-01-06 06:19:02 +01:00
use crate::messages::{CredentialRequestLen, RegistrationUploadLen};
use crate::serialization::{ConcatExt, GenericArrayExt, SliceExt};
2022-01-06 06:19:02 +01:00
use crate::{
CredentialFinalization, CredentialRequest, CredentialResponse, RegistrationRequest,
RegistrationResponse, RegistrationUpload, ServerLoginBuilder,
2022-01-06 06:19:02 +01:00
};
///////////////
// Constants //
// ========= //
///////////////
2021-10-25 02:54:32 -07:00
const STR_CREDENTIAL_RESPONSE_PAD: &[u8; 21] = b"CredentialResponsePad";
const STR_MASKING_KEY: &[u8; 10] = b"MaskingKey";
const STR_OPRF_KEY: &[u8; 7] = b"OprfKey";
const STR_OPAQUE_DERIVE_KEY_PAIR: &[u8; 20] = b"OPAQUE-DeriveKeyPair";
////////////////////////////
// High-level API Structs //
// ====================== //
////////////////////////////
/// The state elements the server holds upon setup
#[cfg_attr(
2022-01-04 00:50:40 +01:00
feature = "serde",
2022-04-02 01:10:00 +02:00
derive(serde::Deserialize, serde::Serialize),
2023-02-04 22:25:41 +01:00
serde(bound(
deserialize = "<KeGroup<CS> as Group>::Pk: serde::Deserialize<'de>, <KeGroup<CS> as \
Group>::Sk: serde::Deserialize<'de>, SK: serde::Deserialize<'de>, OS: \
serde::Deserialize<'de>",
serialize = "<KeGroup<CS> as Group>::Pk: serde::Serialize, <KeGroup<CS> as Group>::Sk: \
serde::Serialize, SK: serde::Serialize, OS: serde::Serialize"
2023-02-04 22:25:41 +01:00
))
)]
2022-01-04 00:50:40 +01:00
#[derive_where(Clone)]
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; <KeGroup<CS> as Group>::Pk, <KeGroup<CS> as Group>::Sk, SK, OS
)]
2025-05-05 13:12:54 +02:00
pub struct ServerSetup<
CS: CipherSuite,
2025-05-19 22:56:25 +02:00
SK: Clone = PrivateKey<KeGroup<CS>>,
OS: Clone = OprfSeed<OprfHash<CS>>,
2025-05-05 13:12:54 +02:00
> {
oprf_seed: OS,
2025-05-19 22:56:25 +02:00
keypair: KeyPair<KeGroup<CS>, SK>,
2025-05-20 21:49:11 +02:00
pub(crate) dummy_pk: PublicKey<KeGroup<CS>>,
}
/// The state elements the client holds to register itself
2022-04-02 01:10:00 +02:00
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
2023-02-04 22:25:41 +01:00
serde(bound = "")
2022-04-02 01:10:00 +02:00
)]
2022-02-25 07:13:22 +01:00
#[derive_where(Clone, ZeroizeOnDrop)]
2022-01-04 00:50:40 +01:00
#[derive_where(
Debug, Eq, Hash, PartialEq;
2022-04-17 16:23:31 -07:00
voprf::OprfClient<CS::OprfCs>,
2022-04-02 01:10:00 +02:00
voprf::BlindedElement<CS::OprfCs>,
2022-01-04 00:50:40 +01:00
)]
2025-04-15 22:31:37 +02:00
pub struct ClientRegistration<CS: CipherSuite> {
pub(crate) oprf_client: OprfClient<CS::OprfCs>,
pub(crate) blinded_element: BlindedElement<CS::OprfCs>,
}
/// The state elements the server holds to record a registration
2022-04-02 01:10:00 +02:00
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(bound(
deserialize = "<KeGroup<CS> as Group>::Pk: serde::Deserialize<'de>",
serialize = "<KeGroup<CS> as Group>::Pk: serde::Serialize"
))
2022-04-02 01:10:00 +02:00
)]
2022-02-25 07:13:22 +01:00
#[derive_where(Clone, ZeroizeOnDrop)]
2025-05-19 22:56:25 +02:00
#[derive_where(Debug, Eq, Hash, Ord, PartialEq, PartialOrd; <KeGroup<CS> as Group>::Pk)]
2025-04-15 22:31:37 +02:00
pub struct ServerRegistration<CS: CipherSuite>(pub(crate) RegistrationUpload<CS>);
/// The state elements the client holds to perform a login
2022-04-02 01:10:00 +02:00
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
2023-02-04 22:25:41 +01:00
serde(bound(
2025-05-19 22:56:25 +02:00
deserialize = "<CS::KeyExchange as KeyExchange>::KE1Message: serde::Deserialize<'de>, \
<CS::KeyExchange as KeyExchange>::KE1State: serde::Deserialize<'de>",
serialize = "<CS::KeyExchange as KeyExchange>::KE1Message: serde::Serialize, \
<CS::KeyExchange as KeyExchange>::KE1State: serde::Serialize"
2023-02-04 22:25:41 +01:00
))
2022-04-02 01:10:00 +02:00
)]
2022-02-25 07:13:22 +01:00
#[derive_where(Clone, ZeroizeOnDrop)]
2022-01-04 00:50:40 +01:00
#[derive_where(
Debug, Eq, Hash, PartialEq;
2022-04-17 16:23:31 -07:00
voprf::OprfClient<CS::OprfCs>,
2025-05-19 22:56:25 +02:00
<CS::KeyExchange as KeyExchange>::KE1State,
2022-01-04 00:50:40 +01:00
CredentialRequest<CS>,
)]
2025-04-15 22:31:37 +02:00
pub struct ClientLogin<CS: CipherSuite> {
pub(crate) oprf_client: OprfClient<CS::OprfCs>,
2025-05-19 22:56:25 +02:00
pub(crate) ke1_state: <CS::KeyExchange as KeyExchange>::KE1State,
2022-02-25 07:13:22 +01:00
pub(crate) credential_request: CredentialRequest<CS>,
}
/// The state elements the server holds to record a login
2022-04-02 01:10:00 +02:00
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
2023-02-04 22:25:41 +01:00
serde(bound(
2025-05-19 22:56:25 +02:00
deserialize = "<CS::KeyExchange as KeyExchange>::KE2State<CS>: serde::Deserialize<'de>",
serialize = "<CS::KeyExchange as KeyExchange>::KE2State<CS>: serde::Serialize"
2023-02-04 22:25:41 +01:00
))
2022-04-02 01:10:00 +02:00
)]
2022-02-25 07:13:22 +01:00
#[derive_where(Clone, ZeroizeOnDrop)]
2025-05-19 22:56:25 +02:00
#[derive_where(Debug, Eq, Hash, PartialEq; <CS::KeyExchange as KeyExchange>::KE2State<CS>)]
2025-04-15 22:31:37 +02:00
pub struct ServerLogin<CS: CipherSuite> {
2025-05-19 22:56:25 +02:00
ke2_state: <CS::KeyExchange as KeyExchange>::KE2State<CS>,
}
////////////////////////////////
// High-level Implementations //
// ========================== //
////////////////////////////////
// Server Setup
// ============
2025-05-19 22:56:25 +02:00
impl<CS: CipherSuite> ServerSetup<CS, PrivateKey<KeGroup<CS>>> {
/// Generate a new instance of server setup
pub fn new<R: CryptoRng + Rng>(rng: &mut R) -> Self {
2025-05-19 22:56:25 +02:00
let keypair = KeyPair::random(rng);
Self::new_with_key_pair(rng, keypair)
2021-07-20 14:16:53 +02:00
}
}
2022-01-04 00:50:40 +01:00
/// Length of [`ServerSetup`] in bytes for serialization.
2025-05-05 13:12:54 +02:00
pub type ServerSetupLen<
CS: CipherSuite,
2025-05-19 22:56:25 +02:00
SK: PrivateKeySerialization<KeGroup<CS>>,
2025-05-05 13:12:54 +02:00
OS: OprfSeedSerialization<OprfHash<CS>, SK::Error>,
2025-05-20 21:49:11 +02:00
> = Sum<Sum<OS::Len, SK::Len>, <KeGroup<CS> as Group>::PkLen>;
2025-05-05 13:12:54 +02:00
impl<CS: CipherSuite, SK: Clone, OS: Clone> ServerSetup<CS, SK, OS> {
/// Create [`ServerSetup`] with the given keypair and OPRF seed.
///
/// This function should not be used to restore a previously-existing
2023-10-08 21:48:43 +02:00
/// instance of [`ServerSetup`]. Instead, use [`ServerSetup::serialize`] and
/// [`ServerSetup::deserialize`] for this purpose.
pub fn new_with_key_pair_and_seed<R: CryptoRng + Rng>(
2021-07-20 14:16:53 +02:00
rng: &mut R,
2025-05-19 22:56:25 +02:00
keypair: KeyPair<KeGroup<CS>, SK>,
2025-05-05 13:12:54 +02:00
oprf_seed: OS,
2022-01-04 00:50:40 +01:00
) -> Self {
Self {
2025-05-05 13:12:54 +02:00
oprf_seed,
2021-07-20 14:16:53 +02:00
keypair,
2025-05-20 21:49:11 +02:00
dummy_pk: KeyPair::<KeGroup<CS>>::random(rng).public().clone(),
2022-01-04 00:50:40 +01:00
}
}
2025-05-05 13:12:54 +02:00
/// The information required to generate the key material for
/// [`ServerRegistration::start_with_key_material()`] and
/// [`ServerLogin::builder_with_key_material()`].
pub fn key_material_info<'ci>(
&self,
credential_identifier: &'ci [u8],
) -> KeyMaterialInfo<'ci, OS> {
KeyMaterialInfo {
ikm: self.oprf_seed.clone(),
info: [credential_identifier, STR_OPRF_KEY],
}
}
/// Serialization into bytes
2025-05-05 13:12:54 +02:00
pub fn serialize(&self) -> GenericArray<u8, ServerSetupLen<CS, SK, OS>>
2022-01-04 00:50:40 +01:00
where
2025-05-19 22:56:25 +02:00
SK: PrivateKeySerialization<KeGroup<CS>>,
2025-05-05 13:12:54 +02:00
OS: OprfSeedSerialization<OprfHash<CS>, SK::Error>,
2025-05-20 21:49:11 +02:00
// ServerSetup: Hash + KeSk + KePk
2025-05-05 13:12:54 +02:00
OS::Len: Add<SK::Len>,
Sum<OS::Len, SK::Len>: ArrayLength + Add<<KeGroup<CS> as Group>::PkLen>,
ServerSetupLen<CS, SK, OS>: ArrayLength,
2022-01-04 00:50:40 +01:00
{
self.oprf_seed
2025-05-05 13:12:54 +02:00
.serialize()
.cat(SK::serialize_key_pair(&self.keypair))
.cat(self.dummy_pk.serialize())
}
/// Deserialization from bytes
2025-05-19 22:56:25 +02:00
pub fn deserialize(mut input: &[u8]) -> Result<Self, ProtocolError<SK::Error>>
where
2025-05-19 22:56:25 +02:00
SK: PrivateKeySerialization<KeGroup<CS>>,
2025-05-05 13:12:54 +02:00
OS: OprfSeedSerialization<OprfHash<CS>, SK::Error>,
{
Ok(Self {
2025-05-19 22:56:25 +02:00
oprf_seed: OS::deserialize_take(&mut input)?,
keypair: SK::deserialize_take_key_pair(&mut input)?,
2025-05-20 21:49:11 +02:00
dummy_pk: PublicKey::deserialize_take(&mut input)
2021-07-20 11:49:37 +02:00
.map_err(ProtocolError::into_custom)?,
})
}
/// Returns the keypair
2025-05-19 22:56:25 +02:00
pub fn keypair(&self) -> &KeyPair<KeGroup<CS>, SK> {
&self.keypair
}
}
2025-05-05 13:12:54 +02:00
impl<CS: CipherSuite, SK: Clone> ServerSetup<CS, SK> {
/// Create [`ServerSetup`] with the given keypair
///
/// This function should not be used to restore a previously-existing
/// instance of [`ServerSetup`]. Instead, use [`ServerSetup::serialize`] and
/// [`ServerSetup::deserialize`] for this purpose.
pub fn new_with_key_pair<R: CryptoRng + Rng>(
2025-05-05 13:12:54 +02:00
rng: &mut R,
2025-05-19 22:56:25 +02:00
keypair: KeyPair<KeGroup<CS>, SK>,
2025-05-05 13:12:54 +02:00
) -> Self {
let mut oprf_seed = Output::<OprfHash<CS>>::default();
2025-05-05 13:12:54 +02:00
rng.fill_bytes(&mut oprf_seed);
2025-05-19 22:56:25 +02:00
Self::new_with_key_pair_and_seed(rng, keypair, OprfSeed(oprf_seed))
2025-05-05 13:12:54 +02:00
}
}
/// The information required to generate the key material for
/// [`ServerRegistration::start_with_key_material()`] and
/// [`ServerLogin::builder_with_key_material()`].
///
2025-05-19 22:56:25 +02:00
/// Use a HKDF, with the input key material [`ikm`](Self::ikm), expand operation
/// with [`info`](Self::info) with an output length
/// of [`CS::OprfCs::ScalarLen`](voprf::Group::ScalarLen).
2025-05-05 13:12:54 +02:00
pub struct KeyMaterialInfo<'ci, OS: Clone> {
/// Input key material for the HKDF.
pub ikm: OS,
/// Info for the HKDF expand operation.
pub info: [&'ci [u8]; 2],
}
2020-06-05 09:35:14 -07:00
// Registration
// ============
2022-01-06 00:10:57 +01:00
pub(crate) type ClientRegistrationLen<CS: CipherSuite> =
2025-05-19 22:56:25 +02:00
Sum<<OprfGroup<CS> as voprf::Group>::ScalarLen, <OprfGroup<CS> as voprf::Group>::ElemLen>;
2022-01-06 00:10:57 +01:00
2025-04-15 22:31:37 +02:00
impl<CS: CipherSuite> ClientRegistration<CS> {
/// Serialization into bytes
2022-01-06 00:10:57 +01:00
pub fn serialize(&self) -> GenericArray<u8, ClientRegistrationLen<CS>>
where
// ClientRegistration: KgSk + KgPk
<OprfGroup<CS> as voprf::Group>::ScalarLen:
Add<<OprfGroup<CS> as voprf::Group>::ElemLen> + ArrayLength,
<OprfGroup<CS> as voprf::Group>::ElemLen: ArrayLength,
ClientRegistrationLen<CS>: ArrayLength,
2022-01-06 00:10:57 +01:00
{
GenericArray::from_ha0_4(self.oprf_client.serialize())
.cat(GenericArray::from_ha0_4(self.blinded_element.serialize()))
}
/// Deserialization from bytes
2025-05-19 22:56:25 +02:00
pub fn deserialize(mut input: &[u8]) -> Result<Self, ProtocolError> {
let oprf_client = OprfClient::deserialize(input)?;
input = &input[OprfClientLen::<CS::OprfCs>::USIZE..];
let blinded_element = BlindedElement::deserialize(input)?;
2021-07-12 12:33:19 -07:00
2020-06-05 09:35:14 -07:00
Ok(Self {
2025-05-19 22:56:25 +02:00
oprf_client,
blinded_element,
2020-06-05 09:35:14 -07:00
})
}
2022-01-06 06:19:02 +01:00
/// Returns an initial "blinded" request to send to the server, as well as a
2023-10-08 21:48:43 +02:00
/// [`ClientRegistration`]
pub fn start<R: Rng + CryptoRng>(
2020-12-12 21:53:33 -08:00
blinding_factor_rng: &mut R,
2020-06-05 09:35:14 -07:00
password: &[u8],
2020-12-12 21:53:33 -08:00
) -> Result<ClientRegistrationStartResult<CS>, ProtocolError> {
2021-10-25 02:54:32 -07:00
let blind_result = blind::<CS, _>(blinding_factor_rng, password)?;
2020-06-05 09:35:14 -07:00
2020-12-12 21:53:33 -08:00
Ok(ClientRegistrationStartResult {
2022-01-04 00:50:40 +01:00
message: RegistrationRequest {
2021-10-25 02:54:32 -07:00
blinded_element: blind_result.message.clone(),
},
state: Self {
oprf_client: blind_result.state,
blinded_element: blind_result.message,
},
2020-12-12 21:53:33 -08:00
})
2020-06-05 09:35:14 -07:00
}
2021-06-15 00:36:17 +02:00
2020-06-05 09:35:14 -07:00
/// "Unblinds" the server's answer and returns a final message containing
2022-01-06 06:19:02 +01:00
/// cryptographic identifiers, to be sent to the server on setup
/// finalization
pub fn finish<R: CryptoRng + Rng>(
self,
rng: &mut R,
2022-01-06 00:10:57 +01:00
password: &[u8],
2021-10-25 02:54:32 -07:00
registration_response: RegistrationResponse<CS>,
2021-09-02 11:28:21 +02:00
params: ClientRegistrationFinishParameters<CS>,
) -> Result<ClientRegistrationFinishResult<CS>, ProtocolError> {
2021-07-12 12:33:19 -07:00
// Check for reflected value from server and halt if detected
2021-10-25 02:54:32 -07:00
if self
.blinded_element
.value()
.ct_eq(&registration_response.evaluation_element.value())
.into()
{
2021-07-12 12:33:19 -07:00
return Err(ProtocolError::ReflectedValueError);
}
2021-07-30 02:13:27 +02:00
#[cfg_attr(not(test), allow(unused_variables))]
2021-10-25 02:54:32 -07:00
let (randomized_pwd, randomized_pwd_hasher) = get_password_derived_key::<CS>(
2022-01-06 00:10:57 +01:00
password,
2021-10-25 02:54:32 -07:00
self.oprf_client.clone(),
registration_response.evaluation_element,
2022-04-02 01:10:00 +02:00
params.ksf,
2021-10-25 02:54:32 -07:00
)?;
2022-02-25 07:13:22 +01:00
let mut masking_key = Output::<OprfHash<CS>>::default();
2021-10-25 02:54:32 -07:00
randomized_pwd_hasher
.expand(STR_MASKING_KEY, &mut masking_key)
2021-08-22 12:28:19 -07:00
.map_err(|_| InternalError::HkdfError)?;
2021-09-02 11:28:21 +02:00
let result = Envelope::<CS>::seal(
rng,
&randomized_pwd_hasher,
2021-10-25 02:54:32 -07:00
&registration_response.server_s_pk,
2021-09-02 11:28:21 +02:00
params.identifiers,
)?;
2020-06-05 09:35:14 -07:00
2020-12-12 21:53:33 -08:00
Ok(ClientRegistrationFinishResult {
message: RegistrationUpload {
2021-07-30 12:06:46 +02:00
envelope: result.0,
2022-01-04 00:50:40 +01:00
masking_key,
2021-07-30 12:06:46 +02:00
client_s_pk: result.1,
2020-06-05 09:35:14 -07:00
},
2021-07-30 12:06:46 +02:00
export_key: result.2,
2021-10-25 02:54:32 -07:00
server_s_pk: registration_response.server_s_pk,
#[cfg(test)]
state: self,
2021-07-30 00:31:12 +02:00
#[cfg(test)]
2021-07-30 12:06:46 +02:00
auth_key: result.3,
#[cfg(test)]
2021-07-30 02:13:27 +02:00
randomized_pwd,
2020-12-12 21:53:33 -08:00
})
2020-06-05 09:35:14 -07:00
}
}
2022-01-04 00:50:40 +01:00
/// Length of [`ServerRegistration`] in bytes for serialization.
pub type ServerRegistrationLen<CS> = RegistrationUploadLen<CS>;
2025-04-15 22:31:37 +02:00
impl<CS: CipherSuite> ServerRegistration<CS> {
/// Serialization into bytes
2022-01-04 00:50:40 +01:00
pub fn serialize(&self) -> GenericArray<u8, ServerRegistrationLen<CS>>
where
// RegistrationUpload: (KePk + Hash) + Envelope
2025-05-19 22:56:25 +02:00
<KeGroup<CS> as Group>::PkLen: Add<OutputSize<OprfHash<CS>>>,
Sum<<KeGroup<CS> as Group>::PkLen, OutputSize<OprfHash<CS>>>:
ArrayLength + Add<EnvelopeLen<CS>>,
RegistrationUploadLen<CS>: ArrayLength,
2022-01-04 00:50:40 +01:00
// ServerRegistration = RegistrationUpload
{
self.0.serialize()
}
2020-06-05 09:35:14 -07:00
/// Deserialization from bytes
pub fn deserialize(input: &[u8]) -> Result<Self, ProtocolError> {
Ok(Self(RegistrationUpload::deserialize(input)?))
2020-06-05 09:35:14 -07:00
}
2025-05-05 13:12:54 +02:00
/// Create a [`RegistrationResponse`] with a remote OPRF seed. To generate
/// the `key_material` see [`ServerSetup::key_material_info()`].
///
/// See [`ServerRegistration::start()`] for the regular path.
pub fn start_with_key_material<SK: Clone, OS: Clone>(
server_setup: &ServerSetup<CS, SK, OS>,
2025-05-19 22:56:25 +02:00
key_material: GenericArray<u8, <OprfGroup<CS> as voprf::Group>::ScalarLen>,
message: RegistrationRequest<CS>,
2020-12-12 21:53:33 -08:00
) -> Result<ServerRegistrationStartResult<CS>, ProtocolError> {
2025-05-05 13:12:54 +02:00
let oprf_key = oprf_key_from_key_material::<CS>(key_material)?;
2020-06-05 09:35:14 -07:00
2022-04-17 16:23:31 -07:00
let server = voprf::OprfServer::new_with_key(&oprf_key)?;
2022-12-11 06:30:05 +01:00
let evaluation_element = server.blind_evaluate(&message.blinded_element);
2020-06-05 09:35:14 -07:00
2020-12-12 21:53:33 -08:00
Ok(ServerRegistrationStartResult {
message: RegistrationResponse {
2022-02-25 07:13:22 +01:00
evaluation_element,
2025-05-05 13:12:54 +02:00
server_s_pk: server_setup.keypair().public().clone(),
2020-06-05 09:35:14 -07:00
},
2021-07-30 14:00:23 +02:00
#[cfg(test)]
2022-01-04 00:50:40 +01:00
oprf_key,
2020-12-12 21:53:33 -08:00
})
2020-06-05 09:35:14 -07:00
}
2025-05-05 13:12:54 +02:00
/// From the client's "blinded" password, returns a response to be sent back
/// to the client, as well as a [`ServerRegistration`]
pub fn start<SK: Clone>(
server_setup: &ServerSetup<CS, SK>,
message: RegistrationRequest<CS>,
credential_identifier: &[u8],
) -> Result<ServerRegistrationStartResult<CS>, ProtocolError> {
let KeyMaterialInfo {
ikm: oprf_seed,
info,
} = server_setup.key_material_info(credential_identifier);
2025-05-19 22:56:25 +02:00
let key_material = oprf_key_material::<CS>(&oprf_seed.0, &info)?;
2025-05-05 13:12:54 +02:00
Self::start_with_key_material(server_setup, key_material, message)
}
2022-01-06 06:19:02 +01:00
/// From the client's cryptographic identifiers, fully populates and returns
2023-10-08 21:48:43 +02:00
/// a [`ServerRegistration`]
pub fn finish(message: RegistrationUpload<CS>) -> Self {
Self(message)
}
// Creates a dummy instance used for faking a [CredentialResponse]
pub(crate) fn dummy<R: Rng + CryptoRng, SK: Clone, S: Clone>(
rng: &mut R,
2025-05-05 13:12:54 +02:00
server_setup: &ServerSetup<CS, SK, S>,
) -> Self {
Self(RegistrationUpload::dummy(rng, server_setup))
2020-06-05 09:35:14 -07:00
}
}
// Login
// =====
2022-01-06 00:10:57 +01:00
pub(crate) type ClientLoginLen<CS: CipherSuite> =
2025-05-19 22:56:25 +02:00
Sum<Sum<<OprfGroup<CS> as voprf::Group>::ScalarLen, CredentialRequestLen<CS>>, Ke1StateLen<CS>>;
2022-01-06 00:10:57 +01:00
2025-04-15 22:31:37 +02:00
impl<CS: CipherSuite> ClientLogin<CS> {
/// Serialization into bytes
2022-01-06 00:10:57 +01:00
pub fn serialize(&self) -> GenericArray<u8, ClientLoginLen<CS>>
2022-01-04 00:50:40 +01:00
where
// CredentialRequest: KgPk + Ke1Message
2025-05-19 22:56:25 +02:00
<CS::KeyExchange as KeyExchange>::KE1Message: Serialize,
<OprfGroup<CS> as voprf::Group>::ElemLen: Add<Ke1MessageLen<CS>>,
CredentialRequestLen<CS>: ArrayLength,
2022-01-06 00:10:57 +01:00
// ClientLogin: KgSk + CredentialRequest + Ke1State
2025-05-19 22:56:25 +02:00
<OprfGroup<CS> as voprf::Group>::ScalarLen: Add<CredentialRequestLen<CS>>,
<CS::KeyExchange as KeyExchange>::KE1State: Serialize,
Sum<<OprfGroup<CS> as voprf::Group>::ScalarLen, CredentialRequestLen<CS>>:
ArrayLength + Add<Ke1StateLen<CS>>,
ClientLoginLen<CS>: ArrayLength,
2022-01-04 00:50:40 +01:00
{
GenericArray::from_ha0_4(self.oprf_client.serialize())
.cat(self.credential_request.serialize())
.cat(self.ke1_state.serialize())
}
/// Deserialization from bytes
2025-05-19 22:56:25 +02:00
pub fn deserialize(mut input: &[u8]) -> Result<Self, ProtocolError>
where
<CS::KeyExchange as KeyExchange>::KE1Message: Deserialize + Serialize,
<CS::KeyExchange as KeyExchange>::KE1State: Deserialize + Serialize,
{
let oprf_client = OprfClient::deserialize(input)?;
input = &input[OprfClientLen::<CS::OprfCs>::USIZE..];
2020-06-05 09:35:14 -07:00
Ok(Self {
2025-05-19 22:56:25 +02:00
oprf_client,
credential_request: CredentialRequest::deserialize_take(&mut input)?,
ke1_state: <CS::KeyExchange as KeyExchange>::KE1State::deserialize_take(&mut input)?,
2020-06-05 09:35:14 -07:00
})
}
}
2025-04-15 22:31:37 +02:00
impl<CS: CipherSuite> ClientLogin<CS> {
2022-01-06 06:19:02 +01:00
/// Returns an initial "blinded" password request to send to the server, as
2023-10-08 21:48:43 +02:00
/// well as a [`ClientLogin`]
pub fn start<R: Rng + CryptoRng>(
2020-06-05 09:35:14 -07:00
rng: &mut R,
2020-12-12 21:53:33 -08:00
password: &[u8],
2020-11-16 14:05:43 -08:00
) -> Result<ClientLoginStartResult<CS>, ProtocolError> {
2021-10-25 02:54:32 -07:00
let blind_result = blind::<CS, _>(rng, password)?;
2025-06-25 00:17:29 +02:00
let ke1_result = CS::KeyExchange::generate_ke1(rng)?;
2020-06-05 09:35:14 -07:00
2021-10-25 02:54:32 -07:00
let credential_request = CredentialRequest {
blinded_element: blind_result.message,
2025-06-25 00:17:29 +02:00
ke1_message: ke1_result.message,
2021-10-25 02:54:32 -07:00
};
2020-06-05 09:35:14 -07:00
2020-11-16 14:05:43 -08:00
Ok(ClientLoginStartResult {
2022-01-04 00:50:40 +01:00
message: credential_request.clone(),
state: Self {
2021-10-25 02:54:32 -07:00
oprf_client: blind_result.state,
2025-06-25 00:17:29 +02:00
ke1_state: ke1_result.state,
2022-01-04 00:50:40 +01:00
credential_request,
},
2020-11-16 14:05:43 -08:00
})
2020-06-05 09:35:14 -07:00
}
2022-01-06 06:19:02 +01:00
/// "Unblinds" the server's answer and returns the opened assets from the
/// server
pub fn finish<R: CryptoRng + Rng>(
2020-06-05 09:35:14 -07:00
self,
2025-05-19 22:56:25 +02:00
rng: &mut R,
2022-01-06 00:10:57 +01:00
password: &[u8],
credential_response: CredentialResponse<CS>,
2021-09-02 11:28:21 +02:00
params: ClientLoginFinishParameters<CS>,
2025-05-19 22:56:25 +02:00
) -> Result<ClientLoginFinishResult<CS>, ProtocolError> {
2021-07-12 12:33:19 -07:00
// Check if beta value from server is equal to alpha value from client
2022-01-04 00:50:40 +01:00
if self
.credential_request
2021-10-25 02:54:32 -07:00
.blinded_element
.value()
.ct_eq(&credential_response.evaluation_element.value())
.into()
{
2021-07-12 12:33:19 -07:00
return Err(ProtocolError::ReflectedValueError);
}
2021-10-25 02:54:32 -07:00
let (_, randomized_pwd_hasher) = get_password_derived_key::<CS>(
2022-01-06 00:10:57 +01:00
password,
2021-10-25 02:54:32 -07:00
self.oprf_client.clone(),
credential_response.evaluation_element.clone(),
2022-04-02 01:10:00 +02:00
params.ksf,
)?;
2022-02-25 07:13:22 +01:00
let mut masking_key = Output::<OprfHash<CS>>::default();
2021-10-25 02:54:32 -07:00
randomized_pwd_hasher
.expand(STR_MASKING_KEY, &mut masking_key)
2021-08-22 12:28:19 -07:00
.map_err(|_| InternalError::HkdfError)?;
2020-06-05 09:35:14 -07:00
let (server_s_pk, envelope) = unmask_response::<CS>(
&masking_key,
&credential_response.masking_nonce,
&credential_response.masked_response,
)
.map_err(|e| match e {
2021-08-22 12:28:19 -07:00
ProtocolError::SerializationError => ProtocolError::InvalidLoginError,
err => err,
})?;
2022-01-04 00:50:40 +01:00
let opened_envelope = envelope
2021-09-02 11:28:21 +02:00
.open(
&randomized_pwd_hasher,
2022-01-04 00:50:40 +01:00
server_s_pk.clone(),
params.identifiers,
2021-09-02 11:28:21 +02:00
)
.map_err(|e| match e {
2021-08-22 12:28:19 -07:00
ProtocolError::LibraryError(InternalError::SealOpenHmacError) => {
ProtocolError::InvalidLoginError
}
2021-07-08 11:04:32 -07:00
err => err,
})?;
2020-06-05 09:35:14 -07:00
2025-05-19 22:56:25 +02:00
let context = SerializedContext::from(params.context)?;
2022-01-04 00:50:40 +01:00
2021-07-30 12:54:16 +02:00
let result = CS::KeyExchange::generate_ke3(
2025-05-19 22:56:25 +02:00
rng,
self.credential_request.to_parts(),
self.credential_request.ke1_message.clone(),
credential_response.to_parts(),
&self.ke1_state,
2025-06-25 00:17:29 +02:00
credential_response.ke2_message,
server_s_pk.clone(),
opened_envelope.client_static_keypair.private().clone(),
2025-05-19 22:56:25 +02:00
opened_envelope.identifiers,
context,
)?;
2020-11-16 14:05:43 -08:00
Ok(ClientLoginFinishResult {
2021-07-30 12:54:16 +02:00
message: CredentialFinalization {
2025-06-25 00:17:29 +02:00
ke3_message: result.message,
2021-07-30 12:54:16 +02:00
},
2025-06-25 00:17:29 +02:00
session_key: result.session_key,
2022-01-04 00:50:40 +01:00
export_key: opened_envelope.export_key,
server_s_pk,
#[cfg(test)]
state: self,
2021-07-30 12:54:16 +02:00
#[cfg(test)]
2025-06-25 00:17:29 +02:00
handshake_secret: result.handshake_secret,
2021-07-30 13:51:02 +02:00
#[cfg(test)]
2025-06-25 00:17:29 +02:00
client_mac_key: result.km3,
2020-11-16 14:05:43 -08:00
})
2020-06-05 09:35:14 -07:00
}
}
2025-04-15 22:31:37 +02:00
impl<CS: CipherSuite> ServerLogin<CS> {
/// Serialization into bytes
2025-05-19 22:56:25 +02:00
pub fn serialize(&self) -> GenericArray<u8, Ke2StateLen<CS>>
where
<CS::KeyExchange as KeyExchange>::KE2State<CS>: Serialize,
{
2022-04-02 01:10:00 +02:00
self.ke2_state.serialize()
2020-06-05 09:35:14 -07:00
}
/// Deserialization from bytes
2025-05-19 22:56:25 +02:00
pub fn deserialize(mut bytes: &[u8]) -> Result<Self, ProtocolError>
where
<CS::KeyExchange as KeyExchange>::KE2State<CS>: Deserialize,
{
Ok(Self {
2021-08-04 21:24:46 +02:00
ke2_state:
2025-05-19 22:56:25 +02:00
<<CS::KeyExchange as KeyExchange>::KE2State<CS> as Deserialize>::deserialize_take(
&mut bytes,
2021-08-04 21:24:46 +02:00
)?,
})
}
2025-05-05 13:12:54 +02:00
/// Create a [`ServerLoginBuilder`] with a remote OPRF seed and private key.
/// To generate the `key_material` see
/// [`ServerSetup::key_material_info()`].
///
2025-05-05 13:12:54 +02:00
/// See [`ServerLogin::start()`] for the regular path. Or
/// [`ServerLogin::builder()`] with just a remote private key.
pub fn builder_with_key_material<'a, R: Rng + CryptoRng, SK: Clone, OS: Clone>(
2020-12-12 21:53:33 -08:00
rng: &mut R,
2025-05-05 13:12:54 +02:00
server_setup: &ServerSetup<CS, SK, OS>,
2025-05-19 22:56:25 +02:00
key_material: GenericArray<u8, <OprfGroup<CS> as voprf::Group>::ScalarLen>,
password_file: Option<ServerRegistration<CS>>,
2021-10-25 02:54:32 -07:00
credential_request: CredentialRequest<CS>,
2025-05-19 22:56:25 +02:00
ServerLoginParameters {
2022-01-04 00:50:40 +01:00
context,
identifiers,
2025-05-19 22:56:25 +02:00
}: ServerLoginParameters<'a, 'a>,
) -> Result<ServerLoginBuilder<'a, CS, SK>, ProtocolError> {
2025-04-28 21:47:39 +02:00
let record = CtOption::new(
ServerRegistration::dummy(rng, server_setup),
Choice::from(password_file.is_none() as u8),
)
.into_option()
.unwrap_or_else(|| password_file.unwrap());
let client_s_pk = record.0.client_s_pk.clone();
2025-05-19 22:56:25 +02:00
let context = SerializedContext::from(context)?;
let server_s_pk = server_setup.keypair.public();
2022-01-04 00:50:40 +01:00
let mut masking_nonce = GenericArray::<_, NonceLen>::default();
rng.fill_bytes(&mut masking_nonce);
let masked_response = mask_response(
&record.0.masking_key,
&masking_nonce,
server_s_pk,
&record.0.envelope,
)?;
2025-05-19 22:56:25 +02:00
let serialized_client_s_pk = client_s_pk.serialize();
let serialized_server_s_pk = server_s_pk.serialize();
let identifiers = SerializedIdentifiers::<KeGroup<CS>>::from_identifiers(
2022-01-04 00:50:40 +01:00
identifiers,
2025-05-19 22:56:25 +02:00
serialized_client_s_pk.clone(),
serialized_server_s_pk.clone(),
)?;
2020-11-16 14:05:43 -08:00
2025-05-05 13:12:54 +02:00
let oprf_key = oprf_key_from_key_material::<CS>(key_material)?;
let server = voprf::OprfServer::new_with_key(&oprf_key).map_err(ProtocolError::from)?;
2022-12-11 06:30:05 +01:00
let evaluation_element = server.blind_evaluate(&credential_request.blinded_element);
2025-06-25 00:17:29 +02:00
let credential_response = SerializedCredentialResponse::new(
2025-05-19 22:56:25 +02:00
&evaluation_element,
masking_nonce,
masked_response.clone(),
);
2020-06-05 09:35:14 -07:00
2025-05-19 22:56:25 +02:00
let ke2_builder = CS::KeyExchange::ke2_builder(
2020-06-05 09:35:14 -07:00
rng,
2025-05-19 22:56:25 +02:00
credential_request.to_parts(),
2022-02-25 07:13:22 +01:00
credential_request.ke1_message.clone(),
2025-05-19 22:56:25 +02:00
credential_response,
client_s_pk,
2025-05-19 22:56:25 +02:00
identifiers,
context,
2020-06-05 09:35:14 -07:00
)?;
Ok(ServerLoginBuilder {
server_s_sk: server_setup.keypair().private().clone(),
2021-10-25 02:54:32 -07:00
evaluation_element,
masking_nonce: Zeroizing::new(masking_nonce),
masked_response,
#[cfg(test)]
oprf_key: Zeroizing::new(oprf_key),
ke2_builder,
})
}
2025-05-05 13:12:54 +02:00
/// Create a [`ServerLoginBuilder`] to use with a remote private key.
///
/// See [`ServerLogin::start()`] for the regular path.
pub fn builder<'a, R: Rng + CryptoRng, SK: Clone>(
2025-05-05 13:12:54 +02:00
rng: &mut R,
server_setup: &ServerSetup<CS, SK>,
password_file: Option<ServerRegistration<CS>>,
credential_request: CredentialRequest<CS>,
credential_identifier: &[u8],
2025-05-19 22:56:25 +02:00
params: ServerLoginParameters<'a, 'a>,
) -> Result<ServerLoginBuilder<'a, CS, SK>, ProtocolError> {
2025-05-05 13:12:54 +02:00
let KeyMaterialInfo {
ikm: oprf_seed,
info,
} = server_setup.key_material_info(credential_identifier);
2025-05-19 22:56:25 +02:00
let key_material = oprf_key_material::<CS>(&oprf_seed.0, &info)?;
2025-05-05 13:12:54 +02:00
Self::builder_with_key_material(
rng,
server_setup,
key_material,
password_file,
credential_request,
params,
)
}
pub(crate) fn build<SK: Clone>(
builder: ServerLoginBuilder<CS, SK>,
2025-05-19 22:56:25 +02:00
input: <CS::KeyExchange as KeyExchange>::KE2BuilderInput<CS>,
) -> Result<ServerLoginStartResult<CS>, ProtocolError> {
let result = CS::KeyExchange::build_ke2(builder.ke2_builder.clone(), input)?;
let credential_response = CredentialResponse {
evaluation_element: builder.evaluation_element.clone(),
masking_nonce: *builder.masking_nonce,
masked_response: builder.masked_response.clone(),
2025-06-25 00:17:29 +02:00
ke2_message: result.message,
2020-06-05 09:35:14 -07:00
};
2020-11-16 14:05:43 -08:00
Ok(ServerLoginStartResult {
message: credential_response,
2020-12-12 21:53:33 -08:00
state: Self {
2025-06-25 00:17:29 +02:00
ke2_state: result.state,
2020-07-13 15:23:29 -07:00
},
2021-07-30 12:54:16 +02:00
#[cfg(test)]
2025-06-25 00:17:29 +02:00
handshake_secret: result.handshake_secret,
2021-07-30 13:41:51 +02:00
#[cfg(test)]
2025-06-25 00:17:29 +02:00
server_mac_key: result.km2,
2021-07-30 14:00:23 +02:00
#[cfg(test)]
oprf_key: (*builder.oprf_key).clone(),
2020-11-16 14:05:43 -08:00
})
2020-06-05 09:35:14 -07:00
}
/// From the client's "blinded" password, returns a challenge to be sent
/// back to the client, as well as a [`ServerLogin`]
pub fn start<R: Rng + CryptoRng>(
rng: &mut R,
server_setup: &ServerSetup<CS>,
password_file: Option<ServerRegistration<CS>>,
credential_request: CredentialRequest<CS>,
credential_identifier: &[u8],
2025-05-19 22:56:25 +02:00
parameters: ServerLoginParameters,
) -> Result<ServerLoginStartResult<CS>, ProtocolError> {
let builder = Self::builder(
rng,
server_setup,
password_file,
credential_request,
credential_identifier,
parameters,
)?;
let input = CS::KeyExchange::generate_ke2_input(
&builder.ke2_builder,
2025-05-19 22:56:25 +02:00
rng,
server_setup.keypair.private(),
);
Self::build(builder, input)
}
2020-11-16 14:05:43 -08:00
/// From the client's second and final message, check the client's
/// authentication and produce a message transport
pub fn finish(
self,
2020-12-12 21:53:33 -08:00
message: CredentialFinalization<CS>,
2025-05-19 22:56:25 +02:00
parameters: ServerLoginParameters,
) -> Result<ServerLoginFinishResult<CS>, ProtocolError> {
2025-05-19 22:56:25 +02:00
let context = SerializedContext::from(parameters.context)?;
let session_key = <CS::KeyExchange as KeyExchange>::finish_ke(
&self.ke2_state,
2025-06-25 00:17:29 +02:00
message.ke3_message,
2025-05-19 22:56:25 +02:00
parameters.identifiers,
context,
2021-08-22 12:28:19 -07:00
)?;
2020-11-16 14:05:43 -08:00
Ok(ServerLoginFinishResult {
session_key,
#[cfg(test)]
state: self,
})
}
}
/////////////////////////
// Convenience Structs //
//==================== //
/////////////////////////
/// Options for specifying custom identifiers
2022-01-04 00:50:40 +01:00
#[derive(Clone, Copy, Debug, Default)]
pub struct Identifiers<'a> {
/// Client identifier
pub client: Option<&'a [u8]>,
/// Server identifier
pub server: Option<&'a [u8]>,
}
/// Optional parameters for client registration finish
2022-01-04 00:50:40 +01:00
#[derive_where(Clone, Default)]
2025-04-15 22:31:37 +02:00
pub struct ClientRegistrationFinishParameters<'i, 'h, CS: CipherSuite> {
/// Specifying the identifiers idU and idS
2022-01-04 00:50:40 +01:00
pub identifiers: Identifiers<'i>,
2022-04-02 01:10:00 +02:00
/// Specifying a configuration for the key stretching function
pub ksf: Option<&'h CS::Ksf>,
}
2025-04-15 22:31:37 +02:00
impl<'i, 'h, CS: CipherSuite> ClientRegistrationFinishParameters<'i, 'h, CS> {
/// Create a new [`ClientRegistrationFinishParameters`]
2022-04-02 01:10:00 +02:00
pub fn new(identifiers: Identifiers<'i>, ksf: Option<&'h CS::Ksf>) -> Self {
Self { identifiers, ksf }
}
}
/// Contains the fields that are returned by a client registration start
2022-01-04 00:50:40 +01:00
#[derive_where(Clone)]
2025-04-15 22:31:37 +02:00
pub struct ClientRegistrationStartResult<CS: CipherSuite> {
/// The registration request message to be sent to the server
pub message: RegistrationRequest<CS>,
2022-01-06 06:19:02 +01:00
/// The client state that must be persisted in order to complete
/// registration
pub state: ClientRegistration<CS>,
}
/// Contains the fields that are returned by a client registration finish
2022-01-04 00:50:40 +01:00
#[derive_where(Clone)]
2025-04-15 22:31:37 +02:00
pub struct ClientRegistrationFinishResult<CS: CipherSuite> {
/// The registration upload message to be sent to the server
pub message: RegistrationUpload<CS>,
/// The export key output by client registration
2022-02-25 07:13:22 +01:00
pub export_key: Output<OprfHash<CS>>,
/// The server's static public key
2025-05-19 22:56:25 +02:00
pub server_s_pk: PublicKey<KeGroup<CS>>,
2025-09-08 13:08:23 +02:00
/// Instance of the `ClientRegistration`, only used in tests for checking
2022-01-06 06:19:02 +01:00
/// zeroize
#[cfg(test)]
pub state: ClientRegistration<CS>,
2025-09-08 13:08:23 +02:00
/// `AuthKey`, only used in tests
#[cfg(test)]
2022-02-25 07:13:22 +01:00
pub auth_key: Output<OprfHash<CS>>,
/// Password derived key, only used in tests
#[cfg(test)]
2022-02-25 07:13:22 +01:00
pub randomized_pwd: Output<OprfHash<CS>>,
}
2022-01-06 06:19:02 +01:00
/// Contains the fields that are returned by a server registration start. Note
/// that there is no state output in this step
2022-01-04 00:50:40 +01:00
#[derive_where(Clone)]
2025-04-15 22:31:37 +02:00
pub struct ServerRegistrationStartResult<CS: CipherSuite> {
/// The registration resposne message to send to the client
pub message: RegistrationResponse<CS>,
/// OPRF key, only used in tests
#[cfg(test)]
2025-05-19 22:56:25 +02:00
pub oprf_key: GenericArray<u8, <OprfGroup<CS> as voprf::Group>::ScalarLen>,
}
/// Contains the fields that are returned by a client login start
2022-01-04 00:50:40 +01:00
#[derive_where(Clone)]
2025-04-15 22:31:37 +02:00
pub struct ClientLoginStartResult<CS: CipherSuite> {
/// The message to send to the server to begin the login protocol
pub message: CredentialRequest<CS>,
/// The state that the client must keep in order to complete the protocol
pub state: ClientLogin<CS>,
}
/// Optional parameters for client login finish
2022-01-04 00:50:40 +01:00
#[derive_where(Clone, Default)]
2025-04-15 22:31:37 +02:00
pub struct ClientLoginFinishParameters<'c, 'i, 'h, CS: CipherSuite> {
/// Specifying a context field that the server must agree on
2022-01-04 00:50:40 +01:00
pub context: Option<&'c [u8]>,
2022-01-06 06:19:02 +01:00
/// Specifying a user identifier and server identifier that will be matched
/// against the server
2022-01-04 00:50:40 +01:00
pub identifiers: Identifiers<'i>,
2022-04-02 01:10:00 +02:00
/// Specifying a configuration for the key stretching hash
pub ksf: Option<&'h CS::Ksf>,
}
2025-04-15 22:31:37 +02:00
impl<'c, 'i, 'h, CS: CipherSuite> ClientLoginFinishParameters<'c, 'i, 'h, CS> {
/// Create a new [`ClientLoginFinishParameters`]
pub fn new(
2022-01-04 00:50:40 +01:00
context: Option<&'c [u8]>,
identifiers: Identifiers<'i>,
2022-04-02 01:10:00 +02:00
ksf: Option<&'h CS::Ksf>,
) -> Self {
Self {
context,
identifiers,
2022-04-02 01:10:00 +02:00
ksf,
}
}
}
/// Contains the fields that are returned by a client login finish
2022-01-04 00:50:40 +01:00
#[derive_where(Clone)]
2025-04-15 22:31:37 +02:00
pub struct ClientLoginFinishResult<CS: CipherSuite> {
/// The message to send to the server to complete the protocol
pub message: CredentialFinalization<CS>,
/// The session key
2025-05-19 22:56:25 +02:00
pub session_key: Output<KeHash<CS>>,
/// The client-side export key
2022-02-25 07:13:22 +01:00
pub export_key: Output<OprfHash<CS>>,
/// The server's static public key
2025-05-19 22:56:25 +02:00
pub server_s_pk: PublicKey<KeGroup<CS>>,
2025-09-08 13:08:23 +02:00
/// Instance of the `ClientLogin`, only used in tests for checking zeroize
#[cfg(test)]
pub state: ClientLogin<CS>,
/// Handshake secret, only used in tests
#[cfg(test)]
2025-05-19 22:56:25 +02:00
pub handshake_secret: Output<KeHash<CS>>,
/// Client MAC key, only used in tests
#[cfg(test)]
2025-05-19 22:56:25 +02:00
pub client_mac_key: Output<KeHash<CS>>,
}
/// Contains the fields that are returned by a server login finish
2022-01-04 00:50:40 +01:00
#[derive_where(Clone)]
#[cfg_attr(not(test), derive_where(Debug))]
#[cfg_attr(test, derive_where(Debug; ServerLogin<CS>))]
2025-04-15 22:31:37 +02:00
pub struct ServerLoginFinishResult<CS: CipherSuite> {
/// The session key between client and server
2025-05-19 22:56:25 +02:00
pub session_key: Output<KeHash<CS>>,
2025-09-08 13:08:23 +02:00
/// Instance of the `ClientRegistration`, only used in tests for checking
2022-01-06 06:19:02 +01:00
/// zeroize
#[cfg(test)]
pub state: ServerLogin<CS>,
}
2025-05-19 22:56:25 +02:00
/// Optional parameters for server login start and finish
2022-01-04 00:50:40 +01:00
#[derive(Clone, Debug, Default)]
2025-05-19 22:56:25 +02:00
pub struct ServerLoginParameters<'c, 'i> {
/// Specifying a context field that the client must agree on
2022-01-04 00:50:40 +01:00
pub context: Option<&'c [u8]>,
2022-01-06 06:19:02 +01:00
/// Specifying a user identifier and server identifier that will be matched
/// against the client
2022-01-04 00:50:40 +01:00
pub identifiers: Identifiers<'i>,
}
/// Contains the fields that are returned by a server login start
2022-01-04 00:50:40 +01:00
#[derive_where(Clone)]
#[derive_where(
Debug;
2025-05-19 22:56:25 +02:00
<KeGroup<CS> as Group>::Pk,
2022-04-02 01:10:00 +02:00
voprf::EvaluationElement<CS::OprfCs>,
2025-05-19 22:56:25 +02:00
<CS::KeyExchange as KeyExchange>::KE2Message,
<CS::KeyExchange as KeyExchange>::KE2State<CS>,
2022-01-04 00:50:40 +01:00
)]
2025-04-15 22:31:37 +02:00
pub struct ServerLoginStartResult<CS: CipherSuite> {
/// The message to send back to the client
pub message: CredentialResponse<CS>,
/// The state that the server must keep in order to finish the protocl
pub state: ServerLogin<CS>,
/// Handshake secret, only used in tests
#[cfg(test)]
2025-05-19 22:56:25 +02:00
pub handshake_secret: Output<KeHash<CS>>,
/// Server MAC key, only used in tests
#[cfg(test)]
2025-05-19 22:56:25 +02:00
pub server_mac_key: Output<KeHash<CS>>,
/// OPRF key, only used in tests
#[cfg(test)]
2025-05-19 22:56:25 +02:00
pub oprf_key: GenericArray<u8, <OprfGroup<CS> as voprf::Group>::ScalarLen>,
}
////////////////////////////////////////////////
// Helper functions and Trait Implementations //
// ========================================== //
////////////////////////////////////////////////
2020-06-05 09:35:14 -07:00
// Helper functions
2021-10-25 02:54:32 -07:00
#[allow(clippy::type_complexity)]
2021-09-02 11:28:21 +02:00
fn get_password_derived_key<CS: CipherSuite>(
2022-01-06 00:10:57 +01:00
input: &[u8],
oprf_client: OprfClient<CS::OprfCs>,
2022-04-02 01:10:00 +02:00
evaluation_element: voprf::EvaluationElement<CS::OprfCs>,
ksf: Option<&CS::Ksf>,
) -> Result<(Output<OprfHash<CS>>, hkdf::SimpleHkdf<OprfHash<CS>>), ProtocolError> {
2022-04-17 16:23:31 -07:00
let oprf_output = oprf_client.finalize(input, &evaluation_element)?;
let oprf_ga = GenericArray::from_ha0_4(oprf_output.clone());
2021-09-02 11:28:21 +02:00
2022-04-02 01:10:00 +02:00
let hardened_output = if let Some(ksf) = ksf {
ksf.hash(oprf_ga.clone())
2021-09-02 11:28:21 +02:00
} else {
CS::Ksf::default().hash(oprf_ga.clone())
2021-09-02 11:28:21 +02:00
}
2021-10-25 02:54:32 -07:00
.map_err(ProtocolError::from)?;
2022-02-25 07:13:22 +01:00
let mut hkdf = HkdfExtract::<OprfHash<CS>>::new(None);
hkdf.input_ikm(&oprf_ga);
2022-01-04 00:50:40 +01:00
hkdf.input_ikm(&hardened_output);
Ok(hkdf.finalize())
2020-06-05 09:35:14 -07:00
}
2025-05-05 13:12:54 +02:00
fn oprf_key_material<CS: CipherSuite>(
2025-04-15 22:31:37 +02:00
oprf_seed: &Output<OprfHash<CS>>,
2025-05-05 13:12:54 +02:00
info: &[&[u8]],
2025-05-19 22:56:25 +02:00
) -> Result<GenericArray<u8, <OprfGroup<CS> as voprf::Group>::ScalarLen>, InternalError> {
let mut ikm = GenericArray::<_, <OprfGroup<CS> as voprf::Group>::ScalarLen>::default();
2025-04-15 22:31:37 +02:00
Hkdf::<OprfHash<CS>>::from_prk(oprf_seed)
2022-01-04 00:50:40 +01:00
.ok()
2025-05-05 13:12:54 +02:00
.and_then(|hkdf| hkdf.expand_multi_info(info, &mut ikm).ok())
2022-01-04 00:50:40 +01:00
.ok_or(InternalError::HkdfError)?;
2022-04-17 16:23:31 -07:00
2025-05-05 13:12:54 +02:00
Ok(ikm)
}
fn oprf_key_from_key_material<CS: CipherSuite>(
2025-05-19 22:56:25 +02:00
input: GenericArray<u8, <OprfGroup<CS> as voprf::Group>::ScalarLen>,
) -> Result<GenericArray<u8, <OprfGroup<CS> as voprf::Group>::ScalarLen>, InternalError> {
Ok(GenericArray::from_ha0_4(OprfGroup::<CS>::serialize_scalar(
voprf::derive_key::<CS::OprfCs>(&input, STR_OPAQUE_DERIVE_KEY_PAIR, voprf::Mode::Oprf)?,
)))
2022-01-04 00:50:40 +01:00
}
2022-04-02 01:10:00 +02:00
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
2023-02-04 22:25:41 +01:00
serde(bound = "")
2022-04-02 01:10:00 +02:00
)]
2025-05-19 22:56:25 +02:00
#[derive_where(Clone, Zeroize)]
2022-01-04 00:50:40 +01:00
#[derive_where(Debug, Eq, Hash, PartialEq)]
2025-04-15 22:31:37 +02:00
pub(crate) struct MaskedResponse<CS: CipherSuite> {
2022-01-04 00:50:40 +01:00
pub(crate) nonce: GenericArray<u8, NonceLen>,
2022-02-25 07:13:22 +01:00
pub(crate) hash: Output<OprfHash<CS>>,
2025-05-19 22:56:25 +02:00
pub(crate) pk: GenericArray<u8, <KeGroup<CS> as Group>::PkLen>,
2022-01-04 00:50:40 +01:00
}
pub(crate) type MaskedResponseLen<CS: CipherSuite> =
2025-05-19 22:56:25 +02:00
Sum<Sum<OutputSize<OprfHash<CS>>, NonceLen>, <KeGroup<CS> as Group>::PkLen>;
2022-01-04 00:50:40 +01:00
2025-04-15 22:31:37 +02:00
impl<CS: CipherSuite> MaskedResponse<CS> {
2025-05-19 22:56:25 +02:00
pub(crate) fn serialize(&self) -> GenericArray<u8, MaskedResponseLen<CS>> {
let hash_ga: &GenericArray<u8, OutputSize<OprfHash<CS>>> =
GenericArray::from_slice(self.hash.as_slice());
2022-01-04 00:50:40 +01:00
self.nonce.concat_ext(hash_ga).cat(self.pk.clone())
}
2025-05-19 22:56:25 +02:00
pub(crate) fn deserialize_take(bytes: &mut &[u8]) -> Result<Self, ProtocolError> {
Ok(Self {
nonce: bytes.take_array("masked nonce")?,
hash: bytes
.take_array::<OutputSize<OprfHash<CS>>>("masked hash")?
.into_ha0_4(),
2025-05-19 22:56:25 +02:00
pk: bytes.take_array("masked public key")?,
})
2022-01-04 00:50:40 +01:00
}
2025-05-19 22:56:25 +02:00
pub(crate) fn iter(&self) -> impl Clone + Iterator<Item = &[u8]> {
[
self.nonce.as_slice(),
self.hash.as_slice(),
self.pk.as_slice(),
]
.into_iter()
2022-01-04 00:50:40 +01:00
}
}
fn mask_response<CS: CipherSuite>(
masking_key: &[u8],
masking_nonce: &[u8],
2025-05-19 22:56:25 +02:00
server_s_pk: &PublicKey<KeGroup<CS>>,
envelope: &Envelope<CS>,
2025-05-19 22:56:25 +02:00
) -> Result<MaskedResponse<CS>, ProtocolError> {
2022-01-04 00:50:40 +01:00
let mut xor_pad = GenericArray::<_, MaskedResponseLen<CS>>::default();
2022-02-25 07:13:22 +01:00
Hkdf::<OprfHash<CS>>::from_prk(masking_key)
2021-08-22 12:28:19 -07:00
.map_err(|_| InternalError::HkdfError)?
2022-01-04 00:50:40 +01:00
.expand_multi_info(&[masking_nonce, STR_CREDENTIAL_RESPONSE_PAD], &mut xor_pad)
2021-08-22 12:28:19 -07:00
.map_err(|_| InternalError::HkdfError)?;
2022-01-04 00:50:40 +01:00
for (x1, x2) in xor_pad.iter_mut().zip(
server_s_pk
2022-04-02 01:10:00 +02:00
.serialize()
2022-01-04 00:50:40 +01:00
.as_slice()
.iter()
.chain(envelope.serialize().iter()),
) {
*x1 ^= x2
}
let mut slice: &[u8] = &xor_pad;
MaskedResponse::deserialize_take(&mut (slice))
}
fn unmask_response<CS: CipherSuite>(
masking_key: &[u8],
masking_nonce: &[u8],
2022-01-04 00:50:40 +01:00
masked_response: &MaskedResponse<CS>,
2025-05-19 22:56:25 +02:00
) -> Result<(PublicKey<KeGroup<CS>>, Envelope<CS>), ProtocolError> {
2022-01-04 00:50:40 +01:00
let mut xor_pad = GenericArray::<_, MaskedResponseLen<CS>>::default();
2022-02-25 07:13:22 +01:00
Hkdf::<OprfHash<CS>>::from_prk(masking_key)
2021-08-22 12:28:19 -07:00
.map_err(|_| InternalError::HkdfError)?
2022-01-04 00:50:40 +01:00
.expand_multi_info(&[masking_nonce, STR_CREDENTIAL_RESPONSE_PAD], &mut xor_pad)
2021-08-22 12:28:19 -07:00
.map_err(|_| InternalError::HkdfError)?;
2022-01-04 00:50:40 +01:00
for (x1, x2) in xor_pad.iter_mut().zip(masked_response.iter().flatten()) {
*x1 ^= x2
}
let mut xor_pad: &[u8] = xor_pad.as_ref();
2025-05-19 22:56:25 +02:00
let server_s_pk =
PublicKey::deserialize_take(&mut xor_pad).map_err(|_| ProtocolError::SerializationError)?;
let envelope = Envelope::deserialize_take(&mut xor_pad)?;
Ok((server_s_pk, envelope))
}
2022-01-06 06:19:02 +01:00
/// Internal function for computing the blind result by calling the voprf
/// library. Note that for tests, we use the deterministic blinding in order to
/// be able to set the blinding factor directly from the passed-in rng.
fn blind<CS: CipherSuite, R: Rng + CryptoRng>(
2021-10-25 02:54:32 -07:00
rng: &mut R,
password: &[u8],
2025-04-15 22:31:37 +02:00
) -> Result<voprf::OprfClientBlindResult<CS::OprfCs>, voprf::Error> {
2021-10-25 02:54:32 -07:00
#[cfg(not(test))]
let result = OprfClient::blind(password, rng)?;
2021-10-25 02:54:32 -07:00
#[cfg(test)]
let result = {
2025-05-19 22:56:25 +02:00
let mut blind_bytes =
GenericArray::<_, <OprfGroup<CS> as voprf::Group>::ScalarLen>::default();
2021-10-25 02:54:32 -07:00
let blind = loop {
rng.fill_bytes(&mut blind_bytes);
2025-05-19 22:56:25 +02:00
if let Ok(scalar) = <OprfGroup<CS> as voprf::Group>::deserialize_scalar(&blind_bytes) {
2022-02-25 07:13:22 +01:00
break scalar;
2021-10-25 02:54:32 -07:00
}
};
OprfClient::deterministic_blind_unchecked(password, blind)?
2021-10-25 02:54:32 -07:00
};
Ok(result)
}