| 1 |
/// TrustDB implementation. |
| 2 |
/// |
| 3 |
/// See doc/DETAILS, section "Layout of the TrustDB". |
| 4 |
|
| 5 |
use std::{ |
| 6 |
collections::BTreeMap, |
| 7 |
io::{self, BufRead}, |
| 8 |
path::{Path, PathBuf}, |
| 9 |
sync::{Mutex, MutexGuard}, |
| 10 |
time::*, |
| 11 |
}; |
| 12 |
|
| 13 |
use anyhow::{Context, Result}; |
| 14 |
|
| 15 |
use buffered_reader::{ |
| 16 |
BufferedReader, |
| 17 |
File, |
| 18 |
}; |
| 19 |
|
| 20 |
use sequoia_openpgp as openpgp; |
| 21 |
use openpgp::{ |
| 22 |
Fingerprint, |
| 23 |
}; |
| 24 |
|
| 25 |
use crate::{ |
| 26 |
Config, |
| 27 |
common::Common, |
| 28 |
gnupg_interface::STRICT_OUTPUT, |
| 29 |
trust::{TrustModel, OwnerTrust, OwnerTrustLevel}, |
| 30 |
}; |
| 31 |
|
| 32 |
// Trust values not covered by the mask. |
| 33 |
|
| 34 |
/// Revoked (r). |
| 35 |
pub const TRUST_FLAG_REVOKED: u32 = 32; |
| 36 |
|
| 37 |
/// Revoked but for subkeys (r). |
| 38 |
pub const TRUST_FLAG_SUB_REVOKED: u32 = 64; |
| 39 |
|
| 40 |
/// Key/uid disabled (d). |
| 41 |
pub const TRUST_FLAG_DISABLED: u32 = 128; |
| 42 |
|
| 43 |
/// Heck-trustdb is pending (a). |
| 44 |
pub const TRUST_FLAG_PENDING_CHECK: u32 = 256; |
| 45 |
|
| 46 |
/// The trust value is based on the TOFU information. |
| 47 |
pub const TRUST_FLAG_TOFU_BASED: u32 = 512; |
| 48 |
|
| 49 |
pub struct TrustDB { |
| 50 |
path: PathBuf, |
| 51 |
ownertrust: Mutex<BTreeMap<Fingerprint, OwnerTrust>>, |
| 52 |
} |
| 53 |
|
| 54 |
impl Default for TrustDB { |
| 55 |
fn default() -> Self { |
| 56 |
Self::with_name("trustdb.gpg") |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
impl TrustDB { |
| 61 |
pub fn with_name(name: impl AsRef<Path>) -> Self { |
| 62 |
TrustDB { |
| 63 |
path: name.as_ref().into(), // XXX |
| 64 |
ownertrust: Default::default(), |
| 65 |
} |
| 66 |
} |
| 67 |
|
| 68 |
pub fn path(&self, config: &Config) -> PathBuf { |
| 69 |
config.make_filename(&self.path) |
| 70 |
} |
| 71 |
|
| 72 |
pub fn version(&self, config: &Config) -> Version { |
| 73 |
let v = self.read_version(config).ok(); |
| 74 |
Version { |
| 75 |
version: 2, |
| 76 |
marginals_needed: config.marginals_needed |
| 77 |
.map(|v| v.try_into().unwrap_or(0xff)) |
| 78 |
.or_else(|| v.as_ref().map(|v| v.marginals_needed)) |
| 79 |
.unwrap_or(crate::trust::DEFAULT_MARGINALS_NEEDED), |
| 80 |
completes_needed: config.completes_needed |
| 81 |
.map(|v| v.try_into().unwrap_or(0xff)) |
| 82 |
.or_else(|| v.as_ref().map(|v| v.completes_needed)) |
| 83 |
.unwrap_or(crate::trust::DEFAULT_COMPLETES_NEEDED), |
| 84 |
max_cert_depth: config.max_cert_depth |
| 85 |
.map(|v| v.try_into().unwrap_or(0xff)) |
| 86 |
.or_else(|| v.as_ref().map(|v| v.max_cert_depth)) |
| 87 |
.unwrap_or(crate::trust::DEFAULT_MAX_CERT_DEPTH), |
| 88 |
model: config.trust_model |
| 89 |
.or_else(|| v.as_ref().map(|v| v.model)) |
| 90 |
.unwrap_or_default(), |
| 91 |
min_cert_level: v.as_ref().map(|v| v.min_cert_level) |
| 92 |
.unwrap_or_default(), |
| 93 |
creation_time: v.as_ref().map(|v| v.creation_time) |
| 94 |
.unwrap_or_else(|| config.now()), |
| 95 |
expiration_time: v.as_ref().and_then(|v| v.expiration_time.clone()), |
| 96 |
first_free: v.as_ref().map(|v| v.first_free) |
| 97 |
.unwrap_or(0.into()), |
| 98 |
hash_table: v.as_ref().map(|v| v.hash_table) |
| 99 |
.unwrap_or(0.into()), |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
fn read_version(&self, config: &Config) -> Result<Version> { |
| 104 |
let mut reader = File::open(config.make_filename(&self.path))?; |
| 105 |
let version_record = Record::from_buffered_reader(&mut reader)?; |
| 106 |
if let Some(Record::Version(v)) = version_record { |
| 107 |
Ok(v) |
| 108 |
} else { |
| 109 |
Err(anyhow::anyhow!( |
| 110 |
"First record in TrustDB {:?} is not a version record", |
| 111 |
config.make_filename(&self.path))) |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
pub fn read_ownertrust(&self, path: PathBuf) -> Result<()> { |
| 116 |
let mut reader = match File::open(path) { |
| 117 |
Ok(r) => r, |
| 118 |
Err(e) => |
| 119 |
return if e.kind() == std::io::ErrorKind::NotFound { |
| 120 |
Ok(()) |
| 121 |
} else { |
| 122 |
Err(e.into()) |
| 123 |
}, |
| 124 |
}; |
| 125 |
|
| 126 |
while let Some(record) = Record::from_buffered_reader(&mut reader)? { |
| 127 |
match record { |
| 128 |
Record::Trust { fingerprint, ownertrust, .. } => |
| 129 |
self.set_ownertrust(fingerprint.clone(), ownertrust), |
| 130 |
_ => (), |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
Ok(()) |
| 135 |
} |
| 136 |
|
| 137 |
pub fn import_ownertrust(&self, |
| 138 |
config: &crate::Config, |
| 139 |
source: &mut dyn io::Read) |
| 140 |
-> Result<()> { |
| 141 |
for (i, line) in io::BufReader::new(source).lines().enumerate() { |
| 142 |
let l = line?; |
| 143 |
if l.is_empty() || l.starts_with("#") { |
| 144 |
continue; |
| 145 |
} |
| 146 |
let f = l.split(':').collect::<Vec<&str>>(); |
| 147 |
if f.len() < 2 { |
| 148 |
return Err(anyhow::anyhow!( |
| 149 |
"Malformed ownertrust line {}: too few fields", i)); |
| 150 |
} |
| 151 |
let fp = f[0].parse() |
| 152 |
.with_context(|| format!("Malformed ownertrust line {}: {}", |
| 153 |
i, l))?; |
| 154 |
let ownertrust: OwnerTrust = f[1].parse::<u8>() |
| 155 |
.map_err(Into::into) |
| 156 |
.and_then(|v| v.try_into()) |
| 157 |
.with_context(|| format!("Malformed ownertrust line {}: {}", |
| 158 |
i, l))?; |
| 159 |
|
| 160 |
config.info(format_args!("inserting ownertrust of {}", |
| 161 |
if STRICT_OUTPUT { |
| 162 |
u8::from(ownertrust).to_string() |
| 163 |
} else { |
| 164 |
ownertrust.to_string() |
| 165 |
})); |
| 166 |
self.set_ownertrust(fp, ownertrust); |
| 167 |
} |
| 168 |
|
| 169 |
Ok(()) |
| 170 |
} |
| 171 |
|
| 172 |
pub fn export_ownertrust(&self, sink: &mut dyn io::Write) |
| 173 |
-> Result<()> { |
| 174 |
for (fp, ownertrust) in self.ownertrust.lock().unwrap().iter() { |
| 175 |
// Skip unknown ownertrust values, like GnuPG. |
| 176 |
if ownertrust.level() == OwnerTrustLevel::Unknown { |
| 177 |
continue; |
| 178 |
} |
| 179 |
|
| 180 |
writeln!(sink, "{:X}:{}:", fp, u8::from(*ownertrust))?; |
| 181 |
} |
| 182 |
|
| 183 |
Ok(()) |
| 184 |
} |
| 185 |
|
| 186 |
pub fn ownertrust(&self) -> MutexGuard<BTreeMap<Fingerprint, OwnerTrust>> { |
| 187 |
self.ownertrust.lock().unwrap() |
| 188 |
} |
| 189 |
|
| 190 |
pub fn get_ownertrust(&self, fp: &Fingerprint) -> Option<OwnerTrust> { |
| 191 |
self.ownertrust.lock().unwrap().get(fp).cloned() |
| 192 |
} |
| 193 |
|
| 194 |
pub fn set_ownertrust(&self, fp: Fingerprint, ownertrust: OwnerTrust) { |
| 195 |
self.ownertrust.lock().unwrap().insert(fp, ownertrust); |
| 196 |
} |
| 197 |
|
| 198 |
/// Writes the in-memory database into our overlay. |
| 199 |
pub fn commit_overlay(&self, keydb: &crate::keydb::KeyDB) -> Result<()> { |
| 200 |
// Write the owner-trusts to our DB. |
| 201 |
// XXX: Currently, this is a plain text file. |
| 202 |
let overlay = keydb.metadata_overlay()?; |
| 203 |
if ! overlay.base_dir().exists() { |
| 204 |
// Importing ownertrust should work before the overlay has |
| 205 |
// been created. |
| 206 |
std::fs::create_dir(overlay.base_dir())?; |
| 207 |
} |
| 208 |
|
| 209 |
let path = |
| 210 |
overlay.base_dir().join("_sequoia_gpg_chameleon_ownertrust"); |
| 211 |
let mut tmp = tempfile::NamedTempFile::new_in(overlay.base_dir())?; |
| 212 |
self.export_ownertrust(&mut tmp)?; |
| 213 |
tmp.persist(path)?; |
| 214 |
|
| 215 |
Ok(()) |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
/// Index into the TrustDB. |
| 220 |
/// |
| 221 |
/// The TrustDB consists of fixed-size records that can reference each |
| 222 |
/// other using their position in the database. |
| 223 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 224 |
pub struct Index(u32); |
| 225 |
|
| 226 |
impl From<u32> for Index { |
| 227 |
fn from(v: u32) -> Self { |
| 228 |
Index(v) |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
/// A TrustDB record. |
| 233 |
#[derive(Debug)] |
| 234 |
pub enum Record { |
| 235 |
Version(Version), |
| 236 |
|
| 237 |
Trust { |
| 238 |
fingerprint: Fingerprint, |
| 239 |
ownertrust: OwnerTrust, |
| 240 |
depth: u8, |
| 241 |
min_ownertrust: u8, |
| 242 |
flags: u8, |
| 243 |
valid_list: Index, |
| 244 |
}, |
| 245 |
|
| 246 |
Unknown { |
| 247 |
typ: u8, |
| 248 |
data: [u8; 40], |
| 249 |
}, |
| 250 |
} |
| 251 |
|
| 252 |
#[derive(Debug)] |
| 253 |
pub struct Version { |
| 254 |
pub version: u8, |
| 255 |
pub marginals_needed: u8, |
| 256 |
pub completes_needed: u8, |
| 257 |
pub max_cert_depth: u8, |
| 258 |
pub model: TrustModel, |
| 259 |
pub min_cert_level: u8, |
| 260 |
pub creation_time: SystemTime, |
| 261 |
pub expiration_time: Option<SystemTime>, |
| 262 |
pub first_free: Index, |
| 263 |
pub hash_table: Index, |
| 264 |
} |
| 265 |
|
| 266 |
impl Record { |
| 267 |
pub fn from_buffered_reader(r: &mut dyn BufferedReader<()>) |
| 268 |
-> Result<Option<Self>> |
| 269 |
{ |
| 270 |
let b = match r.data_consume_hard(40) { |
| 271 |
Ok(v) => &v[..40], |
| 272 |
Err(e) => |
| 273 |
return if e.kind() == std::io::ErrorKind::UnexpectedEof { |
| 274 |
Ok(None) |
| 275 |
} else { |
| 276 |
Err(e.into()) |
| 277 |
}, |
| 278 |
}; |
| 279 |
let typ = b[0]; |
| 280 |
|
| 281 |
let read_be_u32 = |v: &[u8]| -> u32 { |
| 282 |
debug_assert_eq!(v.len(), 4); |
| 283 |
let mut bytes = [0; 4]; |
| 284 |
bytes.copy_from_slice(v); |
| 285 |
u32::from_be_bytes(bytes) |
| 286 |
}; |
| 287 |
let read_time = |v: &[u8]| -> SystemTime { |
| 288 |
UNIX_EPOCH + Duration::new(read_be_u32(v).into(), 0) |
| 289 |
}; |
| 290 |
let read_maybe_time = |v: &[u8]| -> Option<SystemTime> { |
| 291 |
let t = read_time(v); |
| 292 |
if t == UNIX_EPOCH { None } else { Some(t) } |
| 293 |
}; |
| 294 |
|
| 295 |
match typ { |
| 296 |
1 => Ok(Some(Record::Version(Version { |
| 297 |
version: b[4], |
| 298 |
marginals_needed: b[5], |
| 299 |
completes_needed: b[6], |
| 300 |
max_cert_depth: b[7], |
| 301 |
model: b[8].into(), |
| 302 |
min_cert_level: b[9], |
| 303 |
creation_time: read_time(&b[12..16]), |
| 304 |
expiration_time: read_maybe_time(&b[16..20]), |
| 305 |
first_free: read_be_u32(&b[28..32]).into(), |
| 306 |
hash_table: read_be_u32(&b[36..40]).into(), |
| 307 |
}))), |
| 308 |
|
| 309 |
12 => Ok(Some(Record::Trust { |
| 310 |
fingerprint: Fingerprint::from_bytes(4, &b[2..22])?, |
| 311 |
ownertrust: b[22].try_into()?, |
| 312 |
depth: b[23], |
| 313 |
min_ownertrust: b[24], |
| 314 |
flags: b[25], |
| 315 |
valid_list: read_be_u32(&b[26..30]).into(), |
| 316 |
})), |
| 317 |
|
| 318 |
_ => { |
| 319 |
let mut data = [0u8; 40]; |
| 320 |
data.copy_from_slice(b); |
| 321 |
Ok(Some(Record::Unknown { |
| 322 |
typ, |
| 323 |
data, |
| 324 |
})) |
| 325 |
}, |
| 326 |
} |
| 327 |
} |
| 328 |
} |