1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

            
51
// This module uses the `x509-cert` crate to generate certificates;
52
// if we decide to switch, `rcgen` and `x509-certificate`
53
// seem like the likeliest options.
54

            
55
use std::{
56
    sync::Arc,
57
    time::{Duration, SystemTime},
58
};
59

            
60
use digest::Digest;
61
use rand::CryptoRng;
62
use rsa::pkcs8::{EncodePrivateKey as _, SubjectPublicKeyInfo};
63
use tor_error::into_internal;
64
use tor_llcrypto::{pk::rsa::KeyPair as RsaKeypair, util::rng::RngCompat};
65
use x509_cert::{
66
    builder::{Builder, CertificateBuilder, Profile},
67
    der::{DateTime, Encode, asn1::GeneralizedTime, zeroize::Zeroizing},
68
    ext::pkix::{KeyUsage, KeyUsages},
69
    serial_number::SerialNumber,
70
    time::Validity,
71
};
72

            
73
/// Legacy identity keys are required to have this length.
74
const EXPECT_ID_BITS: usize = 1024;
75
/// Legacy identity keys are required to have this exponent.
76
const EXPECT_ID_EXPONENT: u32 = 65537;
77
/// Lifetime of generated id certs, in days.
78
const ID_CERT_LIFETIME_DAYS: u32 = 365;
79

            
80
/// Create an X.509 certificate, for use in a CERTS cell,
81
/// self-certifying the provided RSA identity key.
82
///
83
/// The resulting certificate will be encoded in DER.
84
/// Its cert_type field should be 02 when it is sent in a CERTS cell.
85
///
86
/// The resulting certificate is quite minimal, and has no unnecessary extensions.
87
///
88
/// Returns an error on failure, or if `keypair` is not a 1024-bit RSA key
89
/// with exponent of 65537.
90
10
pub fn create_legacy_rsa_id_cert<Rng: CryptoRng>(
91
10
    rng: &mut Rng,
92
10
    now: SystemTime,
93
10
    hostname: &str,
94
10
    keypair: &RsaKeypair,
95
10
) -> Result<Vec<u8>, X509CertError> {
96
    use rsa::pkcs1v15::SigningKey;
97
    use tor_llcrypto::d::Sha256;
98
10
    let public = keypair.to_public_key();
99
10
    if !public.exponent_is(EXPECT_ID_EXPONENT) {
100
        return Err(X509CertError::InvalidSigningKey("Invalid exponent".into()));
101
10
    }
102
10
    if public.bits() != EXPECT_ID_BITS {
103
2
        return Err(X509CertError::InvalidSigningKey(
104
2
            "Invalid key length".into(),
105
2
        ));
106
8
    }
107

            
108
8
    let self_signed_profile = Profile::Manual { issuer: None };
109
8
    let serial_number = random_serial_number(rng)?;
110
8
    let (validity, _) = cert_validity(now, ID_CERT_LIFETIME_DAYS)?;
111
    // NOTE: This is how C Tor builds its DNs, but that doesn't mean it's a good idea.
112
8
    let subject: x509_cert::name::Name = format!("CN={hostname}")
113
8
        .parse()
114
8
        .map_err(X509CertError::InvalidHostname)?;
115
8
    let spki = SubjectPublicKeyInfo::from_key(keypair.to_public_key().as_key().clone())?;
116

            
117
8
    let signer = SigningKey::<Sha256>::new(keypair.as_key().clone());
118

            
119
8
    let mut builder = CertificateBuilder::new(
120
8
        self_signed_profile,
121
8
        serial_number,
122
8
        validity,
123
8
        subject,
124
8
        spki,
125
8
        &signer,
126
    )?;
127

            
128
    // We do not, strictly speaking, need this extension: Tor doesn't care that it's there.
129
    // We do, however, need _some_ extension, or else we'll generate a v1 certificate,
130
    // which we don't want to do.
131
8
    builder.add_extension(&KeyUsage(
132
8
        KeyUsages::KeyCertSign | KeyUsages::DigitalSignature,
133
8
    ))?;
134

            
135
8
    let cert = builder.build()?;
136

            
137
8
    let mut output = Vec::new();
138
8
    let _ignore_length: x509_cert::der::Length = cert
139
8
        .encode_to_vec(&mut output)
140
8
        .map_err(X509CertError::CouldNotEncode)?;
141
8
    Ok(output)
142
10
}
143

            
144
/// A set of x.509 certificate information and keys for use with a TLS library.
145
///
146
/// Only relays need this: They should set these as the certificate(s) to be used
147
/// for incoming TLS connections.
148
///
149
/// This is not necessarily the most convenient form to manipulate certificates in:
150
/// rather, it is intended to provide the formats that TLS libraries generally
151
/// expect to get.
152
#[derive(Clone, Debug)]
153
#[non_exhaustive]
154
pub struct TlsKeyAndCert {
155
    /// A list of certificates in DER form.
156
    ///
157
    /// (This may contain more than one certificate, but for now only one certificate is used.)
158
    certificates: Vec<Vec<u8>>,
159

            
160
    /// A private key for use in the TLS handshake.
161
    //
162
    // Disabled:
163
    // private_key: ecdsa::SigningKey<p256::NistP256>,
164
    private_key: rsa::RsaPrivateKey,
165

            
166
    /// A SHA256 digest of the link certificate
167
    /// (the one certifying the private key's public component).
168
    ///
169
    /// This digest is the one what will be certified by the relay's
170
    /// `SIGNING_V_TLS_CERT`
171
    /// certificate.
172
    sha256_digest: [u8; 32],
173

            
174
    /// A time after which this set of link information won't be valid,
175
    /// and another should be generated.
176
    expiration: SystemTime,
177
}
178

            
179
/// What lifetime do we pick for a TLS certificate, in days?
180
const TLS_CERT_LIFETIME_DAYS: u32 = 30;
181

            
182
impl TlsKeyAndCert {
183
    /// Return the certificates as a list of DER-encoded values.
184
1079
    pub fn certificates_der(&self) -> Vec<&[u8]> {
185
1092
        self.certificates.iter().map(|der| der.as_ref()).collect()
186
1079
    }
187
    /// Return the certificates as a concatenated list in PEM ("BEGIN CERTIFICATE") format.
188
    pub fn certificate_pem(&self) -> String {
189
        let config = pem::EncodeConfig::new().set_line_ending(pem::LineEnding::LF);
190
        self.certificates
191
            .iter()
192
            .map(|der| pem::encode_config(&pem::Pem::new("CERTIFICATE", &der[..]), config))
193
            .collect()
194
    }
195
    /// Return the private key in (unencrypted) PKCS8 DER format.
196
249
    pub fn private_key_pkcs8_der(&self) -> Result<Zeroizing<Vec<u8>>, X509CertError> {
197
249
        Ok(self
198
249
            .private_key
199
249
            .to_pkcs8_der()
200
249
            .map_err(X509CertError::CouldNotFormatPkcs8)?
201
249
            .to_bytes())
202
249
    }
203
    /// Return the private key in (unencrypted) PKCS8 PEM ("BEGIN PRIVATE KEY") format.
204
    pub fn private_key_pkcs8_pem(&self) -> Result<Zeroizing<String>, X509CertError> {
205
        self.private_key
206
            .to_pkcs8_pem(p256::pkcs8::LineEnding::LF)
207
            .map_err(X509CertError::CouldNotFormatPkcs8)
208
    }
209
    /// Return the earliest time at which any of these certificates will expire.
210
    pub fn expiration(&self) -> SystemTime {
211
        self.expiration
212
    }
213

            
214
    /// Return the SHA256 digest of the link certificate
215
    ///
216
    /// This digest is the one certified with the relay's
217
    /// `SIGNING_V_TLS_CERT`
218
    /// certificate.
219
249
    pub fn link_cert_sha256(&self) -> &[u8; 32] {
220
249
        &self.sha256_digest
221
249
    }
222

            
223
    /// Create a new TLS link key and associated certificate(s).
224
    ///
225
    /// The certificate will be valid at `now`, and for a while after.
226
    ///
227
    /// The certificate parameters and keys are chosen for reasonable security,
228
    /// approximate conformance to RFC5280, and limited fingerprinting resistance.
229
    ///
230
    /// Note: The fingerprinting resistance is quite limited.
231
    /// We will likely want to pursue these avenues for better fingerprinting resistance:
232
    ///
233
    /// - Encourage more use of TLS 1.3, where server certificates are encrypted.
234
    ///   (This prevents passive fingerprinting only.)
235
    /// - Adjust this function to make certificates look even more normal
236
    /// - Integrate with ACME-supporting certificate issuers (Letsencrypt, etc)
237
    ///   to get real certificates for Tor relays.
238
22
    pub fn create<Rng: CryptoRng>(
239
22
        rng: &mut Rng,
240
22
        now: SystemTime,
241
22
        issuer_hostname: &str,
242
22
        subject_hostname: &str,
243
22
    ) -> Result<Self, X509CertError> {
244
        // We would prefer to use p256 here, since it is the most commonly used elliptic curve
245
        // group for X.509 web certificate signing, as of this writing.
246
        //
247
        // We want to use an elliptic curve here for its higher security/performance ratio than RSA,
248
        // and for its _much_ faster key generation time.
249
        //
250
        // But unfortunately, we can't: C tor has a bug where if the subject key is not RSA,
251
        // the connection will be closed with an error:
252
        // <https://gitlab.torproject.org/tpo/core/tor/-/issues/41226>.
253
        // If this bug is fixed, then we will have to wait until all clients and servers upgrade
254
        // before we can send p256 subject keys instead.
255
        //
256
        // DISABLED:
257
        // let private_key = rsa::RsaPrivateKey::p256::ecdsa::SigningKey::random(&mut RngCompat::new(&mut *rng));
258
        // let public_key = p256::ecdsa::VerifyingKey::from(&private_key);
259

            
260
        const RSA_KEY_BITS: usize = 2048;
261
22
        let private_key = rsa::RsaPrivateKey::new(&mut RngCompat::new(&mut *rng), RSA_KEY_BITS)
262
22
            .map_err(into_internal!("Unable to generate RSA key"))?;
263
22
        let public_key = private_key.to_public_key();
264

            
265
        // Note that we'll discard this key after signing the certificate with it:
266
        // The real certification for private_key is done in the SIGNING_V_TLS_CERT
267
        // certificate.
268
22
        let issuer_private_key = p256::ecdsa::SigningKey::random(&mut RngCompat::new(&mut *rng));
269

            
270
        // NOTE: This is how C Tor builds its DNs, but that doesn't mean it's a good idea.
271
22
        let issuer = format!("CN={issuer_hostname}")
272
22
            .parse()
273
22
            .map_err(X509CertError::InvalidHostname)?;
274
22
        let subject: x509_cert::name::Name = format!("CN={subject_hostname}")
275
22
            .parse()
276
22
            .map_err(X509CertError::InvalidHostname)?;
277

            
278
22
        let self_signed_profile = Profile::Leaf {
279
22
            issuer,
280
22
            enable_key_agreement: true,
281
22
            enable_key_encipherment: true,
282
22
            include_subject_key_identifier: true,
283
22
        };
284
22
        let serial_number = random_serial_number(rng)?;
285
22
        let (validity, expiration) = cert_validity(now, TLS_CERT_LIFETIME_DAYS)?;
286
22
        let spki = SubjectPublicKeyInfo::from_key(public_key)?;
287

            
288
22
        let builder = CertificateBuilder::new(
289
22
            self_signed_profile,
290
22
            serial_number,
291
22
            validity,
292
22
            subject,
293
22
            spki,
294
22
            &issuer_private_key,
295
        )?;
296

            
297
22
        let cert = builder.build::<ecdsa::der::Signature<_>>()?;
298

            
299
22
        let mut certificate_der = Vec::new();
300
22
        let _ignore_length: x509_cert::der::Length = cert
301
22
            .encode_to_vec(&mut certificate_der)
302
22
            .map_err(X509CertError::CouldNotEncode)?;
303

            
304
22
        let sha256_digest = tor_llcrypto::d::Sha256::digest(&certificate_der).into();
305
22
        let certificates = vec![certificate_der];
306

            
307
22
        Ok(TlsKeyAndCert {
308
22
            certificates,
309
22
            private_key,
310
22
            sha256_digest,
311
22
            expiration,
312
22
        })
313
22
    }
314
}
315

            
316
/// Return a Validity that includes `now`, and lasts for `lifetime_days` additionally.
317
///
318
/// Additionally, return the time at which the certificate expires.
319
///
320
/// We ensure that our cert is valid at least a day into the past.
321
///
322
/// We obfuscate our current time a little by rounding to the nearest midnight UTC.
323
1083
fn cert_validity(
324
1083
    now: SystemTime,
325
1083
    lifetime_days: u32,
326
1083
) -> Result<(Validity, SystemTime), X509CertError> {
327
    const ONE_DAY: Duration = Duration::new(86400, 0);
328

            
329
2181
    let start_of_day_containing = |when| -> Result<_, X509CertError> {
330
2166
        let dt = DateTime::from_system_time(when)
331
2166
            .map_err(into_internal!("Couldn't represent time as a DER DateTime"))?;
332
2166
        let dt = DateTime::new(dt.year(), dt.month(), dt.day(), 0, 0, 0)
333
2166
            .map_err(into_internal!("Couldn't construct DER DateTime"))?;
334
2166
        Ok(x509_cert::time::Time::GeneralTime(
335
2166
            GeneralizedTime::from_date_time(dt),
336
2166
        ))
337
2166
    };
338

            
339
1083
    let start_on_day = now - ONE_DAY;
340
1083
    let end_on_day = start_on_day + ONE_DAY * lifetime_days;
341

            
342
1083
    let validity = Validity {
343
1083
        not_before: start_of_day_containing(start_on_day)?,
344
1083
        not_after: start_of_day_containing(end_on_day)?,
345
    };
346
1083
    let expiration = validity.not_after.into();
347
1083
    Ok((validity, expiration))
348
1083
}
349

            
350
/// Return a random serial number for use in a new certificate.
351
30
fn random_serial_number<Rng: CryptoRng>(rng: &mut Rng) -> Result<SerialNumber, X509CertError> {
352
    const SER_NUMBER_LEN: usize = 16;
353
30
    let mut buf = [0; SER_NUMBER_LEN];
354
30
    rng.fill_bytes(&mut buf[..]);
355
30
    Ok(SerialNumber::new(&buf[..]).map_err(into_internal!("Couldn't construct serial number!"))?)
356
30
}
357

            
358
/// An error that has occurred while trying to create a certificate.
359
#[derive(Clone, Debug, thiserror::Error)]
360
#[non_exhaustive]
361
pub enum X509CertError {
362
    /// We received a signing key that we can't use.
363
    #[error("Provided signing key not valid: {0}")]
364
    InvalidSigningKey(String),
365

            
366
    /// We received a subject key that we can't use.
367
    #[error("Couldn't use provided key as a subject")]
368
    SubjectKeyError(#[from] x509_cert::spki::Error),
369

            
370
    /// We received a hostname that we couldn't use:
371
    /// probably, it contained an equals sign or a comma.
372
    #[error("Unable to set hostname when creating certificate")]
373
    InvalidHostname(#[source] x509_cert::der::Error),
374

            
375
    /// We couldn't construct the certificate.
376
    #[error("Unable to build certificate")]
377
    CouldNotBuild(#[source] Arc<x509_cert::builder::Error>),
378

            
379
    /// We constructed the certificate, but couldn't encode it as DER.
380
    #[error("Unable to encode certificate")]
381
    CouldNotEncode(#[source] x509_cert::der::Error),
382

            
383
    /// We constructed a key but couldn't format it as PKCS8.
384
    #[error("Unable to format key as PKCS8")]
385
    CouldNotFormatPkcs8(#[source] p256::pkcs8::Error),
386

            
387
    /// We've encountered some kind of a bug.
388
    #[error("Internal error while creating certificate")]
389
    Bug(#[from] tor_error::Bug),
390
}
391

            
392
impl From<x509_cert::builder::Error> for X509CertError {
393
    fn from(value: x509_cert::builder::Error) -> Self {
394
        X509CertError::CouldNotBuild(Arc::new(value))
395
    }
396
}
397

            
398
#[cfg(test)]
399
mod test {
400
    // @@ begin test lint list maintained by maint/add_warning @@
401
    #![allow(clippy::bool_assert_comparison)]
402
    #![allow(clippy::clone_on_copy)]
403
    #![allow(clippy::dbg_macro)]
404
    #![allow(clippy::mixed_attributes_style)]
405
    #![allow(clippy::print_stderr)]
406
    #![allow(clippy::print_stdout)]
407
    #![allow(clippy::single_char_pattern)]
408
    #![allow(clippy::unwrap_used)]
409
    #![allow(clippy::unchecked_time_subtraction)]
410
    #![allow(clippy::useless_vec)]
411
    #![allow(clippy::needless_pass_by_value)]
412
    #![allow(clippy::string_slice)] // See arti#2571
413
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
414

            
415
    use super::*;
416
    use tor_basic_utils::test_rng::testing_rng;
417
    use web_time_compat::SystemTimeExt;
418

            
419
    #[test]
420
    fn identity_cert_generation() {
421
        let mut rng = testing_rng();
422
        let keypair = RsaKeypair::generate(&mut rng).unwrap();
423
        let cert = create_legacy_rsa_id_cert(
424
            &mut rng,
425
            SystemTime::get(),
426
            "www.house-of-pancakes.example.com",
427
            &keypair,
428
        )
429
        .unwrap();
430

            
431
        let key_extracted = tor_llcrypto::util::x509_extract_rsa_subject_kludge(&cert[..]).unwrap();
432
        assert_eq!(key_extracted, keypair.to_public_key());
433

            
434
        // TODO: It would be neat to validate this certificate with an independent x509 implementation,
435
        // but afaict most of them sensibly refuse to handle RSA1024.
436
        //
437
        // I've checked the above-generated cert using `openssl verify`, but that's it.
438
    }
439

            
440
    #[test]
441
    fn identity_cert_generation_size_check() {
442
        let mut rng = testing_rng();
443
        let keypair = rsa::RsaPrivateKey::new(&mut RngCompat::new(&mut rng), 2048).unwrap();
444
        let keypair: RsaKeypair = keypair.into();
445

            
446
        // This fails since it's not 1024 bits.
447
        assert!(
448
            create_legacy_rsa_id_cert(
449
                &mut rng,
450
                SystemTime::get(),
451
                "www.house-of-pancakes.example.com",
452
                &keypair,
453
            )
454
            .unwrap_err()
455
            .to_string()
456
            .contains("Invalid key length")
457
        );
458
    }
459

            
460
    #[test]
461
    fn tls_cert_info() {
462
        let mut rng = testing_rng();
463
        let certified = TlsKeyAndCert::create(
464
            &mut rng,
465
            SystemTime::get(),
466
            "foo.example.com",
467
            "bar.example.com",
468
        )
469
        .unwrap();
470
        dbg!(certified);
471
    }
472
}