Skip to main content

tor_cert_x509/
lib.rs

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#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40#![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44#![allow(clippy::needless_lifetimes)] // See arti#1765
45#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46#![allow(clippy::collapsible_if)] // See arti#2342
47#![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] // See arti#2571
49#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51
52// TODO: add to the list maintained by maint/add_warning once it's available on all crates
53#![warn(unnameable_types)]
54
55// This module uses the `x509-cert` crate to generate certificates;
56// if we decide to switch, `rcgen` and `x509-certificate`
57// seem like the likeliest options.
58
59use std::{
60    sync::Arc,
61    time::{Duration, SystemTime},
62};
63
64use digest::Digest;
65use rand::CryptoRng;
66use rsa::pkcs8::{EncodePrivateKey as _, SubjectPublicKeyInfo};
67use tor_error::into_internal;
68use tor_llcrypto::{pk::rsa::KeyPair as RsaKeypair, util::rng::RngCompat};
69use x509_cert::{
70    builder::{Builder, CertificateBuilder, Profile},
71    der::{DateTime, Encode, asn1::GeneralizedTime, zeroize::Zeroizing},
72    ext::pkix::{KeyUsage, KeyUsages},
73    serial_number::SerialNumber,
74    time::Validity,
75};
76
77/// Legacy identity keys are required to have this length.
78const EXPECT_ID_BITS: usize = 1024;
79/// Legacy identity keys are required to have this exponent.
80const EXPECT_ID_EXPONENT: u32 = 65537;
81/// Lifetime of generated id certs, in days.
82const ID_CERT_LIFETIME_DAYS: u32 = 365;
83
84/// Create an X.509 certificate, for use in a CERTS cell,
85/// self-certifying the provided RSA identity key.
86///
87/// The resulting certificate will be encoded in DER.
88/// Its cert_type field should be 02 when it is sent in a CERTS cell.
89///
90/// The resulting certificate is quite minimal, and has no unnecessary extensions.
91///
92/// Returns an error on failure, or if `keypair` is not a 1024-bit RSA key
93/// with exponent of 65537.
94pub fn create_legacy_rsa_id_cert<Rng: CryptoRng>(
95    rng: &mut Rng,
96    now: SystemTime,
97    hostname: &str,
98    keypair: &RsaKeypair,
99) -> Result<Vec<u8>, X509CertError> {
100    use rsa::pkcs1v15::SigningKey;
101    let public = keypair.to_public_key();
102    if !public.exponent_is(EXPECT_ID_EXPONENT) {
103        return Err(X509CertError::InvalidSigningKey("Invalid exponent".into()));
104    }
105    if public.bits() != EXPECT_ID_BITS {
106        return Err(X509CertError::InvalidSigningKey(
107            "Invalid key length".into(),
108        ));
109    }
110
111    let self_signed_profile = Profile::Manual { issuer: None };
112    let serial_number = random_serial_number(rng)?;
113    let (validity, _) = cert_validity(now, ID_CERT_LIFETIME_DAYS)?;
114    // NOTE: This is how C Tor builds its DNs, but that doesn't mean it's a good idea.
115    let subject: x509_cert::name::Name = format!("CN={hostname}")
116        .parse()
117        .map_err(X509CertError::InvalidHostname)?;
118    let spki = SubjectPublicKeyInfo::from_key(keypair.to_public_key().as_key().clone())?;
119
120    // TODO: Use tor_llcrypto::d::Sha256 once rsa crate upgrades.
121    let signer = SigningKey::<rsa::sha2::Sha256>::new(keypair.as_key().clone());
122
123    let mut builder = CertificateBuilder::new(
124        self_signed_profile,
125        serial_number,
126        validity,
127        subject,
128        spki,
129        &signer,
130    )?;
131
132    // We do not, strictly speaking, need this extension: Tor doesn't care that it's there.
133    // We do, however, need _some_ extension, or else we'll generate a v1 certificate,
134    // which we don't want to do.
135    builder.add_extension(&KeyUsage(
136        KeyUsages::KeyCertSign | KeyUsages::DigitalSignature,
137    ))?;
138
139    let cert = builder.build()?;
140
141    let mut output = Vec::new();
142    let _ignore_length: x509_cert::der::Length = cert
143        .encode_to_vec(&mut output)
144        .map_err(X509CertError::CouldNotEncode)?;
145    Ok(output)
146}
147
148/// A set of x.509 certificate information and keys for use with a TLS library.
149///
150/// Only relays need this: They should set these as the certificate(s) to be used
151/// for incoming TLS connections.
152///
153/// This is not necessarily the most convenient form to manipulate certificates in:
154/// rather, it is intended to provide the formats that TLS libraries generally
155/// expect to get.
156#[derive(Clone, Debug)]
157#[non_exhaustive]
158pub struct TlsKeyAndCert {
159    /// A list of certificates in DER form.
160    ///
161    /// (This may contain more than one certificate, but for now only one certificate is used.)
162    certificates: Vec<Vec<u8>>,
163
164    /// A private key for use in the TLS handshake.
165    //
166    // Disabled:
167    // private_key: ecdsa::SigningKey<p256::NistP256>,
168    private_key: rsa::RsaPrivateKey,
169
170    /// A SHA256 digest of the link certificate
171    /// (the one certifying the private key's public component).
172    ///
173    /// This digest is the one what will be certified by the relay's
174    /// `SIGNING_V_TLS_CERT`
175    /// certificate.
176    sha256_digest: [u8; 32],
177
178    /// A time after which this set of link information won't be valid,
179    /// and another should be generated.
180    expiration: SystemTime,
181}
182
183/// What lifetime do we pick for a TLS certificate, in days?
184const TLS_CERT_LIFETIME_DAYS: u32 = 30;
185
186impl TlsKeyAndCert {
187    /// Return the certificates as a list of DER-encoded values.
188    pub fn certificates_der(&self) -> Vec<&[u8]> {
189        self.certificates.iter().map(|der| der.as_ref()).collect()
190    }
191    /// Return the certificates as a concatenated list in PEM ("BEGIN CERTIFICATE") format.
192    pub fn certificate_pem(&self) -> String {
193        let config = pem::EncodeConfig::new().set_line_ending(pem::LineEnding::LF);
194        self.certificates
195            .iter()
196            .map(|der| pem::encode_config(&pem::Pem::new("CERTIFICATE", &der[..]), config))
197            .collect()
198    }
199    /// Return the private key in (unencrypted) PKCS8 DER format.
200    pub fn private_key_pkcs8_der(&self) -> Result<Zeroizing<Vec<u8>>, X509CertError> {
201        Ok(self
202            .private_key
203            .to_pkcs8_der()
204            .map_err(X509CertError::CouldNotFormatPkcs8)?
205            .to_bytes())
206    }
207    /// Return the private key in (unencrypted) PKCS8 PEM ("BEGIN PRIVATE KEY") format.
208    pub fn private_key_pkcs8_pem(&self) -> Result<Zeroizing<String>, X509CertError> {
209        self.private_key
210            .to_pkcs8_pem(p256::pkcs8::LineEnding::LF)
211            .map_err(X509CertError::CouldNotFormatPkcs8)
212    }
213    /// Return the earliest time at which any of these certificates will expire.
214    pub fn expiration(&self) -> SystemTime {
215        self.expiration
216    }
217
218    /// Return the SHA256 digest of the link certificate
219    ///
220    /// This digest is the one certified with the relay's
221    /// `SIGNING_V_TLS_CERT`
222    /// certificate.
223    pub fn link_cert_sha256(&self) -> &[u8; 32] {
224        &self.sha256_digest
225    }
226
227    /// Create a new TLS link key and associated certificate(s).
228    ///
229    /// The certificate will be valid at `now`, and for a while after.
230    ///
231    /// The certificate parameters and keys are chosen for reasonable security,
232    /// approximate conformance to RFC5280, and limited fingerprinting resistance.
233    ///
234    /// Note: The fingerprinting resistance is quite limited.
235    /// We will likely want to pursue these avenues for better fingerprinting resistance:
236    ///
237    /// - Encourage more use of TLS 1.3, where server certificates are encrypted.
238    ///   (This prevents passive fingerprinting only.)
239    /// - Adjust this function to make certificates look even more normal
240    /// - Integrate with ACME-supporting certificate issuers (Letsencrypt, etc)
241    ///   to get real certificates for Tor relays.
242    pub fn create<Rng: CryptoRng>(
243        rng: &mut Rng,
244        now: SystemTime,
245        issuer_hostname: &str,
246        subject_hostname: &str,
247    ) -> Result<Self, X509CertError> {
248        // We would prefer to use p256 here, since it is the most commonly used elliptic curve
249        // group for X.509 web certificate signing, as of this writing.
250        //
251        // We want to use an elliptic curve here for its higher security/performance ratio than RSA,
252        // and for its _much_ faster key generation time.
253        //
254        // But unfortunately, we can't: C tor has a bug where if the subject key is not RSA,
255        // the connection will be closed with an error:
256        // <https://gitlab.torproject.org/tpo/core/tor/-/issues/41226>.
257        // If this bug is fixed, then we will have to wait until all clients and servers upgrade
258        // before we can send p256 subject keys instead.
259        //
260        // DISABLED:
261        // let private_key = rsa::RsaPrivateKey::p256::ecdsa::SigningKey::random(&mut RngCompat::new(&mut *rng));
262        // let public_key = p256::ecdsa::VerifyingKey::from(&private_key);
263
264        const RSA_KEY_BITS: usize = 2048;
265        let private_key = rsa::RsaPrivateKey::new(&mut RngCompat::new(&mut *rng), RSA_KEY_BITS)
266            .map_err(into_internal!("Unable to generate RSA key"))?;
267        let public_key = private_key.to_public_key();
268
269        // Note that we'll discard this key after signing the certificate with it:
270        // The real certification for private_key is done in the SIGNING_V_TLS_CERT
271        // certificate.
272        let issuer_private_key = p256::ecdsa::SigningKey::random(&mut RngCompat::new(&mut *rng));
273
274        // NOTE: This is how C Tor builds its DNs, but that doesn't mean it's a good idea.
275        let issuer = format!("CN={issuer_hostname}")
276            .parse()
277            .map_err(X509CertError::InvalidHostname)?;
278        let subject: x509_cert::name::Name = format!("CN={subject_hostname}")
279            .parse()
280            .map_err(X509CertError::InvalidHostname)?;
281
282        let self_signed_profile = Profile::Leaf {
283            issuer,
284            enable_key_agreement: true,
285            enable_key_encipherment: true,
286            include_subject_key_identifier: true,
287        };
288        let serial_number = random_serial_number(rng)?;
289        let (validity, expiration) = cert_validity(now, TLS_CERT_LIFETIME_DAYS)?;
290        let spki = SubjectPublicKeyInfo::from_key(public_key)?;
291
292        let builder = CertificateBuilder::new(
293            self_signed_profile,
294            serial_number,
295            validity,
296            subject,
297            spki,
298            &issuer_private_key,
299        )?;
300
301        let cert = builder.build::<ecdsa::der::Signature<_>>()?;
302
303        let mut certificate_der = Vec::new();
304        let _ignore_length: x509_cert::der::Length = cert
305            .encode_to_vec(&mut certificate_der)
306            .map_err(X509CertError::CouldNotEncode)?;
307
308        let sha256_digest = tor_llcrypto::d::Sha256::digest(&certificate_der).into();
309        let certificates = vec![certificate_der];
310
311        Ok(TlsKeyAndCert {
312            certificates,
313            private_key,
314            sha256_digest,
315            expiration,
316        })
317    }
318}
319
320/// Return a Validity that includes `now`, and lasts for `lifetime_days` additionally.
321///
322/// Additionally, return the time at which the certificate expires.
323///
324/// We ensure that our cert is valid at least a day into the past.
325///
326/// We obfuscate our current time a little by rounding to the nearest midnight UTC.
327fn cert_validity(
328    now: SystemTime,
329    lifetime_days: u32,
330) -> Result<(Validity, SystemTime), X509CertError> {
331    const ONE_DAY: Duration = Duration::new(86400, 0);
332
333    let start_of_day_containing = |when| -> Result<_, X509CertError> {
334        let dt = DateTime::from_system_time(when)
335            .map_err(into_internal!("Couldn't represent time as a DER DateTime"))?;
336        let dt = DateTime::new(dt.year(), dt.month(), dt.day(), 0, 0, 0)
337            .map_err(into_internal!("Couldn't construct DER DateTime"))?;
338        Ok(x509_cert::time::Time::GeneralTime(
339            GeneralizedTime::from_date_time(dt),
340        ))
341    };
342
343    let start_on_day = now - ONE_DAY;
344    let end_on_day = start_on_day + ONE_DAY * lifetime_days;
345
346    let validity = Validity {
347        not_before: start_of_day_containing(start_on_day)?,
348        not_after: start_of_day_containing(end_on_day)?,
349    };
350    let expiration = validity.not_after.into();
351    Ok((validity, expiration))
352}
353
354/// Return a random serial number for use in a new certificate.
355fn random_serial_number<Rng: CryptoRng>(rng: &mut Rng) -> Result<SerialNumber, X509CertError> {
356    const SER_NUMBER_LEN: usize = 16;
357    let mut buf = [0; SER_NUMBER_LEN];
358    rng.fill_bytes(&mut buf[..]);
359    Ok(SerialNumber::new(&buf[..]).map_err(into_internal!("Couldn't construct serial number!"))?)
360}
361
362/// An error that has occurred while trying to create a certificate.
363#[derive(Clone, Debug, thiserror::Error)]
364#[non_exhaustive]
365pub enum X509CertError {
366    /// We received a signing key that we can't use.
367    #[error("Provided signing key not valid: {0}")]
368    InvalidSigningKey(String),
369
370    /// We received a subject key that we can't use.
371    #[error("Couldn't use provided key as a subject")]
372    SubjectKeyError(#[from] x509_cert::spki::Error),
373
374    /// We received a hostname that we couldn't use:
375    /// probably, it contained an equals sign or a comma.
376    #[error("Unable to set hostname when creating certificate")]
377    InvalidHostname(#[source] x509_cert::der::Error),
378
379    /// We couldn't construct the certificate.
380    #[error("Unable to build certificate")]
381    CouldNotBuild(#[source] Arc<x509_cert::builder::Error>),
382
383    /// We constructed the certificate, but couldn't encode it as DER.
384    #[error("Unable to encode certificate")]
385    CouldNotEncode(#[source] x509_cert::der::Error),
386
387    /// We constructed a key but couldn't format it as PKCS8.
388    #[error("Unable to format key as PKCS8")]
389    CouldNotFormatPkcs8(#[source] p256::pkcs8::Error),
390
391    /// We've encountered some kind of a bug.
392    #[error("Internal error while creating certificate")]
393    Bug(#[from] tor_error::Bug),
394}
395
396impl From<x509_cert::builder::Error> for X509CertError {
397    fn from(value: x509_cert::builder::Error) -> Self {
398        X509CertError::CouldNotBuild(Arc::new(value))
399    }
400}
401
402#[cfg(test)]
403mod test {
404    // @@ begin test lint list maintained by maint/add_warning @@
405    #![allow(clippy::bool_assert_comparison)]
406    #![allow(clippy::clone_on_copy)]
407    #![allow(clippy::dbg_macro)]
408    #![allow(clippy::mixed_attributes_style)]
409    #![allow(clippy::print_stderr)]
410    #![allow(clippy::print_stdout)]
411    #![allow(clippy::single_char_pattern)]
412    #![allow(clippy::unwrap_used)]
413    #![allow(clippy::unchecked_time_subtraction)]
414    #![allow(clippy::useless_vec)]
415    #![allow(clippy::needless_pass_by_value)]
416    #![allow(clippy::string_slice)] // See arti#2571
417    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
418
419    use super::*;
420    use tor_basic_utils::test_rng::testing_rng;
421    use web_time_compat::SystemTimeExt;
422
423    #[test]
424    fn identity_cert_generation() {
425        let mut rng = testing_rng();
426        let keypair = RsaKeypair::generate(&mut rng).unwrap();
427        let cert = create_legacy_rsa_id_cert(
428            &mut rng,
429            SystemTime::get(),
430            "www.house-of-pancakes.example.com",
431            &keypair,
432        )
433        .unwrap();
434
435        let key_extracted = tor_llcrypto::util::x509_extract_rsa_subject_kludge(&cert[..]).unwrap();
436        assert_eq!(key_extracted, keypair.to_public_key());
437
438        // TODO: It would be neat to validate this certificate with an independent x509 implementation,
439        // but afaict most of them sensibly refuse to handle RSA1024.
440        //
441        // I've checked the above-generated cert using `openssl verify`, but that's it.
442    }
443
444    #[test]
445    fn identity_cert_generation_size_check() {
446        let mut rng = testing_rng();
447        let keypair = rsa::RsaPrivateKey::new(&mut RngCompat::new(&mut rng), 2048).unwrap();
448        let keypair: RsaKeypair = keypair.into();
449
450        // This fails since it's not 1024 bits.
451        assert!(
452            create_legacy_rsa_id_cert(
453                &mut rng,
454                SystemTime::get(),
455                "www.house-of-pancakes.example.com",
456                &keypair,
457            )
458            .unwrap_err()
459            .to_string()
460            .contains("Invalid key length")
461        );
462    }
463
464    #[test]
465    fn tls_cert_info() {
466        let mut rng = testing_rng();
467        let certified = TlsKeyAndCert::create(
468            &mut rng,
469            SystemTime::get(),
470            "foo.example.com",
471            "bar.example.com",
472        )
473        .unwrap();
474        dbg!(certified);
475    }
476}