Debian Codegraph @

src/sqv.rs

raw
1 //! A simple signature verification program.
2 //!
3 //! See <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=872271> for
4 //! the motivation.
5
6 use std::borrow::Cow;
7 use std::io::Read;
8 use std::io;
9 use std::path::PathBuf;
10 use std::process::exit;
11 use std::sync::OnceLock;
12
13 use chrono::{DateTime, offset::Utc};
14 use anyhow::Context;
15
16 use clap::FromArgMatches;
17
18 use sequoia_openpgp as openpgp;
19
20 use crate::openpgp::{
21 Cert,
22 KeyHandle,
23 Packet,
24 Result,
25 parse::PacketParser,
26 parse::PacketParserResult,
27 parse::Parse,
28 };
29 use crate::openpgp::parse::stream::{
30 DetachedVerifierBuilder,
31 MessageLayer,
32 MessageStructure,
33 VerificationHelper,
34 GoodChecksum,
35 VerificationError,
36 VerifierBuilder,
37 };
38 use crate::openpgp::cert::prelude::*;
39
40 mod cli;
41
42 /// Returns stdin.
43 ///
44 /// It is standard to `-` to mean read from `stdin` instead of a file.
45 /// Because it is almost always an error to use `-` more than once,
46 /// this errors out with a helpful error message in this case.
47 fn stdin(option: &'static str) -> Result<std::io::Stdin> {
48 static OPTION: OnceLock<&'static str> = OnceLock::new();
49
50 match OPTION.set(option) {
51 Ok(()) => {
52 Ok(std::io::stdin())
53 }
54 Err(_) => {
55 let previous = OPTION.get().unwrap();
56 Err(anyhow::anyhow!(
57 "Can't use - to read from stdin multiple times \
58 (used with {} and {})",
59 previous, option))
60 }
61 }
62 }
63
64 struct VHelper {
65 not_before: Option<std::time::SystemTime>,
66 not_after: std::time::SystemTime,
67
68 good: usize,
69 total: usize,
70 threshold: usize,
71
72 keyrings: Vec<PathBuf>,
73 }
74
75 impl std::fmt::Debug for VHelper {
76 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
77 f.debug_struct("VHelper")
78 .field("not_before", &self.not_before)
79 .field("not_after", &self.not_after)
80 .field("good", &self.good)
81 .field("total", &self.total)
82 .field("threshold", &self.threshold)
83 .field("keyrings", &self.keyrings)
84 .finish()
85 }
86 }
87
88 impl VHelper {
89 fn new(threshold: usize,
90 not_before: Option<std::time::SystemTime>,
91 not_after: std::time::SystemTime,
92 keyrings: Vec<PathBuf>) -> Self {
93 VHelper {
94 not_before: not_before,
95 not_after: not_after,
96 good: 0,
97 total: 0,
98 threshold: threshold,
99 keyrings: keyrings,
100 }
101 }
102 }
103
104 impl VerificationHelper for VHelper {
105 fn get_certs(&mut self, ids: &[crate::KeyHandle]) -> Result<Vec<Cert>> {
106 let mut certs = Vec::with_capacity(ids.len());
107
108 // Load relevant keys from the keyring.
109 for filename in self.keyrings.iter() {
110 let parser = if filename.as_os_str().as_encoded_bytes() == b"-" {
111 CertParser::from_reader(stdin("--keyring")?)
112 } else {
113 CertParser::from_file(filename)
114 };
115 let parser = parser
116 .map_err(|err| {
117 let Ok(mut file) = std::fs::File::open(filename) else {
118 return err;
119 };
120 let mut buffer = [0; 0x0C];
121 let Ok(()) = file.read_exact(&mut buffer) else {
122 return err;
123 };
124 if buffer.ends_with(b"KBXf") {
125 anyhow::anyhow!("File appears to be in keybox format, \
126 which is not supported")
127 } else {
128 err
129 }
130 })
131 .with_context(|| format!("Failed to parse keyring {:?}",
132 filename))?;
133 for cert in parser
134 .unvalidated_cert_filter(|cert, _| {
135 // We don't skip keys that are valid (not revoked,
136 // alive, etc.) so that
137 cert.keys().key_handles(ids.iter()).next().is_some()
138 })
139 {
140 certs.push(cert.with_context(|| {
141 format!("Malformed certificate in keyring {:?}", filename)
142 })?);
143 }
144 }
145
146 // Dedup. To avoid cloning the certificates, we don't use
147 // Vec::dedup.
148 certs.sort_by(|a, b| a.fingerprint().cmp(&b.fingerprint()));
149 let count = certs.len();
150 let (certs, errs) = certs.into_iter().fold(
151 (Vec::with_capacity(count), Vec::new()),
152 |(mut certs, mut errs), a| {
153 if certs.is_empty() {
154 certs.push(a);
155 } else if certs[certs.len() - 1].fingerprint() == a.fingerprint() {
156 // Merge `a` into the last element.
157 match certs.pop().expect("non-empty vec").merge_public(a) {
158 Ok(cert) => certs.push(cert),
159 Err(err) => errs.push(err),
160 }
161 } else {
162 certs.push(a);
163 }
164
165 (certs, errs)
166 });
167
168 if !errs.is_empty() {
169 eprintln!("Error merging duplicate keys:");
170 for err in errs.iter() {
171 eprintln!(" {}", err);
172 }
173 Err(errs.into_iter().next().expect("non-empty vec"))
174 } else {
175 Ok(certs)
176 }
177 }
178
179 fn check(&mut self, structure: MessageStructure) -> Result<()> {
180 use self::VerificationError::*;
181
182 let mut signers = Vec::with_capacity(2);
183 let mut verification_err = None;
184
185 for layer in structure.into_iter() {
186 match layer {
187 MessageLayer::SignatureGroup { results } =>
188 for result in results {
189 self.total += 1;
190 match result {
191 Ok(GoodChecksum { sig, ka, .. }) => {
192 match (sig.signature_creation_time(),
193 self.not_before,
194 self.not_after)
195 {
196 (None, _, _) => {
197 eprintln!("Malformed signature:");
198 print_error_chain(&anyhow::anyhow!(
199 "no signature creation time"));
200 },
201 (Some(t), Some(not_before), not_after) => {
202 if t < not_before {
203 eprintln!(
204 "Signature by {:X} was created before \
205 the --not-before date.",
206 ka.key().fingerprint());
207 } else if t > not_after {
208 eprintln!(
209 "Signature by {:X} was created after \
210 the --not-after date.",
211 ka.key().fingerprint());
212 } else {
213 signers.push(ka.cert().fingerprint());
214 }
215 }
216 (Some(t), None, not_after) => {
217 if t > not_after {
218 eprintln!(
219 "Signature by {:X} was created after \
220 the --not-after date.",
221 ka.key().fingerprint());
222 } else {
223 signers.push(ka.cert().fingerprint());
224 }
225 }
226 };
227 }
228 Err(MalformedSignature { error, .. }) => {
229 eprintln!("Signature is malformed:");
230 print_error_chain(&error);
231 }
232 Err(MissingKey { sig, .. }) => {
233 let issuers = sig.get_issuers();
234 eprintln!("Missing key {}, which is needed to \
235 verify signature.",
236 issuers
237 .first()
238 .map(|issuer| {
239 Cow::Owned(issuer.to_string())
240 })
241 .unwrap_or_else(|| {
242 Cow::Borrowed("<unknown issuer>")
243 }));
244 }
245 Err(UnboundKey { cert, error, .. }) => {
246 eprintln!("Signing key on {:X} is not bound:",
247 cert.fingerprint());
248 print_error_chain(&error);
249 }
250 Err(BadKey { ka, error, .. }) => {
251 eprintln!("Signing key on {:X} is bad:",
252 ka.cert().fingerprint());
253 print_error_chain(&error);
254 }
255 Err(BadSignature { error, .. }) => {
256 eprintln!("Verifying signature:");
257 print_error_chain(&error);
258 if verification_err.is_none() {
259 verification_err = Some(error)
260 }
261 }
262
263 Err(UnknownSignature { sig, .. }) => {
264 eprintln!("Verifying signature:");
265 print_error_chain(sig.error());
266 if verification_err.is_none() {
267 verification_err =
268 Some(anyhow::anyhow!("{}", sig.error()));
269 }
270 }
271
272 Err(e) => {
273 eprintln!("Verifying signature: {}", e);
274 if verification_err.is_none() {
275 verification_err =
276 Some(anyhow::anyhow!("{}", e));
277 }
278 }
279 }
280 }
281 MessageLayer::Compression { .. } => (),
282 _ => unreachable!(),
283 }
284 }
285
286 // Dedup the keys so that it is not possible to exceed the
287 // threshold by duplicating signatures or by using the same
288 // key.
289 signers.sort();
290 signers.dedup();
291
292 self.good = signers.len();
293 for signer in signers {
294 println!("{:X}", signer);
295 }
296
297 Ok(())
298 }
299 }
300
301 fn print_error_chain(err: &anyhow::Error) {
302 eprintln!(" {}", err);
303 err.chain().skip(1).for_each(|cause| eprintln!(" because: {}", cause));
304 }
305
306
307 fn main() -> Result<()> {
308 let matches = cli::build().get_matches();
309 let cli = cli::SqvCommand::from_arg_matches(&matches)?;
310
311 if cli.data.is_none() && cli.detached.is_none()
312 && ! cli.message && ! cli.cleartext
313 {
314 return Err(anyhow::anyhow!(
315 "Either `--signature-file`, `--message`, or `--cleartext` \
316 must be given."));
317 }
318
319 let verbose = cli.verbose;
320
321 let good_threshold = cli.signatures;
322 if good_threshold < 1 {
323 eprintln!("Value passed to --signatures must be >= 1 (got: {:?}).",
324 good_threshold);
325 exit(2);
326 }
327
328 // Parse the --time argument to get the session reference time.
329 // If not given, defaults to the current time.
330 let ref_time = cli.time.as_ref()
331 .map(|at| at.to_system_time(std::time::SystemTime::now()))
332 .transpose()
333 .with_context(|| format!("Error parsing --time: {}",
334 cli.time.as_ref().unwrap()))?
335 .unwrap_or_else(std::time::SystemTime::now);
336
337 let not_before: Option<std::time::SystemTime> =
338 if let Some(t) = cli.not_before {
339 Some(parse_iso8601(&t, chrono::NaiveTime::from_hms_opt(0, 0, 0).unwrap())
340 .context(format!("Bad value passed to --not-before: {:?}", t))?
341 .into())
342 } else {
343 None
344 };
345 let not_after: std::time::SystemTime =
346 if let Some(t) = cli.not_after {
347 Some(parse_iso8601(&t, chrono::NaiveTime::from_hms_opt(23, 59, 59).unwrap())
348 .context(format!("Bad value passed to --not-after: {:?}", t))?
349 .into())
350 } else {
351 None
352 }.unwrap_or(ref_time);
353
354 let h = VHelper::new(good_threshold, not_before, not_after, cli.keyring);
355
356 let t = cli.policy_as_of.as_ref()
357 .map(|at| at.to_system_time(ref_time))
358 .transpose()
359 .with_context(|| format!("Error parsing --policy-as-of: {}",
360 cli.policy_as_of.unwrap()))?
361 .unwrap_or(ref_time);
362
363 let mut p = sequoia_policy_config::ConfiguredStandardPolicy::at(t);
364 p.parse_default_config()?;
365 let p = p.build();
366
367 // Dispatch.
368 let h = if cli.data.is_some() || cli.detached.is_some() {
369 let sig = cli.detached.as_ref().unwrap_or(&cli.file);
370 let data = cli.data.as_ref().unwrap_or(&cli.file);
371
372 let v = if sig.as_os_str().as_encoded_bytes() == b"-" {
373 DetachedVerifierBuilder::from_reader(stdin("--signature-file")?)?
374 } else {
375 DetachedVerifierBuilder::from_file(sig)?
376 };
377 let mut v = v.with_policy(&p, Some(ref_time), h)
378 .map_err(|err| {
379 // Check if the user reversed the arguments.
380 if data.as_os_str().as_encoded_bytes() != b"-" {
381 if let Ok(ppr) = PacketParser::from_file(data) {
382 if let PacketParserResult::Some(pp) = ppr {
383 if let Packet::Signature(_) = pp.packet {
384 eprintln!(
385 "Hint: Data file ({}) appears to contain \
386 an OpenPGP signature, perhaps you \
387 reversed the arguments.",
388 data.display());
389 }
390 }
391 }
392 }
393 err
394 })?;
395 if data.as_os_str().as_encoded_bytes() == b"-" {
396 v.verify_reader(stdin("FILE")?)?;
397 } else {
398 v.verify_file(data)?;
399 }
400 v.into_helper()
401 } else {
402 assert!(cli.message || cli.cleartext);
403 let mut sink: Box<dyn io::Write> = if let Some(n) = &cli.output {
404 let mut overwrite = cli.overwrite;
405
406 // Imply --overwrite if writing to a special file.
407 #[cfg(unix)]
408 if ! overwrite {
409 use std::os::unix::fs::FileTypeExt;
410
411 if let Ok(metadata) = std::fs::metadata(n) {
412 let ft = metadata.file_type();
413 if ft.is_char_device()
414 || ft.is_block_device()
415 || ft.is_fifo()
416 || ft.is_socket()
417 {
418 overwrite = true;
419 }
420 }
421 }
422
423 Box::new(std::fs::File::options()
424 .write(true)
425 .create(overwrite) // choose create() when allowing overwrite
426 .create_new(!overwrite) // else insist on new file
427 .open(n)?)
428 } else {
429 Box::new(io::stdout())
430 };
431
432 let v = if cli.file.as_os_str().as_encoded_bytes() == b"-" {
433 VerifierBuilder::from_reader(stdin("FILE")?)?
434 } else {
435 VerifierBuilder::from_file(&cli.file)?
436 };
437 let mut v = v.with_policy(&p, Some(ref_time), h)?;
438 io::copy(&mut v, &mut sink)?;
439 v.into_helper()
440 };
441
442 if verbose {
443 eprintln!("{} of {} signatures are valid (threshold is: {}).",
444 h.good, h.total, good_threshold);
445 }
446
447 exit(if h.good >= good_threshold { 0 } else { 1 });
448 }
449
450 /// Parses the given string depicting a ISO 8601 timestamp.
451 fn parse_iso8601(s: &str, pad_date_with: chrono::NaiveTime)
452 -> Result<DateTime<Utc>>
453 {
454 // If you modify this function this function, synchronize the
455 // changes with the copy in sqv.rs!
456 for f in &[
457 "%Y-%m-%dT%H:%M:%S%#z",
458 "%Y-%m-%dT%H:%M:%S",
459 "%Y-%m-%dT%H:%M%#z",
460 "%Y-%m-%dT%H:%M",
461 "%Y-%m-%dT%H%#z",
462 "%Y-%m-%dT%H",
463 "%Y%m%dT%H%M%S%#z",
464 "%Y%m%dT%H%M%S",
465 "%Y%m%dT%H%M%#z",
466 "%Y%m%dT%H%M",
467 "%Y%m%dT%H%#z",
468 "%Y%m%dT%H",
469 ] {
470 if f.ends_with("%#z") {
471 if let Ok(d) = DateTime::parse_from_str(s, *f) {
472 return Ok(d.into());
473 }
474 } else {
475 if let Ok(d) = chrono::NaiveDateTime::parse_from_str(s, *f) {
476 return Ok(DateTime::from_naive_utc_and_offset(d, Utc));
477 }
478 }
479 }
480 for f in &[
481 "%Y-%m-%d",
482 "%Y-%m",
483 "%Y-%j",
484 "%Y%m%d",
485 "%Y%m",
486 "%Y%j",
487 "%Y",
488 ] {
489 if let Ok(d) = chrono::NaiveDate::parse_from_str(s, *f) {
490 return Ok(DateTime::from_naive_utc_and_offset(d.and_time(pad_date_with), Utc));
491 }
492 }
493 Err(anyhow::anyhow!("Malformed ISO8601 timestamp: {}", s))
494 }
495
496 #[test]
497 fn test_parse_iso8601() {
498 let z = chrono::NaiveTime::from_hms_opt(0, 0, 0).unwrap();
499 parse_iso8601("2017-03-04T13:25:35Z", z).unwrap();
500 parse_iso8601("2017-03-04T13:25:35+08:30", z).unwrap();
501 parse_iso8601("2017-03-04T13:25:35", z).unwrap();
502 parse_iso8601("2017-03-04T13:25Z", z).unwrap();
503 parse_iso8601("2017-03-04T13:25", z).unwrap();
504 // parse_iso8601("2017-03-04T13Z", z).unwrap(); // XXX: chrono doesn't like
505 // parse_iso8601("2017-03-04T13", z).unwrap(); // ditto
506 parse_iso8601("2017-03-04", z).unwrap();
507 // parse_iso8601("2017-03", z).unwrap(); // ditto
508 parse_iso8601("2017-031", z).unwrap();
509 parse_iso8601("20170304T132535Z", z).unwrap();
510 parse_iso8601("20170304T132535+0830", z).unwrap();
511 parse_iso8601("20170304T132535", z).unwrap();
512 parse_iso8601("20170304T1325Z", z).unwrap();
513 parse_iso8601("20170304T1325", z).unwrap();
514 // parse_iso8601("20170304T13Z", z).unwrap(); // ditto
515 // parse_iso8601("20170304T13", z).unwrap(); // ditto
516 parse_iso8601("20170304", z).unwrap();
517 // parse_iso8601("201703", z).unwrap(); // ditto
518 parse_iso8601("2017031", z).unwrap();
519 // parse_iso8601("2017", z).unwrap(); // ditto
520 }