Debian Codegraph @

src/cli/mod.rs

raw
1 // XXX: The following comment should be an inner comment, but cannot
2 // until https://github.com/rust-lang/rust/issues/66920 is resolved.
3
4 /// Defines the command-line interface.
5 ///
6 /// This module contains sq's command-line interface, i.e. the clap
7 /// definitions and associated types that can be used by clap.
8 ///
9 /// We also generate manual pages from this module. To that end,
10 /// `build.rs` includes this module, so all of its dependencies must
11 /// be also listed as build-dependencies. Further, this module must
12 /// be self-contained, i.e. it must not use code from other parts of
13 /// sq.
14 ///
15 /// # Interface guidelines
16 ///
17 /// In order to provide a consistent user experience, please follow
18 /// these guidelines.
19 ///
20 /// ## General guidelines
21 ///
22 /// - The same subcommand or option in different places should do the
23 /// same or an equivalent thing, and should use the same phrases in
24 /// the help texts, to the extent possible.
25 ///
26 /// - Subcommands SHOULD be of the form `sq [OBJECT..] VERB`.
27 ///
28 /// - The object SHOULD be present, except for the top level
29 /// commands `encrypt`, `decrypt`, `sign`, `verify`, and
30 /// `inspect`.
31 ///
32 /// - Subcommands SHOULD be grouped by topic, and ordered from most
33 /// often used to least often used.
34 ///
35 /// - Use the imperative mood in the first sentence documenting
36 /// commands, subcommands, and arguments.
37 ///
38 /// ## Terminology
39 ///
40 /// - "certificate" or "cert" instead of "public key", "key", or
41 /// "TPK".
42 ///
43 /// - "key" instead of "secret key", "private key", or "TSK".
44 ///
45 /// - "key server" instead of "keyserver".
46 ///
47 /// - "Web of Trust" instead of other variations.
48 ///
49 /// ## Typography
50 ///
51 /// - The first line of the about texts MUST NOT end in a period.
52 ///
53 /// - To define terms, enclose them in double quotes: `"certificate"`.
54 ///
55 /// - To include inline code fragments, like options or other
56 /// subcommands, use back ticks: `--foo` or `sq foo bar`.
57 ///
58 /// - When referring to options, do not include the `VALUENAME`.
59 ///
60 /// - Enclose URLs in angle brackets: `<https://example.org>`.
61 ///
62 /// - Use a spaced en dash for parenthetical statements (` – `).
63 ///
64 /// ## Examples
65 ///
66 /// - Every subcommand SHOULD have at least one example.
67 ///
68 /// - Every example MUST have a brief description.
69 ///
70 /// - Examples SHOULD be short and to the point, they SHOULD NOT
71 /// include unnecessary options (like `--keyring`).
72 ///
73 /// - Examples MUST use single quotes where necessary.
74 ///
75 /// - Examples MUST NOT use unnecessary quoting.
76 // Workaround so that the above documentation is rendered somewhere in
77 // the API docs.
78 #[allow(dead_code)]
79 pub const USER_INTERFACE_GUIDELINES: () = ();
80
81 use std::borrow::Cow;
82 use std::fmt::Write;
83 use std::path::PathBuf;
84 use std::time::Duration;
85
86 /// Command-line parser for sq.
87 use clap::{Command, CommandFactory, Parser, Subcommand};
88 use clap::builder::StyledStr;
89
90 use sequoia_openpgp as openpgp;
91 use openpgp::Fingerprint;
92
93 #[macro_use]
94 pub mod examples;
95
96 pub mod cert;
97 pub mod config;
98 pub mod decrypt;
99 pub mod download;
100 pub mod encrypt;
101 pub mod inspect;
102 pub mod key;
103 pub mod keyring;
104 pub mod network;
105 pub mod output;
106 pub mod packet;
107 pub mod pki;
108 pub mod sign;
109 pub mod verify;
110 pub mod version;
111
112 pub mod types;
113 use types::paths::{StateDirectory, StateDirectoryValueParser};
114 use types::version::Version;
115 use types::version::VersionInvalidPositionValueParser;
116
117 /// Escapes `s` so when used on the command line, it is recognized as
118 /// a single token with the same value.
119 ///
120 /// "{:?}" escapes a string, but it always adds quotes, which can be
121 /// ugly. We first check check if adding quotes is necessary.
122 /// Specifically, if `s` just consists of alphanumeric characters and
123 /// a few others, then we don't need quotes.
124 pub fn escape_for_shell(s: &str) -> Cow<str> {
125 if s.chars().all(|c| {
126 c.is_ascii_alphanumeric()
127 || ['@', '.', ',', '+', '-', '_', '/'].contains(&c)
128 })
129 {
130 Cow::Borrowed(s)
131 } else {
132 Cow::Owned(format!("{:?}", s))
133 }
134 }
135
136 /// The seconds in a day
137 pub const SECONDS_IN_DAY : u64 = 24 * 60 * 60;
138 /// The seconds in a year
139 pub const SECONDS_IN_YEAR : u64 =
140 // Average number of days in a year.
141 (365.2422222 * SECONDS_IN_DAY as f64) as u64;
142 /// The default validity (in years) for keys and subkeys
143 pub const KEY_VALIDITY_IN_YEARS: u64 = 3;
144 /// The default validity period (as Duration) for keys and subkeys
145 pub const KEY_VALIDITY_DURATION: Duration =
146 Duration::new(SECONDS_IN_YEAR * KEY_VALIDITY_IN_YEARS, 0);
147 /// The default validity (in years) for third party certifications
148 pub const THIRD_PARTY_CERTIFICATION_VALIDITY_IN_YEARS: u64 = 10;
149 /// The default validity period (as Duration) for third party certifications
150 pub const THIRD_PARTY_CERTIFICATION_VALIDITY_DURATION: Duration = Duration::new(
151 SECONDS_IN_YEAR * THIRD_PARTY_CERTIFICATION_VALIDITY_IN_YEARS,
152 0,
153 );
154
155 /// The default time (in days) to retire a certificate after rotation.
156 pub const KEY_ROTATE_RETIRE_IN_IN_DAYS: u64 = 182;
157 /// The default time to retire a certificate after rotation.
158 pub const KEY_ROTATE_RETIRE_IN_DURATION: Duration =
159 Duration::new(SECONDS_IN_DAY * KEY_ROTATE_RETIRE_IN_IN_DAYS, 0);
160
161 pub const GLOBAL_OPTIONS_HEADER: &str = "Global Options";
162
163 /// Builds the top-level Clap command.
164 ///
165 /// If `globals_hidden` is true, then top-level, global arguments are
166 /// marked as hidden, which means they won't be displayed in the help
167 /// output.
168 pub fn build(globals_hidden: bool) -> Command {
169 let sq_version = Box::leak(
170 format!(
171 "{} (sequoia-openpgp {}, using {})",
172 env!("CARGO_PKG_VERSION"),
173 sequoia_openpgp::VERSION,
174 sequoia_openpgp::crypto::backend()
175 )
176 .into_boxed_str(),
177 ) as &str;
178
179 let mut command = SqCommand::command()
180 .version(sq_version)
181 // To improve readability limit the width of the text columns.
182 .max_term_width(100);
183
184 // Change the globals to be hidden.
185 if globals_hidden {
186 fn add_after_help(command: &mut Command) {
187 // We want to append to after_long_help.
188 let mut after_long_help
189 = if let Some(s) = command.get_after_long_help() {
190 let mut s = s.clone();
191 s.write_char('\n').expect("Can write to string");
192 s.write_char('\n').expect("Can write to string");
193 s
194 } else if let Some(s) = command.get_after_help() {
195 // If after_long_help is not explicitly set, it
196 // falls back to after_help. If we set
197 // after_long_help, the fallback no longer happens
198 // so we need to do it manually.
199 let mut s = s.clone();
200 s.write_char('\n').expect("Can write to string");
201 s.write_char('\n').expect("Can write to string");
202 s
203 } else {
204 StyledStr::new()
205 };
206
207 after_long_help.write_str(&format!("\
208 {}:\n See 'sq --help' for a description of the global options.",
209 GLOBAL_OPTIONS_HEADER))
210 .expect("Can write to string");
211
212 *command = command.clone()
213 .after_long_help(after_long_help);
214
215 for sc in command.get_subcommands_mut() {
216 add_after_help(sc);
217 }
218 }
219
220 command = command
221 .mut_args(|mut a| {
222 if a.is_global_set() {
223 a = a.hide(globals_hidden);
224 }
225 a
226 });
227
228 add_after_help(&mut command);
229 };
230
231 command
232 }
233
234 /// Defines the CLI.
235 #[derive(Parser, Debug)]
236 #[clap(
237 name = "sq",
238 about = "A command-line frontend for Sequoia, an implementation of OpenPGP",
239 long_about = "A command-line frontend for Sequoia, an implementation of OpenPGP
240
241 Functionality is grouped and available using subcommands. This \
242 interface is not completely stateless. In particular, the user's \
243 default certificate store is used. This can be disabled using \
244 `--cert-store=none`. Similarly, a key store is used to manage and \
245 protect secret key material. This can be disabled using \
246 `--key-store=none`.
247
248 OpenPGP data can be provided in binary or ASCII armored form. This \
249 will be handled automatically. Emitted OpenPGP data is ASCII armored \
250 by default.
251
252 We use the term \"certificate\", or \"cert\" for short, to refer to OpenPGP \
253 keys that do not contain secrets. Conversely, we use the term \"key\" \
254 to refer to OpenPGP keys that do contain secrets.
255 ",
256 subcommand_required = true,
257 arg_required_else_help = true,
258 disable_colored_help = true,
259 disable_version_flag = true,
260 // We want a top-level `help` subcommand, but we don't want
261 // subcommands groups (like `sq pki`) to have a `help` subcommand.
262 // Users get used to being able to use `help` instead of `--help`,
263 // and then are confused when `sq pki authenticate help` (i.e.,
264 // using the `help` subcommand on an action) doesn't work.
265 //
266 // Note: this option is recursive. So if we disable it here, then
267 // we have to enable it for all of the top-level subcommands.
268 disable_help_subcommand = false,
269 )]
270 pub struct SqCommand {
271 #[clap(
272 long = "cli-version",
273 global = true,
274 value_parser = VersionInvalidPositionValueParser::default(),
275 help_heading = GLOBAL_OPTIONS_HEADER,
276 help = "Select a CLI version",
277 long_help = format!("\
278 Select a CLI version
279
280 `sq`'s CLI is versioned using a semantic versioning scheme. Setting \
281 this options causes `sq` to error out if it does not implement an \
282 interface that is compatible with the specified version. For \
283 instance, if you set this to 1.1.0 and `sq` only implements version
284 1.0.0 of the interface, then `sq` will error out.
285
286 `sq` may implement multiple interfaces (e.g., 1.1.4, and 2.0.5). By \
287 default, it selects the newest version. As such, if you require a \
288 particular interface, you need to set this option for every call to \
289 `sq`.
290
291 This option must be the first option on the command line.
292
293 This version of `sq` implements version {}.{}.{} of the CLI interface.
294
295 Stable since 1.2.0.
296 ",
297 env!("CARGO_PKG_VERSION_MAJOR"),
298 env!("CARGO_PKG_VERSION_MINOR"),
299 env!("CARGO_PKG_VERSION_PATCH")),
300 )]
301 pub cli_version: Option<Version>,
302
303 #[clap(
304 long = "overwrite",
305 global = true,
306 help_heading = GLOBAL_OPTIONS_HEADER,
307 help = "Overwrite existing files",
308 )]
309 pub overwrite: bool,
310
311 #[clap(
312 long = "home",
313 value_name = "PATH",
314 env = "SEQUOIA_HOME",
315 global = true,
316 help_heading = GLOBAL_OPTIONS_HEADER,
317 help = "Set the home directory",
318 long_help = format!("\
319 Set the home directory
320
321 Sequoia's default home directory is `{}`. When using the default \
322 location, files are placed according to the local standard, \
323 e.g., the XDG Base Directory Specification. When an alternate \
324 location is specified, the user data, configuration files, and \
325 cache data are placed under a single, unified directory. This is \
326 a lightweight way to partially isolate `sq`.
327
328 Use 'default' to explicitly use the default location, use 'none' to \
329 not use a home directory.",
330 sequoia_directories::Home::default_location()
331 .map(|p| {
332 let p = p.display().to_string();
333 if let Some(home) = dirs::home_dir() {
334 let home = home.display().to_string();
335 if let Some(rest) = p.strip_prefix(&home) {
336 return format!("$HOME{}", rest);
337 }
338 }
339 p
340 })
341 .unwrap_or("<unknown>".to_string())),
342 value_parser = StateDirectoryValueParser::default(),
343 )]
344 pub home: Option<StateDirectory>,
345
346 #[clap(
347 long = "key-store",
348 value_name = "PATH",
349 env = "SEQUOIA_KEY_STORE",
350 global = true,
351 help_heading = GLOBAL_OPTIONS_HEADER,
352 help = "Override the key store server and its data",
353 long_help = format!("Override the key store server and its data
354
355 A key store server manages and protects secret key material. By \
356 default, `sq` connects to the key store server for Sequoia's default \
357 home directory (see `--home`), {}. If no key store server is running, \
358 one is started.
359
360 This option causes `sq` to use an alternate key store server. If \
361 necessary, a key store server is started, and configured to look for \
362 its data in the specified location.
363
364 Use 'default' to explicitly use the default server, use 'none' to \
365 not use a key store.",
366 sequoia_directories::Home::default()
367 .map(|home| {
368 let p = home.data_dir(sequoia_directories::Component::Keystore);
369 let p = p.display().to_string();
370 if let Some(home) = dirs::home_dir() {
371 let home = home.display().to_string();
372 if let Some(rest) = p.strip_prefix(&home) {
373 return format!("$HOME{}", rest);
374 }
375 }
376 p
377 })
378 .unwrap_or("<unknown>".to_string())),
379 value_parser = StateDirectoryValueParser::default(),
380 )]
381 pub key_store: Option<StateDirectory>,
382
383 #[clap(
384 long = "cert-store",
385 value_name = "PATH",
386 env = "SEQUOIA_CERT_STORE",
387 global = true,
388 help_heading = GLOBAL_OPTIONS_HEADER,
389 help = "Specify the location of the certificate store",
390 long_help = format!("\
391 Specify the location of the certificate store
392
393 By default, `sq` uses \
394 the OpenPGP certificate directory in Sequoia's home directory (see `--home`), \
395 {}. This can be overridden by setting the `PGP_CERT_D` environment \
396 variable.
397
398 Use 'default' to explicitly use the default cert store, use 'none' to \
399 not use a cert store.",
400 sequoia_directories::Home::default()
401 .map(|home| {
402 let p = home.data_dir(sequoia_directories::Component::CertD);
403 let p = p.display().to_string();
404 if let Some(home) = dirs::home_dir() {
405 let home = home.display().to_string();
406 if let Some(rest) = p.strip_prefix(&home) {
407 return format!("$HOME{}", rest);
408 }
409 }
410 p
411 })
412 .unwrap_or("<unknown>".to_string())),
413 value_parser = StateDirectoryValueParser::default(),
414 )]
415 pub cert_store: Option<StateDirectory>,
416
417 #[clap(
418 long,
419 value_name = "PATH",
420 global = true,
421 help_heading = GLOBAL_OPTIONS_HEADER,
422 help = "Specify the location of a keyring to use",
423 long_help = "\
424 Specify the location of a keyring to use
425
426 Keyrings are used in \
427 addition to any certificate store. The content of the keyring is \
428 not imported into the certificate store. When a certificate is \
429 looked up, it is looked up in all keyrings and any certificate \
430 store, and the results are merged together."
431 )]
432 pub keyring: Vec<PathBuf>,
433
434 #[clap(
435 long = "known-notation",
436 value_name = "NOTATION",
437 global = true,
438 help_heading = GLOBAL_OPTIONS_HEADER,
439 help = "Add NOTATION to the list of known notations",
440 long_help = "Add NOTATION to the list of known notations
441
442 This is used when validating signatures. \
443 Signatures that have unknown notations with the \
444 critical bit set are considered invalid."
445 )]
446 // TODO is this the right type?
447 pub known_notation: Vec<String>,
448
449 #[clap(
450 long = "time",
451 allow_hyphen_values = true,
452 value_name = "TIME",
453 help = "Set the reference time as an ISO 8601 formatted timestamp",
454 global = true,
455 help_heading = GLOBAL_OPTIONS_HEADER,
456 long_help = "\
457 Set the reference time as an ISO 8601 formatted timestamp
458
459 Normally, \
460 commands use the current time as the reference time. This argument allows \
461 the user to use a difference reference time. For instance, when creating a \
462 key using `sq key generate`, the creation time is normally set to the \
463 current time, but can be overridden using this option. Similarly, when \
464 verifying a message, the message is verified with respect to the current \
465 time. This option allows the user to use a different time.
466
467 TIME is interpreted as an ISO 8601 timestamp. To set the \
468 certification time to July 21, 2013 at midnight UTC, you can do:
469
470 $ sq --time 20130721 verify --message msg.pgp
471
472 To include a time, say 5:50 AM, add a T, the time and optionally the timezone \
473 (the default timezone is UTC):
474
475 $ sq --time 20130721T0550+0200 --message verify msg.pgp
476 ",
477 )]
478 pub time: Option<types::Time>,
479 #[clap(
480 long = "policy-as-of",
481 allow_hyphen_values = true,
482 value_name = "TIME",
483 help = "Select the cryptographic policy as of the specified time",
484 global = true,
485 help_heading = GLOBAL_OPTIONS_HEADER,
486 long_help = "\
487 Select the cryptographic policy as of the specified time
488
489 The time is \
490 expressed as an ISO 8601 formatted timestamp. The policy determines \
491 what cryptographic constructs are allowed.
492
493 If you are working with a message that sq rejects, because it is \
494 protected by cryptographic constructs that are now considered broken, \
495 you can use this option to select a different cryptographic policy. \
496 If you are relying on the cryptography, e.g., you are verifying a \
497 signature, then you should only do this if you are confident that the \
498 message hasn't been tampered with.
499
500 TIME is interpreted as an ISO 8601 timestamp. To set the \
501 policy time to January 1, 2007 at midnight UTC, you can do:
502
503 $ sq --policy-as-of 20070101 verify --message msg.pgp
504
505 Defaults to the reference time, which can be set using --time.
506 ",
507 )]
508 pub policy_as_of: Option<types::Time>,
509
510 #[clap(
511 long = "trust-root",
512 value_name = "FINGERPRINT|KEYID",
513 global = true,
514 help_heading = GLOBAL_OPTIONS_HEADER,
515 help = "Consider the specified certificate to be a trust root",
516 long_help = "Consider the specified certificate to be a trust root
517
518 Trust roots are used by trust models, e.g., the Web of \
519 Trust, to authenticate certificates and User IDs."
520 )]
521 pub trust_roots: Vec<Fingerprint>,
522 #[clap(
523 long,
524 value_name = "FILE",
525 global = true,
526 help_heading = GLOBAL_OPTIONS_HEADER,
527 help = "Seed the password cache with the specified password",
528 long_help = "\
529 Seed the password cache with the specified password
530
531 The password is added to the password cache. When decrypting secret \
532 key material, the password cache is only used if the key is not \
533 protected by a retry counter, which automatically locks the key if \
534 a wrong password is entered too many times.
535
536 Note that the entire key file will be used as the password, including \
537 any surrounding whitespace like a trailing newline.",
538 )]
539 pub password_file: Vec<PathBuf>,
540
541 #[clap(
542 short = 'v',
543 long,
544 global = true,
545 help_heading = GLOBAL_OPTIONS_HEADER,
546 help = "Be more verbose",
547 long_help = config::augment_help(
548 "ui.verbose",
549 "Be more verbose"),
550 )]
551 pub verbose: bool,
552
553 #[clap(
554 short = 'q',
555 long = "quiet",
556 global = true,
557 help_heading = GLOBAL_OPTIONS_HEADER,
558 help = "Be more quiet",
559 long_help = config::augment_help(
560 "ui.quiet",
561 "Be more quiet"),
562 conflicts_with = "verbose",
563 )]
564 pub quiet: bool,
565
566 #[clap(
567 long = "batch",
568 global = true,
569 help_heading = GLOBAL_OPTIONS_HEADER,
570 help = "Prevents any kind of prompting",
571 long_help = "\
572 Prevents any kind of prompting
573
574 Enables batch mode. In batch mode, sq will never ask for user input,
575 such as prompting for passwords.
576 ",
577 )]
578 pub batch: bool,
579
580 #[clap(subcommand)]
581 pub subcommand: SqSubcommands,
582 }
583
584 /// The order of top-level subcommands is:
585 ///
586 /// - Encryption & decryption
587 /// - Signing & verification
588 /// - Inspection
589 /// - Key & cert-ring management
590 /// - Key discovery & networking
591 /// - Tools for developers, maintainers, forensic specialists
592 ///
593 /// The order is derived from the order of variants in this enum.
594 #[derive(Debug, Subcommand)]
595 pub enum SqSubcommands {
596 Encrypt(encrypt::Command),
597 Decrypt(decrypt::Command),
598
599 Sign(sign::Command),
600 Verify(verify::Command),
601 Download(download::Command),
602
603 Inspect(inspect::Command),
604
605 Cert(cert::Command),
606 Key(key::Command),
607 Pki(pki::Command),
608
609 Network(network::Command),
610
611 Keyring(keyring::Command),
612 Packet(packet::Command),
613
614 Config(config::Command),
615 Version(version::Command),
616 }