certran-logs 0.1.0

Primitives and parsers for Certificate Transparency logs
Documentation
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use base64::{Engine, prelude::BASE64_STANDARD};
use std::fmt;

use ouroboros::self_referencing;
use x509_parser::prelude::*;

use crate::error::{BinaryParsingError, CtLogError};

use super::{
    model::Entry,
    util::{read_exact_bytes, read_u8, read_u16_be, read_u24_be, read_u64_be, read_vec},
};

#[cfg(feature = "debug-fmt")]
use chrono::TimeZone;

#[cfg(feature = "debug-fmt")]
use oid_registry::{OidRegistry, format_oid};

#[cfg(feature = "debug-fmt")]
use super::util::{print_x509_extension, print_x509_ski};

#[self_referencing(pub_extras)]
#[derive(Debug)]
pub struct WrapX509Certificate {
    raw: Vec<u8>,
    #[borrows(raw)]
    #[covariant]
    pub certificate: X509Certificate<'this>,
}

impl WrapX509Certificate {
    pub fn try_from_der(v: &[u8]) -> Result<Self, BinaryParsingError> {
        Ok(WrapX509CertificateBuilder {
            raw: v.to_vec(),
            certificate_builder: |raw: &Vec<u8>| X509Certificate::from_der(raw).unwrap().1,
        }
        .build())
    }
}

#[cfg(feature = "debug-fmt")]
impl fmt::Display for WrapX509Certificate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let certificate = self.borrow_certificate();
        writeln!(f, "Certificate:")?;
        writeln!(f, "  Data:")?;
        writeln!(f, "    Version: {}", certificate.version())?;
        writeln!(
            f,
            "    Serial Number: {} ({})",
            certificate.serial,
            certificate.raw_serial_as_string()
        )?;
        writeln!(
            f,
            "  Signature Algorithm: {}",
            format_oid(
                certificate.signature_algorithm.oid(),
                &OidRegistry::default().with_all_crypto()
            )
        )?;
        writeln!(f, "    Issuer: {}", certificate.issuer())?;
        writeln!(f, "    Validity:")?;
        writeln!(f, "      Not Before: {}", certificate.validity().not_before)?;
        writeln!(f, "      Not After : {}", certificate.validity().not_after)?;
        writeln!(f, "    Subject: {}", certificate.subject())?;
        writeln!(f, "    Subject Public Key Info:")?;
        print_x509_ski(f, certificate.public_key(), 6)?;

        if !certificate.extensions().is_empty() {
            writeln!(f, "    X509v3 extensions:")?;
            for extension in certificate.extensions() {
                print_x509_extension(f, &extension.oid, extension, 6)?;
            }
        }

        Ok(())
    }
}

#[self_referencing(pub_extras)]
#[derive(Debug)]
pub struct WrapTbsCertificate {
    raw: Vec<u8>,
    #[borrows(raw)]
    #[covariant]
    pub certificate: TbsCertificate<'this>,
}

impl WrapTbsCertificate {
    pub fn try_from_der(v: &[u8]) -> Result<Self, BinaryParsingError> {
        Ok(WrapTbsCertificateBuilder {
            raw: v.to_vec(),
            certificate_builder: |raw: &Vec<u8>| TbsCertificate::from_der(raw).unwrap().1,
        }
        .build())
    }
}

#[cfg(feature = "debug-fmt")]
impl fmt::Display for WrapTbsCertificate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let certificate = self.borrow_certificate();

        writeln!(f, "Certificate:")?;
        writeln!(f, "  Data:")?;
        writeln!(f, "    Version: {}", certificate.version())?;
        writeln!(
            f,
            "    Serial Number: {} ({})",
            certificate.serial,
            certificate.raw_serial_as_string()
        )?;
        writeln!(
            f,
            "  Signature Algorithm: {}",
            format_oid(
                certificate.signature.oid(),
                &OidRegistry::default().with_all_crypto()
            )
        )?;
        writeln!(f, "    Issuer: {}", certificate.issuer())?;
        writeln!(f, "    Validity:")?;
        writeln!(f, "      Not Before: {}", certificate.validity().not_before)?;
        writeln!(f, "      Not After : {}", certificate.validity().not_after)?;
        writeln!(f, "    Subject: {}", certificate.subject())?;
        writeln!(f, "    Subject Public Key Info:")?;
        print_x509_ski(f, certificate.public_key(), 6)?;

        if !certificate.extensions().is_empty() {
            writeln!(f, "    X509v3 extensions:")?;
            for extension in certificate.extensions() {
                print_x509_extension(f, &extension.oid, extension, 6)?;
            }
        }

        Ok(())
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum LogEntryType {
    X509Entry = 0,
    PrecertEntry = 1,
}

impl LogEntryType {
    pub fn parse(input: &mut &[u8]) -> Result<Self, BinaryParsingError> {
        let id = read_u16_be(input)?;
        match id {
            0 => Ok(LogEntryType::X509Entry),
            1 => Ok(LogEntryType::PrecertEntry),
            _ => Err(BinaryParsingError::InvalidSequence(format!(
                "Invalid LogEntryType id: {}",
                id
            ))),
        }
    }
}

#[derive(Debug)]
#[allow(dead_code)]
pub struct ASN1Cert {
    pub length: u32,
    pub certificate: Box<WrapX509Certificate>,
}

impl ASN1Cert {
    pub fn parse(input: &mut &[u8]) -> Result<Self, BinaryParsingError> {
        let length = read_u24_be(input)?;
        let cert_data = read_exact_bytes(input, length as usize)?;

        let wrapped_cert = WrapX509Certificate::try_from_der(cert_data)?;

        Ok(ASN1Cert {
            length,
            certificate: Box::new(wrapped_cert),
        })
    }
}

#[cfg(feature = "debug-fmt")]
impl fmt::Display for ASN1Cert {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.certificate.fmt(f)
    }
}

#[derive(Debug)]
pub struct ASN1CertChain {
    pub length: u32,
    pub certificates: Vec<ASN1Cert>,
}

impl ASN1CertChain {
    pub fn parse(input: &mut &[u8]) -> Result<Self, BinaryParsingError> {
        let total_chain_length = read_u24_be(input)?;
        let mut certs_data_slice = read_exact_bytes(input, total_chain_length as usize)?;
        let mut certificates = Vec::new();

        let mut consumed_len = 0;
        while consumed_len < total_chain_length {
            let init_len = certs_data_slice.len();
            if init_len == 0 {
                if consumed_len < total_chain_length {
                    return Err(BinaryParsingError::InsufficientData);
                }

                break;
            }

            let cert = ASN1Cert::parse(&mut certs_data_slice)?;
            consumed_len += (init_len - certs_data_slice.len()) as u32;
            certificates.push(cert);
        }
        if consumed_len != total_chain_length {
            return Err(BinaryParsingError::InvalidSequence(format!(
                "Invalid ASN1CertChain length: {}",
                consumed_len
            )));
        }

        Ok(ASN1CertChain {
            length: total_chain_length,
            certificates,
        })
    }
}

#[derive(Debug)]
pub struct PrecertChainEntry {
    pub pre_certificate: ASN1Cert,
    pub precertificate_chain: ASN1CertChain,
}

impl PrecertChainEntry {
    pub fn parse(input: &mut &[u8]) -> Result<Self, BinaryParsingError> {
        let pre_cert = ASN1Cert::parse(input)?;
        let pre_cert_chain = ASN1CertChain::parse(input)?;
        Ok(PrecertChainEntry {
            pre_certificate: pre_cert,
            precertificate_chain: pre_cert_chain,
        })
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Version {
    V1 = 0,
}

impl Version {
    pub fn parse(input: &mut &[u8]) -> Result<Self, BinaryParsingError> {
        let id = read_u8(input)?;
        match id {
            0 => Ok(Version::V1),
            _ => Err(BinaryParsingError::InvalidSequence(format!(
                "Unknown Version id: {}",
                id
            ))),
        }
    }
}

#[derive(Debug)]
pub struct IssuerKeyHash([u8; 32]);

impl IssuerKeyHash {
    pub fn parse(input: &mut &[u8]) -> Result<Self, BinaryParsingError> {
        let bytes = read_exact_bytes(input, 32)?;
        let mut arr = [0u8; 32];
        arr.copy_from_slice(bytes);
        Ok(IssuerKeyHash(arr))
    }
}

impl fmt::LowerHex for IssuerKeyHash {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for byte in &self.0 {
            write!(f, "{:02x}", byte)?;
        }
        Ok(())
    }
}

#[derive(Debug)]
pub struct PreCert {
    pub issuer_key_hash: IssuerKeyHash,
    pub length: u32,
    pub tbs_certificate: Box<WrapTbsCertificate>,
}

impl PreCert {
    pub fn parse(input: &mut &[u8]) -> Result<Self, BinaryParsingError> {
        let iss_key_hash = IssuerKeyHash::parse(input)?;
        let length = read_u24_be(input)?;
        let tbs_data = read_exact_bytes(input, length as usize)?;

        let wrapped_tbs_cert = WrapTbsCertificate::try_from_der(tbs_data)?;

        Ok(PreCert {
            issuer_key_hash: iss_key_hash,
            length,
            tbs_certificate: Box::new(wrapped_tbs_cert),
        })
    }
}

#[cfg(feature = "debug-fmt")]
impl fmt::Display for PreCert {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.tbs_certificate.fmt(f)
    }
}

#[derive(Debug, Clone)]
pub struct CtExtensions {
    pub length: u16,
    pub extensions: Vec<u8>,
}

impl CtExtensions {
    pub fn parse(input: &mut &[u8]) -> Result<Self, BinaryParsingError> {
        let length = read_u16_be(input)?;
        let ext_data = read_vec(input, length as usize)?;
        Ok(CtExtensions {
            length,
            extensions: ext_data.to_vec(),
        })
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum MerkleLeafType {
    TimestampedEntry = 0,
}

impl MerkleLeafType {
    pub fn parse(input: &mut &[u8]) -> Result<Self, BinaryParsingError> {
        let id = read_u8(input)?;
        match id {
            0 => Ok(MerkleLeafType::TimestampedEntry),
            _ => Err(BinaryParsingError::InvalidSequence(format!(
                "Unknown MerkleLeafType id: {}",
                id
            ))),
        }
    }
}

#[derive(Debug)]
pub enum TimestampedEntrySignedInner {
    X509(ASN1Cert),
    Precert(PreCert),
}

impl TimestampedEntrySignedInner {
    pub fn parse(input: &mut &[u8], entry_type: &LogEntryType) -> Result<Self, BinaryParsingError> {
        match entry_type {
            LogEntryType::X509Entry => {
                ASN1Cert::parse(input).map(TimestampedEntrySignedInner::X509)
            }
            LogEntryType::PrecertEntry => {
                PreCert::parse(input).map(TimestampedEntrySignedInner::Precert)
            }
        }
    }
}

#[derive(Debug)]
pub struct TimestampedEntry {
    pub timestamp: u64,
    pub entry_type: LogEntryType,
    pub signed_entry: TimestampedEntrySignedInner,
    pub extensions: CtExtensions,
}

impl TimestampedEntry {
    pub fn parse(input: &mut &[u8]) -> Result<Self, BinaryParsingError> {
        let timestamp = read_u64_be(input)?;
        let entry_type = LogEntryType::parse(input)?;

        let signed_entry = TimestampedEntrySignedInner::parse(input, &entry_type)?;
        let ext = CtExtensions::parse(input)?;

        Ok(TimestampedEntry {
            timestamp,
            entry_type,
            signed_entry,
            extensions: ext,
        })
    }
}

#[derive(Debug)]
pub struct MerkleTreeLeaf {
    pub version: Version,
    pub leaf_type: MerkleLeafType,
    pub timestamped_entry: TimestampedEntry,
}

impl MerkleTreeLeaf {
    pub fn parse(input: &mut &[u8]) -> Result<Self, BinaryParsingError> {
        let ver = Version::parse(input)?;
        let leaf_type = MerkleLeafType::parse(input)?;
        let timestamped_entry = TimestampedEntry::parse(input)?;

        Ok(MerkleTreeLeaf {
            version: ver,
            leaf_type,
            timestamped_entry,
        })
    }
}

#[derive(Debug)]
pub enum DecodedEntryInner {
    X509(ASN1CertChain),
    Precert(PrecertChainEntry),
}

/// A structure representing a log entry (parsed from the response of /ct/v1/get-entries).
#[derive(Debug)]
pub struct DecodedEntry {
    pub leaf: MerkleTreeLeaf,
    pub extra_data: DecodedEntryInner,
    pub raw_leaf: Vec<u8>,
}

impl TryFrom<&Entry> for DecodedEntry {
    type Error = CtLogError;

    fn try_from(entry: &Entry) -> Result<Self, CtLogError> {
        let decoded_leaf_bytes: Vec<u8> = BASE64_STANDARD.decode(entry.leaf_input.clone())?;

        let mut leaf_in_slice = decoded_leaf_bytes.as_slice();
        let leaf = MerkleTreeLeaf::parse(&mut leaf_in_slice)?;

        if !leaf_in_slice.is_empty() {
            return Err(BinaryParsingError::InvalidSequence(format!(
                "Trailing data after parsing MerkleTreeLeaf: {} bytes left",
                leaf_in_slice.len()
            ))
            .into());
        }

        let extra_data_decoded = BASE64_STANDARD.decode(&entry.extra_data)?;
        let mut extra_data_slice = extra_data_decoded.as_slice();

        let extra_data = match leaf.timestamped_entry.entry_type {
            LogEntryType::X509Entry => {
                let cert_chain = ASN1CertChain::parse(&mut extra_data_slice)?;
                DecodedEntryInner::X509(cert_chain)
            }
            LogEntryType::PrecertEntry => {
                let precert_chain = PrecertChainEntry::parse(&mut extra_data_slice)?;
                DecodedEntryInner::Precert(precert_chain)
            }
        };

        if !extra_data_slice.is_empty() {
            return Err(BinaryParsingError::InvalidSequence(format!(
                "Trailing data after parsing extra_data: {} bytes left",
                extra_data_slice.len()
            ))
            .into());
        }

        Ok(Self {
            leaf,
            extra_data,
            raw_leaf: decoded_leaf_bytes,
        })
    }
}

#[cfg(feature = "debug-fmt")]
impl fmt::Display for DecodedEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Timestamp={} ({}) ",
            self.leaf.timestamped_entry.timestamp,
            chrono::Utc
                .timestamp_millis_opt(self.leaf.timestamped_entry.timestamp as i64)
                .unwrap()
        )?;

        match (
            &self.leaf.timestamped_entry.entry_type,
            &self.leaf.timestamped_entry.signed_entry,
        ) {
            (LogEntryType::X509Entry, TimestampedEntrySignedInner::X509(certificate)) => {
                writeln!(f, "X.509 certificate:")?;
                writeln!(f, "{certificate}")?;

                // TODO: print the chain
            }
            (LogEntryType::PrecertEntry, TimestampedEntrySignedInner::Precert(certificate)) => {
                writeln!(
                    f,
                    "pre-certificate from issuer with keyhash {:x}:",
                    certificate.issuer_key_hash
                )?;
                writeln!(f, "{certificate}")?;

                // TODO: print the chain
            }
            _ => unreachable!(),
        }

        Ok(())
    }
}