/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rcgen-0.14.7/src/certificate.rs
Line | Count | Source |
1 | | use std::net::IpAddr; |
2 | | use std::str::FromStr; |
3 | | |
4 | | #[cfg(feature = "pem")] |
5 | | use pem::Pem; |
6 | | use pki_types::{CertificateDer, CertificateSigningRequestDer}; |
7 | | use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time}; |
8 | | use yasna::models::ObjectIdentifier; |
9 | | use yasna::{DERWriter, DERWriterSeq, Tag}; |
10 | | |
11 | | use crate::crl::CrlDistributionPoint; |
12 | | use crate::csr::CertificateSigningRequest; |
13 | | use crate::key_pair::{serialize_public_key_der, sign_der, PublicKeyData}; |
14 | | #[cfg(feature = "crypto")] |
15 | | use crate::ring_like::digest; |
16 | | #[cfg(feature = "pem")] |
17 | | use crate::ENCODE_CONFIG; |
18 | | use 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)] |
26 | | pub struct Certificate { |
27 | | pub(crate) der: CertificateDer<'static>, |
28 | | } |
29 | | |
30 | | impl 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 | 0 | pub fn der(&self) -> &CertificateDer<'static> { |
36 | 0 | &self.der |
37 | 0 | } |
38 | | |
39 | | /// Get the certificate in PEM encoded format. |
40 | | #[cfg(feature = "pem")] |
41 | 0 | pub fn pem(&self) -> String { |
42 | 0 | pem::encode_config(&Pem::new("CERTIFICATE", self.der().to_vec()), ENCODE_CONFIG) |
43 | 0 | } |
44 | | } |
45 | | |
46 | | impl From<Certificate> for CertificateDer<'static> { |
47 | 0 | fn from(cert: Certificate) -> Self { |
48 | 0 | cert.der |
49 | 0 | } |
50 | | } |
51 | | |
52 | | /// Parameters used for certificate generation |
53 | | #[allow(missing_docs)] |
54 | | #[non_exhaustive] |
55 | | #[derive(Debug, PartialEq, Eq, Clone)] |
56 | | pub 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 | | |
81 | | impl Default for CertificateParams { |
82 | 0 | fn default() -> Self { |
83 | | // not_before and not_after set to reasonably long dates |
84 | 0 | let not_before = date_time_ymd(1975, 1, 1); |
85 | 0 | let not_after = date_time_ymd(4096, 1, 1); |
86 | 0 | let mut distinguished_name = DistinguishedName::new(); |
87 | 0 | distinguished_name.push(DnType::CommonName, "rcgen self signed cert"); |
88 | 0 | CertificateParams { |
89 | 0 | not_before, |
90 | 0 | not_after, |
91 | 0 | serial_number: None, |
92 | 0 | subject_alt_names: Vec::new(), |
93 | 0 | distinguished_name, |
94 | 0 | is_ca: IsCa::NoCa, |
95 | 0 | key_usages: Vec::new(), |
96 | 0 | extended_key_usages: Vec::new(), |
97 | 0 | name_constraints: None, |
98 | 0 | crl_distribution_points: Vec::new(), |
99 | 0 | custom_extensions: Vec::new(), |
100 | 0 | use_authority_key_identifier_extension: false, |
101 | 0 | #[cfg(feature = "crypto")] |
102 | 0 | key_identifier_method: KeyIdMethod::Sha256, |
103 | 0 | #[cfg(not(feature = "crypto"))] |
104 | 0 | key_identifier_method: KeyIdMethod::PreSpecified(Vec::new()), |
105 | 0 | } |
106 | 0 | } |
107 | | } |
108 | | |
109 | | impl CertificateParams { |
110 | | /// Generate certificate parameters with reasonable defaults |
111 | 0 | pub fn new(subject_alt_names: impl Into<Vec<String>>) -> Result<Self, Error> { |
112 | 0 | let subject_alt_names = subject_alt_names |
113 | 0 | .into() |
114 | 0 | .into_iter() |
115 | 0 | .map(|s| { |
116 | 0 | Ok(match IpAddr::from_str(&s) { |
117 | 0 | Ok(ip) => SanType::IpAddress(ip), |
118 | 0 | Err(_) => SanType::DnsName(s.try_into()?), |
119 | | }) |
120 | 0 | }) |
121 | 0 | .collect::<Result<Vec<_>, _>>()?; |
122 | 0 | Ok(CertificateParams { |
123 | 0 | subject_alt_names, |
124 | 0 | ..Default::default() |
125 | 0 | }) |
126 | 0 | } |
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 | 0 | pub fn signed_by( |
141 | 0 | &self, |
142 | 0 | public_key: &impl PublicKeyData, |
143 | 0 | issuer: &Issuer<'_, impl SigningKey>, |
144 | 0 | ) -> Result<Certificate, Error> { |
145 | | Ok(Certificate { |
146 | 0 | der: self.serialize_der_with_signer(public_key, issuer)?, |
147 | | }) |
148 | 0 | } |
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 | 0 | pub fn self_signed(&self, signing_key: &impl SigningKey) -> Result<Certificate, Error> { |
155 | 0 | let issuer = Issuer::from_params(self, signing_key); |
156 | | Ok(Certificate { |
157 | 0 | der: self.serialize_der_with_signer(signing_key, &issuer)?, |
158 | | }) |
159 | 0 | } |
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 | 0 | pub fn key_identifier(&self, key: &impl PublicKeyData) -> Vec<u8> { |
164 | 0 | self.key_identifier_method |
165 | 0 | .derive(key.subject_public_key_info()) |
166 | 0 | } |
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 | 0 | fn write_extension_request_attribute(&self, writer: DERWriter) { |
192 | 0 | writer.write_sequence(|writer| { |
193 | 0 | writer.next().write_oid(&ObjectIdentifier::from_slice( |
194 | 0 | oid::PKCS_9_AT_EXTENSION_REQUEST, |
195 | 0 | )); |
196 | 0 | writer.next().write_set(|writer| { |
197 | 0 | writer.next().write_sequence(|writer| { |
198 | | // Write key_usage |
199 | 0 | self.write_key_usage(writer.next()); |
200 | | // Write subject_alt_names |
201 | 0 | self.write_subject_alt_names(writer.next()); |
202 | 0 | self.write_extended_key_usage(writer.next()); |
203 | | |
204 | | // Write custom extensions |
205 | 0 | for ext in &self.custom_extensions { |
206 | 0 | write_x509_extension(writer.next(), &ext.oid, ext.critical, |writer| { |
207 | 0 | writer.write_der(ext.content()) |
208 | 0 | }); |
209 | | } |
210 | 0 | }); |
211 | 0 | }); |
212 | 0 | }); |
213 | 0 | } |
214 | | |
215 | | /// Write a certificate's KeyUsage as defined in RFC 5280. |
216 | 0 | fn write_key_usage(&self, writer: DERWriter) { |
217 | 0 | if self.key_usages.is_empty() { |
218 | 0 | return; |
219 | 0 | } |
220 | | |
221 | | // "When present, conforming CAs SHOULD mark this extension as critical." |
222 | 0 | write_x509_extension(writer, oid::KEY_USAGE, true, |writer| { |
223 | | // u16 is large enough to encode the largest possible key usage (two-bytes) |
224 | 0 | let bit_string = self.key_usages.iter().fold(0u16, |bit_string, key_usage| { |
225 | 0 | bit_string | key_usage.to_u16() |
226 | 0 | }); |
227 | | |
228 | 0 | match u16::BITS - bit_string.trailing_zeros() { |
229 | 0 | bits @ 0..=8 => { |
230 | 0 | writer.write_bitvec_bytes(&bit_string.to_be_bytes()[..1], bits as usize) |
231 | | }, |
232 | 0 | bits @ 9..=16 => { |
233 | 0 | writer.write_bitvec_bytes(&bit_string.to_be_bytes(), bits as usize) |
234 | | }, |
235 | 0 | _ => unreachable!(), |
236 | | } |
237 | 0 | }); |
238 | 0 | } |
239 | | |
240 | 0 | fn write_extended_key_usage(&self, writer: DERWriter) { |
241 | 0 | if !self.extended_key_usages.is_empty() { |
242 | 0 | write_x509_extension(writer, oid::EXT_KEY_USAGE, false, |writer| { |
243 | 0 | writer.write_sequence(|writer| { |
244 | 0 | for usage in &self.extended_key_usages { |
245 | 0 | writer |
246 | 0 | .next() |
247 | 0 | .write_oid(&ObjectIdentifier::from_slice(usage.oid())); |
248 | 0 | } |
249 | 0 | }); |
250 | 0 | }); |
251 | 0 | } |
252 | 0 | } |
253 | | |
254 | 0 | fn write_subject_alt_names(&self, writer: DERWriter) { |
255 | 0 | if self.subject_alt_names.is_empty() { |
256 | 0 | return; |
257 | 0 | } |
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 | 0 | let critical = self.distinguished_name.entries.is_empty(); |
262 | 0 | write_x509_extension(writer, oid::SUBJECT_ALT_NAME, critical, |writer| { |
263 | 0 | writer.write_sequence(|writer| { |
264 | 0 | for san in self.subject_alt_names.iter() { |
265 | 0 | writer.next().write_tagged_implicit( |
266 | 0 | Tag::context(san.tag()), |
267 | 0 | |writer| match san { |
268 | 0 | SanType::Rfc822Name(name) |
269 | 0 | | SanType::DnsName(name) |
270 | 0 | | SanType::URI(name) => writer.write_ia5_string(name.as_str()), |
271 | 0 | SanType::IpAddress(IpAddr::V4(addr)) => { |
272 | 0 | writer.write_bytes(&addr.octets()) |
273 | | }, |
274 | 0 | SanType::IpAddress(IpAddr::V6(addr)) => { |
275 | 0 | writer.write_bytes(&addr.octets()) |
276 | | }, |
277 | 0 | 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 | 0 | writer.write_sequence(|writer| { |
281 | 0 | writer.next().write_oid(&ObjectIdentifier::from_slice(oid)); |
282 | 0 | value.write_der(writer.next()); |
283 | 0 | }); |
284 | | }, |
285 | 0 | }, |
286 | | ); |
287 | | } |
288 | 0 | }); |
289 | 0 | }); |
290 | 0 | } |
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 | 0 | pub fn serialize_request( |
301 | 0 | &self, |
302 | 0 | subject_key: &impl SigningKey, |
303 | 0 | ) -> Result<CertificateSigningRequest, Error> { |
304 | 0 | self.serialize_request_with_attributes(subject_key, Vec::new()) |
305 | 0 | } Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request::<rcgen::key_pair::KeyPair> Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request::<_> |
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 | 0 | pub fn serialize_request_with_attributes( |
319 | 0 | &self, |
320 | 0 | subject_key: &impl SigningKey, |
321 | 0 | attrs: Vec<Attribute>, |
322 | 0 | ) -> Result<CertificateSigningRequest, Error> { |
323 | | // No .. pattern, we use this to ensure every field is used |
324 | | #[deny(unused)] |
325 | | let Self { |
326 | 0 | not_before, |
327 | 0 | not_after, |
328 | 0 | serial_number, |
329 | 0 | subject_alt_names, |
330 | 0 | distinguished_name, |
331 | 0 | is_ca, |
332 | 0 | key_usages, |
333 | 0 | extended_key_usages, |
334 | 0 | name_constraints, |
335 | 0 | crl_distribution_points, |
336 | 0 | custom_extensions, |
337 | 0 | use_authority_key_identifier_extension, |
338 | 0 | key_identifier_method, |
339 | 0 | } = 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 | 0 | let _ = ( |
348 | 0 | not_before, |
349 | 0 | not_after, |
350 | 0 | key_identifier_method, |
351 | 0 | extended_key_usages, |
352 | 0 | ); |
353 | 0 | if serial_number.is_some() |
354 | 0 | || *is_ca != IsCa::NoCa |
355 | 0 | || name_constraints.is_some() |
356 | 0 | || !crl_distribution_points.is_empty() |
357 | 0 | || *use_authority_key_identifier_extension |
358 | | { |
359 | 0 | return Err(Error::UnsupportedInCsr); |
360 | 0 | } |
361 | | |
362 | | // Whether or not to write an extension request attribute |
363 | 0 | let write_extension_request = !key_usages.is_empty() |
364 | 0 | || !subject_alt_names.is_empty() |
365 | 0 | || !extended_key_usages.is_empty() |
366 | 0 | || !custom_extensions.is_empty(); |
367 | | |
368 | 0 | let der = sign_der(subject_key, |writer| { |
369 | | // Write version |
370 | 0 | writer.next().write_u8(0); |
371 | 0 | write_distinguished_name(writer.next(), distinguished_name); |
372 | 0 | 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 | 0 | writer |
376 | 0 | .next() |
377 | 0 | .write_tagged_implicit(Tag::context(0), |writer| { |
378 | | // RFC 2986 specifies that attributes are a SET OF Attribute |
379 | 0 | writer.write_set_of(|writer| { |
380 | 0 | if write_extension_request { |
381 | 0 | self.write_extension_request_attribute(writer.next()); |
382 | 0 | } |
383 | | |
384 | 0 | for Attribute { oid, values } in attrs { |
385 | 0 | writer.next().write_sequence(|writer| { |
386 | 0 | writer.next().write_oid(&ObjectIdentifier::from_slice(oid)); |
387 | 0 | writer.next().write_der(&values); |
388 | 0 | }); Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request_with_attributes::<rcgen::key_pair::KeyPair>::{closure#0}::{closure#0}::{closure#0}::{closure#0}Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request_with_attributes::<_>::{closure#0}::{closure#0}::{closure#0}::{closure#0} |
389 | | } |
390 | 0 | }); Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request_with_attributes::<rcgen::key_pair::KeyPair>::{closure#0}::{closure#0}::{closure#0}Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request_with_attributes::<_>::{closure#0}::{closure#0}::{closure#0} |
391 | 0 | }); Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request_with_attributes::<rcgen::key_pair::KeyPair>::{closure#0}::{closure#0}Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request_with_attributes::<_>::{closure#0}::{closure#0} |
392 | | |
393 | 0 | Ok(()) |
394 | 0 | })?; Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request_with_attributes::<rcgen::key_pair::KeyPair>::{closure#0}Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request_with_attributes::<_>::{closure#0} |
395 | | |
396 | 0 | Ok(CertificateSigningRequest { |
397 | 0 | der: CertificateSigningRequestDer::from(der), |
398 | 0 | }) |
399 | 0 | } Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request_with_attributes::<rcgen::key_pair::KeyPair> Unexecuted instantiation: <rcgen::certificate::CertificateParams>::serialize_request_with_attributes::<_> |
400 | | |
401 | 0 | pub(crate) fn serialize_der_with_signer<K: PublicKeyData>( |
402 | 0 | &self, |
403 | 0 | pub_key: &K, |
404 | 0 | issuer: &Issuer<'_, impl SigningKey>, |
405 | 0 | ) -> Result<CertificateDer<'static>, Error> { |
406 | 0 | let der = sign_der(&issuer.signing_key, |writer| { |
407 | 0 | let pub_key_spki = pub_key.subject_public_key_info(); |
408 | | // Write version |
409 | 0 | writer.next().write_tagged(Tag::context(0), |writer| { |
410 | 0 | writer.write_u8(2); |
411 | 0 | }); |
412 | | // Write serialNumber |
413 | 0 | if let Some(ref serial) = self.serial_number { |
414 | 0 | writer.next().write_bigint_bytes(serial.as_ref(), true); |
415 | 0 | } else { |
416 | | #[cfg(feature = "crypto")] |
417 | 0 | { |
418 | 0 | let hash = digest::digest(&digest::SHA256, pub_key.der_bytes()); |
419 | 0 | // RFC 5280 specifies at most 20 bytes for a serial number |
420 | 0 | let mut sl = hash.as_ref()[0..20].to_vec(); |
421 | 0 | sl[0] &= 0x7f; // MSB must be 0 to ensure encoding bignum in 20 bytes |
422 | 0 | writer.next().write_bigint_bytes(&sl, true); |
423 | 0 | } |
424 | | #[cfg(not(feature = "crypto"))] |
425 | | if self.serial_number.is_none() { |
426 | | return Err(Error::MissingSerialNumber); |
427 | | } |
428 | | }; |
429 | | // Write signature algorithm |
430 | 0 | issuer |
431 | 0 | .signing_key |
432 | 0 | .algorithm() |
433 | 0 | .write_alg_ident(writer.next()); |
434 | | // Write issuer name |
435 | 0 | write_distinguished_name(writer.next(), issuer.distinguished_name.as_ref()); |
436 | | // Write validity |
437 | 0 | writer.next().write_sequence(|writer| { |
438 | | // Not before |
439 | 0 | write_dt_utc_or_generalized(writer.next(), self.not_before); |
440 | | // Not after |
441 | 0 | write_dt_utc_or_generalized(writer.next(), self.not_after); |
442 | 0 | Ok::<(), Error>(()) |
443 | 0 | })?; |
444 | | // Write subject |
445 | 0 | write_distinguished_name(writer.next(), &self.distinguished_name); |
446 | | // Write subjectPublicKeyInfo |
447 | 0 | serialize_public_key_der(pub_key, writer.next()); |
448 | | // write extensions |
449 | 0 | let should_write_exts = self.use_authority_key_identifier_extension |
450 | 0 | || !self.subject_alt_names.is_empty() |
451 | 0 | || !self.extended_key_usages.is_empty() |
452 | 0 | || self.name_constraints.iter().any(|c| !c.is_empty()) |
453 | 0 | || matches!(self.is_ca, IsCa::ExplicitNoCa) |
454 | 0 | || matches!(self.is_ca, IsCa::Ca(_)) |
455 | 0 | || !self.custom_extensions.is_empty(); |
456 | 0 | if !should_write_exts { |
457 | 0 | return Ok(()); |
458 | 0 | } |
459 | | |
460 | 0 | writer.next().write_tagged(Tag::context(3), |writer| { |
461 | 0 | writer.write_sequence(|writer| self.write_extensions(writer, &pub_key_spki, issuer)) |
462 | 0 | })?; |
463 | | |
464 | 0 | Ok(()) |
465 | 0 | })?; |
466 | | |
467 | 0 | Ok(der.into()) |
468 | 0 | } |
469 | | |
470 | 0 | fn write_extensions( |
471 | 0 | &self, |
472 | 0 | writer: &mut DERWriterSeq, |
473 | 0 | pub_key_spki: &[u8], |
474 | 0 | issuer: &Issuer<'_, impl SigningKey>, |
475 | 0 | ) -> Result<(), Error> { |
476 | 0 | if self.use_authority_key_identifier_extension { |
477 | 0 | write_x509_authority_key_identifier( |
478 | 0 | writer.next(), |
479 | 0 | match issuer.key_identifier_method.as_ref() { |
480 | 0 | KeyIdMethod::PreSpecified(aki) => aki.clone(), |
481 | | #[cfg(feature = "crypto")] |
482 | 0 | _ => issuer |
483 | 0 | .key_identifier_method |
484 | 0 | .derive(issuer.signing_key.subject_public_key_info()), |
485 | | }, |
486 | | ); |
487 | 0 | } |
488 | | |
489 | | // Write subject_alt_names |
490 | 0 | self.write_subject_alt_names(writer.next()); |
491 | | |
492 | | // Write standard key usage |
493 | 0 | self.write_key_usage(writer.next()); |
494 | | |
495 | | // Write extended key usage |
496 | 0 | if !self.extended_key_usages.is_empty() { |
497 | 0 | write_x509_extension(writer.next(), oid::EXT_KEY_USAGE, false, |writer| { |
498 | 0 | writer.write_sequence(|writer| { |
499 | 0 | for usage in self.extended_key_usages.iter() { |
500 | 0 | let oid = ObjectIdentifier::from_slice(usage.oid()); |
501 | 0 | writer.next().write_oid(&oid); |
502 | 0 | } |
503 | 0 | }); |
504 | 0 | }); |
505 | 0 | } |
506 | | |
507 | 0 | if let Some(name_constraints) = &self.name_constraints { |
508 | | // If both trees are empty, the extension must be omitted. |
509 | 0 | if !name_constraints.is_empty() { |
510 | 0 | write_x509_extension(writer.next(), oid::NAME_CONSTRAINTS, true, |writer| { |
511 | 0 | writer.write_sequence(|writer| { |
512 | 0 | if !name_constraints.permitted_subtrees.is_empty() { |
513 | 0 | write_general_subtrees( |
514 | 0 | writer.next(), |
515 | 0 | 0, |
516 | 0 | &name_constraints.permitted_subtrees, |
517 | 0 | ); |
518 | 0 | } |
519 | 0 | if !name_constraints.excluded_subtrees.is_empty() { |
520 | 0 | write_general_subtrees( |
521 | 0 | writer.next(), |
522 | 0 | 1, |
523 | 0 | &name_constraints.excluded_subtrees, |
524 | 0 | ); |
525 | 0 | } |
526 | 0 | }); |
527 | 0 | }); |
528 | 0 | } |
529 | 0 | } |
530 | | |
531 | 0 | if !self.crl_distribution_points.is_empty() { |
532 | 0 | write_x509_extension( |
533 | 0 | writer.next(), |
534 | 0 | oid::CRL_DISTRIBUTION_POINTS, |
535 | | false, |
536 | 0 | |writer| { |
537 | 0 | writer.write_sequence(|writer| { |
538 | 0 | for distribution_point in &self.crl_distribution_points { |
539 | 0 | distribution_point.write_der(writer.next()); |
540 | 0 | } |
541 | 0 | }) |
542 | 0 | }, |
543 | | ); |
544 | 0 | } |
545 | | |
546 | 0 | match self.is_ca { |
547 | 0 | IsCa::Ca(ref constraint) => { |
548 | | // Write subject_key_identifier |
549 | 0 | write_x509_extension( |
550 | 0 | writer.next(), |
551 | 0 | oid::SUBJECT_KEY_IDENTIFIER, |
552 | | false, |
553 | 0 | |writer| { |
554 | 0 | writer.write_bytes(&self.key_identifier_method.derive(pub_key_spki)); |
555 | 0 | }, |
556 | | ); |
557 | | // Write basic_constraints |
558 | 0 | write_x509_extension(writer.next(), oid::BASIC_CONSTRAINTS, true, |writer| { |
559 | 0 | writer.write_sequence(|writer| { |
560 | 0 | writer.next().write_bool(true); // cA flag |
561 | 0 | if let BasicConstraints::Constrained(path_len_constraint) = constraint { |
562 | 0 | writer.next().write_u8(*path_len_constraint); |
563 | 0 | } |
564 | 0 | }); |
565 | 0 | }); |
566 | | }, |
567 | | IsCa::ExplicitNoCa => { |
568 | | // Write subject_key_identifier |
569 | 0 | write_x509_extension( |
570 | 0 | writer.next(), |
571 | 0 | oid::SUBJECT_KEY_IDENTIFIER, |
572 | | false, |
573 | 0 | |writer| { |
574 | 0 | writer.write_bytes(&self.key_identifier_method.derive(pub_key_spki)); |
575 | 0 | }, |
576 | | ); |
577 | | // Write basic_constraints |
578 | 0 | write_x509_extension(writer.next(), oid::BASIC_CONSTRAINTS, true, |writer| { |
579 | 0 | writer.write_sequence(|writer| { |
580 | 0 | writer.next().write_bool(false); // cA flag |
581 | 0 | }); |
582 | 0 | }); |
583 | | }, |
584 | 0 | IsCa::NoCa => {}, |
585 | | } |
586 | | |
587 | | // Write the custom extensions |
588 | 0 | for ext in &self.custom_extensions { |
589 | 0 | write_x509_extension(writer.next(), &ext.oid, ext.critical, |writer| { |
590 | 0 | writer.write_der(ext.content()) |
591 | 0 | }); |
592 | | } |
593 | | |
594 | 0 | Ok(()) |
595 | 0 | } |
596 | | |
597 | | /// Insert an extended key usage (EKU) into the parameters if it does not already exist |
598 | 0 | pub fn insert_extended_key_usage(&mut self, eku: ExtendedKeyUsagePurpose) { |
599 | 0 | if !self.extended_key_usages.contains(&eku) { |
600 | 0 | self.extended_key_usages.push(eku); |
601 | 0 | } |
602 | 0 | } |
603 | | } |
604 | | |
605 | | impl AsRef<CertificateParams> for CertificateParams { |
606 | 0 | fn as_ref(&self) -> &CertificateParams { |
607 | 0 | self |
608 | 0 | } |
609 | | } |
610 | | |
611 | 0 | fn write_general_subtrees(writer: DERWriter, tag: u64, general_subtrees: &[GeneralSubtree]) { |
612 | 0 | writer.write_tagged_implicit(Tag::context(tag), |writer| { |
613 | 0 | writer.write_sequence(|writer| { |
614 | 0 | for subtree in general_subtrees.iter() { |
615 | 0 | writer.next().write_sequence(|writer| { |
616 | 0 | writer |
617 | 0 | .next() |
618 | 0 | .write_tagged_implicit( |
619 | 0 | Tag::context(subtree.tag()), |
620 | 0 | |writer| match subtree { |
621 | 0 | GeneralSubtree::Rfc822Name(name) |
622 | 0 | | GeneralSubtree::DnsName(name) => writer.write_ia5_string(name), |
623 | 0 | GeneralSubtree::DirectoryName(name) => { |
624 | 0 | write_distinguished_name(writer, name) |
625 | | }, |
626 | 0 | GeneralSubtree::IpAddress(subnet) => { |
627 | 0 | writer.write_bytes(&subnet.to_bytes()) |
628 | | }, |
629 | 0 | }, |
630 | | ); |
631 | | // minimum must be 0 (the default) and maximum must be absent |
632 | 0 | }); |
633 | | } |
634 | 0 | }); |
635 | 0 | }); |
636 | 0 | } |
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)] |
644 | | pub 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)] |
660 | | pub struct CustomExtension { |
661 | | oid: Vec<u64>, |
662 | | critical: bool, |
663 | | |
664 | | /// The content must be DER-encoded |
665 | | content: Vec<u8>, |
666 | | } |
667 | | |
668 | | impl 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 | 0 | pub fn new_acme_identifier(sha_digest: &[u8]) -> Self { |
674 | 0 | assert_eq!(sha_digest.len(), 32, "wrong size of sha_digest"); |
675 | 0 | let content = yasna::construct_der(|writer| { |
676 | 0 | writer.write_bytes(sha_digest); |
677 | 0 | }); |
678 | 0 | Self { |
679 | 0 | oid: oid::PE_ACME.to_owned(), |
680 | 0 | critical: true, |
681 | 0 | content, |
682 | 0 | } |
683 | 0 | } |
684 | | /// Create a new custom extension with the specified content |
685 | 0 | pub fn from_oid_content(oid: &[u64], content: Vec<u8>) -> Self { |
686 | 0 | Self { |
687 | 0 | oid: oid.to_owned(), |
688 | 0 | critical: false, |
689 | 0 | content, |
690 | 0 | } |
691 | 0 | } |
692 | | /// Sets the criticality flag of the extension. |
693 | 0 | pub fn set_criticality(&mut self, criticality: bool) { |
694 | 0 | self.critical = criticality; |
695 | 0 | } |
696 | | /// Obtains the criticality flag of the extension. |
697 | 0 | pub fn criticality(&self) -> bool { |
698 | 0 | self.critical |
699 | 0 | } |
700 | | /// Obtains the content of the extension. |
701 | 0 | pub fn content(&self) -> &[u8] { |
702 | 0 | &self.content |
703 | 0 | } |
704 | | /// Obtains the OID components of the extensions, as u64 pieces |
705 | 0 | pub fn oid_components(&self) -> impl Iterator<Item = u64> + '_ { |
706 | 0 | self.oid.iter().copied() |
707 | 0 | } |
708 | | } |
709 | | |
710 | | #[derive(Debug, PartialEq, Eq, Hash, Clone)] |
711 | | #[non_exhaustive] |
712 | | /// The attribute type of a distinguished name entry |
713 | | pub 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 | | |
730 | | impl DnType { |
731 | 0 | pub(crate) fn to_oid(&self) -> ObjectIdentifier { |
732 | 0 | let sl = match self { |
733 | 0 | DnType::CountryName => oid::COUNTRY_NAME, |
734 | 0 | DnType::LocalityName => oid::LOCALITY_NAME, |
735 | 0 | DnType::StateOrProvinceName => oid::STATE_OR_PROVINCE_NAME, |
736 | 0 | DnType::OrganizationName => oid::ORG_NAME, |
737 | 0 | DnType::OrganizationalUnitName => oid::ORG_UNIT_NAME, |
738 | 0 | DnType::CommonName => oid::COMMON_NAME, |
739 | 0 | DnType::CustomDnType(ref oid) => oid.as_slice(), |
740 | | }; |
741 | 0 | ObjectIdentifier::from_slice(sl) |
742 | 0 | } |
743 | | |
744 | | /// Generate a DnType for the provided OID |
745 | 0 | pub fn from_oid(slice: &[u64]) -> Self { |
746 | 0 | match slice { |
747 | 0 | oid::COUNTRY_NAME => DnType::CountryName, |
748 | 0 | oid::LOCALITY_NAME => DnType::LocalityName, |
749 | 0 | oid::STATE_OR_PROVINCE_NAME => DnType::StateOrProvinceName, |
750 | 0 | oid::ORG_NAME => DnType::OrganizationName, |
751 | 0 | oid::ORG_UNIT_NAME => DnType::OrganizationalUnitName, |
752 | 0 | oid::COMMON_NAME => DnType::CommonName, |
753 | 0 | oid => DnType::CustomDnType(oid.into()), |
754 | | } |
755 | 0 | } |
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) |
760 | | pub 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 | | |
779 | | impl 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 | 0 | fn oid(&self) -> &[u64] { |
816 | | use ExtendedKeyUsagePurpose::*; |
817 | 0 | match self { |
818 | | // anyExtendedKeyUsage |
819 | 0 | Any => &[2, 5, 29, 37, 0], |
820 | | // id-kp-* |
821 | 0 | ServerAuth => &[1, 3, 6, 1, 5, 5, 7, 3, 1], |
822 | 0 | ClientAuth => &[1, 3, 6, 1, 5, 5, 7, 3, 2], |
823 | 0 | CodeSigning => &[1, 3, 6, 1, 5, 5, 7, 3, 3], |
824 | 0 | EmailProtection => &[1, 3, 6, 1, 5, 5, 7, 3, 4], |
825 | 0 | TimeStamping => &[1, 3, 6, 1, 5, 5, 7, 3, 8], |
826 | 0 | OcspSigning => &[1, 3, 6, 1, 5, 5, 7, 3, 9], |
827 | 0 | Other(oid) => oid, |
828 | | } |
829 | 0 | } |
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)] |
835 | | pub 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 | | |
844 | | impl 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 | 0 | fn is_empty(&self) -> bool { |
877 | 0 | self.permitted_subtrees.is_empty() && self.excluded_subtrees.is_empty() |
878 | 0 | } |
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. |
889 | | pub enum GeneralSubtree { |
890 | | /// Also known as E-Mail address |
891 | | Rfc822Name(String), |
892 | | DnsName(String), |
893 | | DirectoryName(DistinguishedName), |
894 | | IpAddress(CidrSubnet), |
895 | | } |
896 | | |
897 | | impl 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 | 0 | 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 | 0 | match self { |
939 | 0 | GeneralSubtree::Rfc822Name(_name) => TAG_RFC822_NAME, |
940 | 0 | GeneralSubtree::DnsName(_name) => TAG_DNS_NAME, |
941 | 0 | GeneralSubtree::DirectoryName(_name) => TAG_DIRECTORY_NAME, |
942 | 0 | GeneralSubtree::IpAddress(_addr) => TAG_IP_ADDRESS, |
943 | | } |
944 | 0 | } |
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. |
957 | | pub enum CidrSubnet { |
958 | | V4([u8; 4], [u8; 4]), |
959 | | V6([u8; 16], [u8; 16]), |
960 | | } |
961 | | |
962 | | macro_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 | | |
970 | | impl 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 | 0 | pub fn from_addr_prefix(addr: IpAddr, prefix: u8) -> Self { |
985 | 0 | match addr { |
986 | 0 | IpAddr::V4(addr) => Self::from_v4_prefix(addr.octets(), prefix), |
987 | 0 | IpAddr::V6(addr) => Self::from_v6_prefix(addr.octets(), prefix), |
988 | | } |
989 | 0 | } |
990 | | /// Obtains the CidrSubnet from an IPv4 address in network byte order |
991 | | /// as well as the specified prefix. |
992 | 0 | pub fn from_v4_prefix(addr: [u8; 4], prefix: u8) -> Self { |
993 | 0 | CidrSubnet::V4(addr, mask!(u32, prefix)) |
994 | 0 | } |
995 | | /// Obtains the CidrSubnet from an IPv6 address in network byte order |
996 | | /// as well as the specified prefix. |
997 | 0 | pub fn from_v6_prefix(addr: [u8; 16], prefix: u8) -> Self { |
998 | 0 | CidrSubnet::V6(addr, mask!(u128, prefix)) |
999 | 0 | } |
1000 | 0 | fn to_bytes(self) -> Vec<u8> { |
1001 | 0 | let mut res = Vec::new(); |
1002 | 0 | match self { |
1003 | 0 | CidrSubnet::V4(addr, mask) => { |
1004 | 0 | res.extend_from_slice(&addr); |
1005 | 0 | res.extend_from_slice(&mask); |
1006 | 0 | }, |
1007 | 0 | CidrSubnet::V6(addr, mask) => { |
1008 | 0 | res.extend_from_slice(&addr); |
1009 | 0 | res.extend_from_slice(&mask); |
1010 | 0 | }, |
1011 | | } |
1012 | 0 | res |
1013 | 0 | } |
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 | | /// ``` |
1026 | | impl FromStr for CidrSubnet { |
1027 | | type Err = (); |
1028 | | |
1029 | 0 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
1030 | 0 | let mut iter = s.split('/'); |
1031 | 0 | if let (Some(addr_s), Some(prefix_s)) = (iter.next(), iter.next()) { |
1032 | 0 | let addr = IpAddr::from_str(addr_s).map_err(|_| ())?; |
1033 | 0 | let prefix = u8::from_str(prefix_s).map_err(|_| ())?; |
1034 | 0 | Ok(Self::from_addr_prefix(addr, prefix)) |
1035 | | } else { |
1036 | 0 | Err(()) |
1037 | | } |
1038 | 0 | } |
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`]. |
1049 | 0 | pub fn date_time_ymd(year: i32, month: u8, day: u8) -> OffsetDateTime { |
1050 | 0 | let month = Month::try_from(month).expect("out-of-range month"); |
1051 | 0 | let primitive_dt = PrimitiveDateTime::new( |
1052 | 0 | Date::from_calendar_date(year, month, day).expect("invalid or out-of-range date"), |
1053 | | Time::MIDNIGHT, |
1054 | | ); |
1055 | 0 | primitive_dt.assume_utc() |
1056 | 0 | } |
1057 | | |
1058 | | /// Whether the certificate is allowed to sign other certificates |
1059 | | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
1060 | | pub 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 | | |
1069 | | impl 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)] |
1103 | | pub enum BasicConstraints { |
1104 | | /// No constraint |
1105 | | Unconstrained, |
1106 | | /// Constrain to the contained number of intermediate certificates |
1107 | | Constrained(u8), |
1108 | | } |
1109 | | |
1110 | | #[cfg(test)] |
1111 | | mod 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----- |
1364 | | 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 |
1391 | | Ng== |
1392 | | -----END CERTIFICATE-----"#; |
1393 | | |
1394 | | let ca_key = r#"-----BEGIN PRIVATE KEY----- |
1395 | | MIIJQQIBADANBgkqhkiG9w0BAQEFAASCCSswggknAgEAAoICAQCl8mbL+2cHpPcn |
1396 | | OeCF1owpDMFOHgzM/VMNOlhExYWbWrsA6OLrAnmCWv+8fEWWxnCPfbP7zjB4yHVc |
1397 | | 2OoPaeXOqkvuxFAYVwEWFQe+M11BsIFRrLO5YMPtHTcYUPBdDNrJgV1D/RZSSYya |
1398 | | W1nlPvd4spxsvj01xbWDJzqFSOBu2CrBuZV9MwSVDWGbJRM+iqfHkWLuxQHXHFNL |
1399 | | uW5oNNmtVolzmCXjdfgIn1G0TczSJ2QqjAhYKB3M29A7ylN0F/8a3AcX6/0jST6s |
1400 | | ZXnFL7KM7XlKABQFBdbk8R99anFZgh3/SNK+iSaBsbPlzFWx9kiS3bKv/s6Y3h8+ |
1401 | | oMtM+GkTAaWlFlEPaRBDXkqteT1wrl98j09gSCN9Ji/OjljuqoJrO9IgC2pOsWf8 |
1402 | | QE+0U9thNWzhflybIlDNzoBhdEz5g3KWnxDB+JMM3Wgu1OYaoWJPSNpX0zBIIVfO |
1403 | | pFFwpRMbhxEA+BmS3HdRzA/1oKjmTuMv7f8swTzatNRaXopRaYf7Vuqca9V+yZaM |
1404 | | 9f8iLjRStKF0wduCf01Ivv0tQZGrzgYN3jRxw1w4xEirZ1fosKNXBbei1Qq5yoSi |
1405 | | epvefnPmCkBiK3MJEfdTsWfWUwxM8krDw6Vq7XmX9ytVQNFLeNWkyrvKWMMbJ1XT |
1406 | | ogRmiZDof5a3ryOlPRIOL1aveIcgGQIDAQABAoICACVWAWzZdlfQ9M59hhd2qvg9 |
1407 | | Z2yE9EpWoI30V5G5gxLt+e79drh7SQ1cHfexWhLPONn/5TO9M0ipiUZHg3nOUKcL |
1408 | | x6PDxWWEhbkLKD/R3KR/6siOe600qUA6939gDoRQ9RSrJ2m5koEXDSxZa0NZxGIC |
1409 | | hZEtyCXGAs2sUM1WFTC7L/uAHrMZfGlwpko6sDa9CXysKD8iUgSs2czKvp1xbpxC |
1410 | | QRCh5bxkeVavSbmwW2nY9P9hnCsBc5r4xcP+BIK1N286m9n0/XIn85LkDd6gmaJ9 |
1411 | | d3F/zQFITA4cdgJIpZIG5WrfXpMB1okNizUjoRA2IiPw/1f7k03vg8YadUMvDKye |
1412 | | FOYsHePLYkq8COfGJaPq0b3ekkiS5CO/Aeo0rFVlDj9003N6IJ67oAHHPLpALNLR |
1413 | | RCJpztcGbfZHc1tLKvUnK56IL1FCbCm0SpsuNtTXXPd14i15ei4BkVUkANsEKOAR |
1414 | | BHlA/rn2As2lntZ/oJ07Torj2cKpn7uKw65ajtM7wAoVW1oL0qDyhGi/JGuL9zlg |
1415 | | CB7jVaPqzlo+bxWyCmfHW3erR0Y3QIMTBNMUZU/NKba3HjSVDadZK563mbfgWw0W |
1416 | | qP17gfM5tOFUVulAnMTjsmmjqoUZs9irku0bd1J+CfzF4Z56qFoiolBTUD8RdSSm |
1417 | | sXJytHZj3ajH8D3e3SDFAoIBAQDc6td5UqAc+KGrpW3+y6R6+PM8T6NySCu3jvF+ |
1418 | | WMt5O7lsKCXUbVRo6w07bUN+4nObJOi41uR6nC8bdKhsuex97h7tpmtN3yGM6I9m |
1419 | | zFulfkRafaVTS8CH7l0nTBkd7wfdUX0bjznxB1xVDPFoPC3ybRXoub4he9MLlHQ9 |
1420 | | JPiIXGxJQI3CTYQRXwKTtovBV70VSzuaZERAgta0uH1yS6Rqk3lAyWrAKifPnG2I |
1421 | | kSOC/ZTxX0sEliJ5xROvRoBVsWG2W/fDRRwavzJVWnNAR1op+gbVNKFrKuGnYsEF |
1422 | | 5AfeF2tEnCHa+E6Vzo4lNOKkNSSVPQGbp8MVE43PU3EPW2BDAoIBAQDATMtWrW0R |
1423 | | 9qRiHDtYZAvFk1pJHhDzSjtPhZoNk+/8WJ7VXDnV9/raEkXktE1LQdSeER0uKFgz |
1424 | | vwZTLh74FVQQWu0HEFgy/Fm6S8ogO4xsRvS+zAhKUfPsjT+aHo0JaJUmPYW+6+d2 |
1425 | | +nXC6MNrA9tzZnSJzM+H8bE1QF2cPriEDdImYUUAbsYlPjPyfOd2qF8ehVg5UmoT |
1426 | | fFnkvmQO0Oi/vR1GMXtT2I92TEOLMJq836COhYYPyYkU7/boxYRRt7XL6cK3xpwv |
1427 | | 51zNeQ4COR/8DGDydzuAunzjiiJUcPRFpPvf171AVZNg/ow+UMRvWLUtl076n5Pi |
1428 | | Kf+7IIlXtHZzAoIBAD4ZLVSHK0a5hQhwygiTSbrfe8/6OuGG8/L3FV8Eqr17UlXa |
1429 | | uzeJO+76E5Ae2Jg0I3b62wgKL9NfT8aR9j4JzTZg1wTKgOM004N+Y8DrtN9CLQia |
1430 | | xPwzEP2kvT6sn2rQpA9MNrSmgA0Gmqe1qa45LFk23K+8dnuHCP36TupZGBuMj0vP |
1431 | | /4kcrQENCfZnm8VPWnE/4pM1mBHiNWQ7b9fO93qV1cGmXIGD2Aj92bRHyAmsKk/n |
1432 | | D3lMkohUI4JjePOdlu/hzjVvmcTS9d0UPc1VwTyHcaBA2Rb8yM16bvOu8580SgzR |
1433 | | LpsUrVJi64X95a9u2MeyjF8quyWTh4s900wTzW0CggEAJrGNHMTKtJmfXAp4OoHv |
1434 | | CHNs8Fd3a6zdIFQuulqxKGKgmyfyj0ZVmHmizLEm+GSnpqKk73u4u7jNSgF2w85u |
1435 | | 2teg6BH23VN/roe/hRrWV5czegzOAj5ZSZjmWlmZYXJEyKwKdG89ZOhit7RkVe0x |
1436 | | xBeyjWPDwoP0d1WbQGwyboflaEmcO8kOX8ITa9CMNokMkrScGvSlWYRlBiz1LzIE |
1437 | | E0i3Uj90pFtoCpKv6JsAF88bnHHrltOjnK3oTdAontTLZNuFjbsOBGmWd9XK5tGd |
1438 | | yPaor0EknPNpW9OYsssDq9vVvqXHc+GERTkS+RsBW7JKyoCuqKlhdVmkFoAmgppS |
1439 | | VwKCAQB7nOsjguXliXXpayr1ojg1T5gk+R+JJMbOw7fuhexavVLi2I/yGqAq9gfQ |
1440 | | KoumYrd8EYb0WddqK0rdfjZyPmiqCNr72w3QKiEDx8o3FHUajSL1+eXpJJ03shee |
1441 | | BqN6QWlRz8fu7MAZ0oqv06Cln+3MZRUvc6vtMHAEzD7y65HV+Do7z61YmvwVZ2N2 |
1442 | | +30kckNnDVdggOklBmlSk5duej+RVoAKP8U5wV3Z/bS5J0OI75fxhuzybPcVfkwE |
1443 | | JiY98T5oN1X0C/qAXxJfSvklbru9fipwGt3dho5Tm6Ee3cYf+plnk4WZhSnqyef4 |
1444 | | PITGdT9dgN88nHPCle0B1+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 | | } |