1
//! Public-key cryptography for Tor.
2
//!
3
//! In old places, Tor uses RSA; newer Tor public-key cryptography is
4
//! based on curve25519 and ed25519.
5

            
6
pub mod ed25519;
7
pub mod keymanip;
8
pub mod rsa;
9

            
10
/// Re-exporting Curve25519 implementations.
11
///
12
/// *TODO*: Eventually we should probably recommend using this code via some
13
/// key-agreement trait, but for now we are just re-using the APIs from
14
/// [`x25519_dalek`].
15
pub mod curve25519 {
16
    use derive_deftly::Deftly;
17
    use educe::Educe;
18
    use subtle::ConstantTimeEq;
19

            
20
    use crate::util::ct::derive_deftly_template_PartialEqFromCtEq;
21

            
22
    /// A keypair containing a [`StaticSecret`] and its corresponding public key.
23
    #[allow(clippy::exhaustive_structs)]
24
    #[derive(Clone, Educe)]
25
    #[educe(Debug)]
26
    pub struct StaticKeypair {
27
        /// The secret part of the key.
28
        #[educe(Debug(ignore))]
29
        pub secret: StaticSecret,
30
        /// The public part of this key.
31
        pub public: PublicKey,
32
    }
33

            
34
    /// A curve25519 secret key that can only be used once,
35
    /// and that can never be inspected.
36
    ///
37
    /// See [`x25519_dalek::EphemeralSecret`] for more information.
38
    pub struct EphemeralSecret(x25519_dalek::EphemeralSecret);
39

            
40
    /// A curve25519 secret key that can be used more than once,
41
    /// and whose value can be inspected.
42
    ///
43
    /// See [`x25519_dalek::StaticSecret`] for more information.
44
    //
45
    // TODO: We may want eventually want to expose ReusableSecret instead of
46
    // StaticSecret, for use in places where we need to use a single secret
47
    // twice in one handshake, but we do not need that secret to be persistent.
48
    //
49
    // The trouble here is that if we use ReusableSecret in these cases, we
50
    // cannot easily construct it for testing purposes.  We could in theory
51
    // kludge something together using a fake Rng, but that might be more
52
    // trouble than we want to go looking for.
53
    #[derive(Clone)]
54
    pub struct StaticSecret(x25519_dalek::StaticSecret);
55

            
56
    impl ConstantTimeEq for StaticSecret {
57
        fn ct_eq(&self, other: &Self) -> subtle::Choice {
58
            let Self { 0: self_secret } = self;
59
            let Self { 0: other_secret } = other;
60

            
61
            self_secret.as_bytes().ct_eq(other_secret.as_bytes())
62
        }
63
    }
64

            
65
    /// A curve15519 public key.
66
    ///
67
    /// See [`x25519_dalek::PublicKey`] for more information.
68
    #[derive(Clone, Copy, Debug, Eq, Hash, Deftly)]
69
    // Sadly not Ord because x25519_dalek::PublicKey isn't
70
    #[allow(clippy::derived_hash_with_manual_eq)]
71
    #[derive_deftly(PartialEqFromCtEq)]
72
    pub struct PublicKey(x25519_dalek::PublicKey);
73

            
74
    impl ConstantTimeEq for PublicKey {
75
5115
        fn ct_eq(&self, other: &Self) -> subtle::Choice {
76
5115
            let Self { 0: self_secret } = self;
77
5115
            let Self { 0: other_secret } = other;
78

            
79
5115
            self_secret.as_bytes().ct_eq(other_secret.as_bytes())
80
5115
        }
81
    }
82

            
83
    /// A shared secret negotiated using curve25519.
84
    ///
85
    /// See [`x25519_dalek::SharedSecret`] for more information
86
    pub struct SharedSecret(x25519_dalek::SharedSecret);
87

            
88
    impl<'a> From<&'a EphemeralSecret> for PublicKey {
89
11346
        fn from(secret: &'a EphemeralSecret) -> Self {
90
11346
            Self((&secret.0).into())
91
11346
        }
92
    }
93

            
94
    impl<'a> From<&'a StaticSecret> for PublicKey {
95
33298
        fn from(secret: &'a StaticSecret) -> Self {
96
33298
            Self((&secret.0).into())
97
33298
        }
98
    }
99

            
100
    impl From<[u8; 32]> for StaticSecret {
101
9208
        fn from(value: [u8; 32]) -> Self {
102
9208
            Self(value.into())
103
9208
        }
104
    }
105
    impl From<[u8; 32]> for PublicKey {
106
987381
        fn from(value: [u8; 32]) -> Self {
107
987381
            Self(value.into())
108
987381
        }
109
    }
110

            
111
    impl EphemeralSecret {
112
        /// Return a new random ephemeral secret key.
113
123
        pub fn random_from_rng<R: ?Sized + rand_core::Rng + rand_core::CryptoRng>(
114
123
            csprng: &mut R,
115
123
        ) -> Self {
116
123
            Self(x25519_dalek::EphemeralSecret::random_from_rng(csprng))
117
123
        }
118
        /// Negotiate a shared secret using this secret key and a public key.
119
1674
        pub fn diffie_hellman(self, their_public: &PublicKey) -> SharedSecret {
120
1674
            SharedSecret(self.0.diffie_hellman(&their_public.0))
121
1674
        }
122
    }
123
    impl StaticSecret {
124
        /// Return a new random static secret key.
125
5679
        pub fn random_from_rng<R: ?Sized + rand_core::Rng + rand_core::CryptoRng>(
126
5679
            csprng: &mut R,
127
5679
        ) -> Self {
128
5679
            Self(x25519_dalek::StaticSecret::random_from_rng(csprng))
129
5679
        }
130
        /// Negotiate a shared secret using this secret key and a public key.
131
26319
        pub fn diffie_hellman(&self, their_public: &PublicKey) -> SharedSecret {
132
26319
            SharedSecret(self.0.diffie_hellman(&their_public.0))
133
26319
        }
134
        /// Return the bytes that represent this key.
135
6421
        pub fn to_bytes(&self) -> [u8; 32] {
136
6421
            self.0.to_bytes()
137
6421
        }
138
        /// Return a reference to the bytes that represent this key.
139
        pub fn as_bytes(&self) -> &[u8; 32] {
140
            self.0.as_bytes()
141
        }
142
    }
143
    impl SharedSecret {
144
        /// Return the shared secret as an array of bytes.
145
32643
        pub fn as_bytes(&self) -> &[u8; 32] {
146
32643
            self.0.as_bytes()
147
32643
        }
148
        /// Return true if both keys contributed to this shared secret.
149
        ///
150
        /// See [`x25519_dalek::SharedSecret::was_contributory`] for more information.
151
17856
        pub fn was_contributory(&self) -> bool {
152
17856
            self.0.was_contributory()
153
17856
        }
154
    }
155
    impl PublicKey {
156
        /// Return this public key as a reference to an array of bytes.
157
282352
        pub fn as_bytes(&self) -> &[u8; 32] {
158
282352
            self.0.as_bytes()
159
282352
        }
160
        /// Return this public key as an array of bytes.
161
38688
        pub fn to_bytes(&self) -> [u8; 32] {
162
38688
            self.0.to_bytes()
163
38688
        }
164
    }
165
}
166

            
167
/// A type for a validatable signature.
168
///
169
/// It necessarily includes the signature, the public key, and (a hash
170
/// of?) the document being checked.
171
///
172
/// Having this trait enables us to write code for checking a large number
173
/// of validatable signatures in a way that permits batch signatures for
174
/// Ed25519.
175
///
176
/// To be used with [`validate_all_sigs`].
177
pub trait ValidatableSignature {
178
    /// Check whether this signature is a correct signature for the document.
179
    fn is_valid(&self) -> bool;
180

            
181
    /// Return this value as a validatable Ed25519 signature, if it is one.
182
29
    fn as_ed25519(&self) -> Option<&ed25519::ValidatableEd25519Signature> {
183
29
        None
184
29
    }
185
}
186

            
187
/// Check whether all of the signatures in this Vec are valid.
188
///
189
/// Return `true` if every signature is valid; return `false` if even
190
/// one is invalid.
191
///
192
/// This function should typically give the same result as just
193
/// calling `v.iter().all(ValidatableSignature::is_valid))`, while taking
194
/// advantage of batch verification to whatever extent possible.
195
///
196
/// (See [`ed25519::validate_batch`] for caveats.)
197
48825
pub fn validate_all_sigs(v: &[Box<dyn ValidatableSignature>]) -> bool {
198
    // First we break out the ed25519 signatures (if any) so we can do
199
    // a batch-verification on them.
200
48825
    let mut ed_sigs = Vec::new();
201
48825
    let mut non_ed_sigs = Vec::new();
202
48825
    for sig in v.iter() {
203
60357
        match sig.as_ed25519() {
204
57660
            Some(ed_sig) => ed_sigs.push(ed_sig),
205
2697
            None => non_ed_sigs.push(sig),
206
        }
207
    }
208

            
209
    // Find out if the ed25519 batch is valid.
210
48825
    let ed_batch_is_valid = crate::pk::ed25519::validate_batch(&ed_sigs[..]);
211

            
212
    // if so, verify the rest.
213
48825
    ed_batch_is_valid && non_ed_sigs.iter().all(|b| b.is_valid())
214
48825
}
215

            
216
#[cfg(test)]
217
mod test {
218
    // @@ begin test lint list maintained by maint/add_warning @@
219
    #![allow(clippy::bool_assert_comparison)]
220
    #![allow(clippy::clone_on_copy)]
221
    #![allow(clippy::dbg_macro)]
222
    #![allow(clippy::mixed_attributes_style)]
223
    #![allow(clippy::print_stderr)]
224
    #![allow(clippy::print_stdout)]
225
    #![allow(clippy::single_char_pattern)]
226
    #![allow(clippy::unwrap_used)]
227
    #![allow(clippy::unchecked_time_subtraction)]
228
    #![allow(clippy::useless_vec)]
229
    #![allow(clippy::needless_pass_by_value)]
230
    #![allow(clippy::string_slice)] // See arti#2571
231
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
232
    #[test]
233
    fn validatable_ed_sig() {
234
        use super::ValidatableSignature;
235
        use super::ed25519::{PublicKey, Signature, ValidatableEd25519Signature};
236
        use hex_literal::hex;
237
        let pk = PublicKey::from_bytes(&hex!(
238
            "fc51cd8e6218a1a38da47ed00230f058
239
             0816ed13ba3303ac5deb911548908025"
240
        ))
241
        .unwrap();
242
        let sig: Signature = hex!(
243
            "6291d657deec24024827e69c3abe01a3
244
             0ce548a284743a445e3680d7db5ac3ac
245
             18ff9b538d16f290ae67f760984dc659
246
             4a7c15e9716ed28dc027beceea1ec40a"
247
        )
248
        .into();
249

            
250
        let valid = ValidatableEd25519Signature::new(pk, sig, &hex!("af82"));
251
        let invalid = ValidatableEd25519Signature::new(pk, sig, &hex!("af83"));
252

            
253
        assert!(valid.is_valid());
254
        assert!(!invalid.is_valid());
255
    }
256
}