Skip to main content

coqui_peer_tls/
fields.rs

1//! The identifying fields of a certificate, parsed once for every consumer: names, subject
2//! alternative names, serial, fingerprint and validity.
3
4use alloc::collections::BTreeMap;
5use core::fmt;
6use core::net::{IpAddr, Ipv4Addr, Ipv6Addr};
7
8use x509_parser::asn1_rs::{Any, FromDer};
9use x509_parser::extensions::GeneralName;
10use x509_parser::x509::X509Name;
11
12use crate::error::PeerError;
13use coqui_peer::PeerId;
14
15/// The Microsoft user principal name, an `otherName` holding a UTF8String.
16const UPN: &str = "1.3.6.1.4.1.311.20.2.3";
17
18/// A distinguished name: its text as x509-parser displays it (`CN=a, O=b`) and its
19/// attributes in certificate order, each `(short name, value)`.
20#[derive(Debug, Clone, PartialEq, Eq)]
21#[non_exhaustive]
22pub struct Name {
23    /// The whole name as text.
24    pub text: String,
25    /// The attributes in order: `cn`, `o`, `ou`, `c`, `st`, `l`, `dc`, `uid`, `email`,
26    /// `serialnumber`, or the dotted OID for any other. A value that is not a string type is
27    /// `#` and its hex.
28    pub attributes: Vec<(String, String)>,
29}
30
31/// A subject alternative name.
32#[derive(Debug, Clone, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum San {
35    /// A `dNSName`. Some issuers put an IP address here, for clients that do not read IP
36    /// SANs; [`San::ip`] gives it as an address.
37    Dns(String),
38    /// An `rfc822Name` (email).
39    Email(String),
40    /// A `uniformResourceIdentifier`.
41    Uri(String),
42    /// An `iPAddress`.
43    Ip(IpAddr),
44    /// A Microsoft user principal name (`otherName` 1.3.6.1.4.1.311.20.2.3).
45    Upn(String),
46    /// Any other `otherName`: its OID and the DER of its value.
47    Other {
48        /// The dotted OID.
49        oid: String,
50        /// The DER encoding of the value, its `[0]` wrapper included.
51        der: Vec<u8>,
52    },
53}
54
55impl San {
56    /// The address this name holds: an `iPAddress`, or a `dNSName` whose text is an IP
57    /// literal. Canonical: an IPv4-mapped IPv6 address is its IPv4 address.
58    pub fn ip(&self) -> Option<IpAddr> {
59        match self {
60            Self::Ip(address) => Some(address.to_canonical()),
61            Self::Dns(name) => name
62                .parse::<IpAddr>()
63                .ok()
64                .map(|address| address.to_canonical()),
65            _ => None,
66        }
67    }
68}
69
70/// The identifying fields of a certificate (feature `fields`).
71///
72/// `Debug` shows only the fingerprint.
73#[derive(Clone, PartialEq, Eq)]
74#[non_exhaustive]
75pub struct CertificateFields {
76    /// The subject.
77    pub subject: Name,
78    /// The issuer.
79    pub issuer: Name,
80    /// The subject alternative names, in certificate order.
81    pub sans: Vec<San>,
82    /// The serial number's bytes as encoded.
83    pub serial: Vec<u8>,
84    /// The certificate's SHA-256 id.
85    pub fingerprint: PeerId,
86    /// The start of the validity period, Unix seconds.
87    pub not_before: i64,
88    /// The end of the validity period, Unix seconds.
89    pub not_after: i64,
90}
91
92impl fmt::Debug for CertificateFields {
93    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
94        formatter
95            .debug_struct("CertificateFields")
96            .field("fingerprint", &self.fingerprint)
97            .finish_non_exhaustive()
98    }
99}
100
101impl CertificateFields {
102    /// Parses the DER encoding of one certificate. Nothing is verified: the fields are what
103    /// the certificate says.
104    ///
105    /// # Errors
106    ///
107    /// [`PeerError::Certificate`] when `der` is not exactly one well-formed certificate, or
108    /// its subject alternative names cannot be read.
109    pub fn parse(der: &[u8]) -> Result<Self, PeerError> {
110        let (rest, certificate) =
111            x509_parser::parse_x509_certificate(der).map_err(|_| PeerError::Certificate)?;
112        if !rest.is_empty() {
113            return Err(PeerError::Certificate);
114        }
115        let extension = certificate
116            .subject_alternative_name()
117            .map_err(|_| PeerError::Certificate)?;
118        let sans = extension
119            .into_iter()
120            .flat_map(|extension| extension.value.general_names.iter())
121            .filter_map(san)
122            .collect();
123        let validity = certificate.validity();
124        Ok(Self {
125            subject: name(certificate.subject()),
126            issuer: name(certificate.issuer()),
127            sans,
128            serial: certificate.raw_serial().to_vec(),
129            fingerprint: PeerId::of(der),
130            not_before: validity.not_before.timestamp(),
131            not_after: validity.not_after.timestamp(),
132        })
133    }
134
135    /// The fields as a map a consumer picks identities from, every value in certificate order:
136    ///
137    /// - `subject`, `issuer`: the names as text;
138    /// - `subject.<attr>`, `issuer.<attr>`: each attribute, by the short names of
139    ///   [`Name::attributes`];
140    /// - `san.dns`, `san.email`, `san.uri`, `san.upn`: the names as written;
141    /// - `san.ip`: each `iPAddress`, canonical (IPv6 compressed, IPv4-mapped as IPv4);
142    /// - `san.dns.ip`: each `dNSName` that is an IP literal, canonical, for a consumer that
143    ///   treats such a name as an address;
144    /// - `san.other.<oid>`: the hex DER of each other `otherName`;
145    /// - `serial`: lowercase hex, leading zero bytes dropped (`0` for zero);
146    /// - `fingerprint`: `sha256:<hex>`;
147    /// - `not_before`, `not_after`: Unix seconds.
148    pub fn to_map(&self) -> BTreeMap<String, Vec<String>> {
149        let mut map: BTreeMap<String, Vec<String>> = BTreeMap::new();
150        let mut put = |key: String, value: String| map.entry(key).or_default().push(value);
151        for (prefix, name) in [("subject", &self.subject), ("issuer", &self.issuer)] {
152            put(prefix.to_owned(), name.text.clone());
153            for (attribute, value) in &name.attributes {
154                put(format!("{prefix}.{attribute}"), value.clone());
155            }
156        }
157        for san in &self.sans {
158            match san {
159                San::Dns(name) => {
160                    put("san.dns".to_owned(), name.clone());
161                    if let Some(address) = san.ip() {
162                        put("san.dns.ip".to_owned(), address.to_string());
163                    }
164                }
165                San::Email(name) => put("san.email".to_owned(), name.clone()),
166                San::Uri(name) => put("san.uri".to_owned(), name.clone()),
167                San::Ip(_) => {
168                    if let Some(address) = san.ip() {
169                        put("san.ip".to_owned(), address.to_string());
170                    }
171                }
172                San::Upn(name) => put("san.upn".to_owned(), name.clone()),
173                San::Other { oid, der } => put(format!("san.other.{oid}"), hex(der)),
174            }
175        }
176        let serial = self
177            .serial
178            .iter()
179            .position(|byte| *byte != 0)
180            .map_or_else(|| "0".to_owned(), |first| hex(&self.serial[first..]));
181        put("serial".to_owned(), serial);
182        put("fingerprint".to_owned(), self.fingerprint.canonical());
183        put("not_before".to_owned(), self.not_before.to_string());
184        put("not_after".to_owned(), self.not_after.to_string());
185        map
186    }
187}
188
189fn hex(bytes: &[u8]) -> String {
190    use fmt::Write as _;
191    bytes.iter().fold(String::new(), |mut text, byte| {
192        let _ = write!(text, "{byte:02x}");
193        text
194    })
195}
196
197fn name(name: &X509Name<'_>) -> Name {
198    let attributes = name
199        .iter_attributes()
200        .map(|attribute| {
201            let oid = attribute.attr_type().to_id_string();
202            let short = match oid.as_str() {
203                "2.5.4.3" => "cn",
204                "2.5.4.10" => "o",
205                "2.5.4.11" => "ou",
206                "2.5.4.6" => "c",
207                "2.5.4.8" => "st",
208                "2.5.4.7" => "l",
209                "0.9.2342.19200300.100.1.25" => "dc",
210                "0.9.2342.19200300.100.1.1" => "uid",
211                "1.2.840.113549.1.9.1" => "email",
212                "2.5.4.5" => "serialnumber",
213                _ => oid.as_str(),
214            }
215            .to_owned();
216            let value = attribute.as_str().map_or_else(
217                |_| format!("#{}", hex(attribute.attr_value().data)),
218                str::to_owned,
219            );
220            (short, value)
221        })
222        .collect();
223    Name {
224        text: name.to_string(),
225        attributes,
226    }
227}
228
229fn san(name: &GeneralName<'_>) -> Option<San> {
230    Some(match name {
231        GeneralName::DNSName(text) => San::Dns((*text).to_owned()),
232        GeneralName::RFC822Name(text) => San::Email((*text).to_owned()),
233        GeneralName::URI(text) => San::Uri((*text).to_owned()),
234        GeneralName::IPAddress(bytes) => San::Ip(match bytes.len() {
235            4 => IpAddr::V4(Ipv4Addr::from(<[u8; 4]>::try_from(*bytes).ok()?)),
236            16 => IpAddr::V6(Ipv6Addr::from(<[u8; 16]>::try_from(*bytes).ok()?)),
237            _ => return None,
238        }),
239        GeneralName::OtherName(oid, value) => {
240            let oid = oid.to_id_string();
241            match (oid == UPN).then(|| upn(value)).flatten() {
242                Some(upn) => San::Upn(upn),
243                None => San::Other {
244                    oid,
245                    der: value.to_vec(),
246                },
247            }
248        }
249        _ => return None,
250    })
251}
252
253/// The UTF8String inside an `otherName` value's `[0] EXPLICIT` wrapper.
254fn upn(value: &[u8]) -> Option<String> {
255    let (_, wrapper) = Any::from_der(value).ok()?;
256    let (_, inner) = Any::from_der(wrapper.data).ok()?;
257    (inner.tag() == x509_parser::asn1_rs::Tag::Utf8String)
258        .then(|| core::str::from_utf8(inner.data).ok().map(str::to_owned))
259        .flatten()
260}