Skip to main content

webpki/
sct.rs

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