1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![allow(renamed_and_removed_lints)] #![allow(unknown_lints)] #![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)] #![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)] #![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] #![allow(clippy::result_large_err)] #![allow(clippy::needless_raw_string_hashes)] #![allow(clippy::needless_lifetimes)] #![allow(mismatched_lifetime_syntaxes)] #![allow(clippy::collapsible_if)] #![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] #![allow(recursion_depth_exceeding_limit)] #![warn(unnameable_types)]
54
55use 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
77const EXPECT_ID_BITS: usize = 1024;
79const EXPECT_ID_EXPONENT: u32 = 65537;
81const ID_CERT_LIFETIME_DAYS: u32 = 365;
83
84pub 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 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 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 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#[derive(Clone, Debug)]
157#[non_exhaustive]
158pub struct TlsKeyAndCert {
159 certificates: Vec<Vec<u8>>,
163
164 private_key: rsa::RsaPrivateKey,
169
170 sha256_digest: [u8; 32],
177
178 expiration: SystemTime,
181}
182
183const TLS_CERT_LIFETIME_DAYS: u32 = 30;
185
186impl TlsKeyAndCert {
187 pub fn certificates_der(&self) -> Vec<&[u8]> {
189 self.certificates.iter().map(|der| der.as_ref()).collect()
190 }
191 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 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 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 pub fn expiration(&self) -> SystemTime {
215 self.expiration
216 }
217
218 pub fn link_cert_sha256(&self) -> &[u8; 32] {
224 &self.sha256_digest
225 }
226
227 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 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 let issuer_private_key = p256::ecdsa::SigningKey::random(&mut RngCompat::new(&mut *rng));
273
274 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
320fn 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
354fn 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#[derive(Clone, Debug, thiserror::Error)]
364#[non_exhaustive]
365pub enum X509CertError {
366 #[error("Provided signing key not valid: {0}")]
368 InvalidSigningKey(String),
369
370 #[error("Couldn't use provided key as a subject")]
372 SubjectKeyError(#[from] x509_cert::spki::Error),
373
374 #[error("Unable to set hostname when creating certificate")]
377 InvalidHostname(#[source] x509_cert::der::Error),
378
379 #[error("Unable to build certificate")]
381 CouldNotBuild(#[source] Arc<x509_cert::builder::Error>),
382
383 #[error("Unable to encode certificate")]
385 CouldNotEncode(#[source] x509_cert::der::Error),
386
387 #[error("Unable to format key as PKCS8")]
389 CouldNotFormatPkcs8(#[source] p256::pkcs8::Error),
390
391 #[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 #![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)] 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 }
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 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}