1use base64::Engine;
19use sha1::{Digest, Sha1};
20
21#[derive(Debug, Clone, PartialEq)]
23pub struct KeyInfo {
24 pub fingerprint: String,
26 pub key_id: String,
28 pub created: i64,
30 pub expires: Option<i64>,
32 pub algorithm: u8,
34 pub revoked: bool,
35}
36
37#[derive(Debug, Clone, PartialEq)]
39pub struct PgpInfo {
40 pub primary: KeyInfo,
41 pub user_ids: Vec<String>,
42 pub subkeys: Vec<KeyInfo>,
43}
44
45impl PgpInfo {
46 pub fn soonest_expiry(&self) -> Option<i64> {
49 std::iter::once(&self.primary)
50 .chain(self.subkeys.iter())
51 .filter(|k| !k.revoked)
52 .filter_map(|k| k.expires)
53 .min()
54 }
55}
56
57pub fn iso(epoch: i64) -> String {
59 let t = time::OffsetDateTime::from_unix_timestamp(epoch)
60 .unwrap_or(time::OffsetDateTime::UNIX_EPOCH);
61 format!(
62 "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
63 t.year(),
64 t.month() as u8,
65 t.day(),
66 t.hour(),
67 t.minute(),
68 t.second()
69 )
70}
71
72const MAX_PACKETS: usize = 4096;
73
74fn dearmor(input: &[u8]) -> Result<Vec<u8>, String> {
76 let Ok(text) = std::str::from_utf8(input) else {
77 return Ok(input.to_vec()); };
79 if !text.contains("-----BEGIN PGP") {
80 return Ok(input.to_vec());
81 }
82 let mut body = String::new();
83 let mut in_block = false;
84 let mut in_headers = false;
85 for line in text.lines() {
86 let l = line.trim();
87 if l.starts_with("-----BEGIN PGP") {
88 in_block = true;
89 in_headers = true;
90 continue;
91 }
92 if l.starts_with("-----END PGP") {
93 break;
94 }
95 if !in_block {
96 continue;
97 }
98 if in_headers {
99 if l.is_empty() {
100 in_headers = false;
101 }
102 continue;
103 }
104 if l.starts_with('=') {
105 continue; }
107 body.push_str(l);
108 }
109 base64::engine::general_purpose::STANDARD
110 .decode(body.as_bytes())
111 .map_err(|e| format!("The armour is not valid base64: {e}"))
112}
113
114struct Packet<'a> {
115 tag: u8,
116 body: &'a [u8],
117}
118
119fn packets(data: &[u8]) -> Result<Vec<Packet<'_>>, String> {
120 let mut out = Vec::new();
121 let mut i = 0;
122 while i < data.len() {
123 if out.len() >= MAX_PACKETS {
124 return Err("The key has too many packets to read".into());
125 }
126 let b = data[i];
127 if b & 0x80 == 0 {
128 return Err("Not an OpenPGP packet stream".into());
129 }
130 i += 1;
131 let (tag, len) = if b & 0x40 != 0 {
132 let tag = b & 0x3f;
133 let first = *data.get(i).ok_or("Truncated packet header")?;
134 i += 1;
135 let len = match first {
136 0..=191 => usize::from(first),
137 192..=223 => {
138 let second = *data.get(i).ok_or("Truncated packet header")?;
139 i += 1;
140 ((usize::from(first) - 192) << 8) + usize::from(second) + 192
141 }
142 255 => {
143 let n = data.get(i..i + 4).ok_or("Truncated packet header")?;
144 i += 4;
145 u32::from_be_bytes([n[0], n[1], n[2], n[3]]) as usize
146 }
147 _ => return Err("Partial-length packets are not supported".into()),
148 };
149 (tag, len)
150 } else {
151 let tag = (b >> 2) & 0x0f;
152 let len = match b & 3 {
153 0 => {
154 let n = *data.get(i).ok_or("Truncated packet header")?;
155 i += 1;
156 usize::from(n)
157 }
158 1 => {
159 let n = data.get(i..i + 2).ok_or("Truncated packet header")?;
160 i += 2;
161 usize::from(u16::from_be_bytes([n[0], n[1]]))
162 }
163 2 => {
164 let n = data.get(i..i + 4).ok_or("Truncated packet header")?;
165 i += 4;
166 u32::from_be_bytes([n[0], n[1], n[2], n[3]]) as usize
167 }
168 _ => return Err("Indeterminate-length packets are not supported".into()),
169 };
170 (tag, len)
171 };
172 let body = data
173 .get(i..i.checked_add(len).ok_or("Packet length overflows")?)
174 .ok_or("A packet runs past the end of the data")?;
175 i += len;
176 out.push(Packet { tag, body });
177 }
178 Ok(out)
179}
180
181fn public_material_len(algo: u8, m: &[u8]) -> Result<usize, String> {
184 let mpi = |at: usize| -> Result<usize, String> {
185 let h = m.get(at..at + 2).ok_or("Truncated key material")?;
186 let bits = usize::from(u16::from_be_bytes([h[0], h[1]]));
187 Ok(2 + bits.div_ceil(8))
188 };
189 let mut at = 0;
190 match algo {
191 1..=3 => {
192 for _ in 0..2 {
193 at += mpi(at)?; }
195 }
196 16 | 20 => {
197 for _ in 0..3 {
198 at += mpi(at)?; }
200 }
201 17 => {
202 for _ in 0..4 {
203 at += mpi(at)?; }
205 }
206 18 | 19 | 22 => {
207 let oid_len = usize::from(*m.first().ok_or("Truncated key material")?);
208 at += 1 + oid_len;
209 at += mpi(at)?;
210 if algo == 18 {
211 let kl = usize::from(*m.get(at).ok_or("Truncated key material")?);
213 at += 1 + kl;
214 }
215 }
216 25 | 27 | 28 => {
217 at += match algo {
219 25 | 27 => 32,
220 _ => 56,
221 };
222 }
223 a => return Err(format!("Public-key algorithm {a} is not supported")),
224 }
225 if at > m.len() {
226 return Err("Truncated key material".into());
227 }
228 Ok(at)
229}
230
231fn key_from_packet(body: &[u8]) -> Result<KeyInfo, String> {
232 let version = *body.first().ok_or("Empty key packet")?;
233 if version != 4 {
234 return Err(format!(
235 "Version {version} keys are not supported; only v4 (what gpg has made by default for years)"
236 ));
237 }
238 if body.len() < 6 {
239 return Err("Truncated key packet".into());
240 }
241 let created = i64::from(u32::from_be_bytes([body[1], body[2], body[3], body[4]]));
242 let algorithm = body[5];
243 let n = public_material_len(algorithm, &body[6..])?;
244 let public = &body[..6 + n];
245 let mut h = Sha1::new();
247 h.update([0x99]);
248 h.update((public.len() as u16).to_be_bytes());
249 h.update(public);
250 let fingerprint = hex::encode_upper(h.finalize());
251 Ok(KeyInfo {
252 key_id: fingerprint[24..].to_string(),
253 fingerprint,
254 created,
255 expires: None,
256 algorithm,
257 revoked: false,
258 })
259}
260
261struct SigFacts {
263 sig_type: u8,
264 created: i64,
265 key_expiry: Option<u32>,
266}
267
268fn signature_facts(body: &[u8]) -> Option<SigFacts> {
269 if body.first() != Some(&4) || body.len() < 6 {
270 return None;
271 }
272 let sig_type = body[1];
273 let hashed_len = usize::from(u16::from_be_bytes([body[4], body[5]]));
274 let hashed = body.get(6..6 + hashed_len)?;
275 let (mut created, mut key_expiry) = (0i64, None);
276 let mut i = 0;
277 while i < hashed.len() {
278 let first = usize::from(hashed[i]);
279 i += 1;
280 let len = match first {
281 0..=191 => first,
282 192..=254 => {
283 let second = usize::from(*hashed.get(i)?);
284 i += 1;
285 ((first - 192) << 8) + second + 192
286 }
287 _ => {
288 let n = hashed.get(i..i + 4)?;
289 i += 4;
290 u32::from_be_bytes([n[0], n[1], n[2], n[3]]) as usize
291 }
292 };
293 let sp = hashed.get(i..i.checked_add(len)?)?;
294 i += len;
295 let (&ty, data) = sp.split_first()?;
296 match ty & 0x7f {
297 2 if data.len() == 4 => {
298 created = i64::from(u32::from_be_bytes([data[0], data[1], data[2], data[3]]));
299 }
300 9 if data.len() == 4 => {
301 key_expiry = Some(u32::from_be_bytes([data[0], data[1], data[2], data[3]]));
302 }
303 _ => {}
304 }
305 }
306 Some(SigFacts {
307 sig_type,
308 created,
309 key_expiry,
310 })
311}
312
313pub fn inspect(input: &[u8]) -> Result<PgpInfo, String> {
316 let data = dearmor(input)?;
317 let pk = packets(&data)?;
318 let mut primary: Option<KeyInfo> = None;
319 let mut user_ids: Vec<String> = Vec::new();
320 let mut subkeys: Vec<KeyInfo> = Vec::new();
321 enum Target {
323 Primary,
324 Subkey,
325 Other,
326 }
327 let mut target = Target::Other;
328 let mut primary_sig_at = i64::MIN;
330 let mut sub_sig_at: Vec<i64> = Vec::new();
331
332 for p in &pk {
333 match p.tag {
334 5 | 6 => {
335 if primary.is_some() {
336 break; }
338 primary = Some(key_from_packet(p.body)?);
339 target = Target::Primary;
340 }
341 7 | 14 if primary.is_some() => {
342 subkeys.push(key_from_packet(p.body)?);
343 sub_sig_at.push(i64::MIN);
344 target = Target::Subkey;
345 }
346 13 if primary.is_some() => {
347 user_ids.push(String::from_utf8_lossy(p.body).into_owned());
348 target = Target::Primary;
349 }
350 2 => {
351 let Some(f) = signature_facts(p.body) else {
352 continue;
353 };
354 match (&target, f.sig_type) {
355 (Target::Primary, 0x10..=0x13 | 0x1f) => {
357 if let Some(k) = primary.as_mut() {
358 if f.created >= primary_sig_at {
359 primary_sig_at = f.created;
360 k.expires = f
361 .key_expiry
362 .filter(|s| *s > 0)
363 .map(|s| k.created + i64::from(s));
364 }
365 }
366 }
367 (Target::Primary, 0x20) => {
368 if let Some(k) = primary.as_mut() {
369 k.revoked = true;
370 }
371 }
372 (Target::Subkey, 0x18) => {
374 if let (Some(k), Some(at)) = (subkeys.last_mut(), sub_sig_at.last_mut()) {
375 if f.created >= *at {
376 *at = f.created;
377 k.expires = f
378 .key_expiry
379 .filter(|s| *s > 0)
380 .map(|s| k.created + i64::from(s));
381 }
382 }
383 }
384 (Target::Subkey, 0x28) => {
385 if let Some(k) = subkeys.last_mut() {
386 k.revoked = true;
387 }
388 }
389 _ => {}
390 }
391 }
392 _ => {}
393 }
394 }
395 let primary = primary.ok_or("No OpenPGP key found")?;
396 Ok(PgpInfo {
397 primary,
398 user_ids,
399 subkeys,
400 })
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406
407 const KEY: &str = include_str!("../tests/fixtures/pgp-ed25519.asc");
411
412 #[test]
413 fn reads_the_fingerprint_user_ids_and_both_expiries_exactly_as_gpg_does() {
414 let k = inspect(KEY.as_bytes()).unwrap();
415 assert_eq!(
416 k.primary.fingerprint,
417 "899144971A1F3431B729FE0AFF605C48E0B8A0D4"
418 );
419 assert_eq!(k.primary.key_id, "FF605C48E0B8A0D4");
420 assert_eq!(k.primary.created, 1_791_539_014);
421 assert_eq!(k.primary.expires, Some(1_854_611_014));
422 assert_eq!(k.primary.algorithm, 22);
423 assert_eq!(k.user_ids, ["Test User <test@example.com>"]);
424 assert_eq!(k.subkeys.len(), 1);
425 assert_eq!(
426 k.subkeys[0].fingerprint,
427 "829CE5E113EE851675808E8E231B4410DF551005"
428 );
429 assert_eq!(k.subkeys[0].expires, Some(1_823_075_014));
430 assert_eq!(k.subkeys[0].algorithm, 18);
431 assert_eq!(k.soonest_expiry(), Some(1_823_075_014));
433 assert_eq!(iso(1_823_075_014), "2027-10-09T09:43:34Z");
434 }
435
436 #[test]
437 fn a_key_that_never_expires_has_no_expiry_and_binary_input_reads_the_same() {
438 let k = inspect(include_bytes!("../tests/fixtures/pgp-rsa-never.asc")).unwrap();
439 assert_eq!(k.primary.expires, None);
440 assert_eq!(k.soonest_expiry(), None);
441 assert_eq!(k.primary.algorithm, 1);
442 assert_eq!(
443 k.primary.fingerprint,
444 "6719ED3DEC650A98E29B79B3C3AEA629EABC5467"
445 );
446 assert_eq!(k.primary.key_id, "C3AEA629EABC5467");
447 let armoured =
449 std::str::from_utf8(include_bytes!("../tests/fixtures/pgp-rsa-never.asc")).unwrap();
450 let body: String = armoured
451 .lines()
452 .skip_while(|l| !l.trim().is_empty())
453 .skip(1)
454 .take_while(|l| !l.starts_with('=') && !l.starts_with("-----"))
455 .collect();
456 let raw = base64::engine::general_purpose::STANDARD
457 .decode(body)
458 .unwrap();
459 assert_eq!(inspect(&raw).unwrap().primary, k.primary);
460 }
461
462 #[test]
463 fn refuses_what_it_cannot_read_instead_of_guessing() {
464 assert!(inspect(b"hello").is_err());
465 assert!(inspect(b"-----BEGIN PGP PUBLIC KEY BLOCK-----\n\n!!!notbase64\n-----END PGP PUBLIC KEY BLOCK-----").is_err());
466 let v5 = [0xc6u8, 0x04, 5, 0, 0, 0];
468 assert!(inspect(&v5).unwrap_err().contains("Version 5"));
469 assert!(inspect(&[0xc6, 0x05, 4]).is_err());
471 assert!(inspect(&[0xc6, 0xe0, 4]).is_err());
472 for n in 0..64u8 {
474 let junk: Vec<u8> = (0..32u8).map(|i| 0x80 | i.wrapping_mul(n)).collect();
475 let _ = inspect(&junk);
476 }
477 }
478}