flexible_transcript/
lib.rs

1#![cfg_attr(docsrs, feature(doc_auto_cfg))]
2#![doc = include_str!("../README.md")]
3#![no_std]
4
5use zeroize::Zeroize;
6
7use digest::{
8  typenum::{
9    consts::U32, marker_traits::NonZero, type_operators::IsGreaterOrEqual, operator_aliases::GrEq,
10  },
11  core_api::BlockSizeUser,
12  Digest, Output, HashMarker,
13};
14
15#[cfg(feature = "merlin")]
16mod merlin;
17#[cfg(feature = "merlin")]
18pub use crate::merlin::MerlinTranscript;
19
20/// Tests for a transcript.
21#[cfg(any(test, feature = "tests"))]
22pub mod tests;
23
24/// A transcript trait valid over a variety of transcript formats.
25pub trait Transcript: Send + Clone {
26  type Challenge: Send + Sync + Clone + AsRef<[u8]>;
27
28  /// Create a new transcript with the specified name.
29  fn new(name: &'static [u8]) -> Self;
30
31  /// Apply a domain separator to the transcript.
32  fn domain_separate(&mut self, label: &'static [u8]);
33
34  /// Append a message to the transcript.
35  fn append_message<M: AsRef<[u8]>>(&mut self, label: &'static [u8], message: M);
36
37  /// Produce a challenge.
38  ///
39  /// Implementors MUST update the transcript as it does so, preventing the same challenge from
40  /// being generated multiple times.
41  fn challenge(&mut self, label: &'static [u8]) -> Self::Challenge;
42
43  /// Produce a RNG seed.
44  ///
45  /// Helper function for parties needing to generate random data from an agreed upon state.
46  ///
47  /// Implementors MAY internally call the challenge function for the needed bytes, and accordingly
48  /// produce a transcript conflict between two transcripts, one which called challenge(label) and
49  /// one which called rng_seed(label) at the same point.
50  fn rng_seed(&mut self, label: &'static [u8]) -> [u8; 32];
51}
52
53#[derive(Clone, Copy)]
54enum DigestTranscriptMember {
55  Name,
56  Domain,
57  Label,
58  Value,
59  Challenge,
60  Continued,
61  Challenged,
62}
63
64impl DigestTranscriptMember {
65  fn as_u8(&self) -> u8 {
66    match self {
67      DigestTranscriptMember::Name => 0,
68      DigestTranscriptMember::Domain => 1,
69      DigestTranscriptMember::Label => 2,
70      DigestTranscriptMember::Value => 3,
71      DigestTranscriptMember::Challenge => 4,
72      DigestTranscriptMember::Continued => 5,
73      DigestTranscriptMember::Challenged => 6,
74    }
75  }
76}
77
78/// A trait defining cryptographic Digests with at least a 256-bit output size, assuming at least a
79/// 128-bit level of security accordingly.
80pub trait SecureDigest: Digest + HashMarker {}
81impl<D: Digest + HashMarker> SecureDigest for D
82where
83  // This just lets us perform the comparison
84  D::OutputSize: IsGreaterOrEqual<U32>,
85  // Perform the comparison and make sure it's true (not zero), meaning D::OutputSize is >= U32
86  // This should be U32 as it's length in bytes, not bits
87  GrEq<D::OutputSize, U32>: NonZero,
88{
89}
90
91/// A simple transcript format constructed around the specified hash algorithm.
92#[derive(Clone, Debug)]
93pub struct DigestTranscript<D: Send + Clone + SecureDigest>(D);
94
95impl<D: Send + Clone + SecureDigest> DigestTranscript<D> {
96  fn append(&mut self, kind: DigestTranscriptMember, value: &[u8]) {
97    self.0.update([kind.as_u8()]);
98    // Assumes messages don't exceed 16 exabytes
99    self.0.update(u64::try_from(value.len()).unwrap().to_le_bytes());
100    self.0.update(value);
101  }
102}
103
104impl<D: Send + Clone + SecureDigest> Transcript for DigestTranscript<D> {
105  type Challenge = Output<D>;
106
107  fn new(name: &'static [u8]) -> Self {
108    let mut res = DigestTranscript(D::new());
109    res.append(DigestTranscriptMember::Name, name);
110    res
111  }
112
113  fn domain_separate(&mut self, label: &'static [u8]) {
114    self.append(DigestTranscriptMember::Domain, label);
115  }
116
117  fn append_message<M: AsRef<[u8]>>(&mut self, label: &'static [u8], message: M) {
118    self.append(DigestTranscriptMember::Label, label);
119    self.append(DigestTranscriptMember::Value, message.as_ref());
120  }
121
122  fn challenge(&mut self, label: &'static [u8]) -> Self::Challenge {
123    self.append(DigestTranscriptMember::Challenge, label);
124    let mut cloned = self.0.clone();
125
126    // Explicitly fork these transcripts to prevent length extension attacks from being possible
127    // (at least, without the additional ability to remove a byte from a finalized hash)
128    self.0.update([DigestTranscriptMember::Continued.as_u8()]);
129    cloned.update([DigestTranscriptMember::Challenged.as_u8()]);
130    cloned.finalize()
131  }
132
133  fn rng_seed(&mut self, label: &'static [u8]) -> [u8; 32] {
134    let mut seed = [0; 32];
135    seed.copy_from_slice(&self.challenge(label)[.. 32]);
136    seed
137  }
138}
139
140// Digest doesn't implement Zeroize
141// Implement Zeroize for DigestTranscript by writing twice the block size to the digest in an
142// attempt to overwrite the internal hash state/any leftover bytes
143impl<D: Send + Clone + SecureDigest> Zeroize for DigestTranscript<D>
144where
145  D: BlockSizeUser,
146{
147  fn zeroize(&mut self) {
148    // Update in 4-byte chunks to reduce call quantity and enable word-level update optimizations
149    const WORD_SIZE: usize = 4;
150
151    // block_size returns the block_size in bytes
152    // Use a ceil div in case the block size isn't evenly divisible by our word size
153    let words = D::block_size().div_ceil(WORD_SIZE);
154    for _ in 0 .. (2 * words) {
155      self.0.update([255; WORD_SIZE]);
156    }
157
158    // Hopefully, the hash state is now overwritten to the point no data is recoverable
159    // These writes may be optimized out if they're never read
160    // Attempt to get them marked as read
161
162    #[rustversion::since(1.66)]
163    fn mark_read<D: Send + Clone + SecureDigest>(transcript: &DigestTranscript<D>) {
164      // Just get a challenge from the state
165      let mut challenge = core::hint::black_box(transcript.0.clone().finalize());
166      challenge.as_mut().zeroize();
167    }
168
169    #[rustversion::before(1.66)]
170    fn mark_read<D: Send + Clone + SecureDigest>(transcript: &mut DigestTranscript<D>) {
171      // Get a challenge
172      let challenge = transcript.0.clone().finalize();
173
174      // Attempt to use subtle's, non-exposed black_box function, by creating a Choice from this
175      // challenge
176
177      let mut read = 0;
178      for byte in challenge.as_ref() {
179        read ^= byte;
180      }
181      challenge.as_mut().zeroize();
182
183      // Since this Choice isn't further read, its creation may be optimized out, including its
184      // internal black_box
185      // This remains our best attempt
186      let mut choice = bool::from(subtle::Choice::from(read >> 7));
187      read.zeroize();
188      choice.zeroize();
189    }
190
191    mark_read(self)
192  }
193}
194
195/// The recommended transcript, guaranteed to be secure against length-extension attacks.
196#[cfg(feature = "recommended")]
197pub type RecommendedTranscript = DigestTranscript<blake2::Blake2b512>;