Skip to main content

webpki/
sct.rs

1use core::fmt;
2use core::marker::PhantomData;
3
4use untrusted::{Input, Reader};
5
6pub(crate) struct SctParser<'a> {
7    reader: Reader<'a>,
8    done: bool,
9}
10
11impl<'a> SctParser<'a> {
12    pub(crate) fn new(input: Option<Input<'a>>) -> Result<Self, Error> {
13        Ok(SctParser {
14            reader: match input {
15                Some(input) => Reader::new(
16                    input.read_all(Error::MalformedSct, |rd| read_field(rd, non_zero_u16_len))?,
17                ),
18                None => Reader::new(Input::from(&[])),
19            },
20            done: false,
21        })
22    }
23}
24
25impl<'a> Iterator for SctParser<'a> {
26    type Item = Result<SignedCertificateTimestamp<'a>, Error>;
27
28    fn next(&mut self) -> Option<Self::Item> {
29        if self.done || self.reader.at_end() {
30            return None;
31        }
32
33        let result = read_field(&mut self.reader, non_zero_u16_len)
34            .and_then(|item| SignedCertificateTimestamp::try_from(item.as_slice_less_safe()));
35        match result {
36            Err(Error::UnsupportedSctVersion) | Ok(_) => {}
37            Err(_) => self.done = true,
38        }
39        Some(result)
40    }
41}
42
43/// This is `SignedCertificateTimestamp` defined in [RFC6962][].
44///
45/// [RFC6962]: https://www.rfc-editor.org/rfc/rfc6962.html#section-3.2
46#[derive(Debug, PartialEq)]
47pub(crate) struct SignedCertificateTimestamp<'a> {
48    log_id: [u8; 32],
49    timestamp_ms: u64,
50    _future_lifetime_for_signature: PhantomData<&'a ()>,
51}
52
53impl SignedCertificateTimestamp<'_> {
54    pub(crate) fn log_id_and_timestamp(&self) -> LogIdAndTimestamp {
55        LogIdAndTimestamp {
56            log_id: self.log_id,
57            timestamp_ms: self.timestamp_ms,
58        }
59    }
60}
61
62impl<'a> TryFrom<&'a [u8]> for SignedCertificateTimestamp<'a> {
63    type Error = Error;
64
65    fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
66        let input = Input::from(bytes);
67        input.read_all(Error::MalformedSct, |rd| {
68            match read_array(rd)? {
69                [0] => {}
70                _ => return Err(Error::UnsupportedSctVersion),
71            };
72
73            let log_id = read_array(rd)?;
74            let timestamp_ms = u64::from_be_bytes(read_array(rd)?);
75            let _extensions = read_field(rd, any_u16_len)?;
76            let _signature_algorithm = u16::from_be_bytes(read_array(rd)?);
77            let _signature = read_field(rd, non_zero_u16_len)?;
78
79            Ok(SignedCertificateTimestamp {
80                log_id,
81                timestamp_ms,
82                _future_lifetime_for_signature: PhantomData,
83            })
84        })
85    }
86}
87
88/// The certificate transparency log ID and associated inclusion timestamp.
89#[derive(Clone, Copy, Debug, PartialEq)]
90pub struct LogIdAndTimestamp {
91    /// Log ID
92    pub log_id: [u8; 32],
93    /// Inclusion timestamp in milliseconds.
94    pub timestamp_ms: u64,
95}
96
97/// Read a length-prefixed field from `rd`.
98///
99/// The length is encoded in `N` bytes and those bytes are decoded by `into_size`.
100fn read_field<'a, const N: usize>(
101    rd: &mut Reader<'a>,
102    into_size: fn([u8; N]) -> Result<usize, Error>,
103) -> Result<Input<'a>, Error> {
104    let len = into_size(read_array::<N>(rd)?)?;
105    rd.read_bytes(len).map_err(|_| Error::MalformedSct)
106}
107
108/// Read `N` bytes from `rd` as an array.
109fn read_array<const N: usize>(rd: &mut Reader<'_>) -> Result<[u8; N], Error> {
110    rd.read_bytes(N)
111        .map_err(|_| Error::MalformedSct)?
112        .as_slice_less_safe()
113        .try_into()
114        .map_err(|_| Error::MalformedSct)
115}
116
117/// Converts two bytes into a usize.
118///
119/// Does not fail.
120fn any_u16_len(bytes: [u8; 2]) -> Result<usize, Error> {
121    Ok(usize::from(u16::from_be_bytes(bytes)))
122}
123
124/// Converts two bytes into a usize, erroring if the result is zero.
125fn non_zero_u16_len(bytes: [u8; 2]) -> Result<usize, Error> {
126    match any_u16_len(bytes)? {
127        0 => Err(Error::MalformedSct),
128        len => Ok(len),
129    }
130}
131
132/// Possible errors from SCT parsing and processing
133#[derive(Clone, Debug, PartialEq, Eq)]
134#[non_exhaustive]
135pub enum Error {
136    /// The SCT was somehow misencoded, truncated or otherwise corrupt.
137    MalformedSct,
138
139    /// An unsupported SCT version was encountered.
140    ///
141    /// This library only supports `v1(0)`.
142    UnsupportedSctVersion,
143}
144
145impl fmt::Display for Error {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        match self {
148            Self::MalformedSct => write!(f, "malformed SCT"),
149            Self::UnsupportedSctVersion => write!(f, "unsupported SCT version"),
150        }
151    }
152}
153
154#[cfg(feature = "std")]
155impl std::error::Error for Error {}
156
157#[cfg(test)]
158mod tests {
159    use alloc::vec::Vec;
160
161    use super::*;
162
163    #[test]
164    fn absent_sct_sequence() {
165        assert!(SctParser::new(None).unwrap().next().is_none());
166    }
167
168    #[test]
169    fn empty_sct_sequence() {
170        assert_eq!(
171            Some(Error::MalformedSct),
172            SctParser::new(Some(Input::from(&[]))).err()
173        );
174    }
175
176    #[test]
177    fn truncated_sct_length_in_sequence() {
178        assert_eq!(
179            Some(Error::MalformedSct),
180            SctParser::new(Some(Input::from(&[0]))).err()
181        );
182    }
183
184    #[test]
185    fn empty_sct_in_sequence() {
186        assert_eq!(
187            Some(Error::MalformedSct),
188            SctParser::new(Some(Input::from(&[0, 0]))).err()
189        );
190    }
191
192    #[test]
193    fn truncated_sct_in_sequence() {
194        assert_eq!(
195            Some(Error::MalformedSct),
196            SctParser::new(Some(Input::from(&[0, 1]))).err()
197        );
198    }
199
200    #[test]
201    fn sample_sct() {
202        let bytes = encode_sct_list([TestSct::default().encode()]);
203
204        SignedCertificateTimestamp::try_from(&bytes[4..]).unwrap();
205
206        assert_eq!(
207            SignedCertificateTimestamp {
208                log_id: [b'l'; 32],
209                timestamp_ms: 0x74747474_74747474,
210                _future_lifetime_for_signature: PhantomData
211            },
212            SctParser::new(Some(Input::from(&bytes)))
213                .unwrap()
214                .next()
215                .unwrap()
216                .unwrap()
217        );
218    }
219
220    #[test]
221    fn terminate_iterator_after_error_within_sct() {
222        let bytes = encode_sct_list([TestSct {
223            signature: Vec::new(),
224            ..Default::default()
225        }
226        .encode()]);
227
228        SignedCertificateTimestamp::try_from(&bytes[4..]).unwrap_err();
229
230        let mut iter = SctParser::new(Some(Input::from(&bytes))).unwrap();
231        assert_eq!(iter.next(), Some(Err(Error::MalformedSct)));
232        assert_eq!(iter.next(), None);
233    }
234
235    #[test]
236    fn continue_iterator_after_unsupported_version() {
237        let bytes = encode_sct_list([
238            TestSct::default().encode(),
239            vec![
240                0x1, // unsupported SCT version
241                0x7, 0x0, 0x0, 0x1, b'?', // version-specific contents
242            ],
243            TestSct {
244                log_id: [b'm'; 32],
245                timestamp_ms: u64::from_be_bytes([b'u'; 8]),
246                ..Default::default()
247            }
248            .encode(),
249        ]);
250
251        let mut iter = SctParser::new(Some(Input::from(&bytes))).unwrap();
252        assert_eq!(
253            iter.next().unwrap().unwrap().log_id_and_timestamp(),
254            LogIdAndTimestamp {
255                log_id: [b'l'; 32],
256                timestamp_ms: 0x74747474_74747474,
257            }
258        );
259        assert_eq!(iter.next(), Some(Err(Error::UnsupportedSctVersion)));
260        assert_eq!(
261            iter.next().unwrap().unwrap().log_id_and_timestamp(),
262            LogIdAndTimestamp {
263                log_id: [b'm'; 32],
264                timestamp_ms: 0x75757575_75757575,
265            }
266        );
267        assert_eq!(iter.next(), None);
268    }
269
270    #[test]
271    fn illegal_empty_signature() {
272        let bytes = TestSct {
273            signature: Vec::new(),
274            ..Default::default()
275        }
276        .encode();
277
278        assert_eq!(
279            Some(Error::MalformedSct),
280            SignedCertificateTimestamp::try_from(&bytes[..]).err()
281        );
282    }
283
284    #[test]
285    fn illegal_unknown_version() {
286        let bytes = TestSct {
287            version: 1,
288            ..Default::default()
289        }
290        .encode();
291
292        assert_eq!(
293            Some(Error::UnsupportedSctVersion),
294            SignedCertificateTimestamp::try_from(&bytes[..]).err()
295        );
296    }
297
298    #[test]
299    fn illegal_trailing_extension_data() {
300        let bytes = [
301            0x0, 0x1,  // extension outer length
302            b'?', // doesn't matter
303            b'x', // unexpected trailing data
304        ];
305
306        assert_eq!(
307            Some(Error::MalformedSct),
308            SctParser::new(Some(Input::from(&bytes))).err()
309        );
310    }
311
312    struct TestSct {
313        version: u8,
314        log_id: [u8; 32],
315        timestamp_ms: u64,
316        extensions: Vec<u8>,
317        signature_algorithm: [u8; 2],
318        signature: Vec<u8>,
319    }
320
321    impl TestSct {
322        fn encode(self) -> Vec<u8> {
323            let mut encoded = vec![self.version];
324            encoded.extend_from_slice(&self.log_id);
325            encoded.extend_from_slice(&self.timestamp_ms.to_be_bytes());
326            encoded.extend(u16_length_prefixed(self.extensions));
327            encoded.extend_from_slice(&self.signature_algorithm);
328            encoded.extend(u16_length_prefixed(self.signature));
329            encoded
330        }
331    }
332
333    impl Default for TestSct {
334        fn default() -> Self {
335            Self {
336                version: 0,
337                log_id: [b'l'; 32],
338                timestamp_ms: u64::from_be_bytes([b't'; 8]),
339                extensions: Vec::new(),
340                signature_algorithm: *b"sa",
341                signature: vec![b's'],
342            }
343        }
344    }
345
346    fn encode_sct_list(scts: impl IntoIterator<Item = Vec<u8>>) -> Vec<u8> {
347        let mut encoded = Vec::new();
348        for sct in scts {
349            encoded.extend(u16_length_prefixed(sct));
350        }
351        u16_length_prefixed(encoded)
352    }
353
354    fn u16_length_prefixed(body: Vec<u8>) -> Vec<u8> {
355        let length = u16::try_from(body.len()).unwrap();
356        let mut encoded = Vec::with_capacity(2 + body.len());
357        encoded.extend_from_slice(&length.to_be_bytes());
358        encoded.extend(body);
359        encoded
360    }
361}