1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
|
//! The `keys` subcommand.
// TODO: The output of these subcommands needs improvement. Also, some of the `display_` functions
// are repetitive and redundant.
use std::ops::Deref;
use std::str::FromStr;
use anyhow::Result;
use arti_client::{InertTorClient, TorClient, TorClientBuilder, TorClientConfig};
use clap::{ArgMatches, Args, FromArgMatches, Parser, Subcommand};
use safelog::DisplayRedacted;
use tor_keymgr::{
CTorPath, KeyMgr, KeyPath, KeystoreEntry, KeystoreEntryResult, KeystoreId,
UnrecognizedEntryError,
};
use tor_rtcompat::Runtime;
use crate::{ArtiConfig, subcommands::prompt};
#[cfg(feature = "onion-service-service")]
use tor_hsservice::OnionService;
/// Length of a line, used for formatting
// TODO: use COLUMNS instead of an arbitrary LINE_LEN
const LINE_LEN: usize = 80;
/// The `keys` subcommands the arti CLI will be augmented with.
#[derive(Debug, Parser)]
pub(crate) enum KeysSubcommands {
/// Run keystore management commands.
#[command(subcommand)]
Keys(KeysSubcommand),
}
#[derive(Subcommand, Debug, Clone)]
pub(crate) enum KeysSubcommand {
/// List keys and certificates.
///
/// Note: The output fields "Location" and "Keystore ID" represent,
/// respectively, the raw identifier of an entry (e.g. <ARTI_PATH>.<ENTRY_TYPE>
/// for `ArtiNativeKeystore`), and the identifier of the keystore that
/// contains the entry.
List(ListArgs),
/// List keystores.
ListKeystores,
/// Validate the integrity of keystores.
///
/// Detects and reports unrecognized entries and paths, as well as
/// malformed or expired keys.
///
/// Such entries will be removed if this command is invoked with `--sweep`.
CheckIntegrity(CheckIntegrityArgs),
}
/// The arguments of the [`List`](KeysSubcommand::List) subcommand.
#[derive(Debug, Clone, Args)]
pub(crate) struct ListArgs {
/// Identifier of the keystore.
///
/// If omitted, keys and certificates
/// from all the keystores will be returned.
#[arg(short, long)]
keystore_id: Option<String>,
}
/// The arguments of the [`CheckIntegrity`](KeysSubcommand::CheckIntegrity) subcommand.
#[derive(Debug, Clone, Args)]
pub(crate) struct CheckIntegrityArgs {
/// Identifier of the keystore.
///
/// If omitted, keys and certificates
/// from all the keystores will be checked.
#[arg(short, long)]
keystore_id: Option<KeystoreId>,
/// Remove the detected invalid keystore entries.
#[arg(long, short, default_value_t = false)]
sweep: bool,
/// With this flag active no prompt will be shown
/// and no confirmation will be asked.
// TODO: Rephrase this and the `batch` flags of the
// other commands in the present tense.
#[arg(long, short, default_value_t = false)]
batch: bool,
}
/// Run the `keys` subcommand.
pub(crate) fn run<R: Runtime>(
runtime: R,
keys_matches: &ArgMatches,
config: &ArtiConfig,
client_config: &TorClientConfig,
) -> Result<()> {
let subcommand =
KeysSubcommand::from_arg_matches(keys_matches).expect("Could not parse keys subcommand");
let rt = runtime.clone();
let client_builder = TorClient::with_runtime(runtime).config(client_config.clone());
match subcommand {
KeysSubcommand::List(args) => run_list_keys(&args, &client_builder.create_inert()?),
KeysSubcommand::ListKeystores => run_list_keystores(&client_builder.create_inert()?),
KeysSubcommand::CheckIntegrity(args) => {
run_check_integrity(&args, &client_builder, &rt, config, client_config)
}
}
}
/// Print information about a keystore entry.
fn display_entry(entry: &KeystoreEntry, keymgr: &KeyMgr) {
match entry.key_path() {
KeyPath::Arti(_) => display_arti_entry(entry, keymgr),
KeyPath::CTor(path) => display_ctor_entry(entry, path),
unrecognized => {
eprintln!(
"WARNING: unexpected `tor_keymgr::KeyPath` variant encountered: {:?}",
unrecognized
);
}
}
println!("\n {}", "-".repeat(LINE_LEN));
}
/// Print information about an unrecognized keystore entry.
fn display_unrecognized_entry(entry: &UnrecognizedEntryError) {
let raw_entry = entry.entry();
println!(" Unrecognized entry");
#[allow(clippy::single_match)]
match raw_entry.raw_id() {
tor_keymgr::RawEntryId::Path(p) => {
println!(" Keystore ID: {}", raw_entry.keystore_id());
println!(" Location: {}", p.to_string_lossy());
println!(" Error: {}", entry.error());
}
// NOTE: For the time being Arti only supports
// on-disk keystores, but more supported medium
// will be added.
other => {
panic!("Unhandled enum variant: {:?}", other);
}
}
println!("\n {}\n", "-".repeat(LINE_LEN));
}
/// Run the `keys list` subcommand.
fn run_list_keys(args: &ListArgs, client: &InertTorClient) -> Result<()> {
let keymgr = client.keymgr()?;
// TODO: in the future we could group entries by their type
// (recognized, unrecognized and unrecognized path).
// That way we don't need to print "Unrecognized path",
// "Unrecognized" entry etc. for each unrecognized entry.
match &args.keystore_id {
Some(s) => {
let id = KeystoreId::from_str(s)?;
let empty_err_msg = format!("Currently there are no entries in the keystore {}.", s);
display_keystore_entries(
&keymgr.list_by_id(&id)?,
keymgr,
"Keystore entries",
&empty_err_msg,
);
}
None => {
display_keystore_entries(
&keymgr.list()?,
keymgr,
"Keystore entries",
"Currently there are no entries in any of the keystores.",
);
}
}
Ok(())
}
/// Run `keys list-keystores` subcommand.
fn run_list_keystores(client: &InertTorClient) -> Result<()> {
let keymgr = client.keymgr()?;
let entries = keymgr.list_keystores();
if entries.is_empty() {
println!("Currently there are no keystores available.");
} else {
println!(" Keystores:\n");
for entry in entries {
// TODO: We need something similar to [`KeyPathInfo`](tor_keymgr::KeyPathInfo)
// for `KeystoreId`
println!(" - {:?}\n", entry.as_ref());
}
}
Ok(())
}
/// Run `keys check-integrity` subcommand.
fn run_check_integrity<R: Runtime>(
args: &CheckIntegrityArgs,
builder: &TorClientBuilder<R>,
runtime: &R,
config: &ArtiConfig,
client_config: &TorClientConfig,
) -> Result<()> {
let inert_client = builder.create_inert()?;
let client = runtime.reenter_block_on(builder.create_bootstrapped())?;
// TODO: `TorClient` should have a `KeyMgr` accessor.
let keymgr = inert_client.keymgr()?;
let entries = match &args.keystore_id {
Some(id) => keymgr.list_by_id(id)?,
None => keymgr.list()?,
};
let mut invalid_entries = entries
.into_iter()
.filter(|entry| match entry {
Ok(e) => keymgr.validate_entry_integrity(e).is_err(),
Err(_) => true,
})
.collect::<Vec<_>>();
display_invalid_keystore_entries(&invalid_entries, keymgr, "Invalid keystore entries");
cfg_if::cfg_if! {
if #[cfg(feature = "onion-service-service")] {
let services = create_all_services(config, client_config)?;
let expired_entries = get_expired_keys(&services, &client)?;
display_invalid_keystore_entries(
&expired_entries,
keymgr,
"Expired keystore entries"
);
invalid_entries.extend(expired_entries)
}
}
if invalid_entries.is_empty() {
println!("OK.");
return Ok(());
}
maybe_remove_invalid_entries(args, &invalid_entries, keymgr)?;
Ok(())
}
/// Helper function of `run_check_integrity`, reduces cognitive complexity.
// TODO: code duplication with `display_keystore_entries`.
fn display_invalid_keystore_entries(
entries: &[KeystoreEntryResult<KeystoreEntry>],
keymgr: &KeyMgr,
header: &str,
) {
if entries.is_empty() {
return;
}
println!(" ===== {} =====\n\n", header);
for entry in entries {
match entry {
Ok(entry) => {
display_entry(entry, keymgr);
}
Err(entry) => {
display_unrecognized_entry(entry);
}
}
}
}
/// Helper function of `run_list_keys`, reduces cognitive complexity.
fn display_keystore_entries(
entries: &[KeystoreEntryResult<KeystoreEntry>],
keymgr: &KeyMgr,
header: &str,
empty_err_msg: &str,
) {
if entries.is_empty() {
println!("{empty_err_msg}");
return;
}
println!(" ===== {} =====\n\n", header);
for entry in entries {
match entry {
Ok(entry) => {
display_entry(entry, keymgr);
}
Err(entry) => {
display_unrecognized_entry(entry);
}
}
}
}
/// Displays an Arti native keystore entry.
fn display_arti_entry(entry: &KeystoreEntry, keymgr: &KeyMgr) {
let raw_entry = entry.raw_entry();
match keymgr.describe(entry.key_path()) {
Ok(e) => {
println!(" Keystore ID: {}", entry.keystore_id());
println!(" Role: {}", e.role());
println!(" Summary: {}", e.summary());
println!(" KeystoreItemType: {:?}", entry.key_type());
println!(" Location: {}", raw_entry.raw_id());
let extra_info = e.extra_info();
println!(" Extra info:");
for (key, value) in extra_info {
println!(" - {key}: {value}");
}
}
Err(_) => {
println!(" Unrecognized path {}", raw_entry.raw_id());
}
}
}
/// Displays a CTor keystore entry.
///
/// This function outputs the details of a CTor keystore entry, distinguishing
/// between client and service keys based on [`CTorPath`].
fn display_ctor_entry(entry: &KeystoreEntry, path: &CTorPath) {
let raw_entry = entry.raw_entry();
match path {
CTorPath::ClientHsDescEncKey(id) => {
println!(" CTor client key");
println!(" Hidden service ID: {}", id.display_unredacted());
}
CTorPath::Service { nickname, path: _ } => {
println!(" CTor service key");
println!(" Hidden service nickname: {}", nickname);
}
unrecognized => {
eprintln!(
"WARNING: unexpected `tor_keymgr::CTorPath` variant encountered: {:?}",
unrecognized
);
return;
}
}
println!(" Keystore ID: {}", entry.keystore_id());
println!(" KeystoreItemType: {:?}", entry.key_type());
println!(" Location: {}", raw_entry.raw_id());
}
/// Helper function for `run_check_integrity`.
///
/// Creates an [`OnionService`] for each configured hidden service.
#[cfg(feature = "onion-service-service")]
fn create_all_services(
config: &ArtiConfig,
client_config: &TorClientConfig,
) -> Result<Vec<OnionService>> {
let mut services = Vec::new();
for (_, cfg) in config.onion_services.iter() {
services.push(
TorClient::<tor_rtcompat::PreferredRuntime>::create_onion_service(
client_config,
cfg.svc_cfg.clone(),
)?,
);
}
Ok(services)
}
/// Helper function for `run_check_integrity`.
///
/// Gathers all expired keys from the provided hidden services.
#[cfg(feature = "onion-service-service")]
fn get_expired_keys<'a, R: Runtime>(
services: &'a Vec<OnionService>,
client: &TorClient<R>,
) -> Result<Vec<KeystoreEntryResult<KeystoreEntry<'a>>>> {
let netdir = client.dirmgr().timely_netdir()?;
let mut expired_keys = Vec::new();
for service in services {
expired_keys.append(
&mut service
.list_expired_keys(&netdir)?
.into_iter()
.map(Ok)
.collect(),
);
}
Ok(expired_keys)
}
/// Helper function for `run_check_integrity`.
///
/// Removes invalid keystore entries.
/// Prints an error message if one or more entries fail to be removed.
/// Returns `Err` if an I/O error occurs.
fn maybe_remove_invalid_entries(
args: &CheckIntegrityArgs,
entries: &[KeystoreEntryResult<KeystoreEntry<'_>>],
keymgr: &KeyMgr,
) -> Result<()> {
if entries.is_empty() || !args.sweep {
return Ok(());
}
let should_remove = args.batch || prompt("Remove all invalid entries?")?;
if !should_remove {
return Ok(());
}
for res in entries.iter() {
let raw_entry = match res {
Ok(e) => &e.raw_entry(),
Err(e) => e.entry().deref(),
};
if keymgr
.remove_unchecked(&raw_entry.raw_id().to_string(), raw_entry.keystore_id())
.is_err()
{
eprintln!("Failed to remove entry at location: {}", raw_entry.raw_id());
}
}
Ok(())
}
|