Debian Codegraph @

src/commands/cert/import.rs

raw
1 use std::sync::Arc;
2 use std::path::PathBuf;
3
4 use anyhow::Context;
5
6 use buffered_reader::{BufferedReader, Dup};
7
8 use sequoia_openpgp as openpgp;
9 use openpgp::KeyHandle;
10 use openpgp::Packet;
11 use openpgp::Result;
12 use openpgp::cert::raw::RawCertParser;
13 use openpgp::parse::Cookie;
14 use openpgp::parse::PacketParser;
15 use openpgp::parse::PacketParserResult;
16 use openpgp::parse::Parse;
17 use openpgp::types::SignatureType;
18
19 use sequoia_cert_store as cert_store;
20 use cert_store::LazyCert;
21 use cert_store::StoreUpdate;
22
23 use crate::Sq;
24 use crate::cli::cert::import;
25 use crate::cli::types::FileOrStdin;
26 use crate::common::ui;
27 use crate::commands::autocrypt;
28 use crate::output::import::ImportStats;
29
30 pub fn dispatch<'store, 'rstore>(mut sq: Sq<'store, 'rstore>,
31 cmd: import::Command)
32 -> Result<()>
33 where 'store: 'rstore
34 {
35 // We're going to save the input to the certificate store.
36 // Make sure it is enabled.
37 sq.cert_store_or_else()?;
38
39 let inputs = if cmd.input.is_empty() {
40 vec![ PathBuf::from("-") ]
41 } else {
42 cmd.input
43 };
44
45 let o = &mut std::io::stdout();
46
47 let mut stats = ImportStats::default();
48
49 let inner = || -> Result<()> {
50 for input in inputs.into_iter() {
51 let input = FileOrStdin::from(input);
52 let mut input_reader = input.open("OpenPGP certificates")?;
53
54 if input_reader.eof() {
55 // Empty file. Silently skip it.
56 continue;
57 }
58
59 enum Type {
60 Signature,
61 Keyring,
62 Other,
63 }
64
65 // See if it is OpenPGP data.
66 let dup = Dup::with_cookie(&mut input_reader, Cookie::default());
67 let mut typ = Type::Other;
68 if let Ok(ppr) = PacketParser::from_buffered_reader(dup) {
69 // See if it is a keyring, or a bare revocation
70 // certificate.
71 if let PacketParserResult::Some(ref pp) = ppr {
72 if let Packet::Signature(sig) = &pp.packet {
73 typ = match sig.typ() {
74 SignatureType::KeyRevocation |
75 SignatureType::SubkeyRevocation |
76 SignatureType::CertificationRevocation =>
77 // Looks like a bare revocation.
78 Type::Signature,
79 _ => Type::Other,
80 };
81 } else if pp.possible_keyring().is_ok() {
82 typ = Type::Keyring;
83 } else {
84 // If we have a message, then it might
85 // actually be an email with autocrypt data.
86 }
87 }
88 }
89
90 let result = match typ {
91 Type::Signature => {
92 import_rev(
93 o, &mut sq, &mut input_reader, &mut stats)
94 }
95 Type::Keyring => {
96 import_certs(
97 o, &mut sq, &mut input_reader,
98 input.path(), &mut stats)
99 }
100 Type::Other => {
101 autocrypt::import_certs(
102 &mut sq, &mut input_reader, &mut stats)
103 }
104 };
105
106 if result.is_err() {
107 if let Some(path) = input.path() {
108 result.with_context(|| {
109 format!("Reading {}", path.display())
110 })
111 } else {
112 result
113 }?;
114 }
115 }
116
117 Ok(())
118 };
119
120 let result = inner();
121
122 wwriteln!(o);
123 stats.print_summary(o, &sq)?;
124
125 Ok(result?)
126 }
127
128 /// Imports the certs and reports on the individual certs.
129 pub fn import_and_report<F>(o: &mut dyn std::io::Write,
130 sq: &mut Sq,
131 certs: Vec<openpgp::Cert>,
132 source_path: Option<&PathBuf>,
133 stats: &mut ImportStats,
134 additional: F)
135 -> Result<()>
136 where
137 F: Fn(&mut dyn std::io::Write, &openpgp::Cert)
138 -> Result<()>,
139 {
140 let cert_store = sq.cert_store_or_else()?;
141
142 for cert in certs {
143 ui::emit_cert(o, sq, &cert)?;
144 let cert = Arc::new(LazyCert::from(cert));
145 if let Err(err) = cert_store.update_by(cert.clone(), stats) {
146 wwriteln!(stream = o,
147 initial_indent = " - ", "failed: {}", err);
148 wwriteln!(o);
149 stats.certs.inc_errors();
150 continue;
151 } else {
152 wwriteln!(stream = o,
153 initial_indent = " - ", "imported");
154 }
155
156 additional(o, cert.to_cert().expect("was a cert"))?;
157
158 if cert.is_tsk() {
159 let mut cmd = sq.hint(format_args!(
160 "Certificate {} contains secret key material. \
161 To import keys, do:", cert.fingerprint()))
162 .sq().arg("key").arg("import");
163
164 if let Some(file) = source_path {
165 cmd = cmd.arg(file.display());
166 }
167
168 cmd.done();
169 }
170 }
171
172 wwriteln!(o);
173 Ok(())
174 }
175
176 /// Imports certs encoded as OpenPGP keyring.
177 fn import_certs(o: &mut dyn std::io::Write,
178 sq: &mut Sq,
179 source: &mut Box<dyn BufferedReader<Cookie>>,
180 source_path: Option<&PathBuf>,
181 stats: &mut ImportStats)
182 -> Result<()>
183 {
184 let dup = Dup::with_cookie(source, Cookie::default());
185 let raw_certs = RawCertParser::from_buffered_reader(dup)?;
186
187 let mut one_ok = false;
188 let mut errors = Vec::new();
189 for raw_cert in raw_certs {
190 let cert = match raw_cert
191 .and_then(|raw| LazyCert::from(raw).to_cert().cloned())
192 {
193 Ok(cert) => {
194 one_ok = true;
195 cert
196 },
197 Err(err) => {
198 errors.push(err);
199 stats.certs.inc_errors();
200 continue;
201 }
202 };
203
204 import_and_report(o, sq, vec![cert], source_path, stats,
205 |_, _| Ok(()))?;
206 }
207
208 if ! one_ok {
209 // This likely wasn't a keyring.
210 errors.reverse();
211 Err(errors.pop().ok_or_else(|| anyhow::anyhow!("no cert found"))?)
212 } else {
213 for err in errors {
214 wwriteln!(o, "Error parsing input: {}", err);
215 }
216 Ok(())
217 }
218 }
219
220 /// Import a bare revocation certificate.
221 fn import_rev(o: &mut dyn std::io::Write,
222 sq: &mut Sq,
223 source: &mut Box<dyn BufferedReader<Cookie>>,
224 stats: &mut ImportStats)
225 -> Result<()>
226 {
227 let dup = Dup::with_cookie(source, Cookie::default());
228 let cert_store = sq.cert_store_or_else()?;
229
230 let ppr = PacketParser::from_buffered_reader(dup)?;
231 let sig = if let PacketParserResult::Some(pp) = ppr {
232 let (packet, next_ppr) = pp.next()?;
233
234 let sig = if let Packet::Signature(sig) = packet {
235 sig
236 } else {
237 return Err(anyhow::anyhow!(
238 "Not a revocation certificate: got a {}.",
239 packet.tag()));
240 };
241
242 if let PacketParserResult::Some(_) = next_ppr {
243 return Err(anyhow::anyhow!(
244 "Not a revocation certificate: \
245 got more than one packet."));
246 }
247
248 sig
249 } else {
250 return Err(anyhow::anyhow!(
251 "Not a bare revocation certificate."));
252 };
253
254 if sig.typ() != SignatureType::KeyRevocation {
255 return Err(anyhow::anyhow!(
256 "Not a revocation certificate: got a {} signature.",
257 sig.typ()));
258 }
259
260 let issuers = sig.get_issuers();
261 let mut missing = Vec::new();
262 let mut bad = Vec::new();
263 for issuer in issuers.iter() {
264 let certs = if let Ok(certs)
265 = sq.lookup(std::iter::once(issuer), None, false, true)
266 {
267 certs
268 } else {
269 missing.push(issuer);
270 continue;
271 };
272
273 for cert in certs.into_iter() {
274 if let Ok(_) = sig.clone().verify_primary_key_revocation(
275 cert.primary_key().key(),
276 cert.primary_key().key())
277 {
278 let cert = cert.insert_packets(sig.clone())?.0;
279
280 ui::emit_cert(o, sq, &cert)?;
281 if let Err(err) = cert_store.update_by(Arc::new(cert.into()),
282 stats)
283 {
284 wwriteln!(stream = o, initial_indent = " - ",
285 "error importing revocation certificate: {}",
286 err);
287 stats.certs.inc_errors();
288 continue;
289 } else {
290 wwriteln!(stream = o, initial_indent = " - ",
291 "imported revocation certificate");
292 }
293
294 return Ok(());
295 } else {
296 bad.push(issuer);
297 }
298 }
299 }
300
301 let search: Option<&KeyHandle> = if let Some(bad) = bad.first() {
302 wwriteln!(o,
303 "Appears to be a revocation for {}, \
304 but the certificate is not available.",
305 bad);
306 Some(bad)
307 } else if ! missing.is_empty() {
308 wwriteln!(o,
309 "Appears to be a revocation for {}, \
310 but the certificate is not available.",
311 missing.iter()
312 .map(|issuer| issuer.to_string())
313 .collect::<Vec<_>>()
314 .join(" or "));
315 Some(missing[0])
316 } else {
317 None
318 };
319
320 if let Some(search) = search {
321 sq.hint(format_args!("{}", "To search for a certificate, try:"))
322 .sq().arg("network").arg("search")
323 .arg(search.to_string())
324 .done();
325 }
326
327 Err(anyhow::anyhow!("Failed to import revocation certificate."))
328 }