forked from rustls/rcgen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcertificate.rs
More file actions
1532 lines (1414 loc) · 49.5 KB
/
certificate.rs
File metadata and controls
1532 lines (1414 loc) · 49.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::net::IpAddr;
use std::str::FromStr;
#[cfg(feature = "pem")]
use pem::Pem;
use pki_types::{CertificateDer, CertificateSigningRequestDer};
use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time};
use yasna::models::ObjectIdentifier;
use yasna::{DERWriter, Tag};
use crate::crl::CrlDistributionPoint;
use crate::csr::CertificateSigningRequest;
use crate::key_pair::{serialize_public_key_der, PublicKeyData};
#[cfg(feature = "crypto")]
use crate::ring_like::digest;
#[cfg(feature = "pem")]
use crate::ENCODE_CONFIG;
use crate::{
oid, write_distinguished_name, write_dt_utc_or_generalized,
write_x509_authority_key_identifier, write_x509_extension, DistinguishedName, Error, Issuer,
KeyIdMethod, KeyPair, KeyUsagePurpose, SanType, SerialNumber,
};
/// An issued certificate together with the parameters used to generate it.
#[derive(Debug, Clone)]
pub struct Certificate {
pub(crate) params: CertificateParams,
pub(crate) subject_public_key_info: Vec<u8>,
pub(crate) der: CertificateDer<'static>,
}
impl Certificate {
/// Returns the certificate parameters
pub fn params(&self) -> &CertificateParams {
&self.params
}
/// Calculates a subject key identifier for the certificate subject's public key.
/// This key identifier is used in the SubjectKeyIdentifier X.509v3 extension.
pub fn key_identifier(&self) -> Vec<u8> {
self.params
.key_identifier_method
.derive(&self.subject_public_key_info)
}
/// Get the certificate in DER encoded format.
///
/// [`CertificateDer`] implements `Deref<Target = [u8]>` and `AsRef<[u8]>`, so you can easily
/// extract the DER bytes from the return value.
pub fn der(&self) -> &CertificateDer<'static> {
&self.der
}
/// Get the certificate in PEM encoded format.
#[cfg(feature = "pem")]
pub fn pem(&self) -> String {
pem::encode_config(&Pem::new("CERTIFICATE", self.der().to_vec()), ENCODE_CONFIG)
}
}
impl From<Certificate> for CertificateDer<'static> {
fn from(cert: Certificate) -> Self {
cert.der
}
}
impl AsRef<CertificateParams> for Certificate {
fn as_ref(&self) -> &CertificateParams {
&self.params
}
}
/// Parameters used for certificate generation
#[allow(missing_docs)]
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct CertificateParams {
pub not_before: OffsetDateTime,
pub not_after: OffsetDateTime,
pub serial_number: Option<SerialNumber>,
pub subject_alt_names: Vec<SanType>,
pub distinguished_name: DistinguishedName,
pub is_ca: IsCa,
pub key_usages: Vec<KeyUsagePurpose>,
pub extended_key_usages: Vec<ExtendedKeyUsagePurpose>,
pub name_constraints: Option<NameConstraints>,
/// An optional list of certificate revocation list (CRL) distribution points as described
/// in RFC 5280 Section 4.2.1.13[^1]. Each distribution point contains one or more URIs where
/// an up-to-date CRL with scope including this certificate can be retrieved.
///
/// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.13>
pub crl_distribution_points: Vec<CrlDistributionPoint>,
pub custom_extensions: Vec<CustomExtension>,
/// If `true`, the 'Authority Key Identifier' extension will be added to the generated cert
pub use_authority_key_identifier_extension: bool,
/// Method to generate key identifiers from public keys
///
/// Defaults to a truncated SHA-256 digest. See [`KeyIdMethod`] for more information.
pub key_identifier_method: KeyIdMethod,
}
impl Default for CertificateParams {
fn default() -> Self {
// not_before and not_after set to reasonably long dates
let not_before = date_time_ymd(1975, 01, 01);
let not_after = date_time_ymd(4096, 01, 01);
let mut distinguished_name = DistinguishedName::new();
distinguished_name.push(DnType::CommonName, "rcgen self signed cert");
CertificateParams {
not_before,
not_after,
serial_number: None,
subject_alt_names: Vec::new(),
distinguished_name,
is_ca: IsCa::NoCa,
key_usages: Vec::new(),
extended_key_usages: Vec::new(),
name_constraints: None,
crl_distribution_points: Vec::new(),
custom_extensions: Vec::new(),
use_authority_key_identifier_extension: false,
#[cfg(feature = "crypto")]
key_identifier_method: KeyIdMethod::Sha256,
#[cfg(not(feature = "crypto"))]
key_identifier_method: KeyIdMethod::PreSpecified(Vec::new()),
}
}
}
impl CertificateParams {
/// Generate certificate parameters with reasonable defaults
pub fn new(subject_alt_names: impl Into<Vec<String>>) -> Result<Self, Error> {
let subject_alt_names = subject_alt_names
.into()
.into_iter()
.map(|s| {
Ok(match IpAddr::from_str(&s) {
Ok(ip) => SanType::IpAddress(ip),
Err(_) => SanType::DnsName(s.try_into()?),
})
})
.collect::<Result<Vec<_>, _>>()?;
Ok(CertificateParams {
subject_alt_names,
..Default::default()
})
}
/// Generate a new certificate from the given parameters, signed by the provided issuer.
///
/// The returned certificate will have its issuer field set to the subject of the
/// provided `issuer`, and the authority key identifier extension will be populated using
/// the subject public key of `issuer` (typically either a [`CertificateParams`] or
/// [`Certificate`]). It will be signed by `issuer_key`.
///
/// Note that no validation of the `issuer` certificate is performed. Rcgen will not require
/// the certificate to be a CA certificate, or have key usage extensions that allow signing.
///
/// The returned [`Certificate`] may be serialized using [`Certificate::der`] and
/// [`Certificate::pem`].
pub fn signed_by(
self,
public_key: &impl PublicKeyData,
issuer: &impl AsRef<CertificateParams>,
issuer_key: &KeyPair,
) -> Result<Certificate, Error> {
let issuer = Issuer {
distinguished_name: &issuer.as_ref().distinguished_name,
key_identifier_method: &issuer.as_ref().key_identifier_method,
key_usages: &issuer.as_ref().key_usages,
key_pair: issuer_key,
};
let subject_public_key_info =
yasna::construct_der(|writer| serialize_public_key_der(public_key, writer));
let der = self.serialize_der_with_signer(public_key, issuer)?;
Ok(Certificate {
params: self,
subject_public_key_info,
der,
})
}
/// Generates a new self-signed certificate from the given parameters.
///
/// The returned [`Certificate`] may be serialized using [`Certificate::der`] and
/// [`Certificate::pem`].
pub fn self_signed(self, key_pair: &KeyPair) -> Result<Certificate, Error> {
let issuer = Issuer {
distinguished_name: &self.distinguished_name,
key_identifier_method: &self.key_identifier_method,
key_usages: &self.key_usages,
key_pair,
};
let subject_public_key_info = key_pair.public_key_der();
let der = self.serialize_der_with_signer(key_pair, issuer)?;
Ok(Certificate {
params: self,
subject_public_key_info,
der,
})
}
/// Parses an existing ca certificate from the ASCII PEM format.
///
/// See [`from_ca_cert_der`](Self::from_ca_cert_der) for more details.
#[cfg(all(feature = "pem", feature = "x509-parser"))]
pub fn from_ca_cert_pem(pem_str: &str) -> Result<Self, Error> {
let certificate = pem::parse(pem_str).or(Err(Error::CouldNotParseCertificate))?;
Self::from_ca_cert_der(&certificate.contents().into())
}
/// Parses an existing ca certificate from the DER format.
///
/// This function is only of use if you have an existing CA certificate
/// you would like to use to sign a certificate generated by `rcgen`.
/// By providing the constructed [`CertificateParams`] and the [`KeyPair`]
/// associated with your existing `ca_cert` you can use [`CertificateParams::signed_by()`]
/// or [`crate::CertificateSigningRequestParams::signed_by()`] to issue new certificates
/// using the CA cert.
///
/// In general this function only extracts the information needed for signing.
/// Other attributes of the [`Certificate`] may be left as defaults.
///
/// This function assumes the provided certificate is a CA. It will not check
/// for the presence of the `BasicConstraints` extension, or perform any other
/// validation.
///
/// [`rustls_pemfile::certs()`] is often used to obtain a [`CertificateDer`] from PEM input.
/// If you already have a byte slice containing DER, it can trivially be converted into
/// [`CertificateDer`] using the [`Into`] trait.
///
/// [`rustls_pemfile::certs()`]: https://docs.rs/rustls-pemfile/latest/rustls_pemfile/fn.certs.html
#[cfg(feature = "x509-parser")]
pub fn from_ca_cert_der(ca_cert: &CertificateDer<'_>) -> Result<Self, Error> {
let (_remainder, x509) = x509_parser::parse_x509_certificate(ca_cert)
.or(Err(Error::CouldNotParseCertificate))?;
let dn = DistinguishedName::from_name(&x509.tbs_certificate.subject)?;
let is_ca = Self::convert_x509_is_ca(&x509)?;
let validity = x509.validity();
let subject_alt_names = Self::convert_x509_subject_alternative_name(&x509)?;
let key_usages = Self::convert_x509_key_usages(&x509)?;
let extended_key_usages = Self::convert_x509_extended_key_usages(&x509)?;
let name_constraints = Self::convert_x509_name_constraints(&x509)?;
let serial_number = Some(x509.serial.to_bytes_be().into());
let key_identifier_method =
x509.iter_extensions()
.find_map(|ext| match ext.parsed_extension() {
x509_parser::extensions::ParsedExtension::SubjectKeyIdentifier(key_id) => {
Some(KeyIdMethod::PreSpecified(key_id.0.into()))
},
_ => None,
});
let key_identifier_method = match key_identifier_method {
Some(method) => method,
None => {
#[cfg(not(feature = "crypto"))]
return Err(Error::UnsupportedSignatureAlgorithm);
#[cfg(feature = "crypto")]
KeyIdMethod::Sha256
},
};
Ok(CertificateParams {
is_ca,
subject_alt_names,
key_usages,
extended_key_usages,
name_constraints,
serial_number,
key_identifier_method,
distinguished_name: dn,
not_before: validity.not_before.to_datetime(),
not_after: validity.not_after.to_datetime(),
..Default::default()
})
}
#[cfg(feature = "x509-parser")]
fn convert_x509_is_ca(
x509: &x509_parser::certificate::X509Certificate<'_>,
) -> Result<IsCa, Error> {
use x509_parser::extensions::BasicConstraints as B;
let basic_constraints = x509
.basic_constraints()
.or(Err(Error::CouldNotParseCertificate))?
.map(|ext| ext.value);
let is_ca = match basic_constraints {
Some(B {
ca: true,
path_len_constraint: Some(n),
}) if *n <= u8::MAX as u32 => IsCa::Ca(BasicConstraints::Constrained(*n as u8)),
Some(B {
ca: true,
path_len_constraint: Some(_),
}) => return Err(Error::CouldNotParseCertificate),
Some(B {
ca: true,
path_len_constraint: None,
}) => IsCa::Ca(BasicConstraints::Unconstrained),
Some(B { ca: false, .. }) => IsCa::ExplicitNoCa,
None => IsCa::NoCa,
};
Ok(is_ca)
}
#[cfg(feature = "x509-parser")]
fn convert_x509_subject_alternative_name(
x509: &x509_parser::certificate::X509Certificate<'_>,
) -> Result<Vec<SanType>, Error> {
let sans = x509
.subject_alternative_name()
.or(Err(Error::CouldNotParseCertificate))?
.map(|ext| &ext.value.general_names);
if let Some(sans) = sans {
let mut subject_alt_names = Vec::with_capacity(sans.len());
for san in sans {
subject_alt_names.push(SanType::try_from_general(san)?);
}
Ok(subject_alt_names)
} else {
Ok(Vec::new())
}
}
#[cfg(feature = "x509-parser")]
fn convert_x509_key_usages(
x509: &x509_parser::certificate::X509Certificate<'_>,
) -> Result<Vec<KeyUsagePurpose>, Error> {
let key_usage = x509
.key_usage()
.or(Err(Error::CouldNotParseCertificate))?
.map(|ext| ext.value);
// This x509 parser stores flags in reversed bit BIT STRING order
let flags = key_usage.map_or(0u16, |k| k.flags).reverse_bits();
Ok(KeyUsagePurpose::from_u16(flags))
}
#[cfg(feature = "x509-parser")]
fn convert_x509_extended_key_usages(
x509: &x509_parser::certificate::X509Certificate<'_>,
) -> Result<Vec<ExtendedKeyUsagePurpose>, Error> {
let extended_key_usage = x509
.extended_key_usage()
.or(Err(Error::CouldNotParseCertificate))?
.map(|ext| ext.value);
let mut extended_key_usages = Vec::new();
if let Some(extended_key_usage) = extended_key_usage {
if extended_key_usage.any {
extended_key_usages.push(ExtendedKeyUsagePurpose::Any);
}
if extended_key_usage.server_auth {
extended_key_usages.push(ExtendedKeyUsagePurpose::ServerAuth);
}
if extended_key_usage.client_auth {
extended_key_usages.push(ExtendedKeyUsagePurpose::ClientAuth);
}
if extended_key_usage.code_signing {
extended_key_usages.push(ExtendedKeyUsagePurpose::CodeSigning);
}
if extended_key_usage.email_protection {
extended_key_usages.push(ExtendedKeyUsagePurpose::EmailProtection);
}
if extended_key_usage.time_stamping {
extended_key_usages.push(ExtendedKeyUsagePurpose::TimeStamping);
}
if extended_key_usage.ocsp_signing {
extended_key_usages.push(ExtendedKeyUsagePurpose::OcspSigning);
}
}
Ok(extended_key_usages)
}
#[cfg(feature = "x509-parser")]
fn convert_x509_name_constraints(
x509: &x509_parser::certificate::X509Certificate<'_>,
) -> Result<Option<NameConstraints>, Error> {
let constraints = x509
.name_constraints()
.or(Err(Error::CouldNotParseCertificate))?
.map(|ext| ext.value);
if let Some(constraints) = constraints {
let permitted_subtrees = if let Some(permitted) = &constraints.permitted_subtrees {
Self::convert_x509_general_subtrees(permitted)?
} else {
Vec::new()
};
let excluded_subtrees = if let Some(excluded) = &constraints.excluded_subtrees {
Self::convert_x509_general_subtrees(excluded)?
} else {
Vec::new()
};
let name_constraints = NameConstraints {
permitted_subtrees,
excluded_subtrees,
};
Ok(Some(name_constraints))
} else {
Ok(None)
}
}
#[cfg(feature = "x509-parser")]
fn convert_x509_general_subtrees(
subtrees: &[x509_parser::extensions::GeneralSubtree<'_>],
) -> Result<Vec<GeneralSubtree>, Error> {
use x509_parser::extensions::GeneralName;
let mut result = Vec::new();
for subtree in subtrees {
let subtree = match &subtree.base {
GeneralName::RFC822Name(s) => GeneralSubtree::Rfc822Name(s.to_string()),
GeneralName::DNSName(s) => GeneralSubtree::DnsName(s.to_string()),
GeneralName::DirectoryName(n) => {
GeneralSubtree::DirectoryName(DistinguishedName::from_name(n)?)
},
GeneralName::IPAddress(bytes) if bytes.len() == 8 => {
let addr: [u8; 4] = bytes[..4].try_into().unwrap();
let mask: [u8; 4] = bytes[4..].try_into().unwrap();
GeneralSubtree::IpAddress(CidrSubnet::V4(addr, mask))
},
GeneralName::IPAddress(bytes) if bytes.len() == 32 => {
let addr: [u8; 16] = bytes[..16].try_into().unwrap();
let mask: [u8; 16] = bytes[16..].try_into().unwrap();
GeneralSubtree::IpAddress(CidrSubnet::V6(addr, mask))
},
_ => continue,
};
result.push(subtree);
}
Ok(result)
}
/// Write a CSR extension request attribute as defined in [RFC 2985].
///
/// [RFC 2985]: <https://datatracker.ietf.org/doc/html/rfc2985>
fn write_extension_request_attribute(&self, writer: DERWriter) {
writer.write_sequence(|writer| {
writer.next().write_oid(&ObjectIdentifier::from_slice(
oid::PKCS_9_AT_EXTENSION_REQUEST,
));
writer.next().write_set(|writer| {
writer.next().write_sequence(|writer| {
// Write key_usage
self.write_key_usage(writer.next());
// Write subject_alt_names
self.write_subject_alt_names(writer.next());
self.write_extended_key_usage(writer.next());
// Write custom extensions
for ext in &self.custom_extensions {
write_x509_extension(writer.next(), &ext.oid, ext.critical, |writer| {
writer.write_der(ext.content())
});
}
});
});
});
}
/// Write a certificate's KeyUsage as defined in RFC 5280.
fn write_key_usage(&self, writer: DERWriter) {
// RFC 5280 defines 9 key usages, which we detail in our key usage enum
// We could use std::mem::variant_count here, but it's experimental
const KEY_USAGE_BITS: usize = 9;
if self.key_usages.is_empty() {
return;
}
// "When present, conforming CAs SHOULD mark this extension as critical."
write_x509_extension(writer, oid::KEY_USAGE, true, |writer| {
// u16 is large enough to encode the largest possible key usage (two-bytes)
let bit_string = self.key_usages.iter().fold(0u16, |bit_string, key_usage| {
bit_string | key_usage.to_u16()
});
writer.write_bitvec_bytes(&bit_string.to_be_bytes(), KEY_USAGE_BITS);
});
}
fn write_extended_key_usage(&self, writer: DERWriter) {
if !self.extended_key_usages.is_empty() {
write_x509_extension(writer, oid::EXT_KEY_USAGE, false, |writer| {
writer.write_sequence(|writer| {
for usage in &self.extended_key_usages {
writer
.next()
.write_oid(&ObjectIdentifier::from_slice(usage.oid()));
}
});
});
}
}
fn write_subject_alt_names(&self, writer: DERWriter) {
if self.subject_alt_names.is_empty() {
return;
}
// Per https://tools.ietf.org/html/rfc5280#section-4.1.2.6, SAN must be marked
// as critical if subject is empty.
let critical = self.distinguished_name.entries.is_empty();
write_x509_extension(writer, oid::SUBJECT_ALT_NAME, critical, |writer| {
writer.write_sequence(|writer| {
for san in self.subject_alt_names.iter() {
writer.next().write_tagged_implicit(
Tag::context(san.tag()),
|writer| match san {
SanType::Rfc822Name(name)
| SanType::DnsName(name)
| SanType::URI(name) => writer.write_ia5_string(name.as_str()),
SanType::IpAddress(IpAddr::V4(addr)) => {
writer.write_bytes(&addr.octets())
},
SanType::IpAddress(IpAddr::V6(addr)) => {
writer.write_bytes(&addr.octets())
},
SanType::OtherName((oid, value)) => {
// otherName SEQUENCE { OID, [0] explicit any defined by oid }
// https://datatracker.ietf.org/doc/html/rfc5280#page-38
writer.write_sequence(|writer| {
writer.next().write_oid(&ObjectIdentifier::from_slice(oid));
value.write_der(writer.next());
});
},
},
);
}
});
});
}
/// Generate and serialize a certificate signing request (CSR).
///
/// The constructed CSR will contain attributes based on the certificate parameters,
/// and include the subject public key information from `subject_key`. Additionally,
/// the CSR will be signed using the subject key.
///
/// Note that subsequent invocations of `serialize_request()` will not produce the exact
/// same output.
pub fn serialize_request(
&self,
subject_key: &KeyPair,
) -> Result<CertificateSigningRequest, Error> {
self.serialize_request_with_attributes(subject_key, Vec::new())
}
/// Generate and serialize a certificate signing request (CSR) with custom PKCS #10 attributes.
/// as defined in [RFC 2986].
///
/// The constructed CSR will contain attributes based on the certificate parameters,
/// and include the subject public key information from `subject_key`. Additionally,
/// the CSR will be self-signed using the subject key.
///
/// Note that subsequent invocations of `serialize_request_with_attributes()` will not produce the exact
/// same output.
///
/// [RFC 2986]: <https://datatracker.ietf.org/doc/html/rfc2986#section-4>
pub fn serialize_request_with_attributes(
&self,
subject_key: &KeyPair,
attrs: Vec<Attribute>,
) -> Result<CertificateSigningRequest, Error> {
// No .. pattern, we use this to ensure every field is used
#[deny(unused)]
let Self {
not_before,
not_after,
serial_number,
subject_alt_names,
distinguished_name,
is_ca,
key_usages,
extended_key_usages,
name_constraints,
crl_distribution_points,
custom_extensions,
use_authority_key_identifier_extension,
key_identifier_method,
} = self;
// - alg and key_pair will be used by the caller
// - not_before and not_after cannot be put in a CSR
// - key_identifier_method is here because self.write_extended_key_usage uses it
// - There might be a use case for specifying the key identifier
// in the CSR, but in the current API it can't be distinguished
// from the defaults so this is left for a later version if
// needed.
let _ = (
not_before,
not_after,
key_identifier_method,
extended_key_usages,
);
if serial_number.is_some()
|| *is_ca != IsCa::NoCa
|| name_constraints.is_some()
|| !crl_distribution_points.is_empty()
|| *use_authority_key_identifier_extension
{
return Err(Error::UnsupportedInCsr);
}
// Whether or not to write an extension request attribute
let write_extension_request = !key_usages.is_empty()
|| !subject_alt_names.is_empty()
|| !extended_key_usages.is_empty()
|| !custom_extensions.is_empty();
let der = subject_key.sign_der(|writer| {
// Write version
writer.next().write_u8(0);
write_distinguished_name(writer.next(), distinguished_name);
serialize_public_key_der(subject_key, writer.next());
// According to the spec in RFC 2986, even if attributes are empty we need the empty attribute tag
writer
.next()
.write_tagged_implicit(Tag::context(0), |writer| {
// RFC 2986 specifies that attributes are a SET OF Attribute
writer.write_set_of(|writer| {
if write_extension_request {
self.write_extension_request_attribute(writer.next());
}
for Attribute { oid, values } in attrs {
writer.next().write_sequence(|writer| {
writer.next().write_oid(&ObjectIdentifier::from_slice(&oid));
writer.next().write_der(&values);
});
}
});
});
Ok(())
})?;
Ok(CertificateSigningRequest {
der: CertificateSigningRequestDer::from(der),
})
}
pub(crate) fn serialize_der_with_signer<K: PublicKeyData>(
&self,
pub_key: &K,
issuer: Issuer<'_>,
) -> Result<CertificateDer<'static>, Error> {
let der = issuer.key_pair.sign_der(|writer| {
let pub_key_spki =
yasna::construct_der(|writer| serialize_public_key_der(pub_key, writer));
// Write version
writer.next().write_tagged(Tag::context(0), |writer| {
writer.write_u8(2);
});
// Write serialNumber
if let Some(ref serial) = self.serial_number {
writer.next().write_bigint_bytes(serial.as_ref(), true);
} else {
#[cfg(feature = "crypto")]
{
let hash = digest::digest(&digest::SHA256, pub_key.der_bytes());
// RFC 5280 specifies at most 20 bytes for a serial number
let mut sl = hash.as_ref()[0..20].to_vec();
sl[0] &= 0x7f; // MSB must be 0 to ensure encoding bignum in 20 bytes
writer.next().write_bigint_bytes(&sl, true);
}
#[cfg(not(feature = "crypto"))]
if self.serial_number.is_none() {
return Err(Error::MissingSerialNumber);
}
};
// Write signature algorithm
issuer.key_pair.alg.write_alg_ident(writer.next());
// Write issuer name
write_distinguished_name(writer.next(), &issuer.distinguished_name);
// Write validity
writer.next().write_sequence(|writer| {
// Not before
write_dt_utc_or_generalized(writer.next(), self.not_before);
// Not after
write_dt_utc_or_generalized(writer.next(), self.not_after);
Ok::<(), Error>(())
})?;
// Write subject
write_distinguished_name(writer.next(), &self.distinguished_name);
// Write subjectPublicKeyInfo
serialize_public_key_der(pub_key, writer.next());
// write extensions
let should_write_exts = self.use_authority_key_identifier_extension
|| !self.subject_alt_names.is_empty()
|| !self.extended_key_usages.is_empty()
|| self.name_constraints.iter().any(|c| !c.is_empty())
|| matches!(self.is_ca, IsCa::ExplicitNoCa)
|| matches!(self.is_ca, IsCa::Ca(_))
|| !self.custom_extensions.is_empty();
if !should_write_exts {
return Ok(());
}
writer.next().write_tagged(Tag::context(3), |writer| {
writer.write_sequence(|writer| {
if self.use_authority_key_identifier_extension {
write_x509_authority_key_identifier(
writer.next(),
match issuer.key_identifier_method {
KeyIdMethod::PreSpecified(aki) => aki.clone(),
#[cfg(feature = "crypto")]
_ => issuer
.key_identifier_method
.derive(issuer.key_pair.public_key_der()),
},
);
}
// Write subject_alt_names
if !self.subject_alt_names.is_empty() {
self.write_subject_alt_names(writer.next());
}
// Write standard key usage
self.write_key_usage(writer.next());
// Write extended key usage
if !self.extended_key_usages.is_empty() {
write_x509_extension(writer.next(), oid::EXT_KEY_USAGE, false, |writer| {
writer.write_sequence(|writer| {
for usage in self.extended_key_usages.iter() {
let oid = ObjectIdentifier::from_slice(usage.oid());
writer.next().write_oid(&oid);
}
});
});
}
if let Some(name_constraints) = &self.name_constraints {
// If both trees are empty, the extension must be omitted.
if !name_constraints.is_empty() {
write_x509_extension(
writer.next(),
oid::NAME_CONSTRAINTS,
true,
|writer| {
writer.write_sequence(|writer| {
if !name_constraints.permitted_subtrees.is_empty() {
write_general_subtrees(
writer.next(),
0,
&name_constraints.permitted_subtrees,
);
}
if !name_constraints.excluded_subtrees.is_empty() {
write_general_subtrees(
writer.next(),
1,
&name_constraints.excluded_subtrees,
);
}
});
},
);
}
}
if !self.crl_distribution_points.is_empty() {
write_x509_extension(
writer.next(),
oid::CRL_DISTRIBUTION_POINTS,
false,
|writer| {
writer.write_sequence(|writer| {
for distribution_point in &self.crl_distribution_points {
distribution_point.write_der(writer.next());
}
})
},
);
}
match self.is_ca {
IsCa::Ca(ref constraint) => {
// Write subject_key_identifier
write_x509_extension(
writer.next(),
oid::SUBJECT_KEY_IDENTIFIER,
false,
|writer| {
writer.write_bytes(
&self.key_identifier_method.derive(pub_key_spki),
);
},
);
// Write basic_constraints
write_x509_extension(
writer.next(),
oid::BASIC_CONSTRAINTS,
true,
|writer| {
writer.write_sequence(|writer| {
writer.next().write_bool(true); // cA flag
if let BasicConstraints::Constrained(path_len_constraint) =
constraint
{
writer.next().write_u8(*path_len_constraint);
}
});
},
);
},
IsCa::ExplicitNoCa => {
// Write subject_key_identifier
write_x509_extension(
writer.next(),
oid::SUBJECT_KEY_IDENTIFIER,
false,
|writer| {
writer.write_bytes(
&self.key_identifier_method.derive(pub_key_spki),
);
},
);
// Write basic_constraints
write_x509_extension(
writer.next(),
oid::BASIC_CONSTRAINTS,
true,
|writer| {
writer.write_sequence(|writer| {
writer.next().write_bool(false); // cA flag
});
},
);
},
IsCa::NoCa => {},
}
// Write the custom extensions
for ext in &self.custom_extensions {
write_x509_extension(writer.next(), &ext.oid, ext.critical, |writer| {
writer.write_der(ext.content())
});
}
});
});
Ok(())
})?;
Ok(der.into())
}
/// Insert an extended key usage (EKU) into the parameters if it does not already exist
pub fn insert_extended_key_usage(&mut self, eku: ExtendedKeyUsagePurpose) {
if !self.extended_key_usages.contains(&eku) {
self.extended_key_usages.push(eku);
}
}
}
impl AsRef<CertificateParams> for CertificateParams {
fn as_ref(&self) -> &CertificateParams {
self
}
}
fn write_general_subtrees(writer: DERWriter, tag: u64, general_subtrees: &[GeneralSubtree]) {
writer.write_tagged_implicit(Tag::context(tag), |writer| {
writer.write_sequence(|writer| {
for subtree in general_subtrees.iter() {
writer.next().write_sequence(|writer| {
writer
.next()
.write_tagged_implicit(
Tag::context(subtree.tag()),
|writer| match subtree {
GeneralSubtree::Rfc822Name(name)
| GeneralSubtree::DnsName(name) => writer.write_ia5_string(name),
GeneralSubtree::DirectoryName(name) => {
write_distinguished_name(writer, name)
},
GeneralSubtree::IpAddress(subnet) => {
writer.write_bytes(&subnet.to_bytes())
},
},
);
// minimum must be 0 (the default) and maximum must be absent
});
}
});
});
}
/// A PKCS #10 CSR attribute, as defined in [RFC 5280] and constrained
/// by [RFC 2986].
///
/// [RFC 5280]: <https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1>
/// [RFC 2986]: <https://datatracker.ietf.org/doc/html/rfc2986#section-4>
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct Attribute {
/// `AttributeType` of the `Attribute`, defined as an `OBJECT IDENTIFIER`.
pub oid: &'static [u64],
/// DER-encoded values of the `Attribute`, defined by [RFC 2986] as:
///
/// ```text
/// SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
/// ```
///
/// [RFC 2986]: https://datatracker.ietf.org/doc/html/rfc2986#section-4
pub values: Vec<u8>,
}
/// A custom extension of a certificate, as specified in
/// [RFC 5280](https://tools.ietf.org/html/rfc5280#section-4.2)
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct CustomExtension {
oid: Vec<u64>,
critical: bool,
/// The content must be DER-encoded
content: Vec<u8>,
}
impl CustomExtension {
/// Creates a new acmeIdentifier extension for ACME TLS-ALPN-01
/// as specified in [RFC 8737](https://tools.ietf.org/html/rfc8737#section-3)
///
/// Panics if the passed `sha_digest` parameter doesn't hold 32 bytes (256 bits).
pub fn new_acme_identifier(sha_digest: &[u8]) -> Self {
assert_eq!(sha_digest.len(), 32, "wrong size of sha_digest");
let content = yasna::construct_der(|writer| {
writer.write_bytes(sha_digest);
});
Self {
oid: oid::PE_ACME.to_owned(),
critical: true,
content,
}
}
/// Create a new custom extension with the specified content
pub fn from_oid_content(oid: &[u64], content: Vec<u8>) -> Self {
Self {
oid: oid.to_owned(),
critical: false,
content,
}
}
/// Sets the criticality flag of the extension.
pub fn set_criticality(&mut self, criticality: bool) {
self.critical = criticality;
}
/// Obtains the criticality flag of the extension.
pub fn criticality(&self) -> bool {
self.critical
}
/// Obtains the content of the extension.
pub fn content(&self) -> &[u8] {
&self.content
}
/// Obtains the OID components of the extensions, as u64 pieces
pub fn oid_components(&self) -> impl Iterator<Item = u64> + '_ {
self.oid.iter().copied()
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[non_exhaustive]
/// The attribute type of a distinguished name entry
pub enum DnType {
/// X520countryName
CountryName,
/// X520LocalityName
LocalityName,
/// X520StateOrProvinceName
StateOrProvinceName,
/// X520OrganizationName
OrganizationName,
/// X520OrganizationalUnitName
OrganizationalUnitName,
/// X520CommonName
CommonName,
/// Custom distinguished name type
CustomDnType(Vec<u64>),
}
impl DnType {
pub(crate) fn to_oid(&self) -> ObjectIdentifier {
let sl = match self {
DnType::CountryName => oid::COUNTRY_NAME,
DnType::LocalityName => oid::LOCALITY_NAME,
DnType::StateOrProvinceName => oid::STATE_OR_PROVINCE_NAME,
DnType::OrganizationName => oid::ORG_NAME,
DnType::OrganizationalUnitName => oid::ORG_UNIT_NAME,
DnType::CommonName => oid::COMMON_NAME,
DnType::CustomDnType(ref oid) => oid.as_slice(),
};
ObjectIdentifier::from_slice(sl)
}
/// Generate a DnType for the provided OID
pub fn from_oid(slice: &[u64]) -> Self {
match slice {
oid::COUNTRY_NAME => DnType::CountryName,
oid::LOCALITY_NAME => DnType::LocalityName,