| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
use base64::Engine; |
| 6 |
use clubcard::{ |
| 7 |
ApproximateSizeOf, AsQuery, Clubcard, ClubcardIndex, Equation, Membership, Queryable, |
| 8 |
}; |
| 9 |
use serde::{Deserialize, Serialize}; |
| 10 |
use sha2::{Digest, Sha256}; |
| 11 |
use std::cmp::max; |
| 12 |
use std::collections::HashMap; |
| 13 |
use std::fmt; |
| 14 |
use std::mem::size_of; |
| 15 |
|
| 16 |
const W: usize = 4; |
| 17 |
|
| 18 |
type IssuerSpkiHash = [u8; 32]; |
| 19 |
type LogId = [u8; 32]; |
| 20 |
type Timestamp = u64; |
| 21 |
type TimestampInterval = (Timestamp, Timestamp); |
| 22 |
|
| 23 |
#[derive(Serialize, Deserialize)] |
| 24 |
pub struct CRLiteCoverage(pub(crate) HashMap<LogId, TimestampInterval>); |
| 25 |
|
| 26 |
#[derive(Debug)] |
| 27 |
pub struct CRLiteKey<'a> { |
| 28 |
pub(crate) issuer: &'a IssuerSpkiHash, |
| 29 |
pub(crate) serial: &'a [u8], |
| 30 |
pub(crate) issuer_serial_hash: [u8; 32], |
| 31 |
} |
| 32 |
|
| 33 |
impl<'a> CRLiteKey<'a> { |
| 34 |
pub fn new(issuer: &'a IssuerSpkiHash, serial: &'a [u8]) -> CRLiteKey<'a> { |
| 35 |
let mut issuer_serial_hash = [0u8; 32]; |
| 36 |
let mut hasher = Sha256::new(); |
| 37 |
hasher.update(issuer); |
| 38 |
hasher.update(serial); |
| 39 |
hasher.finalize_into((&mut issuer_serial_hash).into()); |
| 40 |
CRLiteKey { |
| 41 |
issuer, |
| 42 |
serial, |
| 43 |
issuer_serial_hash, |
| 44 |
} |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
#[derive(Clone, Debug)] |
| 49 |
pub struct CRLiteQuery<'a> { |
| 50 |
pub(crate) key: &'a CRLiteKey<'a>, |
| 51 |
pub(crate) log_timestamp: Option<(&'a LogId, Timestamp)>, |
| 52 |
} |
| 53 |
|
| 54 |
impl<'a> CRLiteQuery<'a> { |
| 55 |
pub fn new(key: &'a CRLiteKey<'a>, log_timestamp: Option<(&'a LogId, u64)>) -> CRLiteQuery<'a> { |
| 56 |
CRLiteQuery { key, log_timestamp } |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
impl<'a> AsQuery<W> for CRLiteQuery<'a> { |
| 61 |
fn block(&self) -> &[u8] { |
| 62 |
self.key.issuer.as_ref() |
| 63 |
} |
| 64 |
|
| 65 |
fn as_query(&self, m: usize) -> Equation<W> { |
| 66 |
let mut a = [0u64; 4]; |
| 67 |
for (i, x) in self |
| 68 |
.key |
| 69 |
.issuer_serial_hash |
| 70 |
.chunks_exact(8) // TODO: use array_chunks::<8>() when stable |
| 71 |
.map(|x| TryInto::<[u8; 8]>::try_into(x).unwrap()) |
| 72 |
.map(u64::from_le_bytes) |
| 73 |
.enumerate() |
| 74 |
{ |
| 75 |
a[i] = x; |
| 76 |
} |
| 77 |
a[0] |= 1; |
| 78 |
let s = (a[3] % (max(1, m) as u64)) as usize; |
| 79 |
Equation::homogeneous(s, a) |
| 80 |
} |
| 81 |
|
| 82 |
fn discriminant(&self) -> &[u8] { |
| 83 |
self.key.serial |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
impl<'a> Queryable<W> for CRLiteQuery<'a> { |
| 88 |
type UniverseMetadata = CRLiteCoverage; |
| 89 |
|
| 90 |
// The set of CRLiteKeys is partitioned by issuer, and each |
| 91 |
// CRLiteKey knows its issuer. So there's no need for additional |
| 92 |
// partition metadata. |
| 93 |
type PartitionMetadata = (); |
| 94 |
|
| 95 |
fn in_universe(&self, universe: &Self::UniverseMetadata) -> bool { |
| 96 |
let Some((log_id, timestamp)) = self.log_timestamp else { |
| 97 |
return false; |
| 98 |
}; |
| 99 |
if let Some((low, high)) = universe.0.get(log_id) { |
| 100 |
if *low <= timestamp && timestamp <= *high { |
| 101 |
return true; |
| 102 |
} |
| 103 |
} |
| 104 |
false |
| 105 |
} |
| 106 |
} |
| 107 |
|
| 108 |
#[derive(Debug)] |
| 109 |
pub enum ClubcardError { |
| 110 |
Serialize, |
| 111 |
Deserialize, |
| 112 |
UnsupportedVersion, |
| 113 |
} |
| 114 |
|
| 115 |
#[derive(Debug, PartialEq, Eq)] |
| 116 |
pub enum CRLiteStatus { |
| 117 |
Good, |
| 118 |
NotCovered, |
| 119 |
NotEnrolled, |
| 120 |
Revoked, |
| 121 |
} |
| 122 |
|
| 123 |
impl From<Membership> for CRLiteStatus { |
| 124 |
fn from(membership: Membership) -> CRLiteStatus { |
| 125 |
match membership { |
| 126 |
Membership::Nonmember => CRLiteStatus::Good, |
| 127 |
Membership::NotInUniverse => CRLiteStatus::NotCovered, |
| 128 |
Membership::NoData => CRLiteStatus::NotEnrolled, |
| 129 |
Membership::Member => CRLiteStatus::Revoked, |
| 130 |
} |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
pub struct CRLiteClubcard(Clubcard<W, CRLiteCoverage, ()>); |
| 135 |
|
| 136 |
impl From<Clubcard<W, CRLiteCoverage, ()>> for CRLiteClubcard { |
| 137 |
fn from(inner: Clubcard<W, CRLiteCoverage, ()>) -> CRLiteClubcard { |
| 138 |
CRLiteClubcard(inner) |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
impl AsRef<Clubcard<W, CRLiteCoverage, ()>> for CRLiteClubcard { |
| 143 |
fn as_ref(&self) -> &Clubcard<W, CRLiteCoverage, ()> { |
| 144 |
&self.0 |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
impl std::fmt::Display for CRLiteClubcard { |
| 149 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 150 |
writeln!(f, "{}", self.0)?; |
| 151 |
writeln!(f, "{:=^80}", " Coverage ")?; |
| 152 |
writeln!( |
| 153 |
f, |
| 154 |
"{: ^46} {: >16}{: >16}", |
| 155 |
"CT Log ID", "Min Time", "Max Time" |
| 156 |
)?; |
| 157 |
writeln!(f, "{:-<80}", "")?; |
| 158 |
let mut coverage_data = self |
| 159 |
.universe() |
| 160 |
.0 |
| 161 |
.iter() |
| 162 |
.map(|(log_id, (low, high))| { |
| 163 |
(base64::prelude::BASE64_STANDARD.encode(log_id), *low, *high) |
| 164 |
}) |
| 165 |
.collect::<Vec<(String, u64, u64)>>(); |
| 166 |
coverage_data.sort_by_key(|x| u64::MAX - x.2); |
| 167 |
for (log_id, low, high) in coverage_data { |
| 168 |
writeln!(f, "{: >46},{: >16},{: >16}", log_id, low, high)?; |
| 169 |
} |
| 170 |
writeln!(f)?; |
| 171 |
writeln!(f, "{:=^80}", " Index ")?; |
| 172 |
writeln!( |
| 173 |
f, |
| 174 |
"{: ^46}{: >10}{: >10}{: >14}", |
| 175 |
"Issuer ID", "Exceptions", "Rank", "Bits" |
| 176 |
)?; |
| 177 |
writeln!(f, "{:-<80}", "")?; |
| 178 |
let mut index_data = self |
| 179 |
.0 |
| 180 |
.index() |
| 181 |
.iter() |
| 182 |
.map(|(block, entry)| { |
| 183 |
let filter_size = |
| 184 |
entry.approx_filter_m * entry.approx_filter_rank + entry.exact_filter_m; |
| 185 |
( |
| 186 |
base64::prelude::BASE64_URL_SAFE.encode(block), |
| 187 |
entry.approx_filter_rank, |
| 188 |
entry.exceptions.len(), |
| 189 |
filter_size, |
| 190 |
) |
| 191 |
}) |
| 192 |
.collect::<Vec<(String, usize, usize, usize)>>(); |
| 193 |
index_data.sort_by_key(|x| usize::MAX - x.3); |
| 194 |
|
| 195 |
for (issuer, rank, exceptions, filter_size) in &index_data { |
| 196 |
writeln!( |
| 197 |
f, |
| 198 |
"{: >46},{: >9},{: >9},{: >13}", |
| 199 |
issuer, exceptions, rank, filter_size |
| 200 |
)?; |
| 201 |
} |
| 202 |
Ok(()) |
| 203 |
} |
| 204 |
} |
| 205 |
|
| 206 |
impl CRLiteClubcard { |
| 207 |
// Cascade-based CRLite filters use version numbers 0x0000, 0x0001, and 0x0002. |
| 208 |
const SERIALIZATION_VERSION: u16 = 0x0003; |
| 209 |
|
| 210 |
/// Serialize this clubcard. |
| 211 |
pub fn to_bytes(&self) -> Result<Vec<u8>, ClubcardError> { |
| 212 |
let mut out = u16::to_le_bytes(Self::SERIALIZATION_VERSION).to_vec(); |
| 213 |
bincode::serialize_into(&mut out, &self.0).map_err(|_| ClubcardError::Serialize)?; |
| 214 |
Ok(out) |
| 215 |
} |
| 216 |
|
| 217 |
/// Deserialize a clubcard. |
| 218 |
pub fn from_bytes(bytes: &[u8]) -> Result<Self, ClubcardError> { |
| 219 |
if bytes.len() < size_of::<u16>() { |
| 220 |
return Err(ClubcardError::Deserialize); |
| 221 |
} |
| 222 |
let (version_bytes, rest) = bytes.split_at(size_of::<u16>()); |
| 223 |
let Ok(version_bytes) = version_bytes.try_into() else { |
| 224 |
return Err(ClubcardError::Deserialize); |
| 225 |
}; |
| 226 |
let version = u16::from_le_bytes(version_bytes); |
| 227 |
if version != Self::SERIALIZATION_VERSION { |
| 228 |
return Err(ClubcardError::UnsupportedVersion); |
| 229 |
} |
| 230 |
bincode::deserialize(rest) |
| 231 |
.map(CRLiteClubcard) |
| 232 |
.map_err(|_| ClubcardError::Deserialize) |
| 233 |
} |
| 234 |
|
| 235 |
pub fn universe(&self) -> &CRLiteCoverage { |
| 236 |
self.0.universe() |
| 237 |
} |
| 238 |
|
| 239 |
pub fn index(&self) -> &ClubcardIndex { |
| 240 |
self.0.index() |
| 241 |
} |
| 242 |
|
| 243 |
pub fn contains<'a>( |
| 244 |
&self, |
| 245 |
key: &'a CRLiteKey<'a>, |
| 246 |
timestamps: impl Iterator<Item = (&'a LogId, Timestamp)>, |
| 247 |
) -> CRLiteStatus { |
| 248 |
for (log_id, timestamp) in timestamps { |
| 249 |
let crlite_query = CRLiteQuery::new(key, Some((log_id, timestamp))); |
| 250 |
let status = self.0.contains(&crlite_query).into(); |
| 251 |
if status == CRLiteStatus::NotCovered { |
| 252 |
continue; |
| 253 |
} |
| 254 |
return status; |
| 255 |
} |
| 256 |
CRLiteStatus::NotCovered |
| 257 |
} |
| 258 |
} |
| 259 |
|
| 260 |
impl ApproximateSizeOf for CRLiteCoverage { |
| 261 |
fn approximate_size_of(&self) -> usize { |
| 262 |
size_of::<HashMap<LogId, TimestampInterval>>() |
| 263 |
+ self.0.len() * (size_of::<LogId>() + size_of::<TimestampInterval>()) |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
impl ApproximateSizeOf for CRLiteClubcard { |
| 268 |
fn approximate_size_of(&self) -> usize { |
| 269 |
self.0.approximate_size_of() |
| 270 |
} |
| 271 |
} |