rcgen/
certificate.rs

1use std::net::IpAddr;
2use std::str::FromStr;
3
4#[cfg(feature = "pem")]
5use pem::Pem;
6use pki_types::{CertificateDer, CertificateSigningRequestDer};
7use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time};
8use yasna::models::ObjectIdentifier;
9use yasna::{DERWriter, DERWriterSeq, Tag};
10
11use crate::crl::CrlDistributionPoint;
12use crate::csr::CertificateSigningRequest;
13use crate::key_pair::{serialize_public_key_der, sign_der, PublicKeyData};
14#[cfg(feature = "crypto")]
15use crate::ring_like::digest;
16#[cfg(feature = "pem")]
17use crate::ENCODE_CONFIG;
18use crate::{
19	oid, write_distinguished_name, write_dt_utc_or_generalized,
20	write_x509_authority_key_identifier, write_x509_extension, DistinguishedName, Error, Issuer,
21	KeyIdMethod, KeyUsagePurpose, SanType, SerialNumber, SigningKey,
22};
23
24/// An issued certificate
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct Certificate {
27	pub(crate) der: CertificateDer<'static>,
28}
29
30impl Certificate {
31	/// Get the certificate in DER encoded format.
32	///
33	/// [`CertificateDer`] implements `Deref<Target = [u8]>` and `AsRef<[u8]>`, so you can easily
34	/// extract the DER bytes from the return value.
35	pub fn der(&self) -> &CertificateDer<'static> {
36		&self.der
37	}
38
39	/// Get the certificate in PEM encoded format.
40	#[cfg(feature = "pem")]
41	pub fn pem(&self) -> String {
42		pem::encode_config(&Pem::new("CERTIFICATE", self.der().to_vec()), ENCODE_CONFIG)
43	}
44}
45
46impl From<Certificate> for CertificateDer<'static> {
47	fn from(cert: Certificate) -> Self {
48		cert.der
49	}
50}
51
52/// Parameters used for certificate generation
53#[allow(missing_docs)]
54#[non_exhaustive]
55#[derive(Debug, PartialEq, Eq, Clone)]
56pub struct CertificateParams {
57	pub not_before: OffsetDateTime,
58	pub not_after: OffsetDateTime,
59	pub serial_number: Option<SerialNumber>,
60	pub subject_alt_names: Vec<SanType>,
61	pub distinguished_name: DistinguishedName,
62	pub is_ca: IsCa,
63	pub key_usages: Vec<KeyUsagePurpose>,
64	pub extended_key_usages: Vec<ExtendedKeyUsagePurpose>,
65	pub name_constraints: Option<NameConstraints>,
66	/// An optional list of certificate revocation list (CRL) distribution points as described
67	/// in RFC 5280 Section 4.2.1.13[^1]. Each distribution point contains one or more URIs where
68	/// an up-to-date CRL with scope including this certificate can be retrieved.
69	///
70	/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.13>
71	pub crl_distribution_points: Vec<CrlDistributionPoint>,
72	pub custom_extensions: Vec<CustomExtension>,
73	/// If `true`, the 'Authority Key Identifier' extension will be added to the generated cert
74	pub use_authority_key_identifier_extension: bool,
75	/// Method to generate key identifiers from public keys
76	///
77	/// Defaults to a truncated SHA-256 digest. See [`KeyIdMethod`] for more information.
78	pub key_identifier_method: KeyIdMethod,
79}
80
81impl Default for CertificateParams {
82	fn default() -> Self {
83		// not_before and not_after set to reasonably long dates
84		let not_before = date_time_ymd(1975, 1, 1);
85		let not_after = date_time_ymd(4096, 1, 1);
86		let mut distinguished_name = DistinguishedName::new();
87		distinguished_name.push(DnType::CommonName, "rcgen self signed cert");
88		CertificateParams {
89			not_before,
90			not_after,
91			serial_number: None,
92			subject_alt_names: Vec::new(),
93			distinguished_name,
94			is_ca: IsCa::NoCa,
95			key_usages: Vec::new(),
96			extended_key_usages: Vec::new(),
97			name_constraints: None,
98			crl_distribution_points: Vec::new(),
99			custom_extensions: Vec::new(),
100			use_authority_key_identifier_extension: false,
101			#[cfg(feature = "crypto")]
102			key_identifier_method: KeyIdMethod::Sha256,
103			#[cfg(not(feature = "crypto"))]
104			key_identifier_method: KeyIdMethod::PreSpecified(Vec::new()),
105		}
106	}
107}
108
109impl CertificateParams {
110	/// Generate certificate parameters with reasonable defaults
111	pub fn new(subject_alt_names: impl Into<Vec<String>>) -> Result<Self, Error> {
112		let subject_alt_names = subject_alt_names
113			.into()
114			.into_iter()
115			.map(|s| {
116				Ok(match IpAddr::from_str(&s) {
117					Ok(ip) => SanType::IpAddress(ip),
118					Err(_) => SanType::DnsName(s.try_into()?),
119				})
120			})
121			.collect::<Result<Vec<_>, _>>()?;
122		Ok(CertificateParams {
123			subject_alt_names,
124			..Default::default()
125		})
126	}
127
128	/// Generate a new certificate from the given parameters, signed by the provided issuer.
129	///
130	/// The returned certificate will have its issuer field set to the subject of the
131	/// provided `issuer`, and the authority key identifier extension will be populated using
132	/// the subject public key of `issuer` (typically either a [`CertificateParams`] or
133	/// [`Certificate`]). It will be signed by `issuer_key`.
134	///
135	/// Note that no validation of the `issuer` certificate is performed. Rcgen will not require
136	/// the certificate to be a CA certificate, or have key usage extensions that allow signing.
137	///
138	/// The returned [`Certificate`] may be serialized using [`Certificate::der`] and
139	/// [`Certificate::pem`].
140	pub fn signed_by(
141		&self,
142		public_key: &impl PublicKeyData,
143		issuer: &Issuer<'_, impl SigningKey>,
144	) -> Result<Certificate, Error> {
145		Ok(Certificate {
146			der: self.serialize_der_with_signer(public_key, issuer)?,
147		})
148	}
149
150	/// Generates a new self-signed certificate from the given parameters.
151	///
152	/// The returned [`Certificate`] may be serialized using [`Certificate::der`] and
153	/// [`Certificate::pem`].
154	pub fn self_signed(&self, signing_key: &impl SigningKey) -> Result<Certificate, Error> {
155		let issuer = Issuer::from_params(self, signing_key);
156		Ok(Certificate {
157			der: self.serialize_der_with_signer(signing_key, &issuer)?,
158		})
159	}
160
161	/// Calculates a subject key identifier for the certificate subject's public key.
162	/// This key identifier is used in the SubjectKeyIdentifier X.509v3 extension.
163	pub fn key_identifier(&self, key: &impl PublicKeyData) -> Vec<u8> {
164		self.key_identifier_method
165			.derive(key.subject_public_key_info())
166	}
167
168	#[cfg(all(test, feature = "x509-parser"))]
169	pub(crate) fn from_ca_cert_der(ca_cert: &CertificateDer<'_>) -> Result<Self, Error> {
170		let (_remainder, x509) = x509_parser::parse_x509_certificate(ca_cert)
171			.map_err(|_| Error::CouldNotParseCertificate)?;
172
173		Ok(CertificateParams {
174			is_ca: IsCa::from_x509(&x509)?,
175			subject_alt_names: SanType::from_x509(&x509)?,
176			key_usages: KeyUsagePurpose::from_x509(&x509)?,
177			extended_key_usages: ExtendedKeyUsagePurpose::from_x509(&x509)?,
178			name_constraints: NameConstraints::from_x509(&x509)?,
179			serial_number: Some(x509.serial.to_bytes_be().into()),
180			key_identifier_method: KeyIdMethod::from_x509(&x509)?,
181			distinguished_name: DistinguishedName::from_name(&x509.tbs_certificate.subject)?,
182			not_before: x509.validity().not_before.to_datetime(),
183			not_after: x509.validity().not_after.to_datetime(),
184			..Default::default()
185		})
186	}
187
188	/// Write a CSR extension request attribute as defined in [RFC 2985].
189	///
190	/// [RFC 2985]: <https://datatracker.ietf.org/doc/html/rfc2985>
191	fn write_extension_request_attribute(&self, writer: DERWriter) {
192		writer.write_sequence(|writer| {
193			writer.next().write_oid(&ObjectIdentifier::from_slice(
194				oid::PKCS_9_AT_EXTENSION_REQUEST,
195			));
196			writer.next().write_set(|writer| {
197				writer.next().write_sequence(|writer| {
198					// Write key_usage
199					self.write_key_usage(writer.next());
200					// Write subject_alt_names
201					self.write_subject_alt_names(writer.next());
202					self.write_extended_key_usage(writer.next());
203
204					// Write custom extensions
205					for ext in &self.custom_extensions {
206						write_x509_extension(writer.next(), &ext.oid, ext.critical, |writer| {
207							writer.write_der(ext.content())
208						});
209					}
210				});
211			});
212		});
213	}
214
215	/// Write a certificate's KeyUsage as defined in RFC 5280.
216	fn write_key_usage(&self, writer: DERWriter) {
217		if self.key_usages.is_empty() {
218			return;
219		}
220
221		// "When present, conforming CAs SHOULD mark this extension as critical."
222		write_x509_extension(writer, oid::KEY_USAGE, true, |writer| {
223			// u16 is large enough to encode the largest possible key usage (two-bytes)
224			let bit_string = self.key_usages.iter().fold(0u16, |bit_string, key_usage| {
225				bit_string | key_usage.to_u16()
226			});
227
228			match u16::BITS - bit_string.trailing_zeros() {
229				bits @ 0..=8 => {
230					writer.write_bitvec_bytes(&bit_string.to_be_bytes()[..1], bits as usize)
231				},
232				bits @ 9..=16 => {
233					writer.write_bitvec_bytes(&bit_string.to_be_bytes(), bits as usize)
234				},
235				_ => unreachable!(),
236			}
237		});
238	}
239
240	fn write_extended_key_usage(&self, writer: DERWriter) {
241		if !self.extended_key_usages.is_empty() {
242			write_x509_extension(writer, oid::EXT_KEY_USAGE, false, |writer| {
243				writer.write_sequence(|writer| {
244					for usage in &self.extended_key_usages {
245						writer
246							.next()
247							.write_oid(&ObjectIdentifier::from_slice(usage.oid()));
248					}
249				});
250			});
251		}
252	}
253
254	fn write_subject_alt_names(&self, writer: DERWriter) {
255		if self.subject_alt_names.is_empty() {
256			return;
257		}
258
259		// Per https://tools.ietf.org/html/rfc5280#section-4.1.2.6, SAN must be marked
260		// as critical if subject is empty.
261		let critical = self.distinguished_name.entries.is_empty();
262		write_x509_extension(writer, oid::SUBJECT_ALT_NAME, critical, |writer| {
263			writer.write_sequence(|writer| {
264				for san in self.subject_alt_names.iter() {
265					writer.next().write_tagged_implicit(
266						Tag::context(san.tag()),
267						|writer| match san {
268							SanType::Rfc822Name(name)
269							| SanType::DnsName(name)
270							| SanType::URI(name) => writer.write_ia5_string(name.as_str()),
271							SanType::IpAddress(IpAddr::V4(addr)) => {
272								writer.write_bytes(&addr.octets())
273							},
274							SanType::IpAddress(IpAddr::V6(addr)) => {
275								writer.write_bytes(&addr.octets())
276							},
277							SanType::OtherName((oid, value)) => {
278								// otherName SEQUENCE { OID, [0] explicit any defined by oid }
279								// https://datatracker.ietf.org/doc/html/rfc5280#page-38
280								writer.write_sequence(|writer| {
281									writer.next().write_oid(&ObjectIdentifier::from_slice(oid));
282									value.write_der(writer.next());
283								});
284							},
285						},
286					);
287				}
288			});
289		});
290	}
291
292	/// Generate and serialize a certificate signing request (CSR).
293	///
294	/// The constructed CSR will contain attributes based on the certificate parameters,
295	/// and include the subject public key information from `subject_key`. Additionally,
296	/// the CSR will be signed using the subject key.
297	///
298	/// Note that subsequent invocations of `serialize_request()` will not produce the exact
299	/// same output.
300	pub fn serialize_request(
301		&self,
302		subject_key: &impl SigningKey,
303	) -> Result<CertificateSigningRequest, Error> {
304		self.serialize_request_with_attributes(subject_key, Vec::new())
305	}
306
307	/// Generate and serialize a certificate signing request (CSR) with custom PKCS #10 attributes.
308	/// as defined in [RFC 2986].
309	///
310	/// The constructed CSR will contain attributes based on the certificate parameters,
311	/// and include the subject public key information from `subject_key`. Additionally,
312	/// the CSR will be self-signed using the subject key.
313	///
314	/// Note that subsequent invocations of `serialize_request_with_attributes()` will not produce the exact
315	/// same output.
316	///
317	/// [RFC 2986]: <https://datatracker.ietf.org/doc/html/rfc2986#section-4>
318	pub fn serialize_request_with_attributes(
319		&self,
320		subject_key: &impl SigningKey,
321		attrs: Vec<Attribute>,
322	) -> Result<CertificateSigningRequest, Error> {
323		// No .. pattern, we use this to ensure every field is used
324		#[deny(unused)]
325		let Self {
326			not_before,
327			not_after,
328			serial_number,
329			subject_alt_names,
330			distinguished_name,
331			is_ca,
332			key_usages,
333			extended_key_usages,
334			name_constraints,
335			crl_distribution_points,
336			custom_extensions,
337			use_authority_key_identifier_extension,
338			key_identifier_method,
339		} = self;
340		// - subject_key will be used by the caller
341		// - not_before and not_after cannot be put in a CSR
342		// - key_identifier_method is here because self.write_extended_key_usage uses it
343		// - There might be a use case for specifying the key identifier
344		// in the CSR, but in the current API it can't be distinguished
345		// from the defaults so this is left for a later version if
346		// needed.
347		let _ = (
348			not_before,
349			not_after,
350			key_identifier_method,
351			extended_key_usages,
352		);
353		if serial_number.is_some()
354			|| *is_ca != IsCa::NoCa
355			|| name_constraints.is_some()
356			|| !crl_distribution_points.is_empty()
357			|| *use_authority_key_identifier_extension
358		{
359			return Err(Error::UnsupportedInCsr);
360		}
361
362		// Whether or not to write an extension request attribute
363		let write_extension_request = !key_usages.is_empty()
364			|| !subject_alt_names.is_empty()
365			|| !extended_key_usages.is_empty()
366			|| !custom_extensions.is_empty();
367
368		let der = sign_der(subject_key, |writer| {
369			// Write version
370			writer.next().write_u8(0);
371			write_distinguished_name(writer.next(), distinguished_name);
372			serialize_public_key_der(subject_key, writer.next());
373
374			// According to the spec in RFC 2986, even if attributes are empty we need the empty attribute tag
375			writer
376				.next()
377				.write_tagged_implicit(Tag::context(0), |writer| {
378					// RFC 2986 specifies that attributes are a SET OF Attribute
379					writer.write_set_of(|writer| {
380						if write_extension_request {
381							self.write_extension_request_attribute(writer.next());
382						}
383
384						for Attribute { oid, values } in attrs {
385							writer.next().write_sequence(|writer| {
386								writer.next().write_oid(&ObjectIdentifier::from_slice(oid));
387								writer.next().write_der(&values);
388							});
389						}
390					});
391				});
392
393			Ok(())
394		})?;
395
396		Ok(CertificateSigningRequest {
397			der: CertificateSigningRequestDer::from(der),
398		})
399	}
400
401	pub(crate) fn serialize_der_with_signer<K: PublicKeyData>(
402		&self,
403		pub_key: &K,
404		issuer: &Issuer<'_, impl SigningKey>,
405	) -> Result<CertificateDer<'static>, Error> {
406		let der = sign_der(&issuer.signing_key, |writer| {
407			let pub_key_spki = pub_key.subject_public_key_info();
408			// Write version
409			writer.next().write_tagged(Tag::context(0), |writer| {
410				writer.write_u8(2);
411			});
412			// Write serialNumber
413			if let Some(ref serial) = self.serial_number {
414				writer.next().write_bigint_bytes(serial.as_ref(), true);
415			} else {
416				#[cfg(feature = "crypto")]
417				{
418					let hash = digest::digest(&digest::SHA256, pub_key.der_bytes());
419					// RFC 5280 specifies at most 20 bytes for a serial number
420					let mut sl = hash.as_ref()[0..20].to_vec();
421					sl[0] &= 0x7f; // MSB must be 0 to ensure encoding bignum in 20 bytes
422					writer.next().write_bigint_bytes(&sl, true);
423				}
424				#[cfg(not(feature = "crypto"))]
425				if self.serial_number.is_none() {
426					return Err(Error::MissingSerialNumber);
427				}
428			};
429			// Write signature algorithm
430			issuer
431				.signing_key
432				.algorithm()
433				.write_alg_ident(writer.next());
434			// Write issuer name
435			write_distinguished_name(writer.next(), issuer.distinguished_name.as_ref());
436			// Write validity
437			writer.next().write_sequence(|writer| {
438				// Not before
439				write_dt_utc_or_generalized(writer.next(), self.not_before);
440				// Not after
441				write_dt_utc_or_generalized(writer.next(), self.not_after);
442				Ok::<(), Error>(())
443			})?;
444			// Write subject
445			write_distinguished_name(writer.next(), &self.distinguished_name);
446			// Write subjectPublicKeyInfo
447			serialize_public_key_der(pub_key, writer.next());
448			// write extensions
449			let should_write_exts = self.use_authority_key_identifier_extension
450				|| !self.subject_alt_names.is_empty()
451				|| !self.extended_key_usages.is_empty()
452				|| self.name_constraints.iter().any(|c| !c.is_empty())
453				|| matches!(self.is_ca, IsCa::ExplicitNoCa)
454				|| matches!(self.is_ca, IsCa::Ca(_))
455				|| !self.custom_extensions.is_empty();
456			if !should_write_exts {
457				return Ok(());
458			}
459
460			writer.next().write_tagged(Tag::context(3), |writer| {
461				writer.write_sequence(|writer| self.write_extensions(writer, &pub_key_spki, issuer))
462			})?;
463
464			Ok(())
465		})?;
466
467		Ok(der.into())
468	}
469
470	fn write_extensions(
471		&self,
472		writer: &mut DERWriterSeq,
473		pub_key_spki: &[u8],
474		issuer: &Issuer<'_, impl SigningKey>,
475	) -> Result<(), Error> {
476		if self.use_authority_key_identifier_extension {
477			write_x509_authority_key_identifier(
478				writer.next(),
479				match issuer.key_identifier_method.as_ref() {
480					KeyIdMethod::PreSpecified(aki) => aki.clone(),
481					#[cfg(feature = "crypto")]
482					_ => issuer
483						.key_identifier_method
484						.derive(issuer.signing_key.subject_public_key_info()),
485				},
486			);
487		}
488
489		// Write subject_alt_names
490		self.write_subject_alt_names(writer.next());
491
492		// Write standard key usage
493		self.write_key_usage(writer.next());
494
495		// Write extended key usage
496		if !self.extended_key_usages.is_empty() {
497			write_x509_extension(writer.next(), oid::EXT_KEY_USAGE, false, |writer| {
498				writer.write_sequence(|writer| {
499					for usage in self.extended_key_usages.iter() {
500						let oid = ObjectIdentifier::from_slice(usage.oid());
501						writer.next().write_oid(&oid);
502					}
503				});
504			});
505		}
506
507		if let Some(name_constraints) = &self.name_constraints {
508			// If both trees are empty, the extension must be omitted.
509			if !name_constraints.is_empty() {
510				write_x509_extension(writer.next(), oid::NAME_CONSTRAINTS, true, |writer| {
511					writer.write_sequence(|writer| {
512						if !name_constraints.permitted_subtrees.is_empty() {
513							write_general_subtrees(
514								writer.next(),
515								0,
516								&name_constraints.permitted_subtrees,
517							);
518						}
519						if !name_constraints.excluded_subtrees.is_empty() {
520							write_general_subtrees(
521								writer.next(),
522								1,
523								&name_constraints.excluded_subtrees,
524							);
525						}
526					});
527				});
528			}
529		}
530
531		if !self.crl_distribution_points.is_empty() {
532			write_x509_extension(
533				writer.next(),
534				oid::CRL_DISTRIBUTION_POINTS,
535				false,
536				|writer| {
537					writer.write_sequence(|writer| {
538						for distribution_point in &self.crl_distribution_points {
539							distribution_point.write_der(writer.next());
540						}
541					})
542				},
543			);
544		}
545
546		match self.is_ca {
547			IsCa::Ca(ref constraint) => {
548				// Write subject_key_identifier
549				write_x509_extension(
550					writer.next(),
551					oid::SUBJECT_KEY_IDENTIFIER,
552					false,
553					|writer| {
554						writer.write_bytes(&self.key_identifier_method.derive(pub_key_spki));
555					},
556				);
557				// Write basic_constraints
558				write_x509_extension(writer.next(), oid::BASIC_CONSTRAINTS, true, |writer| {
559					writer.write_sequence(|writer| {
560						writer.next().write_bool(true); // cA flag
561						if let BasicConstraints::Constrained(path_len_constraint) = constraint {
562							writer.next().write_u8(*path_len_constraint);
563						}
564					});
565				});
566			},
567			IsCa::ExplicitNoCa => {
568				// Write subject_key_identifier
569				write_x509_extension(
570					writer.next(),
571					oid::SUBJECT_KEY_IDENTIFIER,
572					false,
573					|writer| {
574						writer.write_bytes(&self.key_identifier_method.derive(pub_key_spki));
575					},
576				);
577				// Write basic_constraints
578				write_x509_extension(writer.next(), oid::BASIC_CONSTRAINTS, true, |writer| {
579					writer.write_sequence(|writer| {
580						writer.next().write_bool(false); // cA flag
581					});
582				});
583			},
584			IsCa::NoCa => {},
585		}
586
587		// Write the custom extensions
588		for ext in &self.custom_extensions {
589			write_x509_extension(writer.next(), &ext.oid, ext.critical, |writer| {
590				writer.write_der(ext.content())
591			});
592		}
593
594		Ok(())
595	}
596
597	/// Insert an extended key usage (EKU) into the parameters if it does not already exist
598	pub fn insert_extended_key_usage(&mut self, eku: ExtendedKeyUsagePurpose) {
599		if !self.extended_key_usages.contains(&eku) {
600			self.extended_key_usages.push(eku);
601		}
602	}
603}
604
605impl AsRef<CertificateParams> for CertificateParams {
606	fn as_ref(&self) -> &CertificateParams {
607		self
608	}
609}
610
611fn write_general_subtrees(writer: DERWriter, tag: u64, general_subtrees: &[GeneralSubtree]) {
612	writer.write_tagged_implicit(Tag::context(tag), |writer| {
613		writer.write_sequence(|writer| {
614			for subtree in general_subtrees.iter() {
615				writer.next().write_sequence(|writer| {
616					writer
617						.next()
618						.write_tagged_implicit(
619							Tag::context(subtree.tag()),
620							|writer| match subtree {
621								GeneralSubtree::Rfc822Name(name)
622								| GeneralSubtree::DnsName(name) => writer.write_ia5_string(name),
623								GeneralSubtree::DirectoryName(name) => {
624									write_distinguished_name(writer, name)
625								},
626								GeneralSubtree::IpAddress(subnet) => {
627									writer.write_bytes(&subnet.to_bytes())
628								},
629							},
630						);
631					// minimum must be 0 (the default) and maximum must be absent
632				});
633			}
634		});
635	});
636}
637
638/// A PKCS #10 CSR attribute, as defined in [RFC 5280] and constrained
639/// by [RFC 2986].
640///
641/// [RFC 5280]: <https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1>
642/// [RFC 2986]: <https://datatracker.ietf.org/doc/html/rfc2986#section-4>
643#[derive(Debug, PartialEq, Eq, Hash, Clone)]
644pub struct Attribute {
645	/// `AttributeType` of the `Attribute`, defined as an `OBJECT IDENTIFIER`.
646	pub oid: &'static [u64],
647	/// DER-encoded values of the `Attribute`, defined by [RFC 2986] as:
648	///
649	/// ```text
650	/// SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
651	/// ```
652	///
653	/// [RFC 2986]: https://datatracker.ietf.org/doc/html/rfc2986#section-4
654	pub values: Vec<u8>,
655}
656
657/// A custom extension of a certificate, as specified in
658/// [RFC 5280](https://tools.ietf.org/html/rfc5280#section-4.2)
659#[derive(Debug, PartialEq, Eq, Hash, Clone)]
660pub struct CustomExtension {
661	oid: Vec<u64>,
662	critical: bool,
663
664	/// The content must be DER-encoded
665	content: Vec<u8>,
666}
667
668impl CustomExtension {
669	/// Creates a new acmeIdentifier extension for ACME TLS-ALPN-01
670	/// as specified in [RFC 8737](https://tools.ietf.org/html/rfc8737#section-3)
671	///
672	/// Panics if the passed `sha_digest` parameter doesn't hold 32 bytes (256 bits).
673	pub fn new_acme_identifier(sha_digest: &[u8]) -> Self {
674		assert_eq!(sha_digest.len(), 32, "wrong size of sha_digest");
675		let content = yasna::construct_der(|writer| {
676			writer.write_bytes(sha_digest);
677		});
678		Self {
679			oid: oid::PE_ACME.to_owned(),
680			critical: true,
681			content,
682		}
683	}
684	/// Create a new custom extension with the specified content
685	pub fn from_oid_content(oid: &[u64], content: Vec<u8>) -> Self {
686		Self {
687			oid: oid.to_owned(),
688			critical: false,
689			content,
690		}
691	}
692	/// Sets the criticality flag of the extension.
693	pub fn set_criticality(&mut self, criticality: bool) {
694		self.critical = criticality;
695	}
696	/// Obtains the criticality flag of the extension.
697	pub fn criticality(&self) -> bool {
698		self.critical
699	}
700	/// Obtains the content of the extension.
701	pub fn content(&self) -> &[u8] {
702		&self.content
703	}
704	/// Obtains the OID components of the extensions, as u64 pieces
705	pub fn oid_components(&self) -> impl Iterator<Item = u64> + '_ {
706		self.oid.iter().copied()
707	}
708}
709
710#[derive(Debug, PartialEq, Eq, Hash, Clone)]
711#[non_exhaustive]
712/// The attribute type of a distinguished name entry
713pub enum DnType {
714	/// X520countryName
715	CountryName,
716	/// X520LocalityName
717	LocalityName,
718	/// X520StateOrProvinceName
719	StateOrProvinceName,
720	/// X520OrganizationName
721	OrganizationName,
722	/// X520OrganizationalUnitName
723	OrganizationalUnitName,
724	/// X520CommonName
725	CommonName,
726	/// Custom distinguished name type
727	CustomDnType(Vec<u64>),
728}
729
730impl DnType {
731	pub(crate) fn to_oid(&self) -> ObjectIdentifier {
732		let sl = match self {
733			DnType::CountryName => oid::COUNTRY_NAME,
734			DnType::LocalityName => oid::LOCALITY_NAME,
735			DnType::StateOrProvinceName => oid::STATE_OR_PROVINCE_NAME,
736			DnType::OrganizationName => oid::ORG_NAME,
737			DnType::OrganizationalUnitName => oid::ORG_UNIT_NAME,
738			DnType::CommonName => oid::COMMON_NAME,
739			DnType::CustomDnType(ref oid) => oid.as_slice(),
740		};
741		ObjectIdentifier::from_slice(sl)
742	}
743
744	/// Generate a DnType for the provided OID
745	pub fn from_oid(slice: &[u64]) -> Self {
746		match slice {
747			oid::COUNTRY_NAME => DnType::CountryName,
748			oid::LOCALITY_NAME => DnType::LocalityName,
749			oid::STATE_OR_PROVINCE_NAME => DnType::StateOrProvinceName,
750			oid::ORG_NAME => DnType::OrganizationName,
751			oid::ORG_UNIT_NAME => DnType::OrganizationalUnitName,
752			oid::COMMON_NAME => DnType::CommonName,
753			oid => DnType::CustomDnType(oid.into()),
754		}
755	}
756}
757
758#[derive(Debug, PartialEq, Eq, Hash, Clone)]
759/// One of the purposes contained in the [extended key usage extension](https://tools.ietf.org/html/rfc5280#section-4.2.1.12)
760pub enum ExtendedKeyUsagePurpose {
761	/// anyExtendedKeyUsage
762	Any,
763	/// id-kp-serverAuth
764	ServerAuth,
765	/// id-kp-clientAuth
766	ClientAuth,
767	/// id-kp-codeSigning
768	CodeSigning,
769	/// id-kp-emailProtection
770	EmailProtection,
771	/// id-kp-timeStamping
772	TimeStamping,
773	/// id-kp-OCSPSigning
774	OcspSigning,
775	/// A custom purpose not from the pre-specified list of purposes
776	Other(Vec<u64>),
777}
778
779impl ExtendedKeyUsagePurpose {
780	#[cfg(all(test, feature = "x509-parser"))]
781	fn from_x509(x509: &x509_parser::certificate::X509Certificate<'_>) -> Result<Vec<Self>, Error> {
782		let extended_key_usage = x509
783			.extended_key_usage()
784			.map_err(|_| Error::CouldNotParseCertificate)?
785			.map(|ext| ext.value);
786
787		let mut extended_key_usages = Vec::new();
788		if let Some(extended_key_usage) = extended_key_usage {
789			if extended_key_usage.any {
790				extended_key_usages.push(Self::Any);
791			}
792			if extended_key_usage.server_auth {
793				extended_key_usages.push(Self::ServerAuth);
794			}
795			if extended_key_usage.client_auth {
796				extended_key_usages.push(Self::ClientAuth);
797			}
798			if extended_key_usage.code_signing {
799				extended_key_usages.push(Self::CodeSigning);
800			}
801			if extended_key_usage.email_protection {
802				extended_key_usages.push(Self::EmailProtection);
803			}
804			if extended_key_usage.time_stamping {
805				extended_key_usages.push(Self::TimeStamping);
806			}
807			if extended_key_usage.ocsp_signing {
808				extended_key_usages.push(Self::OcspSigning);
809			}
810		}
811
812		Ok(extended_key_usages)
813	}
814
815	fn oid(&self) -> &[u64] {
816		use ExtendedKeyUsagePurpose::*;
817		match self {
818			// anyExtendedKeyUsage
819			Any => &[2, 5, 29, 37, 0],
820			// id-kp-*
821			ServerAuth => &[1, 3, 6, 1, 5, 5, 7, 3, 1],
822			ClientAuth => &[1, 3, 6, 1, 5, 5, 7, 3, 2],
823			CodeSigning => &[1, 3, 6, 1, 5, 5, 7, 3, 3],
824			EmailProtection => &[1, 3, 6, 1, 5, 5, 7, 3, 4],
825			TimeStamping => &[1, 3, 6, 1, 5, 5, 7, 3, 8],
826			OcspSigning => &[1, 3, 6, 1, 5, 5, 7, 3, 9],
827			Other(oid) => oid,
828		}
829	}
830}
831
832/// The [NameConstraints extension](https://tools.ietf.org/html/rfc5280#section-4.2.1.10)
833/// (only relevant for CA certificates)
834#[derive(Debug, PartialEq, Eq, Clone)]
835pub struct NameConstraints {
836	/// A list of subtrees that the domain has to match.
837	pub permitted_subtrees: Vec<GeneralSubtree>,
838	/// A list of subtrees that the domain must not match.
839	///
840	/// Any name matching an excluded subtree is invalid even if it also matches a permitted subtree.
841	pub excluded_subtrees: Vec<GeneralSubtree>,
842}
843
844impl NameConstraints {
845	#[cfg(all(test, feature = "x509-parser"))]
846	fn from_x509(
847		x509: &x509_parser::certificate::X509Certificate<'_>,
848	) -> Result<Option<Self>, Error> {
849		let constraints = x509
850			.name_constraints()
851			.map_err(|_| Error::CouldNotParseCertificate)?
852			.map(|ext| ext.value);
853
854		let Some(constraints) = constraints else {
855			return Ok(None);
856		};
857
858		let permitted_subtrees = if let Some(permitted) = &constraints.permitted_subtrees {
859			GeneralSubtree::from_x509(permitted)?
860		} else {
861			Vec::new()
862		};
863
864		let excluded_subtrees = if let Some(excluded) = &constraints.excluded_subtrees {
865			GeneralSubtree::from_x509(excluded)?
866		} else {
867			Vec::new()
868		};
869
870		Ok(Some(Self {
871			permitted_subtrees,
872			excluded_subtrees,
873		}))
874	}
875
876	fn is_empty(&self) -> bool {
877		self.permitted_subtrees.is_empty() && self.excluded_subtrees.is_empty()
878	}
879}
880
881#[derive(Debug, PartialEq, Eq, Clone)]
882#[allow(missing_docs)]
883#[non_exhaustive]
884/// General Subtree type.
885///
886/// This type has similarities to the [`SanType`] enum but is not equal.
887/// For example, `GeneralSubtree` has CIDR subnets for ip addresses
888/// while [`SanType`] has IP addresses.
889pub enum GeneralSubtree {
890	/// Also known as E-Mail address
891	Rfc822Name(String),
892	DnsName(String),
893	DirectoryName(DistinguishedName),
894	IpAddress(CidrSubnet),
895}
896
897impl GeneralSubtree {
898	#[cfg(all(test, feature = "x509-parser"))]
899	fn from_x509(
900		subtrees: &[x509_parser::extensions::GeneralSubtree<'_>],
901	) -> Result<Vec<Self>, Error> {
902		use x509_parser::extensions::GeneralName;
903
904		let mut result = Vec::new();
905		for subtree in subtrees {
906			let subtree = match &subtree.base {
907				GeneralName::RFC822Name(s) => Self::Rfc822Name(s.to_string()),
908				GeneralName::DNSName(s) => Self::DnsName(s.to_string()),
909				GeneralName::DirectoryName(n) => {
910					Self::DirectoryName(DistinguishedName::from_name(n)?)
911				},
912				GeneralName::IPAddress(bytes) if bytes.len() == 8 => {
913					let addr: [u8; 4] = bytes[..4].try_into().unwrap();
914					let mask: [u8; 4] = bytes[4..].try_into().unwrap();
915					Self::IpAddress(CidrSubnet::V4(addr, mask))
916				},
917				GeneralName::IPAddress(bytes) if bytes.len() == 32 => {
918					let addr: [u8; 16] = bytes[..16].try_into().unwrap();
919					let mask: [u8; 16] = bytes[16..].try_into().unwrap();
920					Self::IpAddress(CidrSubnet::V6(addr, mask))
921				},
922				_ => continue,
923			};
924			result.push(subtree);
925		}
926
927		Ok(result)
928	}
929
930	fn tag(&self) -> u64 {
931		// Defined in the GeneralName list in
932		// https://tools.ietf.org/html/rfc5280#page-38
933		const TAG_RFC822_NAME: u64 = 1;
934		const TAG_DNS_NAME: u64 = 2;
935		const TAG_DIRECTORY_NAME: u64 = 4;
936		const TAG_IP_ADDRESS: u64 = 7;
937
938		match self {
939			GeneralSubtree::Rfc822Name(_name) => TAG_RFC822_NAME,
940			GeneralSubtree::DnsName(_name) => TAG_DNS_NAME,
941			GeneralSubtree::DirectoryName(_name) => TAG_DIRECTORY_NAME,
942			GeneralSubtree::IpAddress(_addr) => TAG_IP_ADDRESS,
943		}
944	}
945}
946
947#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
948#[allow(missing_docs)]
949/// CIDR subnet, as per [RFC 4632](https://tools.ietf.org/html/rfc4632)
950///
951/// You might know CIDR subnets better by their textual representation
952/// where they consist of an ip address followed by a slash and a prefix
953/// number, for example `192.168.99.0/24`.
954///
955/// The first field in the enum is the address, the second is the mask.
956/// Both are specified in network byte order.
957pub enum CidrSubnet {
958	V4([u8; 4], [u8; 4]),
959	V6([u8; 16], [u8; 16]),
960}
961
962macro_rules! mask {
963	($t:ty, $d:expr) => {{
964		let v = <$t>::MAX;
965		let v = v.checked_shr($d as u32).unwrap_or(0);
966		(!v).to_be_bytes()
967	}};
968}
969
970impl CidrSubnet {
971	/// Obtains the CidrSubnet from an ip address
972	/// as well as the specified prefix number.
973	///
974	/// ```
975	/// # use std::net::IpAddr;
976	/// # use std::str::FromStr;
977	/// # use rcgen::CidrSubnet;
978	/// // The "192.0.2.0/24" example from
979	/// // https://tools.ietf.org/html/rfc5280#page-42
980	/// let addr = IpAddr::from_str("192.0.2.0").unwrap();
981	/// let subnet = CidrSubnet::from_addr_prefix(addr, 24);
982	/// assert_eq!(subnet, CidrSubnet::V4([0xC0, 0x00, 0x02, 0x00], [0xFF, 0xFF, 0xFF, 0x00]));
983	/// ```
984	pub fn from_addr_prefix(addr: IpAddr, prefix: u8) -> Self {
985		match addr {
986			IpAddr::V4(addr) => Self::from_v4_prefix(addr.octets(), prefix),
987			IpAddr::V6(addr) => Self::from_v6_prefix(addr.octets(), prefix),
988		}
989	}
990	/// Obtains the CidrSubnet from an IPv4 address in network byte order
991	/// as well as the specified prefix.
992	pub fn from_v4_prefix(addr: [u8; 4], prefix: u8) -> Self {
993		CidrSubnet::V4(addr, mask!(u32, prefix))
994	}
995	/// Obtains the CidrSubnet from an IPv6 address in network byte order
996	/// as well as the specified prefix.
997	pub fn from_v6_prefix(addr: [u8; 16], prefix: u8) -> Self {
998		CidrSubnet::V6(addr, mask!(u128, prefix))
999	}
1000	fn to_bytes(self) -> Vec<u8> {
1001		let mut res = Vec::new();
1002		match self {
1003			CidrSubnet::V4(addr, mask) => {
1004				res.extend_from_slice(&addr);
1005				res.extend_from_slice(&mask);
1006			},
1007			CidrSubnet::V6(addr, mask) => {
1008				res.extend_from_slice(&addr);
1009				res.extend_from_slice(&mask);
1010			},
1011		}
1012		res
1013	}
1014}
1015
1016/// Obtains the CidrSubnet from the well-known
1017/// addr/prefix notation.
1018/// ```
1019/// # use std::str::FromStr;
1020/// # use rcgen::CidrSubnet;
1021/// // The "192.0.2.0/24" example from
1022/// // https://tools.ietf.org/html/rfc5280#page-42
1023/// let subnet = CidrSubnet::from_str("192.0.2.0/24").unwrap();
1024/// assert_eq!(subnet, CidrSubnet::V4([0xC0, 0x00, 0x02, 0x00], [0xFF, 0xFF, 0xFF, 0x00]));
1025/// ```
1026impl FromStr for CidrSubnet {
1027	type Err = ();
1028
1029	fn from_str(s: &str) -> Result<Self, Self::Err> {
1030		let mut iter = s.split('/');
1031		if let (Some(addr_s), Some(prefix_s)) = (iter.next(), iter.next()) {
1032			let addr = IpAddr::from_str(addr_s).map_err(|_| ())?;
1033			let prefix = u8::from_str(prefix_s).map_err(|_| ())?;
1034			Ok(Self::from_addr_prefix(addr, prefix))
1035		} else {
1036			Err(())
1037		}
1038	}
1039}
1040
1041/// Helper to obtain an `OffsetDateTime` from year, month, day values
1042///
1043/// The year, month, day values are assumed to be in UTC.
1044///
1045/// This helper function serves two purposes: first, so that you don't
1046/// have to import the time crate yourself in order to specify date
1047/// information, second so that users don't have to type unproportionately
1048/// long code just to generate an instance of [`OffsetDateTime`].
1049pub fn date_time_ymd(year: i32, month: u8, day: u8) -> OffsetDateTime {
1050	let month = Month::try_from(month).expect("out-of-range month");
1051	let primitive_dt = PrimitiveDateTime::new(
1052		Date::from_calendar_date(year, month, day).expect("invalid or out-of-range date"),
1053		Time::MIDNIGHT,
1054	);
1055	primitive_dt.assume_utc()
1056}
1057
1058/// Whether the certificate is allowed to sign other certificates
1059#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1060pub enum IsCa {
1061	/// The certificate can only sign itself
1062	NoCa,
1063	/// The certificate can only sign itself, adding the extension and `CA:FALSE`
1064	ExplicitNoCa,
1065	/// The certificate may be used to sign other certificates
1066	Ca(BasicConstraints),
1067}
1068
1069impl IsCa {
1070	#[cfg(all(test, feature = "x509-parser"))]
1071	fn from_x509(x509: &x509_parser::certificate::X509Certificate<'_>) -> Result<Self, Error> {
1072		use x509_parser::extensions::BasicConstraints as B;
1073
1074		let basic_constraints = x509
1075			.basic_constraints()
1076			.map_err(|_| Error::CouldNotParseCertificate)?
1077			.map(|ext| ext.value);
1078
1079		Ok(match basic_constraints {
1080			Some(B {
1081				ca: true,
1082				path_len_constraint: Some(n),
1083			}) if *n <= u8::MAX as u32 => Self::Ca(BasicConstraints::Constrained(*n as u8)),
1084			Some(B {
1085				ca: true,
1086				path_len_constraint: Some(_),
1087			}) => return Err(Error::CouldNotParseCertificate),
1088			Some(B {
1089				ca: true,
1090				path_len_constraint: None,
1091			}) => Self::Ca(BasicConstraints::Unconstrained),
1092			Some(B { ca: false, .. }) => Self::ExplicitNoCa,
1093			None => Self::NoCa,
1094		})
1095	}
1096}
1097
1098/// The path length constraint (only relevant for CA certificates)
1099///
1100/// Sets an optional upper limit on the length of the intermediate certificate chain
1101/// length allowed for this CA certificate (not including the end entity certificate).
1102#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1103pub enum BasicConstraints {
1104	/// No constraint
1105	Unconstrained,
1106	/// Constrain to the contained number of intermediate certificates
1107	Constrained(u8),
1108}
1109
1110#[cfg(test)]
1111mod tests {
1112	#[cfg(feature = "x509-parser")]
1113	use std::net::Ipv4Addr;
1114
1115	#[cfg(feature = "x509-parser")]
1116	use pki_types::pem::PemObject;
1117
1118	#[cfg(feature = "pem")]
1119	use super::*;
1120	#[cfg(feature = "x509-parser")]
1121	use crate::DnValue;
1122	#[cfg(feature = "crypto")]
1123	use crate::KeyPair;
1124
1125	#[cfg(feature = "crypto")]
1126	#[test]
1127	fn test_with_key_usages() {
1128		let params = CertificateParams {
1129			// Set key usages
1130			key_usages: vec![
1131				KeyUsagePurpose::DigitalSignature,
1132				KeyUsagePurpose::KeyEncipherment,
1133				KeyUsagePurpose::ContentCommitment,
1134			],
1135			// This can sign things!
1136			is_ca: IsCa::Ca(BasicConstraints::Constrained(0)),
1137			..CertificateParams::default()
1138		};
1139
1140		// Make the cert
1141		let key_pair = KeyPair::generate().unwrap();
1142		let cert = params.self_signed(&key_pair).unwrap();
1143
1144		// Parse it
1145		let (_rem, cert) = x509_parser::parse_x509_certificate(cert.der()).unwrap();
1146
1147		// Check oid
1148		let key_usage_oid_str = "2.5.29.15";
1149
1150		// Found flag
1151		let mut found = false;
1152
1153		for ext in cert.extensions() {
1154			if key_usage_oid_str == ext.oid.to_id_string() {
1155				// should have the minimal number of octets, and no extra trailing zero bytes
1156				// ref. https://github.com/rustls/rcgen/issues/368
1157				assert_eq!(ext.value, vec![0x03, 0x02, 0x05, 0xe0]);
1158				if let x509_parser::extensions::ParsedExtension::KeyUsage(usage) =
1159					ext.parsed_extension()
1160				{
1161					assert!(usage.flags == 7);
1162					found = true;
1163				}
1164			}
1165		}
1166
1167		assert!(found);
1168	}
1169
1170	#[cfg(feature = "crypto")]
1171	#[test]
1172	fn test_with_key_usages_decipheronly_only() {
1173		let params = CertificateParams {
1174			// Set key usages
1175			key_usages: vec![KeyUsagePurpose::DecipherOnly],
1176			// This can sign things!
1177			is_ca: IsCa::Ca(BasicConstraints::Constrained(0)),
1178			..CertificateParams::default()
1179		};
1180
1181		// Make the cert
1182		let key_pair = KeyPair::generate().unwrap();
1183		let cert = params.self_signed(&key_pair).unwrap();
1184
1185		// Parse it
1186		let (_rem, cert) = x509_parser::parse_x509_certificate(cert.der()).unwrap();
1187
1188		// Check oid
1189		let key_usage_oid_str = "2.5.29.15";
1190
1191		// Found flag
1192		let mut found = false;
1193
1194		for ext in cert.extensions() {
1195			if key_usage_oid_str == ext.oid.to_id_string() {
1196				if let x509_parser::extensions::ParsedExtension::KeyUsage(usage) =
1197					ext.parsed_extension()
1198				{
1199					assert!(usage.flags == 256);
1200					found = true;
1201				}
1202			}
1203		}
1204
1205		assert!(found);
1206	}
1207
1208	#[cfg(feature = "crypto")]
1209	#[test]
1210	fn test_with_extended_key_usages_any() {
1211		let params = CertificateParams {
1212			extended_key_usages: vec![ExtendedKeyUsagePurpose::Any],
1213			..CertificateParams::default()
1214		};
1215
1216		// Make the cert
1217		let key_pair = KeyPair::generate().unwrap();
1218		let cert = params.self_signed(&key_pair).unwrap();
1219
1220		// Parse it
1221		let (_rem, cert) = x509_parser::parse_x509_certificate(cert.der()).unwrap();
1222
1223		// Ensure we found it.
1224		let maybe_extension = cert.extended_key_usage().unwrap();
1225		let extension = maybe_extension.unwrap();
1226		assert!(extension.value.any);
1227	}
1228
1229	#[cfg(feature = "crypto")]
1230	#[test]
1231	fn test_with_extended_key_usages_other() {
1232		use x509_parser::der_parser::asn1_rs::Oid;
1233		const OID_1: &[u64] = &[1, 2, 3, 4];
1234		const OID_2: &[u64] = &[1, 2, 3, 4, 5, 6];
1235
1236		let params = CertificateParams {
1237			extended_key_usages: vec![
1238				ExtendedKeyUsagePurpose::Other(Vec::from(OID_1)),
1239				ExtendedKeyUsagePurpose::Other(Vec::from(OID_2)),
1240			],
1241			..CertificateParams::default()
1242		};
1243
1244		// Make the cert
1245		let key_pair = KeyPair::generate().unwrap();
1246		let cert = params.self_signed(&key_pair).unwrap();
1247
1248		// Parse it
1249		let (_rem, cert) = x509_parser::parse_x509_certificate(cert.der()).unwrap();
1250
1251		// Ensure we found it.
1252		let maybe_extension = cert.extended_key_usage().unwrap();
1253		let extension = maybe_extension.unwrap();
1254
1255		let expected_oids = vec![Oid::from(OID_1).unwrap(), Oid::from(OID_2).unwrap()];
1256		assert_eq!(extension.value.other, expected_oids);
1257	}
1258
1259	#[cfg(feature = "pem")]
1260	mod test_pem_serialization {
1261		use super::*;
1262
1263		#[test]
1264		#[cfg(windows)]
1265		fn test_windows_line_endings() {
1266			let key_pair = KeyPair::generate().unwrap();
1267			let cert = CertificateParams::default().self_signed(&key_pair).unwrap();
1268			assert!(cert.pem().contains("\r\n"));
1269		}
1270
1271		#[test]
1272		#[cfg(not(windows))]
1273		fn test_not_windows_line_endings() {
1274			let key_pair = KeyPair::generate().unwrap();
1275			let cert = CertificateParams::default().self_signed(&key_pair).unwrap();
1276			assert!(!cert.pem().contains('\r'));
1277		}
1278	}
1279
1280	#[cfg(feature = "x509-parser")]
1281	#[test]
1282	fn parse_other_name_alt_name() {
1283		// Create and serialize a certificate with an alternative name containing an "OtherName".
1284		let mut params = CertificateParams::default();
1285		let other_name = SanType::OtherName((vec![1, 2, 3, 4], "Foo".into()));
1286		params.subject_alt_names.push(other_name.clone());
1287		let key_pair = KeyPair::generate().unwrap();
1288		let cert = params.self_signed(&key_pair).unwrap();
1289
1290		// We should be able to parse the certificate with x509-parser.
1291		assert!(x509_parser::parse_x509_certificate(cert.der()).is_ok());
1292
1293		// We should be able to reconstitute params from the DER using x509-parser.
1294		let params_from_cert = CertificateParams::from_ca_cert_der(cert.der()).unwrap();
1295
1296		// We should find the expected distinguished name in the reconstituted params.
1297		let expected_alt_names = &[&other_name];
1298		let subject_alt_names = params_from_cert
1299			.subject_alt_names
1300			.iter()
1301			.collect::<Vec<_>>();
1302		assert_eq!(subject_alt_names, expected_alt_names);
1303	}
1304
1305	#[cfg(feature = "x509-parser")]
1306	#[test]
1307	fn parse_ia5string_subject() {
1308		// Create and serialize a certificate with a subject containing an IA5String email address.
1309		let email_address_dn_type = DnType::CustomDnType(vec![1, 2, 840, 113549, 1, 9, 1]); // id-emailAddress
1310		let email_address_dn_value = DnValue::Ia5String("foo@bar.com".try_into().unwrap());
1311		let mut params = CertificateParams::new(vec!["crabs".to_owned()]).unwrap();
1312		params.distinguished_name = DistinguishedName::new();
1313		params.distinguished_name.push(
1314			email_address_dn_type.clone(),
1315			email_address_dn_value.clone(),
1316		);
1317		let key_pair = KeyPair::generate().unwrap();
1318		let cert = params.self_signed(&key_pair).unwrap();
1319
1320		// We should be able to parse the certificate with x509-parser.
1321		assert!(x509_parser::parse_x509_certificate(cert.der()).is_ok());
1322
1323		// We should be able to reconstitute params from the DER using x509-parser.
1324		let params_from_cert = CertificateParams::from_ca_cert_der(cert.der()).unwrap();
1325
1326		// We should find the expected distinguished name in the reconstituted params.
1327		let expected_names = &[(&email_address_dn_type, &email_address_dn_value)];
1328		let names = params_from_cert
1329			.distinguished_name
1330			.iter()
1331			.collect::<Vec<(_, _)>>();
1332		assert_eq!(names, expected_names);
1333	}
1334
1335	#[cfg(feature = "x509-parser")]
1336	#[test]
1337	fn converts_from_ip() {
1338		let ip = Ipv4Addr::new(2, 4, 6, 8);
1339		let ip_san = SanType::IpAddress(IpAddr::V4(ip));
1340
1341		let mut params = CertificateParams::new(vec!["crabs".to_owned()]).unwrap();
1342		let ca_key = KeyPair::generate().unwrap();
1343
1344		// Add the SAN we want to test the parsing for
1345		params.subject_alt_names.push(ip_san.clone());
1346
1347		// Because we're using a function for CA certificates
1348		params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
1349
1350		// Serialize our cert that has our chosen san, so we can testing parsing/deserializing it.
1351		let cert = params.self_signed(&ca_key).unwrap();
1352
1353		let actual = CertificateParams::from_ca_cert_der(cert.der()).unwrap();
1354		assert!(actual.subject_alt_names.contains(&ip_san));
1355	}
1356
1357	#[cfg(feature = "x509-parser")]
1358	mod test_key_identifier_from_ca {
1359		use super::*;
1360
1361		#[test]
1362		fn load_ca_and_sign_cert() {
1363			let ca_cert = r#"-----BEGIN CERTIFICATE-----
1364MIIFDTCCAvWgAwIBAgIUVuDfDt/BUVfObGOHsM+L5/qPZfIwDQYJKoZIhvcNAQEL
1365BQAwFjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wHhcNMjMxMjA4MTAwOTI2WhcNMjQx
1366MTI4MTAwOTI2WjAWMRQwEgYDVQQDDAtleGFtcGxlLmNvbTCCAiIwDQYJKoZIhvcN
1367AQEBBQADggIPADCCAgoCggIBAKXyZsv7Zwek9yc54IXWjCkMwU4eDMz9Uw06WETF
1368hZtauwDo4usCeYJa/7x8RZbGcI99s/vOMHjIdVzY6g9p5c6qS+7EUBhXARYVB74z
1369XUGwgVGss7lgw+0dNxhQ8F0M2smBXUP9FlJJjJpbWeU+93iynGy+PTXFtYMnOoVI
13704G7YKsG5lX0zBJUNYZslEz6Kp8eRYu7FAdccU0u5bmg02a1WiXOYJeN1+AifUbRN
1371zNInZCqMCFgoHczb0DvKU3QX/xrcBxfr/SNJPqxlecUvsozteUoAFAUF1uTxH31q
1372cVmCHf9I0r6JJoGxs+XMVbH2SJLdsq/+zpjeHz6gy0z4aRMBpaUWUQ9pEENeSq15
1373PXCuX3yPT2BII30mL86OWO6qgms70iALak6xZ/xAT7RT22E1bOF+XJsiUM3OgGF0
1374TPmDcpafEMH4kwzdaC7U5hqhYk9I2l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/j+1Jdk1c9PJ6xhCjof4nzI9YsLbI8lPtu8K/
1391Ng==
1392-----END CERTIFICATE-----"#;
1393
1394			let ca_key = r#"-----BEGIN PRIVATE KEY-----
1395MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQCl8mbL+2cHpPcn
1396OeCF1owpDMFOHgzM/VMNOlhExYWbWrsA6OLrAnmCWv+8fEWWxnCPfbP7zjB4yHVc
13972OoPaeXOqkvuxFAYVwEWFQe+M11BsIFRrLO5YMPtHTcYUPBdDNrJgV1D/RZSSYya
1398W1nlPvd4spxsvj01xbWDJzqFSOBu2CrBuZV9MwSVDWGbJRM+iqfHkWLuxQHXHFNL
1399uW5oNNmtVolzmCXjdfgIn1G0TczSJ2QqjAhYKB3M29A7ylN0F/8a3AcX6/0jST6s
1400ZXnFL7KM7XlKABQFBdbk8R99anFZgh3/SNK+iSaBsbPlzFWx9kiS3bKv/s6Y3h8+
1401oMtM+GkTAaWlFlEPaRBDXkqteT1wrl98j09gSCN9Ji/OjljuqoJrO9IgC2pOsWf8
1402QE+0U9thNWzhflybIlDNzoBhdEz5g3KWnxDB+JMM3Wgu1OYaoWJPSNpX0zBIIVfO
1403pFFwpRMbhxEA+BmS3HdRzA/1oKjmTuMv7f8swTzatNRaXopRaYf7Vuqca9V+yZaM
14049f8iLjRStKF0wduCf01Ivv0tQZGrzgYN3jRxw1w4xEirZ1fosKNXBbei1Qq5yoSi
1405epvefnPmCkBiK3MJEfdTsWfWUwxM8krDw6Vq7XmX9ytVQNFLeNWkyrvKWMMbJ1XT
1406ogRmiZDof5a3ryOlPRIOL1aveIcgGQIDAQABAoICACVWAWzZdlfQ9M59hhd2qvg9
1407Z2yE9EpWoI30V5G5gxLt+e79drh7SQ1cHfexWhLPONn/5TO9M0ipiUZHg3nOUKcL
1408x6PDxWWEhbkLKD/R3KR/6siOe600qUA6939gDoRQ9RSrJ2m5koEXDSxZa0NZxGIC
1409hZEtyCXGAs2sUM1WFTC7L/uAHrM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V+Do7z61YmvwVZ2N2
1442+30kckNnDVdggOklBmlSk5duej+RVoAKP8U5wV3Z/bS5J0OI75fxhuzybPcVfkwE
1443JiY98T5oN1X0C/qAXxJfSvklbru9fipwGt3dho5Tm6Ee3cYf+plnk4WZhSnqyef4
1444PITGdT9dgN88nHPCle0B1+OY+OZ5
1445-----END PRIVATE KEY-----"#;
1446
1447			let ca_kp = KeyPair::from_pem(ca_key).unwrap();
1448			let ca = Issuer::from_ca_cert_pem(ca_cert, ca_kp).unwrap();
1449			let ca_ski = vec![
1450				0x97, 0xD4, 0x76, 0xA1, 0x9B, 0x1A, 0x71, 0x35, 0x2A, 0xC7, 0xF4, 0xA1, 0x84, 0x12,
1451				0x56, 0x06, 0xBA, 0x5D, 0x61, 0x84,
1452			];
1453
1454			assert_eq!(
1455				&KeyIdMethod::PreSpecified(ca_ski.clone()),
1456				ca.key_identifier_method.as_ref()
1457			);
1458
1459			let ca_cert_der = CertificateDer::from_pem_slice(ca_cert.as_bytes()).unwrap();
1460			let (_, x509_ca) = x509_parser::parse_x509_certificate(ca_cert_der.as_ref()).unwrap();
1461			assert_eq!(
1462				&ca_ski,
1463				&x509_ca
1464					.iter_extensions()
1465					.find_map(|ext| match ext.parsed_extension() {
1466						x509_parser::extensions::ParsedExtension::SubjectKeyIdentifier(key_id) => {
1467							Some(key_id.0.to_vec())
1468						},
1469						_ => None,
1470					})
1471					.unwrap()
1472			);
1473
1474			let ee_key = KeyPair::generate().unwrap();
1475			let ee_params = CertificateParams {
1476				use_authority_key_identifier_extension: true,
1477				..CertificateParams::default()
1478			};
1479			let ee_cert = ee_params.signed_by(&ee_key, &ca).unwrap();
1480
1481			let (_, x509_ee) = x509_parser::parse_x509_certificate(ee_cert.der()).unwrap();
1482			assert_eq!(
1483				&ca_ski,
1484				&x509_ee
1485					.iter_extensions()
1486					.find_map(|ext| match ext.parsed_extension() {
1487						x509_parser::extensions::ParsedExtension::AuthorityKeyIdentifier(aki) => {
1488							aki.key_identifier.as_ref().map(|ki| ki.0.to_vec())
1489						},
1490						_ => None,
1491					})
1492					.unwrap()
1493			);
1494		}
1495	}
1496}