Adding deserialization checks (#10)

This commit is contained in:
Kevin Lewi
2021-09-27 18:29:08 -07:00
committed by GitHub
parent 0445a9461c
commit f6f85e0a25
11 changed files with 155 additions and 55 deletions
+45 -8
View File
@@ -31,7 +31,7 @@ pub trait Group:
const SUITE_ID: usize;
/// transforms a password and domain separation tag (DST) into a curve point
fn map_to_curve<H: Hash>(msg: &[u8], dst: &[u8]) -> Result<Self, InternalError>;
fn hash_to_curve<H: Hash>(msg: &[u8], dst: &[u8]) -> Result<Self, InternalError>;
/// Hashes a slice of pseudo-random bytes to a scalar
fn hash_to_scalar<H: Hash>(input: &[u8], dst: &[u8]) -> Result<Self::Scalar, InternalError>;
@@ -44,10 +44,25 @@ pub trait Group:
+ for<'a> Mul<&'a Self::Scalar, Output = Self::Scalar>;
/// The byte length necessary to represent scalars
type ScalarLen: ArrayLength<u8> + 'static;
/// Return a scalar from its fixed-length bytes representation
fn from_scalar_slice(
/// Return a scalar from its fixed-length bytes representation, without
/// checking if the scalar is zero.
fn from_scalar_slice_unchecked(
scalar_bits: &GenericArray<u8, Self::ScalarLen>,
) -> Result<Self::Scalar, InternalError>;
/// Return a scalar from its fixed-length bytes representation. If the scalar
/// is zero, then return an error.
fn from_scalar_slice(
scalar_bits: &GenericArray<u8, Self::ScalarLen>,
) -> Result<Self::Scalar, InternalError> {
let scalar = Self::from_scalar_slice_unchecked(scalar_bits)?;
if Self::ct_equal_scalar(&scalar, &Self::scalar_zero()) {
return Err(InternalError::ZeroScalarError);
}
Ok(scalar)
}
/// picks a scalar at random
fn random_nonzero_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar;
/// Serializes a scalar to bytes
@@ -57,19 +72,35 @@ pub trait Group:
/// The byte length necessary to represent group elements
type ElemLen: ArrayLength<u8> + 'static;
/// Return an element from its fixed-length bytes representation
fn from_element_slice(
/// Return an element from its fixed-length bytes representation. This is
/// the unchecked version, which does not check for deserializing the identity
/// element
fn from_element_slice_unchecked(
element_bits: &GenericArray<u8, Self::ElemLen>,
) -> Result<Self, InternalError>;
/// Return an element from its fixed-length bytes representation. If the element
/// is the identity element, return an error.
fn from_element_slice(
element_bits: &GenericArray<u8, Self::ElemLen>,
) -> Result<Self, InternalError> {
let elem = Self::from_element_slice_unchecked(element_bits)?;
if Self::ct_equal(&elem, &<Self as Group>::identity()) {
// found the identity element
return Err(InternalError::PointError);
}
Ok(elem)
}
/// Serializes the `self` group element
fn to_arr(&self) -> GenericArray<u8, Self::ElemLen>;
/// Get the base point for the group
fn base_point() -> Self;
/// Multiply the point by a scalar, represented as a slice
fn mult_by_slice(&self, scalar: &GenericArray<u8, Self::ScalarLen>) -> Self;
/// Returns if the group element is equal to the identity (1)
fn is_identity(&self) -> bool {
self.ct_equal(&<Self as Group>::identity())
@@ -78,9 +109,15 @@ pub trait Group:
/// Returns the identity group element
fn identity() -> Self;
/// Returns the scalar representing zero
fn scalar_zero() -> Self::Scalar;
/// Compares in constant time if the group elements are equal
fn ct_equal(&self, other: &Self) -> bool;
/// Compares in constant time if the scalars are equal
fn ct_equal_scalar(s1: &Self::Scalar, s2: &Self::Scalar) -> bool;
}
#[cfg(test)]
mod tests;
+18 -18
View File
@@ -17,7 +17,7 @@ use generic_array::typenum::{U32, U33};
use generic_array::{ArrayLength, GenericArray};
use num_bigint::{BigInt, Sign};
use num_integer::Integer;
use num_traits::{One, ToPrimitive};
use num_traits::{One, ToPrimitive, Zero};
use once_cell::unsync::Lazy;
use p256_::elliptic_curve::group::prime::PrimeCurveAffine;
use p256_::elliptic_curve::group::GroupEncoding;
@@ -35,7 +35,7 @@ impl Group for ProjectivePoint {
// Implements the `hash_to_curve()` function from
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-3
fn map_to_curve<H: Hash>(msg: &[u8], dst: &[u8]) -> Result<Self, InternalError> {
fn hash_to_curve<H: Hash>(msg: &[u8], dst: &[u8]) -> Result<Self, InternalError> {
// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#section-8.2
// `p: 2^256 - 2^224 + 2^192 + 2^96 - 1`
const P: Lazy<BigInt> = Lazy::new(|| {
@@ -63,9 +63,9 @@ impl Group for ProjectivePoint {
// `hash_to_field` calls `expand_message` with a `len_in_bytes` of `count * L`
let uniform_bytes = super::expand::expand_message_xmd::<H>(msg, dst, 2 * L)?;
// map to curve
let (q0x, q0y) = map_to_curve_simple_swu(&uniform_bytes[..L], &A, &B, &P, &Z);
let (q1x, q1y) = map_to_curve_simple_swu(&uniform_bytes[L..], &A, &B, &P, &Z);
// hash to curve
let (q0x, q0y) = hash_to_curve_simple_swu(&uniform_bytes[..L], &A, &B, &P, &Z);
let (q1x, q1y) = hash_to_curve_simple_swu(&uniform_bytes[L..], &A, &B, &P, &Z);
// convert to `p256` types
let p0 = AffinePoint::from_encoded_point(&EncodedPoint::from_affine_coordinates(
@@ -111,7 +111,7 @@ impl Group for ProjectivePoint {
type Scalar = p256_::Scalar;
type ScalarLen = U32;
fn from_scalar_slice(
fn from_scalar_slice_unchecked(
scalar_bits: &GenericArray<u8, Self::ScalarLen>,
) -> Result<Self::Scalar, InternalError> {
Ok(Self::Scalar::from_bytes_reduced(scalar_bits))
@@ -129,7 +129,7 @@ impl Group for ProjectivePoint {
scalar.invert().unwrap_or(Self::Scalar::zero())
}
fn from_element_slice(
fn from_element_slice_unchecked(
element_bits: &GenericArray<u8, Self::ElemLen>,
) -> Result<Self, InternalError> {
Option::from(Self::from_bytes(element_bits)).ok_or(InternalError::PointError)
@@ -145,14 +145,14 @@ impl Group for ProjectivePoint {
Self::generator()
}
fn mult_by_slice(&self, scalar: &GenericArray<u8, Self::ScalarLen>) -> Self {
self * &Self::Scalar::from_bytes_reduced(scalar)
}
fn identity() -> Self {
Self::identity()
}
fn scalar_zero() -> Self::Scalar {
Self::Scalar::zero()
}
fn ct_equal(&self, other: &Self) -> bool {
self.ct_eq(other).into()
}
@@ -162,10 +162,10 @@ impl Group for ProjectivePoint {
}
}
/// Corresponds to the map_to_curve_simple_swu() function defined in
/// Corresponds to the hash_to_curve_simple_swu() function defined in
/// <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-11#appendix-F.2>
#[allow(clippy::many_single_char_names)]
fn map_to_curve_simple_swu<N: ArrayLength<u8>>(
fn hash_to_curve_simple_swu<N: ArrayLength<u8>>(
u: &[u8],
a: &BigInt,
b: &BigInt,
@@ -311,7 +311,7 @@ fn map_to_curve_simple_swu<N: ArrayLength<u8>>(
}
fn is_zero(&self) -> bool {
self.number.is_one()
self.number.is_zero()
}
/// Corresponds to the is_square() function defined in
@@ -321,7 +321,7 @@ fn map_to_curve_simple_swu<N: ArrayLength<u8>>(
let exponent = (self.f.0 - 1) >> 1;
let result = self.pow_internal(&exponent);
result.number.is_one() || result.is_zero()
result.is_zero() || result.number.is_one()
}
fn to_bytes<N: ArrayLength<u8>>(&self) -> GenericArray<u8, N> {
@@ -413,7 +413,7 @@ mod tests {
}
#[test]
fn map_to_curve_simple_swu() {
fn hash_to_curve_simple_swu() {
const P: Lazy<BigInt> = Lazy::new(|| {
BigInt::from_str(
"115792089210356248762697446949407573530086143415290314195533631308867097853951",
@@ -515,8 +515,8 @@ mod tests {
assert_eq!(BigInt::parse_bytes(tv.u0.as_bytes(), 16).unwrap(), u0);
assert_eq!(BigInt::parse_bytes(tv.u1.as_bytes(), 16).unwrap(), u1);
let (q0x, q0y) = super::map_to_curve_simple_swu(&u0.to_bytes_be().1, &A, &B, &P, &Z);
let (q1x, q1y) = super::map_to_curve_simple_swu(&u1.to_bytes_be().1, &A, &B, &P, &Z);
let (q0x, q0y) = super::hash_to_curve_simple_swu(&u0.to_bytes_be().1, &A, &B, &P, &Z);
let (q1x, q1y) = super::hash_to_curve_simple_swu(&u1.to_bytes_be().1, &A, &B, &P, &Z);
assert_eq!(tv.q0x, hex::encode(q0x));
assert_eq!(tv.q0y, hex::encode(q0y));
+8 -7
View File
@@ -23,7 +23,7 @@ impl Group for RistrettoPoint {
// Implements the `hash_to_ristretto255()` function from
// https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-10.txt
fn map_to_curve<H: Hash>(msg: &[u8], dst: &[u8]) -> Result<Self, InternalError> {
fn hash_to_curve<H: Hash>(msg: &[u8], dst: &[u8]) -> Result<Self, InternalError> {
let uniform_bytes = super::expand::expand_message_xmd::<H>(msg, dst, 64)?;
Ok(RistrettoPoint::from_uniform_bytes(
@@ -49,11 +49,12 @@ impl Group for RistrettoPoint {
type Scalar = Scalar;
type ScalarLen = U32;
fn from_scalar_slice(
fn from_scalar_slice_unchecked(
scalar_bits: &GenericArray<u8, Self::ScalarLen>,
) -> Result<Self::Scalar, InternalError> {
Ok(Scalar::from_bytes_mod_order(*scalar_bits.as_ref()))
}
fn random_nonzero_scalar<R: RngCore + CryptoRng>(rng: &mut R) -> Self::Scalar {
loop {
let scalar = {
@@ -89,7 +90,7 @@ impl Group for RistrettoPoint {
// The byte length necessary to represent group elements
type ElemLen = U32;
fn from_element_slice(
fn from_element_slice_unchecked(
element_bits: &GenericArray<u8, Self::ElemLen>,
) -> Result<Self, InternalError> {
CompressedRistretto::from_slice(element_bits)
@@ -105,14 +106,14 @@ impl Group for RistrettoPoint {
RISTRETTO_BASEPOINT_POINT
}
fn mult_by_slice(&self, scalar: &GenericArray<u8, Self::ScalarLen>) -> Self {
self * Scalar::from_bits(*scalar.as_ref())
}
fn identity() -> Self {
<Self as Identity>::identity()
}
fn scalar_zero() -> Self::Scalar {
Self::Scalar::zero()
}
fn ct_equal(&self, other: &Self) -> bool {
ConstantTimeEq::ct_eq(self, other).into()
}
+55
View File
@@ -0,0 +1,55 @@
// 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.
//! Includes a series of tests for the group implementations
use crate::errors::InternalError;
use crate::group::Group;
use crate::CipherSuite;
// Test that the deserialization of a group element should throw an error
// if the identity element can be deserialized properly
#[test]
fn test_group_properties() -> Result<(), InternalError> {
use crate::tests::Ristretto255Sha512;
test_identity_element_error::<Ristretto255Sha512>()?;
test_zero_scalar_error::<Ristretto255Sha512>()?;
#[cfg(feature = "p256")]
{
use crate::tests::P256Sha256;
test_identity_element_error::<P256Sha256>()?;
test_zero_scalar_error::<P256Sha256>()?;
}
Ok(())
}
// Checks that the identity element cannot be deserialized
fn test_identity_element_error<CS: CipherSuite>() -> Result<(), InternalError> {
let identity = CS::Group::identity();
let result = CS::Group::from_element_slice(&identity.to_arr());
assert!(match result {
Err(InternalError::PointError) => true,
_ => false,
});
Ok(())
}
// Checks that the zero scalar cannot be deserialized
fn test_zero_scalar_error<CS: CipherSuite>() -> Result<(), InternalError> {
let zero_scalar = CS::Group::scalar_zero();
let result = CS::Group::from_scalar_slice(&CS::Group::scalar_as_bytes(zero_scalar));
assert!(match result {
Err(InternalError::ZeroScalarError) => true,
_ => false,
});
Ok(())
}