| 1 |
//! Improves compatibility with legacy installations. |
| 2 |
|
| 3 |
use std::{ |
| 4 |
fs, |
| 5 |
path::{Path, PathBuf}, |
| 6 |
sync::Arc, |
| 7 |
time::{SystemTime, UNIX_EPOCH}, |
| 8 |
}; |
| 9 |
|
| 10 |
use anyhow::{Context, Result}; |
| 11 |
|
| 12 |
use rusqlite::{Connection, OpenFlags}; |
| 13 |
|
| 14 |
use sequoia_openpgp::{ |
| 15 |
self as openpgp, |
| 16 |
cert::raw::{RawCert, RawCertParser}, |
| 17 |
parse::Parse, |
| 18 |
types::HashAlgorithm, |
| 19 |
}; |
| 20 |
|
| 21 |
use sequoia_cert_store::{ |
| 22 |
CertStore, |
| 23 |
LazyCert, |
| 24 |
StoreUpdate, |
| 25 |
}; |
| 26 |
|
| 27 |
use crate::{ |
| 28 |
Sq, |
| 29 |
print_error_chain, |
| 30 |
}; |
| 31 |
|
| 32 |
/// Controls tracing in this module. |
| 33 |
const TRACE: bool = false; |
| 34 |
|
| 35 |
/// Computes the default home directory. |
| 36 |
pub fn gnupghome() -> Result<PathBuf> { |
| 37 |
platform! { |
| 38 |
unix => { |
| 39 |
Ok(dirs::home_dir() |
| 40 |
.ok_or(anyhow::anyhow!("unsupported platform"))? |
| 41 |
.join(".gnupg")) |
| 42 |
}, |
| 43 |
windows => { |
| 44 |
Err(anyhow::anyhow!("locating GnuPG's state on Windows \ |
| 45 |
is not supported")) |
| 46 |
}, |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
/// Syncs certificates from GnuPG. |
| 51 |
pub fn sync_from_gnupg<'store>(sq: &Sq, cert_store: &CertStore<'store>) |
| 52 |
-> Result<()> { |
| 53 |
tracer!(TRACE, "sync_from_gnupg"); |
| 54 |
|
| 55 |
let overlay = if let Some(certd) = cert_store.certd() { |
| 56 |
Overlay { |
| 57 |
path: certd.certd().base_dir().into(), |
| 58 |
} |
| 59 |
} else { |
| 60 |
t!("no certd in cert store"); |
| 61 |
return Ok(()); |
| 62 |
}; |
| 63 |
|
| 64 |
let home = match gnupghome() { |
| 65 |
Ok(h) => h, |
| 66 |
Err(e) => { |
| 67 |
t!("locating GNUPGHOME failed: {}", e); |
| 68 |
return Ok(()); |
| 69 |
}, |
| 70 |
}; |
| 71 |
|
| 72 |
let resources = [ |
| 73 |
Resource { |
| 74 |
kind: Kind::Keybox, |
| 75 |
path: home.join("pubring.kbx"), |
| 76 |
}, |
| 77 |
|
| 78 |
Resource { |
| 79 |
kind: Kind::Keyring, |
| 80 |
path: home.join("pubring.gpg"), |
| 81 |
}, |
| 82 |
|
| 83 |
Resource { |
| 84 |
kind: Kind::KeyboxDB, |
| 85 |
path: home.join("public-keys.d").join("pubring.db"), |
| 86 |
}, |
| 87 |
]; |
| 88 |
|
| 89 |
for resource in resources { |
| 90 |
if ! resource.path.exists() { |
| 91 |
t!("{}: skipping non-existing resource", resource.path.display()); |
| 92 |
continue; |
| 93 |
} |
| 94 |
|
| 95 |
let f = fs::File::open(&resource.path); |
| 96 |
let modified = match &f { |
| 97 |
Ok(f) => Some(f.metadata()?.modified()?), |
| 98 |
Err(_) => None, |
| 99 |
}; |
| 100 |
t!("{}: last modified {:?}", resource.path.display(), modified); |
| 101 |
|
| 102 |
// Get rid of sub-second precision, filetime doesn't seem |
| 103 |
// to set them reliably on Linux. |
| 104 |
let unix_time = |t: SystemTime| { |
| 105 |
t.duration_since(UNIX_EPOCH).unwrap().as_secs() |
| 106 |
}; |
| 107 |
|
| 108 |
if overlay.get_cached_mtime(&resource).ok() |
| 109 |
.map(|cached| modified.map(unix_time) == Some(unix_time(cached))) |
| 110 |
.unwrap_or(false) |
| 111 |
{ |
| 112 |
// The overlay already contains all data from |
| 113 |
// this resource. |
| 114 |
t!("{}: skipping up-to-date resource", resource.path.display()); |
| 115 |
continue; |
| 116 |
} |
| 117 |
|
| 118 |
let certs = match resource.kind { |
| 119 |
Kind::Keyring => { |
| 120 |
initialize_keyring(sq, f?, &resource.path) |
| 121 |
.with_context(|| format!( |
| 122 |
"Reading the keyring {:?}", resource.path)) |
| 123 |
}, |
| 124 |
Kind::Keybox => { |
| 125 |
initialize_keybox(sq, f?, &resource.path) |
| 126 |
.with_context(|| format!( |
| 127 |
"Reading the keybox {:?}", resource.path)) |
| 128 |
}, |
| 129 |
Kind::KeyboxX509 => { |
| 130 |
t!("ignoring keybox {:?} only used fox X509", |
| 131 |
resource.path); |
| 132 |
Ok(Vec::new()) |
| 133 |
}, |
| 134 |
Kind::KeyboxDB => { |
| 135 |
initialize_keybox_db(&resource.path) |
| 136 |
.with_context(|| format!( |
| 137 |
"{}: reading the keybox database", |
| 138 |
resource.path.display())) |
| 139 |
}, |
| 140 |
}; |
| 141 |
|
| 142 |
match certs { |
| 143 |
Ok(certs) => { |
| 144 |
for cert in certs.into_iter() { |
| 145 |
let keyid = cert.keyid(); |
| 146 |
if let Err(err) = cert_store.update(Arc::new(cert)) { |
| 147 |
if sq.verbose() { |
| 148 |
let err = anyhow::Error::from(err) |
| 149 |
.context(format!( |
| 150 |
"Reading {} from {:?}", |
| 151 |
keyid, resource.path)); |
| 152 |
print_error_chain(&err); |
| 153 |
} |
| 154 |
|
| 155 |
continue; |
| 156 |
} |
| 157 |
} |
| 158 |
} |
| 159 |
Err(err) => if sq.verbose() { |
| 160 |
print_error_chain(&err); |
| 161 |
}, |
| 162 |
} |
| 163 |
|
| 164 |
if let Some(modified) = modified { |
| 165 |
overlay.set_cached_mtime(&resource, modified)?; |
| 166 |
} |
| 167 |
} |
| 168 |
|
| 169 |
Ok(()) |
| 170 |
} |
| 171 |
|
| 172 |
#[derive(Clone)] |
| 173 |
struct Resource { |
| 174 |
kind: Kind, |
| 175 |
path: PathBuf, |
| 176 |
} |
| 177 |
|
| 178 |
#[derive(PartialEq, Eq, Clone, Copy)] |
| 179 |
#[allow(dead_code)] |
| 180 |
pub enum Kind { |
| 181 |
Keybox, |
| 182 |
KeyboxX509, |
| 183 |
KeyboxDB, |
| 184 |
Keyring, |
| 185 |
} |
| 186 |
|
| 187 |
/// Initialize a keyring. |
| 188 |
fn initialize_keyring<'store, P>(sq: &Sq, file: fs::File, path: P) |
| 189 |
-> Result<Vec<LazyCert<'store>>> |
| 190 |
where |
| 191 |
P: AsRef<Path>, |
| 192 |
{ |
| 193 |
tracer!(TRACE, "KeyDB::initialize_keyring"); |
| 194 |
let path = path.as_ref(); |
| 195 |
t!("loading keyring {:?}", path); |
| 196 |
|
| 197 |
let results = { |
| 198 |
let iter = match RawCertParser::from_reader(file) { |
| 199 |
Ok(iter) => iter, |
| 200 |
Err(err) => { |
| 201 |
if sq.verbose() { |
| 202 |
let err = anyhow::Error::from(err).context( |
| 203 |
format!("Loading keyring {:?}", path)); |
| 204 |
print_error_chain(&err); |
| 205 |
return Err(err); |
| 206 |
} else { |
| 207 |
return Err(err); |
| 208 |
} |
| 209 |
} |
| 210 |
}; |
| 211 |
|
| 212 |
iter.filter_map(|cert| { |
| 213 |
match cert { |
| 214 |
Ok(cert) => Some(LazyCert::from(cert)), |
| 215 |
Err(err) => { |
| 216 |
if sq.verbose() { |
| 217 |
let err = anyhow::Error::from(err).context(format!( |
| 218 |
"While parsing cert from keyring {:?}", path)); |
| 219 |
print_error_chain(&err); |
| 220 |
} |
| 221 |
|
| 222 |
None |
| 223 |
} |
| 224 |
} |
| 225 |
}).collect() |
| 226 |
}; |
| 227 |
|
| 228 |
Ok(results) |
| 229 |
} |
| 230 |
|
| 231 |
/// Initialize a keybox. |
| 232 |
fn initialize_keybox<'store, P>(sq: &Sq, file: fs::File, path: P) |
| 233 |
-> Result<Vec<LazyCert<'store>>> |
| 234 |
where |
| 235 |
P: AsRef<Path>, |
| 236 |
{ |
| 237 |
use sequoia_ipc::keybox::*; |
| 238 |
|
| 239 |
tracer!(TRACE, "KeyDB::initialize_keybox"); |
| 240 |
let path = path.as_ref(); |
| 241 |
t!("loading keybox {:?}", path); |
| 242 |
|
| 243 |
let iter = match Keybox::from_reader(file) { |
| 244 |
Ok(iter) => iter, |
| 245 |
Err(err) => { |
| 246 |
if sq.verbose() { |
| 247 |
let err = anyhow::Error::from(err).context(format!( |
| 248 |
"While opening keybox at {:?}", path)); |
| 249 |
print_error_chain(&err); |
| 250 |
return Err(err); |
| 251 |
} else { |
| 252 |
return Err(err); |
| 253 |
} |
| 254 |
} |
| 255 |
}; |
| 256 |
|
| 257 |
let results = iter.filter_map(|record| { |
| 258 |
let record = match record { |
| 259 |
Ok(record) => record, |
| 260 |
Err(err) => { |
| 261 |
if sq.verbose() { |
| 262 |
let err = anyhow::Error::from(err).context(format!( |
| 263 |
"While parsing a record from keybox {:?}", path)); |
| 264 |
print_error_chain(&err); |
| 265 |
} |
| 266 |
|
| 267 |
return None; |
| 268 |
} |
| 269 |
}; |
| 270 |
|
| 271 |
if let KeyboxRecord::OpenPGP(record) = record { |
| 272 |
match record.cert() { |
| 273 |
Ok(cert) => Some(LazyCert::from(cert)), |
| 274 |
Err(err) => { |
| 275 |
if sq.verbose() { |
| 276 |
let err = anyhow::Error::from(err).context(format!( |
| 277 |
"While parsing a cert from keybox {:?}", path)); |
| 278 |
print_error_chain(&err); |
| 279 |
} |
| 280 |
|
| 281 |
None |
| 282 |
} |
| 283 |
} |
| 284 |
} else { |
| 285 |
None |
| 286 |
} |
| 287 |
}).collect(); |
| 288 |
|
| 289 |
Ok(results) |
| 290 |
} |
| 291 |
|
| 292 |
/// Initialize a keybox database. |
| 293 |
fn initialize_keybox_db<'store, P>(path: P) |
| 294 |
-> Result<Vec<LazyCert<'store>>> |
| 295 |
where |
| 296 |
P: AsRef<Path>, |
| 297 |
{ |
| 298 |
tracer!(TRACE, "KeyDB::initialize_keybox_db"); |
| 299 |
let path = path.as_ref(); |
| 300 |
t!("loading keybox database at {}", path.display()); |
| 301 |
|
| 302 |
let conn = Connection::open_with_flags( |
| 303 |
&path, OpenFlags::SQLITE_OPEN_READ_ONLY)?; |
| 304 |
|
| 305 |
let mut stmt = conn.prepare("SELECT keyblob \ |
| 306 |
FROM pubkey \ |
| 307 |
WHERE type = 1")?; |
| 308 |
|
| 309 |
let certs = stmt.query_map([], |row| Ok(row.get::<_, Vec<u8>>(0)?))? |
| 310 |
.filter_map(|bytes| { |
| 311 |
let bytes = std::io::Cursor::new(bytes.ok()?); |
| 312 |
let cert = RawCert::from_reader(bytes).ok()?; |
| 313 |
t!("loaded {}", cert.fingerprint()); |
| 314 |
Some(cert.into()) |
| 315 |
}) |
| 316 |
.collect(); |
| 317 |
drop(stmt); |
| 318 |
|
| 319 |
Ok(certs) |
| 320 |
} |
| 321 |
|
| 322 |
/// Stores metadata in the certd. |
| 323 |
pub struct Overlay { |
| 324 |
path: PathBuf, |
| 325 |
} |
| 326 |
|
| 327 |
impl Overlay { |
| 328 |
pub fn path(&self) -> &Path { |
| 329 |
&self.path |
| 330 |
} |
| 331 |
|
| 332 |
fn mtime_cache_path(&self, of: &Resource) -> PathBuf { |
| 333 |
let mut hash = HashAlgorithm::SHA256.context() |
| 334 |
.expect("MTI hash algorithm") |
| 335 |
.for_digest(); |
| 336 |
hash.update(of.path.to_string_lossy().as_bytes()); |
| 337 |
|
| 338 |
let name = format!( |
| 339 |
"_sequoia_gpg_chameleon_mtime_{}", |
| 340 |
openpgp::fmt::hex::encode( |
| 341 |
hash.into_digest().expect("SHA2 is complete"))); |
| 342 |
|
| 343 |
self.path().join(name) |
| 344 |
} |
| 345 |
|
| 346 |
fn get_cached_mtime(&self, of: &Resource) -> Result<SystemTime> { |
| 347 |
Ok(std::fs::metadata(self.mtime_cache_path(&of))?.modified()?) |
| 348 |
} |
| 349 |
|
| 350 |
fn set_cached_mtime(&self, of: &Resource, new: SystemTime) |
| 351 |
-> Result<()> { |
| 352 |
// Make sure the overlay exists. If we fail to create the |
| 353 |
// directory, caching the mtime would fail anyway, and callers |
| 354 |
// of this function expect a side-effect, so this seems like |
| 355 |
// an okay place to do that. |
| 356 |
std::fs::create_dir_all(self.path())?; |
| 357 |
|
| 358 |
let p = self.mtime_cache_path(&of); |
| 359 |
let f = tempfile::NamedTempFile::new_in(self.path())?; |
| 360 |
filetime::set_file_mtime(f.path(), new.into())?; |
| 361 |
f.persist(p)?; |
| 362 |
Ok(()) |
| 363 |
} |
| 364 |
} |