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 //! ```
19 use std::fmt::Write;
20 
21 use crate::error::ErrorStack;
22 use crate::nid::Nid;
23 use crate::x509::{X509Extension, X509v3Context};
24 
25 /// An extension which indicates whether a certificate is a CA certificate.
26 pub struct BasicConstraints {
27     critical: bool,
28     ca: bool,
29     pathlen: Option<u32>,
30 }
31 
32 impl Default for BasicConstraints {
default() -> BasicConstraints33     fn default() -> BasicConstraints {
34         BasicConstraints::new()
35     }
36 }
37 
38 impl BasicConstraints {
39     /// Construct a new `BasicConstraints` extension.
new() -> BasicConstraints40     pub fn new() -> BasicConstraints {
41         BasicConstraints {
42             critical: false,
43             ca: false,
44             pathlen: None,
45         }
46     }
47 
48     /// Sets the `critical` flag to `true`. The extension will be critical.
critical(&mut self) -> &mut BasicConstraints49     pub fn critical(&mut self) -> &mut BasicConstraints {
50         self.critical = true;
51         self
52     }
53 
54     /// Sets the `ca` flag to `true`.
ca(&mut self) -> &mut BasicConstraints55     pub fn ca(&mut self) -> &mut BasicConstraints {
56         self.ca = true;
57         self
58     }
59 
60     /// Sets the pathlen to an optional non-negative value. The pathlen is the
61     /// maximum number of CAs that can appear below this one in a chain.
pathlen(&mut self, pathlen: u32) -> &mut BasicConstraints62     pub fn pathlen(&mut self, pathlen: u32) -> &mut BasicConstraints {
63         self.pathlen = Some(pathlen);
64         self
65     }
66 
67     /// Return the `BasicConstraints` extension as an `X509Extension`.
build(&self) -> Result<X509Extension, ErrorStack>68     pub fn build(&self) -> Result<X509Extension, ErrorStack> {
69         let mut value = String::new();
70         if self.critical {
71             value.push_str("critical,");
72         }
73         value.push_str("CA:");
74         if self.ca {
75             value.push_str("TRUE");
76         } else {
77             value.push_str("FALSE");
78         }
79         if let Some(pathlen) = self.pathlen {
80             write!(value, ",pathlen:{}", pathlen).unwrap();
81         }
82         X509Extension::new_nid(None, None, Nid::BASIC_CONSTRAINTS, &value)
83     }
84 }
85 
86 /// An extension consisting of a list of names of the permitted key usages.
87 pub struct KeyUsage {
88     critical: bool,
89     digital_signature: bool,
90     non_repudiation: bool,
91     key_encipherment: bool,
92     data_encipherment: bool,
93     key_agreement: bool,
94     key_cert_sign: bool,
95     crl_sign: bool,
96     encipher_only: bool,
97     decipher_only: bool,
98 }
99 
100 impl Default for KeyUsage {
default() -> KeyUsage101     fn default() -> KeyUsage {
102         KeyUsage::new()
103     }
104 }
105 
106 impl KeyUsage {
107     /// Construct a new `KeyUsage` extension.
new() -> KeyUsage108     pub fn new() -> KeyUsage {
109         KeyUsage {
110             critical: false,
111             digital_signature: false,
112             non_repudiation: false,
113             key_encipherment: false,
114             data_encipherment: false,
115             key_agreement: false,
116             key_cert_sign: false,
117             crl_sign: false,
118             encipher_only: false,
119             decipher_only: false,
120         }
121     }
122 
123     /// Sets the `critical` flag to `true`. The extension will be critical.
critical(&mut self) -> &mut KeyUsage124     pub fn critical(&mut self) -> &mut KeyUsage {
125         self.critical = true;
126         self
127     }
128 
129     /// Sets the `digitalSignature` flag to `true`.
digital_signature(&mut self) -> &mut KeyUsage130     pub fn digital_signature(&mut self) -> &mut KeyUsage {
131         self.digital_signature = true;
132         self
133     }
134 
135     /// Sets the `nonRepudiation` flag to `true`.
non_repudiation(&mut self) -> &mut KeyUsage136     pub fn non_repudiation(&mut self) -> &mut KeyUsage {
137         self.non_repudiation = true;
138         self
139     }
140 
141     /// Sets the `keyEncipherment` flag to `true`.
key_encipherment(&mut self) -> &mut KeyUsage142     pub fn key_encipherment(&mut self) -> &mut KeyUsage {
143         self.key_encipherment = true;
144         self
145     }
146 
147     /// Sets the `dataEncipherment` flag to `true`.
data_encipherment(&mut self) -> &mut KeyUsage148     pub fn data_encipherment(&mut self) -> &mut KeyUsage {
149         self.data_encipherment = true;
150         self
151     }
152 
153     /// Sets the `keyAgreement` flag to `true`.
key_agreement(&mut self) -> &mut KeyUsage154     pub fn key_agreement(&mut self) -> &mut KeyUsage {
155         self.key_agreement = true;
156         self
157     }
158 
159     /// Sets the `keyCertSign` flag to `true`.
key_cert_sign(&mut self) -> &mut KeyUsage160     pub fn key_cert_sign(&mut self) -> &mut KeyUsage {
161         self.key_cert_sign = true;
162         self
163     }
164 
165     /// Sets the `cRLSign` flag to `true`.
crl_sign(&mut self) -> &mut KeyUsage166     pub fn crl_sign(&mut self) -> &mut KeyUsage {
167         self.crl_sign = true;
168         self
169     }
170 
171     /// Sets the `encipherOnly` flag to `true`.
encipher_only(&mut self) -> &mut KeyUsage172     pub fn encipher_only(&mut self) -> &mut KeyUsage {
173         self.encipher_only = true;
174         self
175     }
176 
177     /// Sets the `decipherOnly` flag to `true`.
decipher_only(&mut self) -> &mut KeyUsage178     pub fn decipher_only(&mut self) -> &mut KeyUsage {
179         self.decipher_only = true;
180         self
181     }
182 
183     /// Return the `KeyUsage` extension as an `X509Extension`.
build(&self) -> Result<X509Extension, ErrorStack>184     pub fn build(&self) -> Result<X509Extension, ErrorStack> {
185         let mut value = String::new();
186         let mut first = true;
187         append(&mut value, &mut first, self.critical, "critical");
188         append(
189             &mut value,
190             &mut first,
191             self.digital_signature,
192             "digitalSignature",
193         );
194         append(
195             &mut value,
196             &mut first,
197             self.non_repudiation,
198             "nonRepudiation",
199         );
200         append(
201             &mut value,
202             &mut first,
203             self.key_encipherment,
204             "keyEncipherment",
205         );
206         append(
207             &mut value,
208             &mut first,
209             self.data_encipherment,
210             "dataEncipherment",
211         );
212         append(&mut value, &mut first, self.key_agreement, "keyAgreement");
213         append(&mut value, &mut first, self.key_cert_sign, "keyCertSign");
214         append(&mut value, &mut first, self.crl_sign, "cRLSign");
215         append(&mut value, &mut first, self.encipher_only, "encipherOnly");
216         append(&mut value, &mut first, self.decipher_only, "decipherOnly");
217         X509Extension::new_nid(None, None, Nid::KEY_USAGE, &value)
218     }
219 }
220 
221 /// An extension consisting of a list of usages indicating purposes
222 /// for which the certificate public key can be used for.
223 pub struct ExtendedKeyUsage {
224     critical: bool,
225     server_auth: bool,
226     client_auth: bool,
227     code_signing: bool,
228     email_protection: bool,
229     time_stamping: bool,
230     ms_code_ind: bool,
231     ms_code_com: bool,
232     ms_ctl_sign: bool,
233     ms_sgc: bool,
234     ms_efs: bool,
235     ns_sgc: bool,
236     other: Vec<String>,
237 }
238 
239 impl Default for ExtendedKeyUsage {
default() -> ExtendedKeyUsage240     fn default() -> ExtendedKeyUsage {
241         ExtendedKeyUsage::new()
242     }
243 }
244 
245 impl ExtendedKeyUsage {
246     /// Construct a new `ExtendedKeyUsage` extension.
new() -> ExtendedKeyUsage247     pub fn new() -> ExtendedKeyUsage {
248         ExtendedKeyUsage {
249             critical: false,
250             server_auth: false,
251             client_auth: false,
252             code_signing: false,
253             email_protection: false,
254             time_stamping: false,
255             ms_code_ind: false,
256             ms_code_com: false,
257             ms_ctl_sign: false,
258             ms_sgc: false,
259             ms_efs: false,
260             ns_sgc: false,
261             other: vec![],
262         }
263     }
264 
265     /// Sets the `critical` flag to `true`. The extension will be critical.
critical(&mut self) -> &mut ExtendedKeyUsage266     pub fn critical(&mut self) -> &mut ExtendedKeyUsage {
267         self.critical = true;
268         self
269     }
270 
271     /// Sets the `serverAuth` flag to `true`.
server_auth(&mut self) -> &mut ExtendedKeyUsage272     pub fn server_auth(&mut self) -> &mut ExtendedKeyUsage {
273         self.server_auth = true;
274         self
275     }
276 
277     /// Sets the `clientAuth` flag to `true`.
client_auth(&mut self) -> &mut ExtendedKeyUsage278     pub fn client_auth(&mut self) -> &mut ExtendedKeyUsage {
279         self.client_auth = true;
280         self
281     }
282 
283     /// Sets the `codeSigning` flag to `true`.
code_signing(&mut self) -> &mut ExtendedKeyUsage284     pub fn code_signing(&mut self) -> &mut ExtendedKeyUsage {
285         self.code_signing = true;
286         self
287     }
288 
289     /// Sets the `emailProtection` flag to `true`.
email_protection(&mut self) -> &mut ExtendedKeyUsage290     pub fn email_protection(&mut self) -> &mut ExtendedKeyUsage {
291         self.email_protection = true;
292         self
293     }
294 
295     /// Sets the `timeStamping` flag to `true`.
time_stamping(&mut self) -> &mut ExtendedKeyUsage296     pub fn time_stamping(&mut self) -> &mut ExtendedKeyUsage {
297         self.time_stamping = true;
298         self
299     }
300 
301     /// Sets the `msCodeInd` flag to `true`.
ms_code_ind(&mut self) -> &mut ExtendedKeyUsage302     pub fn ms_code_ind(&mut self) -> &mut ExtendedKeyUsage {
303         self.ms_code_ind = true;
304         self
305     }
306 
307     /// Sets the `msCodeCom` flag to `true`.
ms_code_com(&mut self) -> &mut ExtendedKeyUsage308     pub fn ms_code_com(&mut self) -> &mut ExtendedKeyUsage {
309         self.ms_code_com = true;
310         self
311     }
312 
313     /// Sets the `msCTLSign` flag to `true`.
ms_ctl_sign(&mut self) -> &mut ExtendedKeyUsage314     pub fn ms_ctl_sign(&mut self) -> &mut ExtendedKeyUsage {
315         self.ms_ctl_sign = true;
316         self
317     }
318 
319     /// Sets the `msSGC` flag to `true`.
ms_sgc(&mut self) -> &mut ExtendedKeyUsage320     pub fn ms_sgc(&mut self) -> &mut ExtendedKeyUsage {
321         self.ms_sgc = true;
322         self
323     }
324 
325     /// Sets the `msEFS` flag to `true`.
ms_efs(&mut self) -> &mut ExtendedKeyUsage326     pub fn ms_efs(&mut self) -> &mut ExtendedKeyUsage {
327         self.ms_efs = true;
328         self
329     }
330 
331     /// Sets the `nsSGC` flag to `true`.
ns_sgc(&mut self) -> &mut ExtendedKeyUsage332     pub fn ns_sgc(&mut self) -> &mut ExtendedKeyUsage {
333         self.ns_sgc = true;
334         self
335     }
336 
337     /// Sets a flag not already defined.
other(&mut self, other: &str) -> &mut ExtendedKeyUsage338     pub fn other(&mut self, other: &str) -> &mut ExtendedKeyUsage {
339         self.other.push(other.to_owned());
340         self
341     }
342 
343     /// Return the `ExtendedKeyUsage` extension as an `X509Extension`.
build(&self) -> Result<X509Extension, ErrorStack>344     pub fn build(&self) -> Result<X509Extension, ErrorStack> {
345         let mut value = String::new();
346         let mut first = true;
347         append(&mut value, &mut first, self.critical, "critical");
348         append(&mut value, &mut first, self.server_auth, "serverAuth");
349         append(&mut value, &mut first, self.client_auth, "clientAuth");
350         append(&mut value, &mut first, self.code_signing, "codeSigning");
351         append(
352             &mut value,
353             &mut first,
354             self.email_protection,
355             "emailProtection",
356         );
357         append(&mut value, &mut first, self.time_stamping, "timeStamping");
358         append(&mut value, &mut first, self.ms_code_ind, "msCodeInd");
359         append(&mut value, &mut first, self.ms_code_com, "msCodeCom");
360         append(&mut value, &mut first, self.ms_ctl_sign, "msCTLSign");
361         append(&mut value, &mut first, self.ms_sgc, "msSGC");
362         append(&mut value, &mut first, self.ms_efs, "msEFS");
363         append(&mut value, &mut first, self.ns_sgc, "nsSGC");
364         for other in &self.other {
365             append(&mut value, &mut first, true, other);
366         }
367         X509Extension::new_nid(None, None, Nid::EXT_KEY_USAGE, &value)
368     }
369 }
370 
371 /// An extension that provides a means of identifying certificates that contain a
372 /// particular public key.
373 pub struct SubjectKeyIdentifier {
374     critical: bool,
375 }
376 
377 impl Default for SubjectKeyIdentifier {
default() -> SubjectKeyIdentifier378     fn default() -> SubjectKeyIdentifier {
379         SubjectKeyIdentifier::new()
380     }
381 }
382 
383 impl SubjectKeyIdentifier {
384     /// Construct a new `SubjectKeyIdentifier` extension.
new() -> SubjectKeyIdentifier385     pub fn new() -> SubjectKeyIdentifier {
386         SubjectKeyIdentifier { critical: false }
387     }
388 
389     /// Sets the `critical` flag to `true`. The extension will be critical.
critical(&mut self) -> &mut SubjectKeyIdentifier390     pub fn critical(&mut self) -> &mut SubjectKeyIdentifier {
391         self.critical = true;
392         self
393     }
394 
395     /// Return a `SubjectKeyIdentifier` extension as an `X509Extension`.
build(&self, ctx: &X509v3Context<'_>) -> Result<X509Extension, ErrorStack>396     pub fn build(&self, ctx: &X509v3Context<'_>) -> Result<X509Extension, ErrorStack> {
397         let mut value = String::new();
398         let mut first = true;
399         append(&mut value, &mut first, self.critical, "critical");
400         append(&mut value, &mut first, true, "hash");
401         X509Extension::new_nid(None, Some(ctx), Nid::SUBJECT_KEY_IDENTIFIER, &value)
402     }
403 }
404 
405 /// An extension that provides a means of identifying the public key corresponding
406 /// to the private key used to sign a CRL.
407 pub struct AuthorityKeyIdentifier {
408     critical: bool,
409     keyid: Option<bool>,
410     issuer: Option<bool>,
411 }
412 
413 impl Default for AuthorityKeyIdentifier {
default() -> AuthorityKeyIdentifier414     fn default() -> AuthorityKeyIdentifier {
415         AuthorityKeyIdentifier::new()
416     }
417 }
418 
419 impl AuthorityKeyIdentifier {
420     /// Construct a new `AuthorityKeyIdentifier` extension.
new() -> AuthorityKeyIdentifier421     pub fn new() -> AuthorityKeyIdentifier {
422         AuthorityKeyIdentifier {
423             critical: false,
424             keyid: None,
425             issuer: None,
426         }
427     }
428 
429     /// Sets the `critical` flag to `true`. The extension will be critical.
critical(&mut self) -> &mut AuthorityKeyIdentifier430     pub fn critical(&mut self) -> &mut AuthorityKeyIdentifier {
431         self.critical = true;
432         self
433     }
434 
435     /// Sets the `keyid` flag.
keyid(&mut self, always: bool) -> &mut AuthorityKeyIdentifier436     pub fn keyid(&mut self, always: bool) -> &mut AuthorityKeyIdentifier {
437         self.keyid = Some(always);
438         self
439     }
440 
441     /// Sets the `issuer` flag.
issuer(&mut self, always: bool) -> &mut AuthorityKeyIdentifier442     pub fn issuer(&mut self, always: bool) -> &mut AuthorityKeyIdentifier {
443         self.issuer = Some(always);
444         self
445     }
446 
447     /// Return a `AuthorityKeyIdentifier` extension as an `X509Extension`.
build(&self, ctx: &X509v3Context<'_>) -> Result<X509Extension, ErrorStack>448     pub fn build(&self, ctx: &X509v3Context<'_>) -> Result<X509Extension, ErrorStack> {
449         let mut value = String::new();
450         let mut first = true;
451         append(&mut value, &mut first, self.critical, "critical");
452         match self.keyid {
453             Some(true) => append(&mut value, &mut first, true, "keyid:always"),
454             Some(false) => append(&mut value, &mut first, true, "keyid"),
455             None => {}
456         }
457         match self.issuer {
458             Some(true) => append(&mut value, &mut first, true, "issuer:always"),
459             Some(false) => append(&mut value, &mut first, true, "issuer"),
460             None => {}
461         }
462         X509Extension::new_nid(None, Some(ctx), Nid::AUTHORITY_KEY_IDENTIFIER, &value)
463     }
464 }
465 
466 /// An extension that allows additional identities to be bound to the subject
467 /// of the certificate.
468 pub struct SubjectAlternativeName {
469     critical: bool,
470     names: Vec<String>,
471 }
472 
473 impl Default for SubjectAlternativeName {
default() -> SubjectAlternativeName474     fn default() -> SubjectAlternativeName {
475         SubjectAlternativeName::new()
476     }
477 }
478 
479 impl SubjectAlternativeName {
480     /// Construct a new `SubjectAlternativeName` extension.
new() -> SubjectAlternativeName481     pub fn new() -> SubjectAlternativeName {
482         SubjectAlternativeName {
483             critical: false,
484             names: vec![],
485         }
486     }
487 
488     /// Sets the `critical` flag to `true`. The extension will be critical.
critical(&mut self) -> &mut SubjectAlternativeName489     pub fn critical(&mut self) -> &mut SubjectAlternativeName {
490         self.critical = true;
491         self
492     }
493 
494     /// Sets the `email` flag.
email(&mut self, email: &str) -> &mut SubjectAlternativeName495     pub fn email(&mut self, email: &str) -> &mut SubjectAlternativeName {
496         self.names.push(format!("email:{}", email));
497         self
498     }
499 
500     /// Sets the `uri` flag.
uri(&mut self, uri: &str) -> &mut SubjectAlternativeName501     pub fn uri(&mut self, uri: &str) -> &mut SubjectAlternativeName {
502         self.names.push(format!("URI:{}", uri));
503         self
504     }
505 
506     /// Sets the `dns` flag.
dns(&mut self, dns: &str) -> &mut SubjectAlternativeName507     pub fn dns(&mut self, dns: &str) -> &mut SubjectAlternativeName {
508         self.names.push(format!("DNS:{}", dns));
509         self
510     }
511 
512     /// Sets the `rid` flag.
rid(&mut self, rid: &str) -> &mut SubjectAlternativeName513     pub fn rid(&mut self, rid: &str) -> &mut SubjectAlternativeName {
514         self.names.push(format!("RID:{}", rid));
515         self
516     }
517 
518     /// Sets the `ip` flag.
ip(&mut self, ip: &str) -> &mut SubjectAlternativeName519     pub fn ip(&mut self, ip: &str) -> &mut SubjectAlternativeName {
520         self.names.push(format!("IP:{}", ip));
521         self
522     }
523 
524     /// Sets the `dirName` flag.
dir_name(&mut self, dir_name: &str) -> &mut SubjectAlternativeName525     pub fn dir_name(&mut self, dir_name: &str) -> &mut SubjectAlternativeName {
526         self.names.push(format!("dirName:{}", dir_name));
527         self
528     }
529 
530     /// Sets the `otherName` flag.
other_name(&mut self, other_name: &str) -> &mut SubjectAlternativeName531     pub fn other_name(&mut self, other_name: &str) -> &mut SubjectAlternativeName {
532         self.names.push(format!("otherName:{}", other_name));
533         self
534     }
535 
536     /// Return a `SubjectAlternativeName` extension as an `X509Extension`.
build(&self, ctx: &X509v3Context<'_>) -> Result<X509Extension, ErrorStack>537     pub fn build(&self, ctx: &X509v3Context<'_>) -> Result<X509Extension, ErrorStack> {
538         let mut value = String::new();
539         let mut first = true;
540         append(&mut value, &mut first, self.critical, "critical");
541         for name in &self.names {
542             append(&mut value, &mut first, true, name);
543         }
544         X509Extension::new_nid(None, Some(ctx), Nid::SUBJECT_ALT_NAME, &value)
545     }
546 }
547 
append(value: &mut String, first: &mut bool, should: bool, element: &str)548 fn append(value: &mut String, first: &mut bool, should: bool, element: &str) {
549     if !should {
550         return;
551     }
552 
553     if !*first {
554         value.push(',');
555     }
556     *first = false;
557     value.push_str(element);
558 }
559