Files
adler32
aho_corasick
approx
arrayvec
ascii
backtrace
backtrace_sys
base64
bitflags
brotli2
brotli_sys
bstr
buf_redux
byteorder
bytes
cfg_if
chrono
chunked_transfer
color_quant
cookie
cookie_store
crc32fast
crossbeam_deque
crossbeam_epoch
crossbeam_queue
crossbeam_utils
csv
csv_core
csv_user_import
deflate
diesel
associations
connection
expression
expression_methods
macros
migration
mysql
query_builder
query_dsl
query_source
sql_types
type_impls
types
diesel_derives
diesel_migrations
dirs
dotenv
dtoa
either
encoding_rs
error_chain
failure
failure_derive
filetime
flate2
fnv
foreign_types
foreign_types_shared
futures
futures_cpupool
gif
google_signin
gzip_header
h2
http
http_body
httparse
hyper
hyper_rustls
hyper_tls
idna
image
indexmap
inflate
iovec
itoa
jpeg_decoder
language_tags
lazy_static
libc
lock_api
log
lzw
matches
memchr
memoffset
migrations_internals
migrations_macros
mime
mime_guess
miniz_oxide
mio
multipart
mysqlclient_sys
native_tls
net2
nodrop
num_cpus
num_derive
num_integer
num_iter
num_rational
num_traits
openssl
openssl_probe
openssl_sys
ordered_float
owning_ref
parking_lot
parking_lot_core
percent_encoding
phf
phf_shared
png
proc_macro2
publicsuffix
quick_error
quote
r2d2
rand
rand_chacha
rand_core
rand_hc
rand_isaac
rand_jitter
rand_os
rand_pcg
rand_xorshift
rayon
rayon_core
regex
regex_automata
regex_syntax
remove_dir_all
reqwest
ring
rouille
rustc_demangle
rustls
rusttype
ryu
safemem
scheduled_thread_pool
scoped_threadpool
scopeguard
sct
serde
serde_derive
serde_json
serde_urlencoded
sha1
simplelog
siphasher
slab
smallvec
stable_deref_trait
stb_truetype
string
syn
synom
synstructure
tempdir
term
thread_local
threadpool
tiff
time
tiny_http
tokio
tokio_buf
tokio_current_thread
tokio_executor
tokio_io
tokio_reactor
tokio_sync
tokio_tcp
tokio_threadpool
tokio_timer
traitobject
try_from
try_lock
twoway
typeable
unicase
unicode_bidi
unicode_normalization
unicode_xid
untrusted
url
uuid
want
webdev_lib
webpki
webpki_roots
  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
//! # SCT.rs: SCT verification library
//! This library implements verification of Signed Certificate Timestamps.
//! These are third-party assurances that a particular certificate has
//! been included in a Certificate Transparency log.
//!
//! See RFC6962 for the details of the formats implemented here.
//!
//! It is intended to be useful to libraries which perform certificate
//! validation, OCSP libraries, and TLS libraries.

#![forbid(unsafe_code,
          unstable_features)]
#![deny(trivial_casts,
        trivial_numeric_casts,
        missing_docs,
        unused_import_braces,
        unused_extern_crates,
        unused_qualifications)]

extern crate ring;
extern crate untrusted;

/// Describes a CT log
///
/// This structure contains some metadata fields not used by the library.
/// Rationale: it makes sense to keep this metadata with the other
/// values for review purposes.
#[derive(Debug)]
pub struct Log<'a> {
    /// The operator's name/description of the log.
    /// This field is not used by the library.
    pub description: &'a str,

    /// The certificate submission url.
    /// This field is not used by the library.
    pub url: &'a str,

    /// Which entity operates the log.
    /// This field is not used by the library.
    pub operated_by: &'a str,

    /// Public key usable for verifying certificates.
    /// TODO: fixme format of this; should be a SPKI
    /// so the `id` is verifiable, but currently is a
    /// raw public key (like, an ECPoint or RSAPublicKey).
    pub key: &'a [u8],

    /// Key hash, which is SHA256 applied to the SPKI
    /// encoding.
    pub id: [u8; 32],

    /// The log's maximum merge delay.
    /// This field is not used by the library.
    pub max_merge_delay: usize
}

/// How sct.rs reports errors.
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Error {
    /// The SCT was somehow misencoded, truncated or otherwise corrupt.
    MalformedSCT,

    /// The SCT contained an invalid signature.
    InvalidSignature,

    /// The SCT was signed in the future.  Clock skew?
    TimestampInFuture,

    /// The SCT had a version that this library does not handle.
    UnsupportedSCTVersion,

    /// The SCT was refers to an unknown log.
    UnknownLog,
}

impl Error {
    /// Applies a suggested policy for error handling:
    ///
    /// Returns `true` if the error should end processing
    /// for whatever the SCT is attached to (like, abort a TLS
    /// handshake).
    ///
    /// Returns `false` if this error should be a 'soft failure'
    /// -- the SCT is unverifiable with this library and set of
    /// logs.
    pub fn should_be_fatal(&self) -> bool {
        match *self {
            Error::UnknownLog
                | Error::UnsupportedSCTVersion => false,
            _ => true
        }
    }
}

fn lookup(logs: &[&Log], id: &[u8]) -> Result<usize, Error> {
    for (i, l) in logs.iter().enumerate() {
        if id == &l.id {
            return Ok(i);
        }
    }

    Err(Error::UnknownLog)
}

fn decode_u64(inp: untrusted::Input) -> u64 {
    let b = inp.as_slice_less_safe();
    assert_eq!(b.len(), 8);
    (b[0] as u64) << 56 |
        (b[1] as u64) << 48 |
        (b[2] as u64) << 40 |
        (b[3] as u64) << 32 |
        (b[4] as u64) << 24 |
        (b[5] as u64) << 16 |
        (b[6] as u64) << 8 |
        (b[7] as u64)
}

fn decode_u16(inp: untrusted::Input) -> u16 {
    let b = inp.as_slice_less_safe();
    assert_eq!(b.len(), 2);
    (b[0] as u16) << 8 | (b[1] as u16)
}

fn write_u64(v: u64, out: &mut Vec<u8>) {
    out.push((v >> 56) as u8);
    out.push((v >> 48) as u8);
    out.push((v >> 40) as u8);
    out.push((v >> 32) as u8);
    out.push((v >> 24) as u8);
    out.push((v >> 16) as u8);
    out.push((v >> 8) as u8);
    out.push(v as u8);
}

fn write_u24(v: u32, out: &mut Vec<u8>) {
    out.push((v >> 16) as u8);
    out.push((v >> 8) as u8);
    out.push(v as u8);
}

fn write_u16(v: u16, out: &mut Vec<u8>) {
    out.push((v >> 8) as u8);
    out.push(v as u8);
}

struct SCT<'a> {
    log_id: &'a [u8],
    timestamp: u64,
    sig_alg: u16,
    sig: &'a [u8],
    exts: &'a [u8],
}

const ECDSA_SHA256: u16 = 0x0403;
const ECDSA_SHA384: u16 = 0x0503;
const RSA_PKCS1_SHA256: u16 = 0x0401;
const RSA_PKCS1_SHA384: u16 = 0x0501;
const SCT_V1: u8 = 0u8;
const SCT_TIMESTAMP: u8 = 0u8;
const SCT_X509_ENTRY: [u8; 2] = [0, 0];

impl<'a> SCT<'a> {
    fn verify(&self, key: &[u8], cert: &[u8]) -> Result<(), Error> {
        let alg: &ring::signature::VerificationAlgorithm = match self.sig_alg {
            ECDSA_SHA256 => &ring::signature::ECDSA_P256_SHA256_ASN1,
            ECDSA_SHA384 => &ring::signature::ECDSA_P384_SHA384_ASN1,
            RSA_PKCS1_SHA256 => &ring::signature::RSA_PKCS1_2048_8192_SHA256,
            RSA_PKCS1_SHA384 => &ring::signature::RSA_PKCS1_2048_8192_SHA384,
            _ => return Err(Error::InvalidSignature)
        };

        let mut data = Vec::new();
        data.push(SCT_V1);
        data.push(SCT_TIMESTAMP);
        write_u64(self.timestamp, &mut data);
        data.extend_from_slice(&SCT_X509_ENTRY);
        write_u24(cert.len() as u32, &mut data);
        data.extend_from_slice(cert);
        write_u16(self.exts.len() as u16, &mut data);
        data.extend_from_slice(self.exts);

        let sig = untrusted::Input::from(self.sig);
        let data = untrusted::Input::from(&data);
        let key = untrusted::Input::from(key);

        ring::signature::verify(alg, key, data, sig)
            .map_err(|_| Error::InvalidSignature)
    }

    fn parse(enc: &'a [u8]) -> Result<SCT<'a>, Error> {
        let inp = untrusted::Input::from(enc);

        inp.read_all(
            Error::MalformedSCT,
            |rd| {
                let version = rd.read_byte()
                    .map_err(|_| Error::MalformedSCT)?;
                if version != 0 {
                    return Err(Error::UnsupportedSCTVersion);
                }

                let id = rd.skip_and_get_input(32)
                    .map_err(|_| Error::MalformedSCT)?;
                let timestamp = rd.skip_and_get_input(8)
                    .map_err(|_| Error::MalformedSCT)
                    .map(decode_u64)?;

                let ext_len = rd.skip_and_get_input(2)
                    .map_err(|_| Error::MalformedSCT)
                    .map(decode_u16)?;
                let exts = rd.skip_and_get_input(ext_len as usize)
                    .map_err(|_| Error::MalformedSCT)?;

                let sig_alg = rd.skip_and_get_input(2)
                    .map_err(|_| Error::MalformedSCT)
                    .map(decode_u16)?;
                let sig_len = rd.skip_and_get_input(2)
                    .map_err(|_| Error::MalformedSCT)
                    .map(decode_u16)?;
                let sig = rd.skip_and_get_input(sig_len as usize)
                    .map_err(|_| Error::MalformedSCT)?;

                let ret = SCT {
                    log_id: id.as_slice_less_safe(),
                    timestamp: timestamp,
                    sig_alg: sig_alg,
                    sig: sig.as_slice_less_safe(),
                    exts: exts.as_slice_less_safe(),
                };

                Ok(ret)
            })
    }
}

/// Verifies that the SCT `sct` (a `SignedCertificateTimestamp` encoding)
/// is a correctly signed timestamp for `cert` (a DER-encoded X.509 end-entity
/// certificate) valid `at_time`.  `logs` describe the CT logs trusted by
/// the caller to sign such an SCT.
///
/// On success, this function returns the log used as an index into `logs`.
/// Otherwise, it returns an `Error`.
pub fn verify_sct(cert: &[u8],
                  sct: &[u8],
                  at_time: u64,
                  logs: &[&Log]) -> Result<usize, Error> {
    let sct = SCT::parse(sct)?;
    let i = lookup(logs, &sct.log_id)?;
    let log = logs[i];
    sct.verify(log.key, cert)?;

    if sct.timestamp > at_time {
        return Err(Error::TimestampInFuture);
    }

    Ok(i)
}

#[cfg(test)]
mod tests_google;
#[cfg(test)]
mod tests_generated;
#[cfg(test)]
mod tests;