Utilize zeroize (#76)

* Apply Zeroize to nonces used in Bulletproofs

Also makes bit decomposition constant time for a given amount of 
outputs.

* Fix nonce reuse for single-signer CLSAG

* Attach Zeroize to most structures in Monero, and ZOnDrop to anything with private data

* Zeroize private keys and nonces

* Merge prepare_outputs and prepare_transactions

* Ensure CLSAG is constant time

* Pass by borrow where needed, bug fixes

The past few commitments have been one in-progress chunk which I've 
broken up as best read.

* Add Zeroize to FROST structs

Still needs to zeroize internally, yet next step. Not quite as 
aggressive as Monero, partially due to the limitations of HashMaps, 
partially due to less concern about metadata, yet does still delete a 
few smaller items of metadata (group key, context string...).

* Remove Zeroize from most Monero multisig structs

These structs largely didn't have private data, just fields with private 
data, yet those fields implemented ZeroizeOnDrop making them already 
covered. While there is still traces of the transaction left in RAM, 
fully purging that was never the intent.

* Use Zeroize within dleq

bitvec doesn't offer Zeroize, so a manual zeroing has been implemented.

* Use Zeroize for random_nonce

It isn't perfect, due to the inability to zeroize the digest, and due to 
kp256 requiring a few transformations. It does the best it can though.

Does move the per-curve random_nonce to a provided one, which is allowed 
as of https://github.com/cfrg/draft-irtf-cfrg-frost/pull/231.

* Use Zeroize on FROST keygen/signing

* Zeroize constant time multiexp.

* Correct when FROST keygen zeroizes

* Move the FROST keys Arc into FrostKeys

Reduces amount of instances in memory.

* Manually implement Debug for FrostCore to not leak the secret share

* Misc bug fixes

* clippy + multiexp test bug fixes

* Correct FROST key gen share summation

It leaked our own share for ourself.

* Fix cross-group DLEq tests
This commit is contained in:
Luke Parker
2022-08-03 03:25:18 -05:00
committed by GitHub
parent a30568ff57
commit 797be71eb3
56 changed files with 698 additions and 425 deletions

View File

@@ -1,8 +1,10 @@
use core::fmt::Debug;
use std::{io::Read, collections::HashMap};
use core::fmt::{self, Debug};
use std::{io::Read, sync::Arc, collections::HashMap};
use thiserror::Error;
use zeroize::Zeroize;
use group::{
ff::{Field, PrimeField},
GroupEncoding,
@@ -18,6 +20,32 @@ pub mod sign;
pub mod tests;
// Validate a map of serialized values to have the expected included participants
pub(crate) fn validate_map<T>(
map: &mut HashMap<u16, T>,
included: &[u16],
ours: u16,
) -> Result<(), FrostError> {
if (map.len() + 1) != included.len() {
Err(FrostError::InvalidParticipantQuantity(included.len(), map.len() + 1))?;
}
for included in included {
if *included == ours {
if map.contains_key(included) {
Err(FrostError::DuplicatedIndex(*included))?;
}
continue;
}
if !map.contains_key(included) {
Err(FrostError::MissingParticipant(*included))?;
}
}
Ok(())
}
/// Parameters for a multisig
// These fields can not be made public as they should be static
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -89,33 +117,6 @@ pub enum FrostError {
InternalError(&'static str),
}
// View of keys passable to algorithm implementations
#[derive(Clone)]
pub struct FrostView<C: Curve> {
group_key: C::G,
included: Vec<u16>,
secret_share: C::F,
verification_shares: HashMap<u16, C::G>,
}
impl<C: Curve> FrostView<C> {
pub fn group_key(&self) -> C::G {
self.group_key
}
pub fn included(&self) -> Vec<u16> {
self.included.clone()
}
pub fn secret_share(&self) -> C::F {
self.secret_share
}
pub fn verification_share(&self, l: u16) -> C::G {
self.verification_shares[&l]
}
}
/// Calculate the lagrange coefficient for a signing set
pub fn lagrange<F: PrimeField>(i: u16, included: &[u16]) -> F {
let mut num = F::one();
@@ -135,9 +136,11 @@ pub fn lagrange<F: PrimeField>(i: u16, included: &[u16]) -> F {
num * denom.invert().unwrap()
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FrostKeys<C: Curve> {
/// Core keys generated by performing a FROST keygen protocol
#[derive(Clone, PartialEq, Eq, Zeroize)]
pub struct FrostCore<C: Curve> {
/// FROST Parameters
#[zeroize(skip)]
params: FrostParams,
/// Secret share key
@@ -145,32 +148,32 @@ pub struct FrostKeys<C: Curve> {
/// Group key
group_key: C::G,
/// Verification shares
#[zeroize(skip)]
verification_shares: HashMap<u16, C::G>,
/// Offset applied to these keys
offset: Option<C::F>,
}
impl<C: Curve> FrostKeys<C> {
/// Offset the keys by a given scalar to allow for account and privacy schemes
/// This offset is ephemeral and will not be included when these keys are serialized
/// Keys offset multiple times will form a new offset of their sum
/// Not IETF compliant
pub fn offset(&self, offset: C::F) -> FrostKeys<C> {
let mut res = self.clone();
// Carry any existing offset
// Enables schemes like Monero's subaddresses which have a per-subaddress offset and then a
// one-time-key offset
res.offset = Some(offset + res.offset.unwrap_or_else(C::F::zero));
res.group_key += C::GENERATOR * offset;
res
impl<C: Curve> Drop for FrostCore<C> {
fn drop(&mut self) {
self.zeroize()
}
}
impl<C: Curve> Debug for FrostCore<C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FrostCore")
.field("params", &self.params)
.field("group_key", &self.group_key)
.field("verification_shares", &self.verification_shares)
.finish()
}
}
impl<C: Curve> FrostCore<C> {
pub fn params(&self) -> FrostParams {
self.params
}
fn secret_share(&self) -> C::F {
pub(crate) fn secret_share(&self) -> C::F {
self.secret_share
}
@@ -178,39 +181,16 @@ impl<C: Curve> FrostKeys<C> {
self.group_key
}
fn verification_shares(&self) -> HashMap<u16, C::G> {
pub(crate) fn verification_shares(&self) -> HashMap<u16, C::G> {
self.verification_shares.clone()
}
pub fn view(&self, included: &[u16]) -> Result<FrostView<C>, FrostError> {
if (included.len() < self.params.t.into()) || (usize::from(self.params.n) < included.len()) {
Err(FrostError::InvalidSigningSet("invalid amount of participants included"))?;
}
let secret_share = self.secret_share * lagrange::<C::F>(self.params.i, included);
let offset = self.offset.unwrap_or_else(C::F::zero);
let offset_share = offset * C::F::from(included.len().try_into().unwrap()).invert().unwrap();
Ok(FrostView {
group_key: self.group_key,
secret_share: secret_share + offset_share,
verification_shares: self
.verification_shares
.iter()
.map(|(l, share)| {
(*l, (*share * lagrange::<C::F>(*l, included)) + (C::GENERATOR * offset_share))
})
.collect(),
included: included.to_vec(),
})
}
pub fn serialized_len(n: u16) -> usize {
8 + C::ID.len() + (3 * 2) + C::F_len() + C::G_len() + (usize::from(n) * C::G_len())
}
pub fn serialize(&self) -> Vec<u8> {
let mut serialized = Vec::with_capacity(FrostKeys::<C>::serialized_len(self.params.n));
let mut serialized = Vec::with_capacity(FrostCore::<C>::serialized_len(self.params.n));
serialized.extend(u32::try_from(C::ID.len()).unwrap().to_be_bytes());
serialized.extend(C::ID);
serialized.extend(&self.params.t.to_be_bytes());
@@ -224,10 +204,10 @@ impl<C: Curve> FrostKeys<C> {
serialized
}
pub fn deserialize<R: Read>(cursor: &mut R) -> Result<FrostKeys<C>, FrostError> {
pub fn deserialize<R: Read>(cursor: &mut R) -> Result<FrostCore<C>, FrostError> {
{
let missing = FrostError::InternalError("FrostKeys serialization is missing its curve");
let different = FrostError::InternalError("deserializing FrostKeys for another curve");
let missing = FrostError::InternalError("FrostCore serialization is missing its curve");
let different = FrostError::InternalError("deserializing FrostCore for another curve");
let mut id_len = [0; 4];
cursor.read_exact(&mut id_len).map_err(|_| missing)?;
@@ -266,39 +246,133 @@ impl<C: Curve> FrostKeys<C> {
);
}
Ok(FrostKeys {
Ok(FrostCore {
params: FrostParams::new(t, n, i)
.map_err(|_| FrostError::InternalError("invalid parameters"))?,
secret_share,
group_key,
verification_shares,
offset: None,
})
}
}
// Validate a map of serialized values to have the expected included participants
pub(crate) fn validate_map<T>(
map: &mut HashMap<u16, T>,
included: &[u16],
ours: u16,
) -> Result<(), FrostError> {
if (map.len() + 1) != included.len() {
Err(FrostError::InvalidParticipantQuantity(included.len(), map.len() + 1))?;
}
/// FROST keys usable for signing
#[derive(Clone, Debug, Zeroize)]
pub struct FrostKeys<C: Curve> {
/// Core keys
#[zeroize(skip)]
core: Arc<FrostCore<C>>,
for included in included {
if *included == ours {
if map.contains_key(included) {
Err(FrostError::DuplicatedIndex(*included))?;
}
continue;
}
if !map.contains_key(included) {
Err(FrostError::MissingParticipant(*included))?;
}
}
Ok(())
/// Offset applied to these keys
pub(crate) offset: Option<C::F>,
}
// Manually implement Drop due to https://github.com/RustCrypto/utils/issues/786
impl<C: Curve> Drop for FrostKeys<C> {
fn drop(&mut self) {
self.zeroize()
}
}
// View of keys passable to algorithm implementations
#[derive(Clone, Zeroize)]
pub struct FrostView<C: Curve> {
group_key: C::G,
#[zeroize(skip)]
included: Vec<u16>,
secret_share: C::F,
#[zeroize(skip)]
verification_shares: HashMap<u16, C::G>,
}
impl<C: Curve> Drop for FrostView<C> {
fn drop(&mut self) {
self.zeroize()
}
}
impl<C: Curve> FrostKeys<C> {
pub fn new(core: FrostCore<C>) -> FrostKeys<C> {
FrostKeys { core: Arc::new(core), offset: None }
}
/// Offset the keys by a given scalar to allow for account and privacy schemes
/// This offset is ephemeral and will not be included when these keys are serialized
/// Keys offset multiple times will form a new offset of their sum
/// Not IETF compliant
pub fn offset(&self, offset: C::F) -> FrostKeys<C> {
let mut res = self.clone();
// Carry any existing offset
// Enables schemes like Monero's subaddresses which have a per-subaddress offset and then a
// one-time-key offset
res.offset = Some(offset + res.offset.unwrap_or_else(C::F::zero));
res
}
pub fn params(&self) -> FrostParams {
self.core.params
}
pub(crate) fn secret_share(&self) -> C::F {
self.core.secret_share
}
pub fn group_key(&self) -> C::G {
self.core.group_key + (C::GENERATOR * self.offset.unwrap_or_else(C::F::zero))
}
pub(crate) fn verification_shares(&self) -> HashMap<u16, C::G> {
self.core.verification_shares.clone()
}
pub fn serialized_len(n: u16) -> usize {
FrostCore::<C>::serialized_len(n)
}
pub fn serialize(&self) -> Vec<u8> {
self.core.serialize()
}
pub fn view(&self, included: &[u16]) -> Result<FrostView<C>, FrostError> {
if (included.len() < self.params().t.into()) || (usize::from(self.params().n) < included.len())
{
Err(FrostError::InvalidSigningSet("invalid amount of participants included"))?;
}
let offset_share = self.offset.unwrap_or_else(C::F::zero) *
C::F::from(included.len().try_into().unwrap()).invert().unwrap();
let offset_verification_share = C::GENERATOR * offset_share;
Ok(FrostView {
group_key: self.group_key(),
secret_share: (self.secret_share() * lagrange::<C::F>(self.params().i, included)) +
offset_share,
verification_shares: self
.verification_shares()
.iter()
.map(|(l, share)| {
(*l, (*share * lagrange::<C::F>(*l, included)) + offset_verification_share)
})
.collect(),
included: included.to_vec(),
})
}
}
impl<C: Curve> FrostView<C> {
pub fn group_key(&self) -> C::G {
self.group_key
}
pub fn included(&self) -> Vec<u16> {
self.included.clone()
}
pub fn secret_share(&self) -> C::F {
self.secret_share
}
pub fn verification_share(&self, l: u16) -> C::G {
self.verification_shares[&l]
}
}