Debian Codegraph @

src/commands/verify.rs

raw
1 use std::collections::{HashMap, HashSet, btree_map::{BTreeMap, Entry}};
2 use std::io;
3 use std::path::PathBuf;
4
5 use buffered_reader::File;
6
7 use sequoia_openpgp::{
8 self as openpgp,
9 KeyID,
10 Cert,
11 packet::UserID,
12 parse::Cookie,
13 parse::buffered_reader::BufferedReader,
14 parse::stream::*,
15 parse::Parse,
16 types::{
17 AEADAlgorithm,
18 SymmetricAlgorithm,
19 },
20 };
21
22 use sequoia_cert_store::Store;
23 use sequoia_wot::store::Store as _;
24
25 use crate::Sq;
26 use crate::Result;
27 use crate::cli;
28 use crate::commands::inspect::Kind;
29 use crate::common::{PreferredUserID, ui};
30 use crate::sq::TrustThreshold;
31
32 pub fn dispatch(sq: Sq, command: cli::verify::Command)
33 -> Result<()>
34 {
35 tracer!(TRACE, "verify::dispatch");
36
37 let input = command.input.open("a signed message")?;
38 let mut output = command.output.create_safe(&sq)?;
39 let signatures = command.signatures;
40
41 let signers =
42 sq.resolve_certs_or_fail(&command.signers, TrustThreshold::Full)?;
43
44 let result = verify(sq, input,
45 command.detached.clone(),
46 "--signature-file",
47 command.detached,
48 &mut output, signatures, signers);
49 if result.is_err() {
50 if let Some(path) = command.output.path() {
51 // Drop output here so that the file is persisted and
52 // can be deleted.
53 drop(output);
54
55 if let Err(err) = std::fs::remove_file(path) {
56 weprintln!("Verification failed, failed to remove \
57 unverified output saved to {}: {}",
58 path.display(), err);
59 }
60 }
61 }
62 result
63 }
64
65 pub fn verify(mut sq: Sq,
66 input: Box<dyn BufferedReader<Cookie>>,
67 detached: Option<PathBuf>,
68 detached_sig_arg: &str,
69 detached_sig_value: Option<PathBuf>,
70 output: &mut dyn io::Write,
71 signatures: usize, certs: Vec<Cert>)
72 -> Result<()> {
73 let detached = if let Some(sig_path) = detached {
74 let sig = File::with_cookie(&sig_path, Default::default())?;
75
76 let (kind, sig) = Kind::identify(&mut sq, sig)?;
77 kind.expect_or_else(&sq, "verify", Kind::DetachedSig,
78 detached_sig_arg,
79 detached_sig_value.as_deref())?;
80
81 Some(sig)
82 } else {
83 None
84 };
85
86 let helper = VHelper::new(&sq, signatures, certs);
87 let helper = if let Some(dsig) = detached {
88 let mut v = DetachedVerifierBuilder::from_reader(dsig)?
89 .with_policy(sq.policy, Some(sq.time), helper)?;
90 v.verify_buffered_reader(input)?;
91 v.into_helper()
92 } else {
93 let mut v = VerifierBuilder::from_reader(input)?
94 .with_policy(sq.policy, Some(sq.time), helper)?;
95 io::copy(&mut v, output)?;
96 v.into_helper()
97 };
98
99 helper.print_status();
100 Ok(())
101 }
102
103
104 pub struct VHelper<'c, 'store, 'rstore>
105 where 'store: 'rstore
106 {
107 #[allow(dead_code)]
108 pub sq: &'c Sq<'store, 'rstore>,
109 signatures: usize,
110
111 /// Require signatures to be made by this set of certs.
112 designated_signers: Vec<Cert>,
113
114 labels: HashMap<KeyID, String>,
115 trusted: HashSet<KeyID>,
116
117 /// Tracks the inner-most encryption container encountered.
118 pub sym_algo: Option<SymmetricAlgorithm>,
119 /// Tracks the inner-most encryption container encountered.
120 aead_algo: Option<AEADAlgorithm>,
121
122 // Tracks the signatures encountered.
123 authenticated_signatures: usize,
124 unauthenticated_signatures: usize,
125 uncheckable_signatures: usize,
126 bad_signatures: usize,
127 broken_keys: usize,
128 broken_signatures: usize,
129 pub quiet: bool,
130 }
131
132 impl<'c, 'store, 'rstore> VHelper<'c, 'store, 'rstore> {
133 pub fn new(sq: &'c Sq<'store, 'rstore>, signatures: usize,
134 designated_signers: Vec<Cert>)
135 -> Self
136 {
137 VHelper {
138 sq: sq,
139 signatures,
140 designated_signers,
141 labels: HashMap::new(),
142 trusted: HashSet::new(),
143 sym_algo: None,
144 aead_algo: None,
145 authenticated_signatures: 0,
146 unauthenticated_signatures: 0,
147 uncheckable_signatures: 0,
148 broken_keys: 0,
149 bad_signatures: 0,
150 broken_signatures: 0,
151 quiet: sq.quiet(),
152 }
153 }
154
155 /// Enables or disables quiet operation.
156 ///
157 /// In quiet operation, only errors are emitted.
158 pub fn quiet(&mut self, v: bool) {
159 self.quiet = v;
160 }
161
162 pub fn print_status(&self) {
163 fn p(s: &mut String, what: &str, threshold: usize, quantity: usize) {
164 if quantity >= threshold {
165 use std::fmt::Write;
166 use crate::output::pluralize::Pluralize;
167 let dirty = ! s.is_empty();
168 write!(s, "{}{}",
169 if dirty { ", " } else { "" },
170 quantity.of(what))
171 .expect("writing to a string is infallible");
172 }
173 }
174
175 let mut status = String::new();
176 p(&mut status, "authenticated signature", 0, self.authenticated_signatures);
177 p(&mut status, "unauthenticated signature", 1, self.unauthenticated_signatures);
178 p(&mut status, "uncheckable signature", 1, self.uncheckable_signatures);
179 p(&mut status, "bad signature", 1, self.bad_signatures);
180 p(&mut status, "bad key", 1, self.broken_keys);
181 p(&mut status, "broken signatures", 1, self.broken_signatures);
182 if ! status.is_empty() {
183 weprintln!("{}.", status);
184 }
185 }
186
187 fn print_sigs(&mut self, results: &[VerificationResult]) -> Result<()> {
188 make_qprintln!(self.quiet);
189 use crate::common::pki::output::print_path;
190 use crate::print_error_chain;
191
192 let reference_time = self.sq.time;
193
194 use self::VerificationError::*;
195 for result in results {
196 let (sig, ka) = match result {
197 Ok(GoodChecksum { sig, ka, .. }) => (sig, ka),
198 Err(MalformedSignature { error, .. }) => {
199 weprintln!("Malformed signature:");
200 print_error_chain(error);
201 self.broken_signatures += 1;
202 continue;
203 },
204 Err(MissingKey { sig, .. }) => {
205 let issuer = sig.get_issuers().get(0)
206 .expect("missing key checksum has an issuer")
207 .to_string();
208 let what = match sig.level() {
209 0 => "signature".into(),
210 n => format!("level {} notarization", n),
211 };
212 weprintln!("Can't authenticate {} allegedly made by {}: \
213 missing certificate.",
214 what, issuer);
215
216 self.sq.hint(format_args!(
217 "Consider searching for the certificate using:"))
218 .sq().arg("network").arg("search")
219 .arg(issuer)
220 .done();
221
222 self.uncheckable_signatures += 1;
223 continue;
224 },
225 Err(UnboundKey { cert, error, .. }) => {
226 weprintln!("Signing key on {} is not bound:",
227 cert.fingerprint());
228 print_error_chain(error);
229 self.broken_keys += 1;
230 continue;
231 },
232 Err(BadKey { ka, error, .. }) => {
233 weprintln!("Signing key on {} is bad:",
234 ka.cert().fingerprint());
235 print_error_chain(error);
236 self.broken_keys += 1;
237 continue;
238 },
239 Err(BadSignature { sig, ka, error }) => {
240 let issuer = ka.key().fingerprint().to_string();
241 let what = match sig.level() {
242 0 => "signature".into(),
243 n => format!("level {} notarizing signature", n),
244 };
245 weprintln!("Error verifying {} made by {}:",
246 what, issuer);
247 print_error_chain(error);
248 self.bad_signatures += 1;
249 continue;
250 }
251 Err(UnknownSignature { sig, .. }) => {
252 weprintln!("Error parsing signature: {}", sig.error());
253 print_error_chain(sig.error());
254 self.bad_signatures += 1;
255 continue;
256 }
257 Err(e) => {
258 weprintln!("Error parsing signature: {}", e);
259 self.bad_signatures += 1;
260 continue;
261 }
262
263 };
264
265 let cert = ka.cert();
266 let cert_fpr = cert.fingerprint();
267 let issuer = ka.key().keyid();
268 let mut signer_userid = self.sq.best_userid(ka.cert(), true);
269
270 // Direct trust.
271 let mut authenticated = self.trusted.contains(&issuer);
272 let mut prefix = "";
273 let trust_roots = self.sq.trust_roots();
274 if ! authenticated && ! trust_roots.is_empty() {
275 prefix = " ";
276
277 // Web of trust.
278 qprintln!("Authenticating {} ({}) using the web of trust:",
279 cert_fpr, signer_userid.userid_lossy());
280
281 if let Some(cert_store) = self.sq.cert_store()? {
282 // Build the network.
283 let cert_store = sequoia_wot::store::CertStore::from_store(
284 cert_store, self.sq.policy, reference_time);
285
286 let userids =
287 cert_store.certified_userids_of(&cert_fpr);
288
289 if userids.is_empty() {
290 weprintln!(indent=prefix,
291 "{} cannot be authenticated. \
292 It has no User IDs",
293 cert_fpr);
294 } else {
295 let n = sequoia_wot::NetworkBuilder::rooted(
296 &cert_store, &*trust_roots).build();
297
298 let authenticated_userids
299 = userids.into_iter().filter(|userid| {
300 let paths = n.authenticate(
301 userid, cert.fingerprint(),
302 // XXX: Make this user configurable.
303 sequoia_wot::FULLY_TRUSTED);
304
305 let amount = paths.amount();
306 let authenticated = if amount >= sequoia_wot::FULLY_TRUSTED {
307 weprintln!(indent=prefix,
308 "Fully authenticated \
309 ({} of {}) {}, {}",
310 amount,
311 TrustThreshold::Full,
312 cert_fpr,
313 ui::Safe(userid));
314 true
315 } else if amount > 0 {
316 weprintln!(indent=prefix,
317 "Partially authenticated \
318 ({} of {}) {}, {} ",
319 amount,
320 TrustThreshold::Full,
321 cert_fpr,
322 ui::Safe(userid));
323 false
324 } else {
325 weprintln!(indent=prefix,
326 "{}: {} is unauthenticated \
327 and may be an impersonation!",
328 cert_fpr,
329 ui::Safe(userid));
330 false
331 };
332
333 for (i, (path, amount)) in paths.iter().enumerate() {
334 let prefix = if paths.len() > 1 {
335 qprintln!("{} Path #{} of {}, \
336 trust amount {}:",
337 prefix,
338 i + 1, paths.len(), amount);
339 format!("{} ", prefix)
340 } else {
341 format!("{} ", prefix)
342 };
343
344 if ! self.quiet {
345 let _ =
346 print_path(&mut std::io::stderr(),
347 &path.into(), userid,
348 &prefix);
349 }
350 }
351
352 authenticated
353 })
354 .collect::<Vec<UserID>>();
355
356 if authenticated_userids.is_empty() {
357 authenticated = false;
358 } else {
359 authenticated = true;
360
361 // If we managed to authenticate the
362 // signers user ID, prefer that one.
363 if let Some(u) = sig.signers_user_id()
364 .and_then(|u| {
365 authenticated_userids.contains(
366 &UserID::from(u))
367 .then_some(u)
368 })
369 {
370 signer_userid = PreferredUserID::from_string(
371 String::from_utf8_lossy(u),
372 TrustThreshold::Full.into());
373 } else {
374 // Else just pick the first one.
375 signer_userid = PreferredUserID::from_string(
376 String::from_utf8_lossy(
377 authenticated_userids[0].value()),
378 TrustThreshold::Full.into());
379 }
380 }
381 }
382 } else {
383 qprintln!("Skipping, certificate store has been disabled");
384 }
385 }
386
387 let mut label_store = Default::default();
388 let label = self.labels.get(&issuer).unwrap_or_else(|| {
389 label_store = cert_fpr.to_string();
390 &label_store
391 });
392
393 let level = sig.level();
394 match (level == 0, authenticated) {
395 (true, true) => {
396 weprintln!(indent=prefix,
397 "Authenticated signature made by {} ({})",
398 label, signer_userid.userid_lossy());
399 }
400 (false, true) => {
401 weprintln!(indent=prefix,
402 "Authenticated level {} notarization \
403 made by {} ({})",
404 level, label, signer_userid.userid_lossy());
405 }
406 (true, false) => {
407 weprintln!(indent=prefix,
408 "Can't authenticate signature made by {} ({}): \
409 the certificate can't be authenticated.",
410 label, signer_userid.userid_lossy());
411
412 if let Ok(u) = signer_userid.userid() {
413 self.sq.hint(format_args!(
414 "After checking that {} belongs to {}, \
415 you can mark it as authenticated using:",
416 cert_fpr, u))
417 .sq().arg("pki").arg("link").arg("add")
418 .arg_value("--cert", cert_fpr)
419 .arg_value("--userid", u)
420 .done();
421 }
422 }
423 (false, false) => {
424 weprintln!(indent=prefix,
425 "Can't authenticate level {} notarization \
426 made by {} ({}): the certificate \
427 can't be authenticated.",
428 level, label, signer_userid.userid_lossy());
429
430 if let Ok(u) = signer_userid.userid() {
431 self.sq.hint(format_args!(
432 "After checking that {} belongs to {}, \
433 you can mark it as authenticated using:",
434 cert_fpr, u))
435 .sq().arg("pki").arg("link").arg("add")
436 .arg_value("--cert", cert_fpr)
437 .arg_value("--userid", u)
438 .done();
439 }
440 }
441 };
442
443 if authenticated {
444 self.authenticated_signatures += 1;
445 } else {
446 self.unauthenticated_signatures += 1;
447 }
448
449 qprintln!("");
450 }
451
452 Ok(())
453 }
454 }
455
456 impl<'c, 'store, 'rstore> VerificationHelper for VHelper<'c, 'store, 'rstore>
457 where 'store: 'rstore
458 {
459 fn get_certs(&mut self, ids: &[openpgp::KeyHandle]) -> Result<Vec<Cert>> {
460 let mut certs = BTreeMap::new();
461
462 for c in std::mem::take(&mut self.designated_signers) {
463 match certs.entry(c.fingerprint()) {
464 Entry::Vacant(e) => {
465 e.insert(c);
466 },
467 Entry::Occupied(mut e) => {
468 let merged = e.get().clone().merge_public(c)?;
469 e.insert(merged);
470 },
471 }
472 }
473
474 // Get all keys.
475 let seen: HashSet<_> = certs.values()
476 .flat_map(|cert| {
477 cert.keys().map(|ka| ka.key().fingerprint().into())
478 }).collect();
479
480 // Explicitly provided keys are trusted.
481 self.trusted = seen;
482
483 // If we have any designated signers, we do not consider
484 // certificates in the cert store: we require all signatures
485 // to be made by the set of designated signers.
486 if ! self.trusted.is_empty() {
487 return Ok(certs.into_values().collect());
488 }
489
490 // Otherwise, look up the issuer IDs in the certificate store.
491
492 // Avoid initializing the certificate store if we don't actually
493 // need to.
494 if ! ids.is_empty() {
495 if let Some(cert_store) = self.sq.cert_store()? {
496 for id in ids.iter() {
497 for c in cert_store.lookup_by_cert_or_subkey(id)
498 .unwrap_or_default()
499 {
500 let c = c.to_cert()?.clone();
501 match certs.entry(c.fingerprint()) {
502 Entry::Vacant(e) => {
503 e.insert(c);
504 },
505 Entry::Occupied(mut e) => {
506 let merged = e.get().clone().merge_public(c)?;
507 e.insert(merged);
508 },
509 }
510 }
511 }
512 }
513 }
514
515 Ok(certs.into_values().collect())
516 }
517
518 fn check(&mut self, structure: MessageStructure) -> Result<()> {
519 make_qprintln!(self.quiet);
520 for layer in structure {
521 match layer {
522 MessageLayer::Compression { algo } =>
523 qprintln!("Compressed using {}", algo),
524 MessageLayer::Encryption { sym_algo, aead_algo } => {
525 self.sym_algo = Some(sym_algo);
526 self.aead_algo = aead_algo;
527
528 if let Some(aead_algo) = aead_algo {
529 qprintln!("Encrypted and protected using {}/{}",
530 sym_algo, aead_algo);
531 } else {
532 qprintln!("Encrypted using {}", sym_algo);
533 }
534 },
535 MessageLayer::SignatureGroup { ref results } => {
536 self.print_sigs(results)?;
537 },
538 }
539 }
540
541 if self.authenticated_signatures >= self.signatures {
542 Ok(())
543 } else {
544 if ! self.quiet {
545 self.print_status();
546 }
547 Err(anyhow::anyhow!("Verification failed: could not \
548 authenticate any signatures"))
549 }
550 }
551 }