Debian Codegraph @

src/commands/key/approvals.rs

raw
1 use std::{
2 collections::BTreeSet,
3 };
4
5 use sequoia_openpgp::{
6 Result,
7 serialize::Serialize,
8 };
9
10 use sequoia_cert_store::Store;
11 use sequoia_wot as wot;
12
13 use crate::Sq;
14 use crate::cli::key::approvals;
15 use crate::cli;
16 use crate::common::{ca_creation_time, ui};
17 use crate::sq::TrustThreshold;
18
19 pub fn dispatch(sq: Sq, command: approvals::Command)
20 -> Result<()>
21 {
22 match command {
23 approvals::Command::List(c) => list(sq, c),
24 approvals::Command::Update(c) => update(sq, c),
25 }
26 }
27
28 fn list(sq: Sq, cmd: approvals::ListCommand) -> Result<()> {
29 let o = &mut std::io::stdout();
30
31 let store = sq.cert_store_or_else()?;
32
33 let cert =
34 sq.resolve_cert(&cmd.cert, TrustThreshold::Full)?.0;
35 let vcert = cert.with_policy(sq.policy, sq.time)?;
36 let userids = cmd.userids.resolve(&vcert)?;
37
38 // resolve returns ResolvedUserIDs, which contain UserIDs, but we
39 // need ValidUserIDAmalgamations.
40 let all = userids.is_empty();
41 let mut designated_userids = BTreeSet::from_iter(
42 userids.into_iter().map(|u| u.userid().clone()));
43 let mut pending = 0;
44 for uid in vcert.userids() {
45 if ! all && ! designated_userids.remove(uid.userid()) {
46 continue;
47 }
48
49 wwriteln!(stream=o,
50 initial_indent = " - ", "{}",
51 ui::Safe(uid.userid()));
52
53 let approved =
54 uid.approved_certifications().collect::<BTreeSet<_>>();
55
56 let mut any = false;
57 for c in uid.certifications() {
58 // Ignore non-exportable certifications.
59 if c.exportable().is_err() {
60 sq.info(format_args!(
61 "Ignoring non-exportable certification from {} on {}.",
62 c.get_issuers()
63 .into_iter()
64 .next()
65 .map(|kh| kh.to_string())
66 .unwrap_or_else(|| "unknown certificate".to_string()),
67 ui::Safe(uid.userid())));
68 continue;
69 }
70
71 let approved = approved.contains(c);
72 if ! approved {
73 pending += 1;
74 }
75
76 if approved == cmd.pending {
77 // It's approved and we want pending, or it's pending
78 // and we want approved.
79 continue;
80 }
81
82 // Verify certifications by looking up the issuing cert.
83 let mut issuer = None;
84 let mut err = None;
85 for i in c.get_issuers().into_iter()
86 .filter_map(|i| store.lookup_by_cert(&i).ok()
87 .map(IntoIterator::into_iter))
88 .flatten()
89 {
90 match c.verify_signature(&i.primary_key()) {
91 Ok(_) => issuer = Some(i),
92 Err(e) => err = Some(e),
93 }
94 }
95
96 // If the certificate should not be exported, we don't
97 // approve the certification.
98 if let Some(Ok(i)) = issuer.as_ref().map(|i| i.to_cert()) {
99 if ! i.exportable() {
100 sq.info(format_args!(
101 "Ignoring certification from non-exportable \
102 certificate {} on {}.",
103 i.fingerprint(), ui::Safe(uid.userid())));
104 continue;
105 }
106 if i.primary_key().key().creation_time() == ca_creation_time() {
107 sq.info(format_args!(
108 "Ignoring certification from local shadow CA \
109 {} on {}.",
110 i.fingerprint(), ui::Safe(uid.userid())));
111 continue;
112 }
113 }
114
115 wwriteln!(stream=o,
116 initial_indent = " - ", "{}{}: {}",
117 issuer.as_ref()
118 .map(|c| format!("{} ", c.fingerprint()))
119 .unwrap_or_else(|| "".into()),
120 issuer.as_ref()
121 .and_then(|i| Some(sq.best_userid(i.to_cert().ok()?, true)
122 .display().to_string()))
123 .or(c.get_issuers().into_iter().next()
124 .map(|h| h.to_string()))
125 .unwrap_or_else(|| "no issuer information".into()),
126 if issuer.is_none() {
127 if let Some(e) = err {
128 e.to_string()
129 } else {
130 "issuer cert not found".into()
131 }
132 } else if approved {
133 "approved".into()
134 } else {
135 "unapproved".into()
136 });
137 any = true;
138 }
139
140 if ! any {
141 wwriteln!(stream=o,
142 initial_indent = " - ", "no {} certifications",
143 if cmd.pending {
144 "unapproved"
145 } else {
146 "approved"
147 });
148 }
149 }
150 assert!(designated_userids.is_empty());
151
152 if ! cmd.pending && pending > 0 {
153 wwriteln!(stream=o,
154 "{} certifications are pending approval. Using `--pending` \
155 to see them.",
156 pending);
157 }
158
159 Ok(())
160 }
161
162 fn update(
163 sq: Sq,
164 command: cli::key::approvals::UpdateCommand,
165 ) -> Result<()> {
166 let store = sq.cert_store_or_else()?;
167
168 let key = sq.resolve_cert(&command.cert, TrustThreshold::Full)?.0;
169 let vcert = key.with_policy(sq.policy, sq.time)?;
170 let userids = command.userids.resolve(&vcert)?;
171
172 // Lookup any explicitly goodlisted certifiers. We need these to
173 // verify the certifications.
174 let mut add_by = Vec::new();
175 for i in &command.add_by {
176 add_by.append(&mut store.lookup_by_cert(i)?);
177 }
178
179 // If we want to authenticate, prepare the authentication network.
180 let network_threshold = command.add_authenticated.then_some(
181 (wot::NetworkBuilder::rooted(store, &*sq.trust_roots()).build(),
182 sequoia_wot::FULLY_TRUSTED));
183
184 // Get a signer.
185 let mut pk_signer = sq.get_primary_key(&key, None)?;
186
187 // Now, create new approval signatures.
188 let mut approval_signatures = Vec::new();
189
190 // resolve returns ResolvedUserIDs, which contain UserIDs, but we
191 // need ValidUserIDAmalgamations.
192 let all = userids.is_empty();
193 let mut designated_userids = BTreeSet::from_iter(
194 userids.into_iter().map(|u| u.userid().clone()));
195 let mut removed = 0;
196 let mut added = 0;
197 for uid in vcert.userids() {
198 if ! all && ! designated_userids.remove(uid.userid()) {
199 continue;
200 }
201
202 weprintln!(initial_indent = " - ", "{}",
203 ui::Safe(uid.userid()));
204
205 let previously_approved =
206 uid.approved_certifications().collect::<BTreeSet<_>>();
207
208 // Start from scratch or from the current set?
209 let mut next_approved = if command.remove_all {
210 Default::default()
211 } else {
212 previously_approved.clone()
213 };
214
215 // Selectively remove approvals.
216 next_approved.retain(|s| ! s.get_issuers().iter().any(
217 // Quadratic, but how bad can it be...?
218 |i| command.remove_by.iter().any(|j| i.aliases(j))));
219
220 // Selectively add approvals.
221 let next_approved_cloned = next_approved.clone();
222 for sig in uid.certifications()
223 // Don't consider those that we already approved.
224 .filter(|s| ! next_approved_cloned.contains(s))
225 {
226 // Ignore non-exportable certifications.
227 if sig.exportable().is_err() {
228 sq.info(format_args!(
229 "Ignoring non-exportable certification from {} on {}.",
230 sig.get_issuers()
231 .into_iter()
232 .next()
233 .map(|kh| kh.to_string())
234 .unwrap_or_else(|| "unknown certificate".to_string()),
235 ui::Safe(uid.userid())));
236 continue;
237 }
238
239 // Try and get the issuer's certificate.
240 let mut issuer = None;
241 let mut err = None;
242 for i in sig.get_issuers().into_iter()
243 .filter_map(|i| store.lookup_by_cert(&i).ok()
244 .map(IntoIterator::into_iter))
245 .flatten()
246 {
247 match sig.verify_signature(&i.primary_key()) {
248 Ok(_) => {
249 issuer = Some(i)
250 }
251 Err(e) => err = Some((i.fingerprint(), e)),
252 }
253 }
254
255 if issuer.is_none() {
256 if let Some((fpr, err)) = err {
257 // We have the alleged signer, but we couldn't
258 // verify the certification. It's bad; silently
259 // ignore it.
260 sq.info(format_args!(
261 "Ignoring invalid certification from {}: {}",
262 fpr, err));
263 continue;
264 }
265 }
266
267 // Convert it from a lazy cert to a cert.
268 let issuer = if let Some(Ok(i))
269 = issuer.as_ref().map(|i| i.to_cert())
270 {
271 Some(i)
272 } else {
273 None
274 };
275
276 // If the certificate should not be exported, we don't
277 // approve the certification.
278 if let Some(i) = issuer.as_ref() {
279 if ! i.exportable() {
280 sq.info(format_args!(
281 "Ignoring certification from non-exportable \
282 certificate {} on {}.",
283 i.fingerprint(), ui::Safe(uid.userid())));
284 continue;
285 }
286 if i.primary_key().key().creation_time() == ca_creation_time() {
287 sq.info(format_args!(
288 "Ignoring certification from local shadow CA \
289 {} on {}.",
290 i.fingerprint(), ui::Safe(uid.userid())));
291 continue;
292 }
293 }
294
295 // Skip if the issuer is in --remove-by.
296 if let Some(issuer) = issuer.as_ref() {
297 if command.remove_by.iter().any(|j| issuer.key_handle().aliases(j)) {
298 continue;
299 }
300 } else if ! sig.get_issuers().iter().any(
301 // Quadratic, but how bad can it be...?
302 |i| command.remove_by.iter().any(|j| i.aliases(j)))
303 {
304 continue;
305 }
306
307 // Add if --add-all is passed.
308 if command.add_all {
309 next_approved.insert(sig);
310 continue;
311 }
312
313 // Add if the issuer is in --add-by.
314 if let Some(issuer) = issuer.as_ref() {
315 if command.add_by.iter().any(|j| issuer.key_handle().aliases(j)) {
316 next_approved.insert(sig);
317 continue;
318 }
319 } else if let Some(cert) = sig.get_issuers().iter().find_map(
320 // Quadratic, but how bad can it be...?
321 |i| add_by.iter().find_map(
322 |cert| i.aliases(cert.key_handle()).then_some(cert)))
323 {
324 if sig.verify_signature(&cert.primary_key()).is_ok() {
325 next_approved.insert(sig);
326 }
327 continue;
328 }
329
330 // Add authenticated certifiers.
331 if let Some(issuer) = issuer.as_ref() {
332 if let Some((ref network, threshold)) = network_threshold {
333 if issuer.userids().any(
334 |u| network.authenticate(u.userid(),
335 issuer.fingerprint(),
336 threshold)
337 .amount() >= threshold)
338 {
339 next_approved.insert(sig);
340 continue;
341 }
342 }
343 }
344 }
345
346 let mut any = false;
347 for (prev, next, c) in uid.certifications()
348 .map(|c| (previously_approved.contains(c),
349 next_approved.contains(c), c))
350 {
351 // Verify certifications by looking up the issuing cert.
352 let mut issuer = None;
353 let mut err = None;
354 for i in c.get_issuers().into_iter()
355 .filter_map(|i| store.lookup_by_cert(&i).ok()
356 .map(IntoIterator::into_iter))
357 .flatten()
358 {
359 match c.verify_signature(&i.primary_key()) {
360 Ok(_) => issuer = Some(i),
361 Err(e) => err = Some(e),
362 }
363 }
364
365 if ! prev && next {
366 added += 1;
367 }
368 if prev && ! next {
369 removed += 1;
370 }
371
372 weprintln!(initial_indent = " ", "{} {}{}: {}",
373 match (prev, next) {
374 (false, false) => '.',
375 (true, false) => '-',
376 (false, true) => '+',
377 (true, true) => '=',
378 },
379 issuer.as_ref()
380 .map(|c| format!("{} ", c.fingerprint()))
381 .unwrap_or_else(|| "".into()),
382 issuer.as_ref()
383 .and_then(|i| Some(sq.best_userid(i.to_cert().ok()?, true)
384 .display().to_string()))
385 .or(c.get_issuers().into_iter().next()
386 .map(|h| h.to_string()))
387 .unwrap_or_else(|| "no issuer information".into()),
388 if issuer.is_none() {
389 if let Some(e) = err {
390 e.to_string()
391 } else {
392 "issuer cert not found".into()
393 }
394 } else if next {
395 "approved".into()
396 } else if prev {
397 "previously approved".into()
398 } else {
399 "unapproved".into()
400 });
401 any = true;
402 }
403
404 if ! any {
405 weprintln!(" no certifications");
406 }
407
408 approval_signatures.append(&mut uid.approve_of_certifications(
409 &mut pk_signer,
410 next_approved.into_iter(),
411 )?);
412 }
413 assert!(designated_userids.is_empty());
414
415 match (added, removed) {
416 (1, 1) => {
417 weprintln!("1 new approval, 1 approval retracted");
418 }
419 (added, 1) => {
420 weprintln!("{} new approvals, 1 approval retracted",
421 added);
422 }
423 (1, removed) => {
424 weprintln!("1 new approval, {} approvals retracted",
425 removed);
426 }
427 (added, removed) => {
428 weprintln!("{} new approvals, {} approvals retracted",
429 added, removed);
430 }
431 }
432
433 // Finally, add the new signatures.
434 let key = key.insert_packets(approval_signatures)?.0;
435
436 if let Some(sink) = command.output {
437 let path = sink.path().map(Clone::clone);
438 let mut output = sink.for_secrets().create_safe(&sq)?;
439 if false {
440 key.as_tsk().serialize(&mut output)?;
441 } else {
442 key.as_tsk().armored().serialize(&mut output)?;
443 }
444
445 if let Some(path) = path {
446 sq.hint(format_args!(
447 "Updated key written to {}. \
448 To make the update effective, it has to be published \
449 so that others can find it, for example using:",
450 path.display()))
451 .sq().arg("network").arg("keyserver").arg("publish")
452 .arg_value("--cert-file", path.display())
453 .done();
454 } else {
455 sq.hint(format_args!(
456 "To make the update effective, it has to be published \
457 so that others can find it."));
458 }
459 } else {
460 let fipr = key.fingerprint();
461 if let Err(err) = sq.import_cert(key) {
462 weprintln!("Error importing updated cert: {}", err);
463 return Err(err);
464 } else {
465 sq.hint(format_args!(
466 "Imported updated cert into the cert store. \
467 To make the update effective, it has to be published \
468 so that others can find it, for example using:"))
469 .sq().arg("network").arg("keyserver").arg("publish")
470 .arg_value("--cert", fipr)
471 .done();
472 }
473 }
474
475 Ok(())
476 }