1 // Copyright 2015 Brian Smith.
2 //
3 // Permission to use, copy, modify, and/or distribute this software for any
4 // purpose with or without fee is hereby granted, provided that the above
5 // copyright notice and this permission notice appear in all copies.
6 //
7 // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8 // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
10 // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
12 // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
13 // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14 
15 //! Utilities for efficiently embedding trust anchors in programs.
16 
17 use super::der;
18 use crate::{
19     cert::{certificate_serial_number, parse_cert_internal, Cert, EndEntityOrCA},
20     Error, TrustAnchor,
21 };
22 
23 /// Interprets the given DER-encoded certificate as a `TrustAnchor`. The
24 /// certificate is not validated. In particular, there is no check that the
25 /// certificate is self-signed or even that the certificate has the cA basic
26 /// constraint.
cert_der_as_trust_anchor(cert_der: &[u8]) -> Result<TrustAnchor, Error>27 pub fn cert_der_as_trust_anchor(cert_der: &[u8]) -> Result<TrustAnchor, Error> {
28     let cert_der = untrusted::Input::from(cert_der);
29 
30     // XXX: `EndEntityOrCA::EndEntity` is used instead of `EndEntityOrCA::CA`
31     // because we don't have a reference to a child cert, which is needed for
32     // `EndEntityOrCA::CA`. For this purpose, it doesn't matter.
33     //
34     // v1 certificates will result in `Error::BadDER` because `parse_cert` will
35     // expect a version field that isn't there. In that case, try to parse the
36     // certificate using a special parser for v1 certificates. Notably, that
37     // parser doesn't allow extensions, so there's no need to worry about
38     // embedded name constraints in a v1 certificate.
39     match parse_cert_internal(
40         cert_der,
41         EndEntityOrCA::EndEntity,
42         possibly_invalid_certificate_serial_number,
43     ) {
44         Ok(cert) => Ok(trust_anchor_from_cert(cert)),
45         Err(Error::BadDER) => parse_cert_v1(cert_der).or(Err(Error::BadDER)),
46         Err(err) => Err(err),
47     }
48 }
49 
possibly_invalid_certificate_serial_number<'a>( input: &mut untrusted::Reader<'a>, ) -> Result<(), Error>50 fn possibly_invalid_certificate_serial_number<'a>(
51     input: &mut untrusted::Reader<'a>,
52 ) -> Result<(), Error> {
53     // https://tools.ietf.org/html/rfc5280#section-4.1.2.2:
54     // * Conforming CAs MUST NOT use serialNumber values longer than 20 octets."
55     // * "The serial number MUST be a positive integer [...]"
56     //
57     // However, we don't enforce these constraints on trust anchors, as there
58     // are widely-deployed trust anchors that violate these constraints.
59     skip(input, der::Tag::Integer)
60 }
61 
62 /// Generates code for hard-coding the given trust anchors into a program. This
63 /// is designed to be used in a build script. `name` is the name of the public
64 /// static variable that will contain the TrustAnchor array.
generate_code_for_trust_anchors(name: &str, trust_anchors: &[TrustAnchor]) -> String65 pub fn generate_code_for_trust_anchors(name: &str, trust_anchors: &[TrustAnchor]) -> String {
66     let decl = format!(
67         "static {}: [TrustAnchor<'static>; {}] = ",
68         name,
69         trust_anchors.len()
70     );
71 
72     // "{:?}" formats the array of trust anchors as Rust code, approximately,
73     // except that it drops the leading "&" on slices.
74     let value = str::replace(&format!("{:?};\n", trust_anchors), ": [", ": &[");
75 
76     decl + &value
77 }
78 
trust_anchor_from_cert<'a>(cert: Cert<'a>) -> TrustAnchor<'a>79 fn trust_anchor_from_cert<'a>(cert: Cert<'a>) -> TrustAnchor<'a> {
80     TrustAnchor {
81         subject: cert.subject.as_slice_less_safe(),
82         spki: cert.spki.value().as_slice_less_safe(),
83         name_constraints: cert.name_constraints.map(|nc| nc.as_slice_less_safe()),
84     }
85 }
86 
87 /// Parses a v1 certificate directly into a TrustAnchor.
parse_cert_v1<'a>(cert_der: untrusted::Input<'a>) -> Result<TrustAnchor<'a>, Error>88 fn parse_cert_v1<'a>(cert_der: untrusted::Input<'a>) -> Result<TrustAnchor<'a>, Error> {
89     // X.509 Certificate: https://tools.ietf.org/html/rfc5280#section-4.1.
90     cert_der.read_all(Error::BadDER, |cert_der| {
91         der::nested(cert_der, der::Tag::Sequence, Error::BadDER, |cert_der| {
92             let anchor = der::nested(cert_der, der::Tag::Sequence, Error::BadDER, |tbs| {
93                 // The version number field does not appear in v1 certificates.
94                 certificate_serial_number(tbs)?;
95 
96                 skip(tbs, der::Tag::Sequence)?; // signature.
97                 skip(tbs, der::Tag::Sequence)?; // issuer.
98                 skip(tbs, der::Tag::Sequence)?; // validity.
99                 let subject = der::expect_tag_and_get_value(tbs, der::Tag::Sequence)?;
100                 let spki = der::expect_tag_and_get_value(tbs, der::Tag::Sequence)?;
101 
102                 Ok(TrustAnchor {
103                     subject: subject.as_slice_less_safe(),
104                     spki: spki.as_slice_less_safe(),
105                     name_constraints: None,
106                 })
107             });
108 
109             // read and discard signatureAlgorithm + signature
110             skip(cert_der, der::Tag::Sequence)?;
111             skip(cert_der, der::Tag::BitString)?;
112 
113             anchor
114         })
115     })
116 }
117 
skip(input: &mut untrusted::Reader, tag: der::Tag) -> Result<(), Error>118 fn skip(input: &mut untrusted::Reader, tag: der::Tag) -> Result<(), Error> {
119     der::expect_tag_and_get_value(input, tag).map(|_| ())
120 }
121