Skip to main content

variant_ssl/x509/
extension.rs

1//! Add extensions to an `X509` certificate or certificate request.
2//!
3//! The extensions defined for X.509 v3 certificates provide methods for
4//! associating additional attributes with users or public keys and for
5//! managing relationships between CAs. The extensions created using this
6//! module can be used with `X509v3Context` objects.
7//!
8//! # Example
9//!
10//! ```rust
11//! use openssl::x509::extension::BasicConstraints;
12//! use openssl::x509::X509Extension;
13//!
14//! let mut bc = BasicConstraints::new();
15//! let bc = bc.critical().ca().pathlen(1);
16//!
17//! let extension: X509Extension = bc.build().unwrap();
18//! ```
19use std::fmt::Write;
20
21use crate::asn1::{Asn1Integer, Asn1Object};
22use crate::bn::BigNum;
23use crate::cvt_p;
24use crate::error::ErrorStack;
25use crate::nid::Nid;
26use crate::x509::{GeneralName, Stack, X509Extension, X509Name, X509v3Context};
27use foreign_types::ForeignType;
28
29/// An extension which indicates whether a certificate is a CA certificate.
30pub struct BasicConstraints {
31    critical: bool,
32    ca: bool,
33    pathlen: Option<u32>,
34}
35
36impl Default for BasicConstraints {
37    fn default() -> BasicConstraints {
38        BasicConstraints::new()
39    }
40}
41
42impl BasicConstraints {
43    /// Construct a new `BasicConstraints` extension.
44    pub fn new() -> BasicConstraints {
45        BasicConstraints {
46            critical: false,
47            ca: false,
48            pathlen: None,
49        }
50    }
51
52    /// Sets the `critical` flag to `true`. The extension will be critical.
53    pub fn critical(&mut self) -> &mut BasicConstraints {
54        self.critical = true;
55        self
56    }
57
58    /// Sets the `ca` flag to `true`.
59    pub fn ca(&mut self) -> &mut BasicConstraints {
60        self.ca = true;
61        self
62    }
63
64    /// Sets the `pathlen` to an optional non-negative value. The `pathlen` is the
65    /// maximum number of CAs that can appear below this one in a chain.
66    pub fn pathlen(&mut self, pathlen: u32) -> &mut BasicConstraints {
67        self.pathlen = Some(pathlen);
68        self
69    }
70
71    /// Return the `BasicConstraints` extension as an `X509Extension`.
72    // Temporarily silence the deprecation warning - this should be ported to
73    // `X509Extension::new_internal`.
74    #[allow(deprecated)]
75    pub fn build(&self) -> Result<X509Extension, ErrorStack> {
76        let mut value = String::new();
77        if self.critical {
78            value.push_str("critical,");
79        }
80        value.push_str("CA:");
81        if self.ca {
82            value.push_str("TRUE");
83        } else {
84            value.push_str("FALSE");
85        }
86        if let Some(pathlen) = self.pathlen {
87            write!(value, ",pathlen:{}", pathlen).unwrap();
88        }
89        X509Extension::new_nid(None, None, Nid::BASIC_CONSTRAINTS, &value)
90    }
91}
92
93/// An extension consisting of a list of names of the permitted key usages.
94pub struct KeyUsage {
95    critical: bool,
96    digital_signature: bool,
97    non_repudiation: bool,
98    key_encipherment: bool,
99    data_encipherment: bool,
100    key_agreement: bool,
101    key_cert_sign: bool,
102    crl_sign: bool,
103    encipher_only: bool,
104    decipher_only: bool,
105}
106
107impl Default for KeyUsage {
108    fn default() -> KeyUsage {
109        KeyUsage::new()
110    }
111}
112
113impl KeyUsage {
114    /// Construct a new `KeyUsage` extension.
115    pub fn new() -> KeyUsage {
116        KeyUsage {
117            critical: false,
118            digital_signature: false,
119            non_repudiation: false,
120            key_encipherment: false,
121            data_encipherment: false,
122            key_agreement: false,
123            key_cert_sign: false,
124            crl_sign: false,
125            encipher_only: false,
126            decipher_only: false,
127        }
128    }
129
130    /// Sets the `critical` flag to `true`. The extension will be critical.
131    pub fn critical(&mut self) -> &mut KeyUsage {
132        self.critical = true;
133        self
134    }
135
136    /// Sets the `digitalSignature` flag to `true`.
137    pub fn digital_signature(&mut self) -> &mut KeyUsage {
138        self.digital_signature = true;
139        self
140    }
141
142    /// Sets the `nonRepudiation` flag to `true`.
143    pub fn non_repudiation(&mut self) -> &mut KeyUsage {
144        self.non_repudiation = true;
145        self
146    }
147
148    /// Sets the `keyEncipherment` flag to `true`.
149    pub fn key_encipherment(&mut self) -> &mut KeyUsage {
150        self.key_encipherment = true;
151        self
152    }
153
154    /// Sets the `dataEncipherment` flag to `true`.
155    pub fn data_encipherment(&mut self) -> &mut KeyUsage {
156        self.data_encipherment = true;
157        self
158    }
159
160    /// Sets the `keyAgreement` flag to `true`.
161    pub fn key_agreement(&mut self) -> &mut KeyUsage {
162        self.key_agreement = true;
163        self
164    }
165
166    /// Sets the `keyCertSign` flag to `true`.
167    pub fn key_cert_sign(&mut self) -> &mut KeyUsage {
168        self.key_cert_sign = true;
169        self
170    }
171
172    /// Sets the `cRLSign` flag to `true`.
173    pub fn crl_sign(&mut self) -> &mut KeyUsage {
174        self.crl_sign = true;
175        self
176    }
177
178    /// Sets the `encipherOnly` flag to `true`.
179    pub fn encipher_only(&mut self) -> &mut KeyUsage {
180        self.encipher_only = true;
181        self
182    }
183
184    /// Sets the `decipherOnly` flag to `true`.
185    pub fn decipher_only(&mut self) -> &mut KeyUsage {
186        self.decipher_only = true;
187        self
188    }
189
190    /// Return the `KeyUsage` extension as an `X509Extension`.
191    // Temporarily silence the deprecation warning - this should be ported to
192    // `X509Extension::new_internal`.
193    #[allow(deprecated)]
194    pub fn build(&self) -> Result<X509Extension, ErrorStack> {
195        let mut value = String::new();
196        let mut first = true;
197        append(&mut value, &mut first, self.critical, "critical");
198        append(
199            &mut value,
200            &mut first,
201            self.digital_signature,
202            "digitalSignature",
203        );
204        append(
205            &mut value,
206            &mut first,
207            self.non_repudiation,
208            "nonRepudiation",
209        );
210        append(
211            &mut value,
212            &mut first,
213            self.key_encipherment,
214            "keyEncipherment",
215        );
216        append(
217            &mut value,
218            &mut first,
219            self.data_encipherment,
220            "dataEncipherment",
221        );
222        append(&mut value, &mut first, self.key_agreement, "keyAgreement");
223        append(&mut value, &mut first, self.key_cert_sign, "keyCertSign");
224        append(&mut value, &mut first, self.crl_sign, "cRLSign");
225        append(&mut value, &mut first, self.encipher_only, "encipherOnly");
226        append(&mut value, &mut first, self.decipher_only, "decipherOnly");
227        X509Extension::new_nid(None, None, Nid::KEY_USAGE, &value)
228    }
229}
230
231/// An extension consisting of a list of usages indicating purposes
232/// for which the certificate public key can be used for.
233pub struct ExtendedKeyUsage {
234    critical: bool,
235    items: Vec<String>,
236}
237
238impl Default for ExtendedKeyUsage {
239    fn default() -> ExtendedKeyUsage {
240        ExtendedKeyUsage::new()
241    }
242}
243
244impl ExtendedKeyUsage {
245    /// Construct a new `ExtendedKeyUsage` extension.
246    pub fn new() -> ExtendedKeyUsage {
247        ExtendedKeyUsage {
248            critical: false,
249            items: vec![],
250        }
251    }
252
253    /// Sets the `critical` flag to `true`. The extension will be critical.
254    pub fn critical(&mut self) -> &mut ExtendedKeyUsage {
255        self.critical = true;
256        self
257    }
258
259    /// Sets the `serverAuth` flag to `true`.
260    pub fn server_auth(&mut self) -> &mut ExtendedKeyUsage {
261        self.other("serverAuth")
262    }
263
264    /// Sets the `clientAuth` flag to `true`.
265    pub fn client_auth(&mut self) -> &mut ExtendedKeyUsage {
266        self.other("clientAuth")
267    }
268
269    /// Sets the `codeSigning` flag to `true`.
270    pub fn code_signing(&mut self) -> &mut ExtendedKeyUsage {
271        self.other("codeSigning")
272    }
273
274    /// Sets the `emailProtection` flag to `true`.
275    pub fn email_protection(&mut self) -> &mut ExtendedKeyUsage {
276        self.other("emailProtection")
277    }
278
279    /// Sets the `timeStamping` flag to `true`.
280    pub fn time_stamping(&mut self) -> &mut ExtendedKeyUsage {
281        self.other("timeStamping")
282    }
283
284    /// Sets the `msCodeInd` flag to `true`.
285    pub fn ms_code_ind(&mut self) -> &mut ExtendedKeyUsage {
286        self.other("msCodeInd")
287    }
288
289    /// Sets the `msCodeCom` flag to `true`.
290    pub fn ms_code_com(&mut self) -> &mut ExtendedKeyUsage {
291        self.other("msCodeCom")
292    }
293
294    /// Sets the `msCTLSign` flag to `true`.
295    pub fn ms_ctl_sign(&mut self) -> &mut ExtendedKeyUsage {
296        self.other("msCTLSign")
297    }
298
299    /// Sets the `msSGC` flag to `true`.
300    pub fn ms_sgc(&mut self) -> &mut ExtendedKeyUsage {
301        self.other("msSGC")
302    }
303
304    /// Sets the `msEFS` flag to `true`.
305    pub fn ms_efs(&mut self) -> &mut ExtendedKeyUsage {
306        self.other("msEFS")
307    }
308
309    /// Sets the `nsSGC` flag to `true`.
310    pub fn ns_sgc(&mut self) -> &mut ExtendedKeyUsage {
311        self.other("nsSGC")
312    }
313
314    /// Sets a flag not already defined.
315    pub fn other(&mut self, other: &str) -> &mut ExtendedKeyUsage {
316        self.items.push(other.to_string());
317        self
318    }
319
320    /// Return the `ExtendedKeyUsage` extension as an `X509Extension`.
321    pub fn build(&self) -> Result<X509Extension, ErrorStack> {
322        let mut stack = Stack::new()?;
323        for item in &self.items {
324            stack.push(Asn1Object::from_str(item)?)?;
325        }
326        unsafe {
327            X509Extension::new_internal(Nid::EXT_KEY_USAGE, self.critical, stack.as_ptr().cast())
328        }
329    }
330}
331
332/// An extension that provides a means of identifying certificates that contain a
333/// particular public key.
334pub struct SubjectKeyIdentifier {
335    critical: bool,
336}
337
338impl Default for SubjectKeyIdentifier {
339    fn default() -> SubjectKeyIdentifier {
340        SubjectKeyIdentifier::new()
341    }
342}
343
344impl SubjectKeyIdentifier {
345    /// Construct a new `SubjectKeyIdentifier` extension.
346    pub fn new() -> SubjectKeyIdentifier {
347        SubjectKeyIdentifier { critical: false }
348    }
349
350    /// Sets the `critical` flag to `true`. The extension will be critical.
351    pub fn critical(&mut self) -> &mut SubjectKeyIdentifier {
352        self.critical = true;
353        self
354    }
355
356    /// Return a `SubjectKeyIdentifier` extension as an `X509Extension`.
357    // Temporarily silence the deprecation warning - this should be ported to
358    // `X509Extension::new_internal`.
359    #[allow(deprecated)]
360    pub fn build(&self, ctx: &X509v3Context<'_>) -> Result<X509Extension, ErrorStack> {
361        let mut value = String::new();
362        let mut first = true;
363        append(&mut value, &mut first, self.critical, "critical");
364        append(&mut value, &mut first, true, "hash");
365        X509Extension::new_nid(None, Some(ctx), Nid::SUBJECT_KEY_IDENTIFIER, &value)
366    }
367}
368
369/// An extension that provides a means of identifying the public key corresponding
370/// to the private key used to sign a CRL.
371pub struct AuthorityKeyIdentifier {
372    critical: bool,
373    keyid: Option<bool>,
374    issuer: Option<bool>,
375}
376
377impl Default for AuthorityKeyIdentifier {
378    fn default() -> AuthorityKeyIdentifier {
379        AuthorityKeyIdentifier::new()
380    }
381}
382
383impl AuthorityKeyIdentifier {
384    /// Construct a new `AuthorityKeyIdentifier` extension.
385    pub fn new() -> AuthorityKeyIdentifier {
386        AuthorityKeyIdentifier {
387            critical: false,
388            keyid: None,
389            issuer: None,
390        }
391    }
392
393    /// Sets the `critical` flag to `true`. The extension will be critical.
394    pub fn critical(&mut self) -> &mut AuthorityKeyIdentifier {
395        self.critical = true;
396        self
397    }
398
399    /// Sets the `keyid` flag.
400    pub fn keyid(&mut self, always: bool) -> &mut AuthorityKeyIdentifier {
401        self.keyid = Some(always);
402        self
403    }
404
405    /// Sets the `issuer` flag.
406    pub fn issuer(&mut self, always: bool) -> &mut AuthorityKeyIdentifier {
407        self.issuer = Some(always);
408        self
409    }
410
411    /// Return a `AuthorityKeyIdentifier` extension as an `X509Extension`.
412    // Temporarily silence the deprecation warning - this should be ported to
413    // `X509Extension::new_internal`.
414    #[allow(deprecated)]
415    pub fn build(&self, ctx: &X509v3Context<'_>) -> Result<X509Extension, ErrorStack> {
416        let mut value = String::new();
417        let mut first = true;
418        append(&mut value, &mut first, self.critical, "critical");
419        match self.keyid {
420            Some(true) => append(&mut value, &mut first, true, "keyid:always"),
421            Some(false) => append(&mut value, &mut first, true, "keyid"),
422            None => {}
423        }
424        match self.issuer {
425            Some(true) => append(&mut value, &mut first, true, "issuer:always"),
426            Some(false) => append(&mut value, &mut first, true, "issuer"),
427            None => {}
428        }
429        X509Extension::new_nid(None, Some(ctx), Nid::AUTHORITY_KEY_IDENTIFIER, &value)
430    }
431}
432
433enum RustGeneralName {
434    Dns(String),
435    Email(String),
436    Uri(String),
437    Ip(String),
438    Rid(String),
439    OtherName(Asn1Object, Vec<u8>),
440    DirName(X509Name),
441}
442
443/// An extension that allows additional identities to be bound to the subject
444/// of the certificate.
445pub struct SubjectAlternativeName {
446    critical: bool,
447    items: Vec<RustGeneralName>,
448}
449
450impl Default for SubjectAlternativeName {
451    fn default() -> SubjectAlternativeName {
452        SubjectAlternativeName::new()
453    }
454}
455
456impl SubjectAlternativeName {
457    /// Construct a new `SubjectAlternativeName` extension.
458    pub fn new() -> SubjectAlternativeName {
459        SubjectAlternativeName {
460            critical: false,
461            items: vec![],
462        }
463    }
464
465    /// Sets the `critical` flag to `true`. The extension will be critical.
466    pub fn critical(&mut self) -> &mut SubjectAlternativeName {
467        self.critical = true;
468        self
469    }
470
471    /// Sets the `email` flag.
472    pub fn email(&mut self, email: &str) -> &mut SubjectAlternativeName {
473        self.items.push(RustGeneralName::Email(email.to_string()));
474        self
475    }
476
477    /// Sets the `uri` flag.
478    pub fn uri(&mut self, uri: &str) -> &mut SubjectAlternativeName {
479        self.items.push(RustGeneralName::Uri(uri.to_string()));
480        self
481    }
482
483    /// Sets the `dns` flag.
484    pub fn dns(&mut self, dns: &str) -> &mut SubjectAlternativeName {
485        self.items.push(RustGeneralName::Dns(dns.to_string()));
486        self
487    }
488
489    /// Sets the `rid` flag.
490    pub fn rid(&mut self, rid: &str) -> &mut SubjectAlternativeName {
491        self.items.push(RustGeneralName::Rid(rid.to_string()));
492        self
493    }
494
495    /// Sets the `ip` flag.
496    pub fn ip(&mut self, ip: &str) -> &mut SubjectAlternativeName {
497        self.items.push(RustGeneralName::Ip(ip.to_string()));
498        self
499    }
500
501    /// Sets the `dirName` flag.
502    ///
503    /// Not currently actually supported, always panics. Please use dir_name2
504    #[deprecated = "dir_name is deprecated and always panics. Please use dir_name2."]
505    pub fn dir_name(&mut self, _dir_name: &str) -> &mut SubjectAlternativeName {
506        unimplemented!("This has not yet been adapted for the new internals. Use dir_name2.");
507    }
508
509    /// Sets the `dirName` flag.
510    pub fn dir_name2(&mut self, dir_name: X509Name) -> &mut SubjectAlternativeName {
511        self.items.push(RustGeneralName::DirName(dir_name));
512        self
513    }
514
515    /// Sets the `otherName` flag.
516    ///
517    /// Not currently actually supported, always panics. Please use other_name2
518    #[deprecated = "other_name is deprecated and always panics. Please use other_name2."]
519    pub fn other_name(&mut self, _other_name: &str) -> &mut SubjectAlternativeName {
520        unimplemented!("This has not yet been adapted for the new internals. Use other_name2.");
521    }
522
523    /// Sets the `otherName` flag.
524    ///
525    /// `content` must be a valid der encoded ASN1_TYPE
526    ///
527    /// If you want to add just a ia5string use `other_name_ia5string`
528    pub fn other_name2(&mut self, oid: Asn1Object, content: &[u8]) -> &mut SubjectAlternativeName {
529        self.items
530            .push(RustGeneralName::OtherName(oid, content.into()));
531        self
532    }
533
534    /// Return a `SubjectAlternativeName` extension as an `X509Extension`.
535    pub fn build(&self, _ctx: &X509v3Context<'_>) -> Result<X509Extension, ErrorStack> {
536        let mut stack = Stack::new()?;
537        for item in &self.items {
538            let gn = match item {
539                RustGeneralName::Dns(s) => GeneralName::new_dns(s.as_bytes())?,
540                RustGeneralName::Email(s) => GeneralName::new_email(s.as_bytes())?,
541                RustGeneralName::Uri(s) => GeneralName::new_uri(s.as_bytes())?,
542                RustGeneralName::Ip(s) => {
543                    GeneralName::new_ip(s.parse().map_err(|_| ErrorStack::get())?)?
544                }
545                RustGeneralName::Rid(s) => GeneralName::new_rid(Asn1Object::from_str(s)?)?,
546                RustGeneralName::OtherName(oid, content) => {
547                    GeneralName::new_other_name(oid.clone(), content)?
548                }
549                RustGeneralName::DirName(name) => GeneralName::new_dir_name(name.as_ref())?,
550            };
551            stack.push(gn)?;
552        }
553
554        unsafe {
555            X509Extension::new_internal(Nid::SUBJECT_ALT_NAME, self.critical, stack.as_ptr().cast())
556        }
557    }
558}
559
560/// An extension that provides a means of versionning the CRL.
561pub struct CrlNumber(Asn1Integer);
562
563impl CrlNumber {
564    /// Construct a new `CrlNumber` extension.
565    pub fn new(number: BigNum) -> Result<Self, ErrorStack> {
566        let mut max = BigNum::new()?;
567        max.lshift(BigNum::from_u32(1)?.as_ref(), 159)?;
568
569        assert!(
570            !number.is_negative() && number < max,
571            "CrlNumber must be an ASN.1 integer greater than or equal to 0 and less than 2^159"
572        );
573
574        Ok(Self(Asn1Integer::from_bn(&number)?))
575    }
576
577    /// Return a `CrlNumber` extension as an `X509Extension`.
578    pub fn build(self) -> Result<X509Extension, ErrorStack> {
579        unsafe {
580            ffi::init();
581
582            cvt_p(ffi::X509V3_EXT_i2d(
583                Nid::CRL_NUMBER.as_raw(),
584                0,
585                self.0.as_ptr().cast(),
586            ))
587            .map(X509Extension)
588        }
589    }
590}
591
592fn append(value: &mut String, first: &mut bool, should: bool, element: &str) {
593    if !should {
594        return;
595    }
596
597    if !*first {
598        value.push(',');
599    }
600    *first = false;
601    value.push_str(element);
602}