forked from rustls/rcgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
1976 lines (1807 loc) · 58.6 KB
/
lib.rs
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
/*!
Rust X.509 certificate generation utility
This crate provides a way to generate self signed X.509 certificates.
The most simple way of using this crate is by calling the
[`generate_simple_self_signed`] function.
For more customization abilities, we provide the lower level
[`Certificate::from_params`] function.
## Example
```
extern crate rcgen;
use rcgen::generate_simple_self_signed;
# fn main () {
// Generate a certificate that's valid for "localhost" and "hello.world.example"
let subject_alt_names = vec!["hello.world.example".to_string(),
"localhost".to_string()];
let cert = generate_simple_self_signed(subject_alt_names).unwrap();
println!("{}", cert.serialize_pem().unwrap());
println!("{}", cert.serialize_private_key_pem());
# }
```
*/
#![forbid(unsafe_code)]
#![forbid(non_ascii_idents)]
#![deny(missing_docs)]
#![allow(clippy::complexity, clippy::style, clippy::pedantic)]
#[cfg(feature = "pem")]
use pem::Pem;
use ring::digest;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::hash::Hash;
use std::net::IpAddr;
#[cfg(feature = "x509-parser")]
use std::net::{Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time};
use yasna::models::ObjectIdentifier;
use yasna::models::{GeneralizedTime, UTCTime};
use yasna::tags::{TAG_BMPSTRING, TAG_TELETEXSTRING, TAG_UNIVERSALSTRING};
use yasna::DERWriter;
use yasna::Tag;
pub use crate::crl::{
CertificateRevocationList, CertificateRevocationListParams, CrlDistributionPoint,
CrlIssuingDistributionPoint, CrlScope, RevocationReason, RevokedCertParams,
};
pub use crate::csr::{CertificateSigningRequest, PublicKey};
pub use crate::error::RcgenError;
use crate::key_pair::PublicKeyData;
pub use crate::key_pair::{KeyPair, RemoteKeyPair};
use crate::oid::*;
pub use crate::sign_algo::algo::*;
pub use crate::sign_algo::SignatureAlgorithm;
/// A self signed certificate together with signing keys
pub struct Certificate {
params: CertificateParams,
key_pair: KeyPair,
}
/**
KISS function to generate a self signed certificate
Given a set of domain names you want your certificate to be valid for,
this function fills in the other generation parameters with
reasonable defaults and generates a self signed certificate
as output.
## Example
```
extern crate rcgen;
use rcgen::generate_simple_self_signed;
# fn main () {
let subject_alt_names :&[_] = &["hello.world.example".to_string(),
"localhost".to_string()];
let cert = generate_simple_self_signed(subject_alt_names).unwrap();
// The certificate is now valid for localhost and the domain "hello.world.example"
println!("{}", cert.serialize_pem().unwrap());
println!("{}", cert.serialize_private_key_pem());
# }
```
*/
pub fn generate_simple_self_signed(
subject_alt_names: impl Into<Vec<String>>,
) -> Result<Certificate, RcgenError> {
Certificate::from_params(CertificateParams::new(subject_alt_names))
}
// https://tools.ietf.org/html/rfc5280#section-4.1.1
mod crl;
mod csr;
mod error;
mod key_pair;
mod oid;
mod sign_algo;
// Example certs usable as reference:
// Uses ECDSA: https://crt.sh/?asn1=607203242
#[cfg(feature = "pem")]
const ENCODE_CONFIG: pem::EncodeConfig = {
let line_ending = match cfg!(target_family = "windows") {
true => pem::LineEnding::CRLF,
false => pem::LineEnding::LF,
};
pem::EncodeConfig::new().set_line_ending(line_ending)
};
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[allow(missing_docs)]
#[non_exhaustive]
/// The type of subject alt name
pub enum SanType {
/// Also known as E-Mail address
Rfc822Name(String),
DnsName(String),
URI(String),
IpAddress(IpAddr),
}
#[cfg(feature = "x509-parser")]
fn ip_addr_from_octets(octets: &[u8]) -> Result<IpAddr, RcgenError> {
if let Ok(ipv6_octets) = <&[u8; 16]>::try_from(octets) {
Ok(Ipv6Addr::from(*ipv6_octets).into())
} else if let Ok(ipv4_octets) = <&[u8; 4]>::try_from(octets) {
Ok(Ipv4Addr::from(*ipv4_octets).into())
} else {
Err(RcgenError::InvalidIpAddressOctetLength(octets.len()))
}
}
impl SanType {
#[cfg(feature = "x509-parser")]
fn try_from_general(
name: &x509_parser::extensions::GeneralName<'_>,
) -> Result<Self, RcgenError> {
Ok(match name {
x509_parser::extensions::GeneralName::RFC822Name(name) => {
SanType::Rfc822Name((*name).into())
},
x509_parser::extensions::GeneralName::DNSName(name) => SanType::DnsName((*name).into()),
x509_parser::extensions::GeneralName::URI(name) => SanType::URI((*name).into()),
x509_parser::extensions::GeneralName::IPAddress(octets) => {
SanType::IpAddress(ip_addr_from_octets(octets)?)
},
_ => return Err(RcgenError::InvalidNameType),
})
}
fn tag(&self) -> u64 {
// Defined in the GeneralName list in
// https://tools.ietf.org/html/rfc5280#page-38
const TAG_RFC822_NAME: u64 = 1;
const TAG_DNS_NAME: u64 = 2;
const TAG_URI: u64 = 6;
const TAG_IP_ADDRESS: u64 = 7;
match self {
SanType::Rfc822Name(_name) => TAG_RFC822_NAME,
SanType::DnsName(_name) => TAG_DNS_NAME,
SanType::URI(_name) => TAG_URI,
SanType::IpAddress(_addr) => TAG_IP_ADDRESS,
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
#[allow(missing_docs)]
#[non_exhaustive]
/// General Subtree type.
///
/// This type has similarities to the [`SanType`] enum but is not equal.
/// For example, `GeneralSubtree` has CIDR subnets for ip addresses
/// while [`SanType`] has IP addresses.
pub enum GeneralSubtree {
/// Also known as E-Mail address
Rfc822Name(String),
DnsName(String),
DirectoryName(DistinguishedName),
IpAddress(CidrSubnet),
}
impl GeneralSubtree {
fn tag(&self) -> u64 {
// Defined in the GeneralName list in
// https://tools.ietf.org/html/rfc5280#page-38
const TAG_RFC822_NAME: u64 = 1;
const TAG_DNS_NAME: u64 = 2;
const TAG_DIRECTORY_NAME: u64 = 4;
const TAG_IP_ADDRESS: u64 = 7;
match self {
GeneralSubtree::Rfc822Name(_name) => TAG_RFC822_NAME,
GeneralSubtree::DnsName(_name) => TAG_DNS_NAME,
GeneralSubtree::DirectoryName(_name) => TAG_DIRECTORY_NAME,
GeneralSubtree::IpAddress(_addr) => TAG_IP_ADDRESS,
}
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[allow(missing_docs)]
/// CIDR subnet, as per [RFC 4632](https://tools.ietf.org/html/rfc4632)
///
/// You might know CIDR subnets better by their textual representation
/// where they consist of an ip address followed by a slash and a prefix
/// number, for example `192.168.99.0/24`.
///
/// The first field in the enum is the address, the second is the mask.
/// Both are specified in network byte order.
pub enum CidrSubnet {
V4([u8; 4], [u8; 4]),
V6([u8; 16], [u8; 16]),
}
macro_rules! mask {
($t:ty, $d:expr) => {{
let v = <$t>::max_value();
let v = v.checked_shr($d as u32).unwrap_or(0);
(!v).to_be_bytes()
}};
}
impl CidrSubnet {
/// Obtains the CidrSubnet from the well-known
/// addr/prefix notation.
/// ```
/// # use std::str::FromStr;
/// # use rcgen::CidrSubnet;
/// // The "192.0.2.0/24" example from
/// // https://tools.ietf.org/html/rfc5280#page-42
/// let subnet = CidrSubnet::from_str("192.0.2.0/24").unwrap();
/// assert_eq!(subnet, CidrSubnet::V4([0xC0, 0x00, 0x02, 0x00], [0xFF, 0xFF, 0xFF, 0x00]));
/// ```
pub fn from_str(s: &str) -> Result<Self, ()> {
let mut iter = s.split('/');
if let (Some(addr_s), Some(prefix_s)) = (iter.next(), iter.next()) {
let addr = IpAddr::from_str(addr_s).map_err(|_| ())?;
let prefix = u8::from_str(prefix_s).map_err(|_| ())?;
Ok(Self::from_addr_prefix(addr, prefix))
} else {
Err(())
}
}
/// Obtains the CidrSubnet from an ip address
/// as well as the specified prefix number.
///
/// ```
/// # use std::net::IpAddr;
/// # use std::str::FromStr;
/// # use rcgen::CidrSubnet;
/// // The "192.0.2.0/24" example from
/// // https://tools.ietf.org/html/rfc5280#page-42
/// let addr = IpAddr::from_str("192.0.2.0").unwrap();
/// let subnet = CidrSubnet::from_addr_prefix(addr, 24);
/// assert_eq!(subnet, CidrSubnet::V4([0xC0, 0x00, 0x02, 0x00], [0xFF, 0xFF, 0xFF, 0x00]));
/// ```
pub fn from_addr_prefix(addr: IpAddr, prefix: u8) -> Self {
match addr {
IpAddr::V4(addr) => Self::from_v4_prefix(addr.octets(), prefix),
IpAddr::V6(addr) => Self::from_v6_prefix(addr.octets(), prefix),
}
}
/// Obtains the CidrSubnet from an IPv4 address in network byte order
/// as well as the specified prefix.
pub fn from_v4_prefix(addr: [u8; 4], prefix: u8) -> Self {
CidrSubnet::V4(addr, mask!(u32, prefix))
}
/// Obtains the CidrSubnet from an IPv6 address in network byte order
/// as well as the specified prefix.
pub fn from_v6_prefix(addr: [u8; 16], prefix: u8) -> Self {
CidrSubnet::V6(addr, mask!(u128, prefix))
}
fn to_bytes(&self) -> Vec<u8> {
let mut res = Vec::new();
match self {
CidrSubnet::V4(addr, mask) => {
res.extend_from_slice(addr);
res.extend_from_slice(mask);
},
CidrSubnet::V6(addr, mask) => {
res.extend_from_slice(addr);
res.extend_from_slice(mask);
},
}
res
}
}
#[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 {
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,
OID_STATE_OR_PROVINCE_NAME => DnType::StateOrProvinceName,
OID_ORG_NAME => DnType::OrganizationName,
OID_ORG_UNIT_NAME => DnType::OrganizationalUnitName,
OID_COMMON_NAME => DnType::CommonName,
oid => DnType::CustomDnType(oid.into()),
}
}
}
/// A distinguished name entry
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
#[non_exhaustive]
pub enum DnValue {
/// A string of characters from the T.61 character set
TeletexString(Vec<u8>),
/// An ASCII string containing only A-Z, a-z, 0-9, '()+,-./:=? and `<SPACE>`
PrintableString(String),
/// A string encoded using UTF-32
UniversalString(Vec<u8>),
/// A string encoded using UTF-8
Utf8String(String),
/// A string encoded using UCS-2
BmpString(Vec<u8>),
}
impl<T> From<T> for DnValue
where
T: Into<String>,
{
fn from(t: T) -> Self {
DnValue::Utf8String(t.into())
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
/**
Distinguished name used e.g. for the issuer and subject fields of a certificate
A distinguished name is a set of (attribute type, attribute value) tuples.
This datastructure keeps them ordered by insertion order.
See also the RFC 5280 sections on the [issuer](https://tools.ietf.org/html/rfc5280#section-4.1.2.4)
and [subject](https://tools.ietf.org/html/rfc5280#section-4.1.2.6) fields.
*/
pub struct DistinguishedName {
entries: HashMap<DnType, DnValue>,
order: Vec<DnType>,
}
impl DistinguishedName {
/// Creates a new, empty distinguished name
pub fn new() -> Self {
Self {
entries: HashMap::new(),
order: Vec::new(),
}
}
/// Obtains the attribute value for the given attribute type
pub fn get(&self, ty: &DnType) -> Option<&DnValue> {
self.entries.get(ty)
}
/// Removes the attribute with the specified DnType
///
/// Returns true when an actual removal happened, false
/// when no attribute with the specified DnType was
/// found.
pub fn remove(&mut self, ty: DnType) -> bool {
let removed = self.entries.remove(&ty).is_some();
if removed {
self.order.retain(|ty_o| &ty != ty_o);
}
removed
}
/// Inserts or updates an attribute that consists of type and name
///
/// ```
/// # use rcgen::{DistinguishedName, DnType, DnValue};
/// let mut dn = DistinguishedName::new();
/// dn.push(DnType::OrganizationName, "Crab widgits SE");
/// dn.push(DnType::CommonName, DnValue::PrintableString("Master Cert".to_string()));
/// assert_eq!(dn.get(&DnType::OrganizationName), Some(&DnValue::Utf8String("Crab widgits SE".to_string())));
/// assert_eq!(dn.get(&DnType::CommonName), Some(&DnValue::PrintableString("Master Cert".to_string())));
/// ```
pub fn push(&mut self, ty: DnType, s: impl Into<DnValue>) {
if !self.entries.contains_key(&ty) {
self.order.push(ty.clone());
}
self.entries.insert(ty, s.into());
}
/// Iterate over the entries
pub fn iter(&self) -> DistinguishedNameIterator<'_> {
DistinguishedNameIterator {
distinguished_name: self,
iter: self.order.iter(),
}
}
#[cfg(feature = "x509-parser")]
fn from_name(name: &x509_parser::x509::X509Name) -> Result<Self, RcgenError> {
use x509_parser::der_parser::asn1_rs::Tag;
let mut dn = DistinguishedName::new();
for rdn in name.iter() {
let mut rdn_iter = rdn.iter();
let dn_opt = rdn_iter.next();
let attr = if let Some(dn) = dn_opt {
if rdn_iter.next().is_some() {
// no support for distinguished names with more than one attribute
return Err(RcgenError::CouldNotParseCertificate);
} else {
dn
}
} else {
panic!("x509-parser distinguished name set is empty");
};
let attr_type_oid = attr
.attr_type()
.iter()
.ok_or(RcgenError::CouldNotParseCertificate)?;
let dn_type = DnType::from_oid(&attr_type_oid.collect::<Vec<_>>());
let data = attr.attr_value().data;
let dn_value = match attr.attr_value().header.tag() {
Tag::T61String => DnValue::TeletexString(data.into()),
Tag::PrintableString => {
let data = std::str::from_utf8(data)
.map_err(|_| RcgenError::CouldNotParseCertificate)?;
DnValue::PrintableString(data.to_owned())
},
Tag::UniversalString => DnValue::UniversalString(data.into()),
Tag::Utf8String => {
let data = std::str::from_utf8(data)
.map_err(|_| RcgenError::CouldNotParseCertificate)?;
DnValue::Utf8String(data.to_owned())
},
Tag::BmpString => DnValue::BmpString(data.into()),
_ => return Err(RcgenError::CouldNotParseCertificate),
};
dn.push(dn_type, dn_value);
}
Ok(dn)
}
}
/**
Iterator over [`DistinguishedName`] entries
*/
pub struct DistinguishedNameIterator<'a> {
distinguished_name: &'a DistinguishedName,
iter: std::slice::Iter<'a, DnType>,
}
impl<'a> Iterator for DistinguishedNameIterator<'a> {
type Item = (&'a DnType, &'a DnValue);
fn next(&mut self) -> Option<Self::Item> {
self.iter
.next()
.and_then(|ty| self.distinguished_name.entries.get(ty).map(|v| (ty, v)))
}
}
/// Parameters used for certificate generation
#[allow(missing_docs)]
#[non_exhaustive]
pub struct CertificateParams {
pub alg: &'static SignatureAlgorithm,
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>,
/// The certificate's key pair, a new random key pair will be generated if this is `None`
pub key_pair: Option<KeyPair>,
/// 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 SHA-256.
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 {
alg: &PKCS_ECDSA_P256_SHA256,
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(),
key_pair: None,
use_authority_key_identifier_extension: false,
key_identifier_method: KeyIdMethod::Sha256,
}
}
}
impl CertificateParams {
/// Parses a ca certificate from the ASCII PEM format for signing
///
/// See [`from_ca_cert_der`](Self::from_ca_cert_der) for more details.
///
/// *This constructor is only available if rcgen is built with the "pem" and "x509-parser" features*
#[cfg(all(feature = "pem", feature = "x509-parser"))]
pub fn from_ca_cert_pem(pem_str: &str, key_pair: KeyPair) -> Result<Self, RcgenError> {
let certificate = pem::parse(pem_str).or(Err(RcgenError::CouldNotParseCertificate))?;
Self::from_ca_cert_der(certificate.contents(), key_pair)
}
/// Parses a ca certificate from the DER format for signing
///
/// This function is only of use if you have an existing ca certificate with
/// which you want to sign a certificate newly generated by `rcgen` using the
/// [`serialize_der_with_signer`](Certificate::serialize_der_with_signer) or
/// [`serialize_pem_with_signer`](Certificate::serialize_pem_with_signer)
/// functions.
///
/// This function only extracts from the given ca cert the information
/// needed for signing. Any information beyond that is not extracted
/// and left to defaults.
///
/// Will not check if certificate is a ca certificate!
///
/// *This constructor is only available if rcgen is built with the "x509-parser" feature*
#[cfg(feature = "x509-parser")]
pub fn from_ca_cert_der(ca_cert: &[u8], key_pair: KeyPair) -> Result<Self, RcgenError> {
let (_remainder, x509) = x509_parser::parse_x509_certificate(ca_cert)
.or(Err(RcgenError::CouldNotParseCertificate))?;
let alg_oid = x509
.signature_algorithm
.algorithm
.iter()
.ok_or(RcgenError::CouldNotParseCertificate)?;
let alg = SignatureAlgorithm::from_oid(&alg_oid.collect::<Vec<_>>())?;
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());
Ok(CertificateParams {
alg,
is_ca,
subject_alt_names,
key_usages,
extended_key_usages,
name_constraints,
serial_number,
distinguished_name: dn,
key_pair: Some(key_pair),
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, RcgenError> {
use x509_parser::extensions::BasicConstraints as B;
let basic_constraints = x509
.basic_constraints()
.or(Err(RcgenError::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(RcgenError::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>, RcgenError> {
let sans = x509
.subject_alternative_name()
.or(Err(RcgenError::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>, RcgenError> {
let key_usage = x509
.key_usage()
.or(Err(RcgenError::CouldNotParseCertificate))?
.map(|ext| ext.value);
let mut key_usages = Vec::new();
if let Some(key_usage) = key_usage {
if key_usage.digital_signature() {
key_usages.push(KeyUsagePurpose::DigitalSignature);
}
if key_usage.non_repudiation() {
key_usages.push(KeyUsagePurpose::ContentCommitment);
}
if key_usage.key_encipherment() {
key_usages.push(KeyUsagePurpose::KeyEncipherment);
}
if key_usage.data_encipherment() {
key_usages.push(KeyUsagePurpose::DataEncipherment);
}
if key_usage.key_agreement() {
key_usages.push(KeyUsagePurpose::KeyAgreement);
}
if key_usage.key_cert_sign() {
key_usages.push(KeyUsagePurpose::KeyCertSign);
}
if key_usage.crl_sign() {
key_usages.push(KeyUsagePurpose::CrlSign);
}
if key_usage.encipher_only() {
key_usages.push(KeyUsagePurpose::EncipherOnly);
}
if key_usage.decipher_only() {
key_usages.push(KeyUsagePurpose::DecipherOnly);
}
}
Ok(key_usages)
}
#[cfg(feature = "x509-parser")]
fn convert_x509_extended_key_usages(
x509: &x509_parser::certificate::X509Certificate<'_>,
) -> Result<Vec<ExtendedKeyUsagePurpose>, RcgenError> {
let extended_key_usage = x509
.extended_key_usage()
.or(Err(RcgenError::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>, RcgenError> {
let constraints = x509
.name_constraints()
.or(Err(RcgenError::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>, RcgenError> {
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)
}
fn write_subject_alt_names(&self, writer: DERWriter) {
write_x509_extension(writer, OID_SUBJECT_ALT_NAME, false, |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),
SanType::IpAddress(IpAddr::V4(addr)) => {
writer.write_bytes(&addr.octets())
},
SanType::IpAddress(IpAddr::V6(addr)) => {
writer.write_bytes(&addr.octets())
},
},
);
}
});
});
}
fn write_request<K: PublicKeyData>(
&self,
pub_key: &K,
writer: DERWriter,
) -> Result<(), RcgenError> {
// No .. pattern, we use this to ensure every field is used
#[deny(unused)]
let Self {
alg,
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,
key_pair,
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
// - 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 _ = (alg, key_pair, not_before, not_after, key_identifier_method);
if serial_number.is_some()
|| *is_ca != IsCa::NoCa
|| !key_usages.is_empty()
|| !extended_key_usages.is_empty()
|| name_constraints.is_some()
|| !crl_distribution_points.is_empty()
|| *use_authority_key_identifier_extension
{
return Err(RcgenError::UnsupportedInCsr);
}
writer.write_sequence(|writer| {
// Write version
writer.next().write_u8(0);
// Write issuer
writer.next().write_sequence(|writer| {
for (ty, content) in distinguished_name.iter() {
writer.next().write_set(|writer| {
writer.next().write_sequence(|writer| {
writer.next().write_oid(&ty.to_oid());
match content {
DnValue::TeletexString(s) => writer
.next()
.write_tagged_implicit(TAG_TELETEXSTRING, |writer| {
writer.write_bytes(s)
}),
DnValue::PrintableString(s) => {
writer.next().write_printable_string(s)
},
DnValue::UniversalString(s) => writer
.next()
.write_tagged_implicit(TAG_UNIVERSALSTRING, |writer| {
writer.write_bytes(s)
}),
DnValue::Utf8String(s) => writer.next().write_utf8_string(s),
DnValue::BmpString(s) => writer
.next()
.write_tagged_implicit(TAG_BMPSTRING, |writer| {
writer.write_bytes(s)
}),
}
});
});
}
});
// Write subjectPublicKeyInfo
pub_key.serialize_public_key_der(writer.next());
// Write extensions
// According to the spec in RFC 2986, even if attributes are empty we need the empty attribute tag
writer.next().write_tagged(Tag::context(0), |writer| {
if !subject_alt_names.is_empty() || !custom_extensions.is_empty() {
writer.write_sequence(|writer| {
let oid = ObjectIdentifier::from_slice(OID_PKCS_9_AT_EXTENSION_REQUEST);
writer.next().write_oid(&oid);
writer.next().write_set(|writer| {
writer.next().write_sequence(|writer| {
// Write subject_alt_names
self.write_subject_alt_names(writer.next());
// Write custom extensions
for ext in custom_extensions {
write_x509_extension(
writer.next(),
&ext.oid,
ext.critical,
|writer| writer.write_der(ext.content()),
);
}
});
});
});
}
});
});
Ok(())
}
fn write_cert<K: PublicKeyData>(
&self,
writer: DERWriter,
pub_key: &K,
ca: &Certificate,
) -> Result<(), RcgenError> {
writer.write_sequence(|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 {
let hash = digest::digest(&digest::SHA256, pub_key.raw_bytes());
// RFC 5280 specifies at most 20 bytes for a serial number
let sl = &hash.as_ref()[0..20];
writer.next().write_bigint_bytes(sl, true);
};
// Write signature
ca.params.alg.write_alg_ident(writer.next());
// Write issuer
write_distinguished_name(writer.next(), &ca.params.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::<(), RcgenError>(())
})?;
// Write subject
write_distinguished_name(writer.next(), &self.distinguished_name);
// Write subjectPublicKeyInfo
pub_key.serialize_public_key_der(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 {
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(), ca)
}
// Write subject_alt_names
if !self.subject_alt_names.is_empty() {
self.write_subject_alt_names(writer.next());
}
// Write standard key usage
if !self.key_usages.is_empty() {
write_x509_extension(writer.next(), OID_KEY_USAGE, true, |writer| {
let mut bits: u16 = 0;
for entry in self.key_usages.iter() {