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