aboutsummaryrefslogtreecommitdiff
path: root/src/attr.rs
blob: d4cccc30e78ae7e72e2fa164c89210513ff4f90e (plain)
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
//! Attribute-related definitions as defined in X.501 (and updated by RFC 5280).

use alloc::vec::Vec;
use const_oid::db::{
    rfc4519::{COUNTRY_NAME, DOMAIN_COMPONENT, SERIAL_NUMBER},
    Database, DB,
};
use core::{
    fmt::{self, Write},
    str::FromStr,
};
use der::{
    asn1::{
        Any, Ia5StringRef, ObjectIdentifier, PrintableStringRef, SetOfVec, TeletexStringRef,
        Utf8StringRef,
    },
    Decode, Encode, Error, ErrorKind, Sequence, Tag, Tagged, ValueOrd,
};

/// X.501 `AttributeType` as defined in [RFC 5280 Appendix A.1].
///
/// ```text
/// AttributeType           ::= OBJECT IDENTIFIER
/// ```
///
/// [RFC 5280 Appendix A.1]: https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1
pub type AttributeType = ObjectIdentifier;

/// X.501 `AttributeValue` as defined in [RFC 5280 Appendix A.1].
///
/// ```text
/// AttributeValue          ::= ANY
/// ```
///
/// [RFC 5280 Appendix A.1]: https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1
pub type AttributeValue = Any;

/// X.501 `Attribute` as defined in [RFC 5280 Appendix A.1].
///
/// ```text
/// Attribute               ::= SEQUENCE {
///     type             AttributeType,
///     values    SET OF AttributeValue -- at least one value is required
/// }
/// ```
///
/// Note that [RFC 2986 Section 4] defines a constrained version of this type:
///
/// ```text
/// Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
///     type   ATTRIBUTE.&id({IOSet}),
///     values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type})
/// }
/// ```
///
/// The unconstrained version should be preferred.
///
/// [RFC 2986 Section 4]: https://datatracker.ietf.org/doc/html/rfc2986#section-4
/// [RFC 5280 Appendix A.1]: https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1
#[derive(Clone, Debug, PartialEq, Eq, Sequence, ValueOrd)]
#[allow(missing_docs)]
pub struct Attribute {
    pub oid: AttributeType,
    pub values: SetOfVec<AttributeValue>,
}

/// X.501 `Attributes` as defined in [RFC 2986 Section 4].
///
/// ```text
/// Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
/// ```
///
/// [RFC 2986 Section 4]: https://datatracker.ietf.org/doc/html/rfc2986#section-4
pub type Attributes = SetOfVec<Attribute>;

/// X.501 `AttributeTypeAndValue` as defined in [RFC 5280 Appendix A.1].
///
/// ```text
/// AttributeTypeAndValue ::= SEQUENCE {
///   type     AttributeType,
///   value    AttributeValue
/// }
/// ```
///
/// [RFC 5280 Appendix A.1]: https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Sequence, ValueOrd)]
#[allow(missing_docs)]
pub struct AttributeTypeAndValue {
    pub oid: AttributeType,
    pub value: AttributeValue,
}

#[derive(Copy, Clone)]
enum Escape {
    None,
    Some,
    Hex(u8),
}

struct Parser {
    state: Escape,
    bytes: Vec<u8>,
}

impl Parser {
    pub fn new() -> Self {
        Self {
            state: Escape::None,
            bytes: Vec::new(),
        }
    }

    fn push(&mut self, c: u8) {
        self.state = Escape::None;
        self.bytes.push(c);
    }

    pub fn add(&mut self, c: u8) -> Result<(), Error> {
        match (self.state, c) {
            (Escape::Hex(p), b'0'..=b'9') => self.push(p | (c - b'0')),
            (Escape::Hex(p), b'a'..=b'f') => self.push(p | (c - b'a' + 10)),
            (Escape::Hex(p), b'A'..=b'F') => self.push(p | (c - b'A' + 10)),

            (Escape::Some, b'0'..=b'9') => self.state = Escape::Hex((c - b'0') << 4),
            (Escape::Some, b'a'..=b'f') => self.state = Escape::Hex((c - b'a' + 10) << 4),
            (Escape::Some, b'A'..=b'F') => self.state = Escape::Hex((c - b'A' + 10) << 4),

            (Escape::Some, b' ' | b'"' | b'#' | b'=' | b'\\') => self.push(c),
            (Escape::Some, b'+' | b',' | b';' | b'<' | b'>') => self.push(c),

            (Escape::None, b'\\') => self.state = Escape::Some,
            (Escape::None, ..) => self.push(c),

            _ => return Err(ErrorKind::Failed.into()),
        }

        Ok(())
    }

    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }
}

impl AttributeTypeAndValue {
    /// Parses the hex value in the `OID=#HEX` format.
    fn from_hex(oid: ObjectIdentifier, val: &str) -> Result<Self, Error> {
        // Ensure an even number of hex bytes.
        let mut iter = match val.len() % 2 {
            0 => [].iter().cloned().chain(val.bytes()),
            1 => [0u8].iter().cloned().chain(val.bytes()),
            _ => unreachable!(),
        };

        // Decode der bytes from hex.
        let mut bytes = Vec::with_capacity((val.len() + 1) / 2);

        while let (Some(h), Some(l)) = (iter.next(), iter.next()) {
            let mut byte = 0u8;

            for (half, shift) in [(h, 4), (l, 0)] {
                match half {
                    b'0'..=b'9' => byte |= (half - b'0') << shift,
                    b'a'..=b'f' => byte |= (half - b'a' + 10) << shift,
                    b'A'..=b'F' => byte |= (half - b'A' + 10) << shift,
                    _ => return Err(ErrorKind::Failed.into()),
                }
            }

            bytes.push(byte);
        }

        Ok(Self {
            oid,
            value: Any::from_der(&bytes)?,
        })
    }

    /// Parses the string value in the `NAME=STRING` format.
    fn from_delimited_str(oid: ObjectIdentifier, val: &str) -> Result<Self, Error> {
        // Undo escaping.
        let mut parser = Parser::new();
        for c in val.bytes() {
            parser.add(c)?;
        }

        let tag = match oid {
            COUNTRY_NAME => Tag::PrintableString,
            DOMAIN_COMPONENT => Tag::Ia5String,
            // Serial numbers are formatted as Printable String as per RFC 5280 Appendix A.1:
            // https://datatracker.ietf.org/doc/html/rfc5280#appendix-A.1
            SERIAL_NUMBER => Tag::PrintableString,
            _ => Tag::Utf8String,
        };

        Ok(Self {
            oid,
            value: Any::new(tag, parser.as_bytes())?,
        })
    }

    /// Converts an AttributeTypeAndValue string into an encoded AttributeTypeAndValue
    ///
    /// This function follows the rules in [RFC 4514].
    ///
    /// [RFC 4514]: https://datatracker.ietf.org/doc/html/rfc4514
    #[deprecated(
        since = "0.2.1",
        note = "use AttributeTypeAndValue::from_str(...)?.to_der()"
    )]
    pub fn encode_from_string(s: &str) -> Result<Vec<u8>, Error> {
        Self::from_str(s)?.to_der()
    }
}

/// Parse an [`AttributeTypeAndValue`] string.
///
/// This function follows the rules in [RFC 4514].
///
/// [RFC 4514]: https://datatracker.ietf.org/doc/html/rfc4514
impl FromStr for AttributeTypeAndValue {
    type Err = Error;

    fn from_str(s: &str) -> der::Result<Self> {
        let idx = s.find('=').ok_or_else(|| Error::from(ErrorKind::Failed))?;
        let (key, val) = s.split_at(idx);
        let val = &val[1..];

        // Either decode or lookup the OID for the given key.
        let oid = match DB.by_name(key) {
            Some(oid) => *oid,
            None => ObjectIdentifier::new(key)?,
        };

        // If the value is hex-encoded DER...
        match val.strip_prefix('#') {
            Some(val) => Self::from_hex(oid, val),
            None => Self::from_delimited_str(oid, val),
        }
    }
}

/// Serializes the structure according to the rules in [RFC 4514].
///
/// [RFC 4514]: https://datatracker.ietf.org/doc/html/rfc4514
impl fmt::Display for AttributeTypeAndValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let val = match self.value.tag() {
            Tag::PrintableString => PrintableStringRef::try_from(&self.value)
                .ok()
                .map(|s| s.as_str()),
            Tag::Utf8String => Utf8StringRef::try_from(&self.value)
                .ok()
                .map(|s| s.as_str()),
            Tag::Ia5String => Ia5StringRef::try_from(&self.value).ok().map(|s| s.as_str()),
            Tag::TeletexString => TeletexStringRef::try_from(&self.value)
                .ok()
                .map(|s| s.as_str()),
            _ => None,
        };

        if let (Some(key), Some(val)) = (DB.shortest_name_by_oid(&self.oid), val) {
            write!(f, "{}=", key.to_ascii_uppercase())?;

            let mut iter = val.char_indices().peekable();
            while let Some((i, c)) = iter.next() {
                match c {
                    '#' if i == 0 => write!(f, "\\#")?,
                    ' ' if i == 0 || iter.peek().is_none() => write!(f, "\\ ")?,
                    '"' | '+' | ',' | ';' | '<' | '>' | '\\' => write!(f, "\\{}", c)?,
                    '\x00'..='\x1f' | '\x7f' => write!(f, "\\{:02x}", c as u8)?,
                    _ => f.write_char(c)?,
                }
            }
        } else {
            let value = self.value.to_der().or(Err(fmt::Error))?;

            write!(f, "{}=#", self.oid)?;
            for c in value {
                write!(f, "{:02x}", c)?;
            }
        }

        Ok(())
    }
}

/// Helper trait to bring shortest name by oid lookups to Database
trait ShortestName {
    fn shortest_name_by_oid(&self, oid: &ObjectIdentifier) -> Option<&str>;
}

impl<'a> ShortestName for Database<'a> {
    fn shortest_name_by_oid(&self, oid: &ObjectIdentifier) -> Option<&'a str> {
        let mut best_match: Option<&'a str> = None;

        for m in self.find_names_for_oid(*oid) {
            if let Some(previous) = best_match {
                if m.len() < previous.len() {
                    best_match = Some(m);
                }
            } else {
                best_match = Some(m);
            }
        }

        best_match
    }
}