Skip to main content

tor_llcrypto/pk/
ed25519.rs

1//! Re-exporting Ed25519 implementations, and related utilities.
2//!
3//! Here we re-export types from [`ed25519_dalek`] that implement the
4//! Ed25519 signature algorithm.  (TODO: Eventually, this module
5//! should probably be replaced with a wrapper that uses the ed25519
6//! trait and the Signature trait.)
7//!
8//! We additionally provide an `Ed25519Identity` type to represent the
9//! unvalidated Ed25519 "identity keys" that we use throughout the Tor
10//! protocol to uniquely identify a relay.
11
12use base64ct::{Base64Unpadded, Encoding as _};
13use curve25519_dalek::Scalar;
14use derive_deftly::Deftly;
15use safelog::util::write_start_redacted;
16use std::fmt::{self, Debug, Display, Formatter};
17use subtle::{Choice, ConstantTimeEq};
18
19#[cfg(feature = "memquota-memcost")]
20use tor_memquota_cost::derive_deftly_template_HasMemoryCost;
21
22use ed25519_dalek::hazmat::ExpandedSecretKey;
23use ed25519_dalek::{Signer as _, Verifier as _};
24
25use crate::util::ct::{
26    CtByteArray, derive_deftly_template_ConstantTimeEq, derive_deftly_template_PartialEqFromCtEq,
27};
28
29/// An Ed25519 signature.
30///
31/// See [`ed25519_dalek::Signature`] for more information.
32#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33pub struct Signature(pub(crate) ed25519_dalek::Signature);
34
35/// An Ed25519 keypair.
36///
37/// (We do not provide a separate "private key only" type.)
38///
39/// See [`ed25519_dalek::SigningKey`] for more information.
40#[derive(Debug, Deftly)]
41#[derive_deftly(ConstantTimeEq)]
42pub struct Keypair(pub(crate) ed25519_dalek::SigningKey);
43
44/// An Ed25519 public key.
45///
46/// See [`ed25519_dalek::VerifyingKey`] for more information.
47#[derive(Clone, Copy, Debug, Eq, Deftly)]
48#[derive_deftly(PartialEqFromCtEq)]
49pub struct PublicKey(pub(crate) ed25519_dalek::VerifyingKey);
50
51impl<'a> From<&'a Keypair> for PublicKey {
52    fn from(value: &'a Keypair) -> Self {
53        PublicKey((&value.0).into())
54    }
55}
56
57impl ConstantTimeEq for PublicKey {
58    fn ct_eq(&self, other: &Self) -> Choice {
59        self.as_bytes().ct_eq(other.as_bytes())
60    }
61}
62
63impl PublicKey {
64    /// Construct a public key from its byte representation.
65    pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, signature::Error> {
66        Ok(PublicKey(ed25519_dalek::VerifyingKey::from_bytes(bytes)?))
67    }
68
69    /// Return a reference to the byte representation of this public key.
70    pub fn as_bytes(&self) -> &[u8; 32] {
71        self.0.as_bytes()
72    }
73    /// Return the byte representation of this public key.
74    pub fn to_bytes(&self) -> [u8; 32] {
75        self.0.to_bytes()
76    }
77    /// Verify a signature using this public key.
78    ///
79    /// See [`ed25519_dalek::VerifyingKey::verify`] for more information.
80    pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), signature::Error> {
81        self.0.verify(message, &signature.0)
82    }
83}
84impl Keypair {
85    /// Generate a new random ed25519 keypair.
86    pub fn generate<R: rand_core::Rng + rand_core::CryptoRng>(csprng: &mut R) -> Self {
87        Self(ed25519_dalek::SigningKey::generate(csprng))
88    }
89    /// Construct an ed25519 keypair from the byte representation of its secret key.
90    pub fn from_bytes(bytes: &[u8; 32]) -> Self {
91        Self(ed25519_dalek::SigningKey::from_bytes(bytes))
92    }
93    /// Return a reference to the byte representation of the secret key in this keypair.
94    pub fn as_bytes(&self) -> &[u8; 32] {
95        self.0.as_bytes()
96    }
97    /// Return to the byte representation of the secret key in this keypair.
98    pub fn to_bytes(&self) -> [u8; 32] {
99        self.0.to_bytes()
100    }
101    /// Return the public key in this keypair.
102    pub fn verifying_key(&self) -> PublicKey {
103        PublicKey(*self.0.as_ref())
104    }
105    /// Verify a signature generated with this keypair.
106    pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<(), signature::Error> {
107        self.0.verify(message, &signature.0)
108    }
109    /// Sign a message using this keypair.
110    pub fn sign(&self, message: &[u8]) -> Signature {
111        Signature(self.0.sign(message))
112    }
113}
114impl Signature {
115    /// Construct this signature from its byte representation.
116    pub fn from_bytes(bytes: &[u8; 64]) -> Self {
117        Self(ed25519_dalek::Signature::from_bytes(bytes))
118    }
119    /// Return the byte representation of this signature.
120    pub fn to_bytes(&self) -> [u8; 64] {
121        self.0.to_bytes()
122    }
123}
124impl<'a> TryFrom<&'a [u8]> for PublicKey {
125    type Error = signature::Error;
126
127    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
128        Ok(Self(ed25519_dalek::VerifyingKey::try_from(value)?))
129    }
130}
131impl<'a> From<&'a [u8; 32]> for Keypair {
132    fn from(value: &'a [u8; 32]) -> Self {
133        Self(ed25519_dalek::SigningKey::from(value))
134    }
135}
136impl From<[u8; 64]> for Signature {
137    fn from(value: [u8; 64]) -> Self {
138        Signature(value.into())
139    }
140}
141impl<'a> From<&'a [u8; 64]> for Signature {
142    fn from(value: &'a [u8; 64]) -> Self {
143        Signature(value.into())
144    }
145}
146
147/// The length of an ED25519 identity, in bytes.
148pub const ED25519_ID_LEN: usize = 32;
149
150/// The length of an ED25519 signature, in bytes.
151pub const ED25519_SIGNATURE_LEN: usize = 64;
152
153/// A variant of [`Keypair`] containing an [`ExpandedSecretKey`].
154///
155/// In the Tor protocol, we use this type for blinded onion service identity keys
156/// (KS_hs_blind_id).  Since their scalar values are computed, rather than taken
157/// directly from a
158/// SHA-512 transformation of a SecretKey, we cannot use the regular `Keypair`
159/// type.
160#[allow(clippy::exhaustive_structs)]
161#[derive(Deftly)]
162#[derive_deftly(ConstantTimeEq)]
163pub struct ExpandedKeypair {
164    /// The secret part of the key.
165    pub(crate) secret: ExpandedSecretKey,
166    /// The public part of this key.
167    ///
168    /// NOTE: As with [`ed25519_dalek::SigningKey`], this public key _must_ be
169    /// the public key matching `secret`.  Putting a different public key in
170    /// here would enable a class of attacks against ed25519 and enable secret
171    /// key recovery.
172    pub(crate) public: PublicKey,
173}
174
175impl ExpandedKeypair {
176    /// Return the public part of this expanded keypair.
177    pub fn public(&self) -> &PublicKey {
178        &self.public
179    }
180
181    // NOTE: There is deliberately no secret() function.  If we had one, we
182    // would be exposing an unescorted secret key, which is part of
183    // ed25519::hazmat.
184
185    /// Compute a signature over a message using this keypair.
186    pub fn sign(&self, message: &[u8]) -> Signature {
187        use sha2::Sha512;
188        // See notes on ExpandedKeypair about why this hazmat is okay to use.
189        Signature(ed25519_dalek::hazmat::raw_sign::<Sha512>(
190            &self.secret,
191            message,
192            &self.public.0,
193        ))
194    }
195
196    /// Return a representation of the secret key in this keypair.
197    ///
198    /// (Since it is an expanded secret key, we represent it as its scalar part
199    /// followed by its hash_prefix.)
200    pub fn to_secret_key_bytes(&self) -> [u8; 64] {
201        let mut output = [0_u8; 64];
202        output[0..32].copy_from_slice(&self.secret.scalar.to_bytes());
203        output[32..64].copy_from_slice(&self.secret.hash_prefix);
204        output
205    }
206
207    /// Reconstruct a key from its byte representation as returned by
208    /// `to_secret_key_bytes()`.
209    ///
210    /// Return None if the input cannot be the output of `to_secret_key_bytes()`.
211    //
212    // NOTE: Returning None is a bit silly, but that's what Dalek does.
213    pub fn from_secret_key_bytes(bytes: [u8; 64]) -> Option<Self> {
214        let scalar = Option::from(Scalar::from_bytes_mod_order(
215            bytes[0..32].try_into().expect("wrong length on slice"),
216        ))?;
217        let hash_prefix = bytes[32..64].try_into().expect("wrong length on slice");
218        let secret = ExpandedSecretKey {
219            scalar,
220            hash_prefix,
221        };
222        let public = PublicKey((&secret).into());
223        Some(Self { secret, public })
224    }
225
226    // NOTE: There is deliberately no constructor here that takes a (secret,
227    // public) pair.  If there were, you could construct a pair with a
228    // mismatched public key.
229}
230
231impl<'a> From<&'a Keypair> for ExpandedKeypair {
232    fn from(kp: &'a Keypair) -> ExpandedKeypair {
233        ExpandedKeypair {
234            secret: kp.as_bytes().into(),
235            public: kp.into(),
236        }
237    }
238}
239
240impl From<ExpandedKeypair> for PublicKey {
241    fn from(ekp: ExpandedKeypair) -> PublicKey {
242        ekp.public
243    }
244}
245
246/// An unchecked, unvalidated Ed25519 key.
247///
248/// This key is an "identity" in the sense that it identifies (up to) one
249/// Ed25519 key.  It may also represent the identity for a particular entity,
250/// such as a relay or an onion service.
251///
252/// This type is distinct from an Ed25519 [`PublicKey`] for several reasons:
253///  * We're storing it in a compact format, whereas the public key
254///    implementation might want an expanded form for more efficient key
255///    validation.
256///  * This type hasn't checked whether the bytes here actually _are_ a valid
257///    Ed25519 public key.
258#[derive(Clone, Copy, Hash, PartialOrd, Ord, Eq, PartialEq)]
259#[cfg_attr(
260    feature = "memquota-memcost",
261    derive(Deftly),
262    derive_deftly(HasMemoryCost)
263)]
264pub struct Ed25519Identity {
265    /// A raw unchecked Ed25519 public key.
266    id: CtByteArray<ED25519_ID_LEN>,
267}
268
269impl Ed25519Identity {
270    /// Construct a new Ed25519 identity from a 32-byte sequence.
271    ///
272    /// This might or might not actually be a valid Ed25519 public key.
273    ///
274    /// ```
275    /// use tor_llcrypto::pk::ed25519::{Ed25519Identity, PublicKey};
276    ///
277    /// let bytes = b"klsadjfkladsfjklsdafkljasdfsdsd!";
278    /// let id = Ed25519Identity::new(*bytes);
279    /// let pk: Result<PublicKey,_> = (&id).try_into();
280    /// assert!(pk.is_ok());
281    ///
282    /// let bytes = b"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
283    /// let id = Ed25519Identity::new(*bytes);
284    /// let pk: Result<PublicKey,_> = (&id).try_into();
285    /// assert!(pk.is_err());
286    /// ```
287    pub fn new(id: [u8; 32]) -> Self {
288        Ed25519Identity { id: id.into() }
289    }
290    /// If `id` is of the correct length, wrap it in an Ed25519Identity.
291    pub fn from_bytes(id: &[u8]) -> Option<Self> {
292        Some(Ed25519Identity::new(id.try_into().ok()?))
293    }
294    /// Return a reference to the bytes in this key.
295    pub fn as_bytes(&self) -> &[u8] {
296        &self.id.as_ref()[..]
297    }
298    /// Decode an `Ed25519Identity` from a base64-encoded string.
299    ///
300    /// The string must have no padding, spaces, or any extra characters.
301    // We decode without padding to match the serde deserialize impl.
302    pub fn from_base64(s: &str) -> Option<Self> {
303        let bytes = Base64Unpadded::decode_vec(s).ok()?;
304        Ed25519Identity::from_bytes(&bytes)
305    }
306}
307
308impl From<[u8; ED25519_ID_LEN]> for Ed25519Identity {
309    fn from(id: [u8; ED25519_ID_LEN]) -> Self {
310        Ed25519Identity::new(id)
311    }
312}
313
314impl From<Ed25519Identity> for [u8; ED25519_ID_LEN] {
315    fn from(value: Ed25519Identity) -> Self {
316        value.id.into()
317    }
318}
319
320impl From<PublicKey> for Ed25519Identity {
321    fn from(pk: PublicKey) -> Self {
322        (&pk).into()
323    }
324}
325
326impl From<&PublicKey> for Ed25519Identity {
327    fn from(pk: &PublicKey) -> Self {
328        // This unwrap is safe because the public key is always 32 bytes
329        // long.
330        Ed25519Identity::from_bytes(pk.as_bytes()).expect("Ed25519 public key had wrong length?")
331    }
332}
333
334impl TryFrom<&Ed25519Identity> for PublicKey {
335    type Error = ed25519_dalek::SignatureError;
336    fn try_from(id: &Ed25519Identity) -> Result<PublicKey, Self::Error> {
337        PublicKey::from_bytes(id.id.as_ref())
338    }
339}
340
341impl TryFrom<Ed25519Identity> for PublicKey {
342    type Error = ed25519_dalek::SignatureError;
343    fn try_from(id: Ed25519Identity) -> Result<PublicKey, Self::Error> {
344        (&id).try_into()
345    }
346}
347
348impl ConstantTimeEq for Ed25519Identity {
349    fn ct_eq(&self, other: &Self) -> Choice {
350        self.id.ct_eq(&other.id)
351    }
352}
353
354impl Display for Ed25519Identity {
355    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
356        write!(f, "{}", Base64Unpadded::encode_string(self.id.as_ref()))
357    }
358}
359
360impl Debug for Ed25519Identity {
361    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
362        write!(f, "Ed25519Identity {{ {} }}", self)
363    }
364}
365
366impl safelog::Redactable for Ed25519Identity {
367    /// Warning: This displays 12 bits of the ed25519 identity, which is
368    /// enough to narrow down a public relay by a great deal.
369    fn display_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
370        write_start_redacted(f, &Base64Unpadded::encode_string(self.id.as_ref()), 2, "…")
371    }
372
373    fn debug_redacted(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
374        write!(f, "Ed25519Identity {{ {} }}", self.redacted())
375    }
376}
377
378impl serde::Serialize for Ed25519Identity {
379    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
380    where
381        S: serde::Serializer,
382    {
383        if serializer.is_human_readable() {
384            serializer.serialize_str(&Base64Unpadded::encode_string(self.id.as_ref()))
385        } else {
386            serializer.serialize_bytes(&self.id.as_ref()[..])
387        }
388    }
389}
390
391impl<'de> serde::Deserialize<'de> for Ed25519Identity {
392    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
393    where
394        D: serde::Deserializer<'de>,
395    {
396        if deserializer.is_human_readable() {
397            /// Helper for deserialization
398            struct EdIdentityVisitor;
399            impl<'de> serde::de::Visitor<'de> for EdIdentityVisitor {
400                type Value = Ed25519Identity;
401                fn expecting(&self, fmt: &mut std::fmt::Formatter<'_>) -> fmt::Result {
402                    fmt.write_str("base64-encoded Ed25519 public key")
403                }
404                fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
405                where
406                    E: serde::de::Error,
407                {
408                    let bytes = Base64Unpadded::decode_vec(s).map_err(E::custom)?;
409                    Ed25519Identity::from_bytes(&bytes)
410                        .ok_or_else(|| E::custom("wrong length for Ed25519 public key"))
411                }
412            }
413
414            deserializer.deserialize_str(EdIdentityVisitor)
415        } else {
416            /// Helper for deserialization
417            struct EdIdentityVisitor;
418            impl<'de> serde::de::Visitor<'de> for EdIdentityVisitor {
419                type Value = Ed25519Identity;
420                fn expecting(&self, fmt: &mut std::fmt::Formatter<'_>) -> fmt::Result {
421                    fmt.write_str("ed25519 public key")
422                }
423                fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E>
424                where
425                    E: serde::de::Error,
426                {
427                    Ed25519Identity::from_bytes(bytes)
428                        .ok_or_else(|| E::custom("wrong length for ed25519 public key"))
429                }
430            }
431            deserializer.deserialize_bytes(EdIdentityVisitor)
432        }
433    }
434}
435
436/// An ed25519 signature, plus the document that it signs and its
437/// public key.
438#[derive(Clone, Debug)]
439#[cfg_attr(
440    feature = "memquota-memcost",
441    derive(Deftly),
442    derive_deftly(HasMemoryCost)
443)]
444pub struct ValidatableEd25519Signature {
445    /// The key that allegedly produced the signature
446    #[cfg_attr(feature = "memquota-memcost", deftly(has_memory_cost(copy)))]
447    key: PublicKey,
448    /// The alleged signature
449    #[cfg_attr(feature = "memquota-memcost", deftly(has_memory_cost(copy)))]
450    sig: Signature,
451    /// The entire body of text that is allegedly signed here.
452    ///
453    /// TODO: It's not so good to have this included here; it
454    /// would be better to have a patch to ed25519_dalek to allow
455    /// us to pre-hash the signed thing, and just store a digest.
456    /// We can't use that with the 'prehash' variant of ed25519,
457    /// since that has different constants.
458    entire_text_of_signed_thing: Vec<u8>,
459}
460
461impl ValidatableEd25519Signature {
462    /// Create a new ValidatableEd25519Signature
463    pub fn new(key: PublicKey, sig: Signature, text: &[u8]) -> Self {
464        ValidatableEd25519Signature {
465            key,
466            sig,
467            entire_text_of_signed_thing: text.into(),
468        }
469    }
470
471    /// View the interior of this signature object.
472    pub(crate) fn as_parts(&self) -> (&PublicKey, &Signature, &[u8]) {
473        (&self.key, &self.sig, &self.entire_text_of_signed_thing[..])
474    }
475
476    /// Return a reference to the underlying Signature.
477    pub fn signature(&self) -> &Signature {
478        &self.sig
479    }
480}
481
482impl super::ValidatableSignature for ValidatableEd25519Signature {
483    fn is_valid(&self) -> bool {
484        self.key
485            .verify(&self.entire_text_of_signed_thing[..], &self.sig)
486            .is_ok()
487    }
488
489    fn as_ed25519(&self) -> Option<&ValidatableEd25519Signature> {
490        Some(self)
491    }
492}
493
494/// Perform a batch verification operation on the provided signatures
495///
496/// Return `true` if _every_ signature is valid; otherwise return `false`.
497///
498/// Note that the mathematics for batch validation are slightly
499/// different than those for normal one-signature validation.  Because
500/// of this, it is possible for an ostensible signature that passes
501/// one validation algorithm might fail the other.  (Well-formed
502/// signatures generated by a correct Ed25519 implementation will
503/// always pass both kinds of validation, and an attacker should not
504/// be able to forge a signature that passes either kind.)
505pub fn validate_batch(sigs: &[&ValidatableEd25519Signature]) -> bool {
506    use crate::pk::ValidatableSignature;
507    if sigs.is_empty() {
508        // ed25519_dalek has nonzero cost for a batch-verification of
509        // zero sigs.
510        true
511    } else if sigs.len() == 1 {
512        // Validating one signature in the traditional way is faster.
513        sigs[0].is_valid()
514    } else {
515        let mut ed_msgs = Vec::new();
516        let mut ed_sigs = Vec::new();
517        let mut ed_pks = Vec::new();
518        for ed_sig in sigs {
519            let (pk, sig, msg) = ed_sig.as_parts();
520            ed_sigs.push(sig.0);
521            ed_pks.push(pk.0);
522            ed_msgs.push(msg);
523        }
524        ed25519_dalek::verify_batch(&ed_msgs[..], &ed_sigs[..], &ed_pks[..]).is_ok()
525    }
526}
527
528/// An object that has an Ed25519 [`PublicKey`].
529pub trait Ed25519PublicKey {
530    /// Get the Ed25519 [`PublicKey`].
531    fn public_key(&self) -> PublicKey;
532}
533
534impl Ed25519PublicKey for Keypair {
535    fn public_key(&self) -> PublicKey {
536        Keypair::verifying_key(self)
537    }
538}
539
540impl Ed25519PublicKey for ExpandedKeypair {
541    fn public_key(&self) -> PublicKey {
542        self.public
543    }
544}
545
546/// An object that can generate Ed25519 signatures.
547pub trait Ed25519SigningKey {
548    /// Sign a message with this key.
549    fn sign(&self, message: &[u8]) -> Signature;
550}
551
552impl Ed25519SigningKey for Keypair {
553    fn sign(&self, message: &[u8]) -> Signature {
554        Keypair::sign(self, message)
555    }
556}
557impl Ed25519SigningKey for ExpandedKeypair {
558    fn sign(&self, message: &[u8]) -> Signature {
559        ExpandedKeypair::sign(self, message)
560    }
561}
562
563#[cfg(test)]
564mod test {
565    // @@ begin test lint list maintained by maint/add_warning @@
566    #![allow(clippy::bool_assert_comparison)]
567    #![allow(clippy::clone_on_copy)]
568    #![allow(clippy::dbg_macro)]
569    #![allow(clippy::mixed_attributes_style)]
570    #![allow(clippy::print_stderr)]
571    #![allow(clippy::print_stdout)]
572    #![allow(clippy::single_char_pattern)]
573    #![allow(clippy::unwrap_used)]
574    #![allow(clippy::unchecked_time_subtraction)]
575    #![allow(clippy::useless_vec)]
576    #![allow(clippy::needless_pass_by_value)]
577    #![allow(clippy::string_slice)] // See arti#2571
578    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
579
580    use super::*;
581
582    #[test]
583    fn ed_from_base64() {
584        let id =
585            Ed25519Identity::from_base64("qpL/LxLYVEXghU76iG3LsSI/UW7MBpIROZK0AB18560").unwrap();
586
587        assert_eq!(
588            id,
589            Ed25519Identity::from([
590                0xaa, 0x92, 0xff, 0x2f, 0x12, 0xd8, 0x54, 0x45, 0xe0, 0x85, 0x4e, 0xfa, 0x88, 0x6d,
591                0xcb, 0xb1, 0x22, 0x3f, 0x51, 0x6e, 0xcc, 0x06, 0x92, 0x11, 0x39, 0x92, 0xb4, 0x00,
592                0x1d, 0x7c, 0xe7, 0xad
593            ]),
594        );
595    }
596}