gpg-inspector-lib 0.8.0

A library for parsing and inspecting OpenPGP (GPG) packets according to RFC 4880 and RFC 9580
Documentation
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
//! Public key packet parsing.
//!
//! This module parses Public Key (tag 6) and Public Subkey (tag 14) packets,
//! extracting the key version, creation time, algorithm, and key material.

use crate::error::{Error, Result};
use crate::lookup::{lookup_curve_oid, lookup_public_key_algorithm};
use crate::packet::Field;
use crate::packet::fingerprint::{key_id, to_hex, v4_fingerprint, v6_fingerprint};
use crate::stream::ByteStream;
use chrono::{DateTime, TimeZone, Utc};

fn format_timestamp(ts: u32) -> Result<String> {
    Utc.timestamp_opt(ts as i64, 0)
        .single()
        .map(|dt: DateTime<Utc>| dt.to_rfc3339())
        .ok_or(Error::InvalidTimestamp(ts))
}

/// A parsed public key or public subkey packet.
///
/// Contains the common key metadata (version, creation time, algorithm)
/// and the algorithm-specific key material.
#[derive(Debug, Clone)]
pub struct PublicKeyPacket {
    /// Key packet version (typically 4 or 5).
    pub version: u8,
    /// Unix timestamp of key creation.
    pub creation_time: u32,
    /// Public-key algorithm identifier.
    pub algorithm: u8,
    /// Algorithm-specific public key data.
    pub key_material: KeyMaterial,
}

/// Algorithm-specific public key material.
///
/// Different key algorithms use different mathematical structures.
/// Each variant contains the public components needed for that algorithm.
#[derive(Debug, Clone)]
pub enum KeyMaterial {
    /// RSA public key (algorithms 1-3).
    Rsa {
        /// RSA modulus n (product of two primes).
        n: String,
        /// RSA public exponent e.
        e: String,
    },
    /// DSA public key (algorithm 17).
    Dsa {
        /// Prime modulus.
        p: String,
        /// Prime divisor of p-1.
        q: String,
        /// Generator of the subgroup of order q.
        g: String,
        /// Public key value g^x mod p.
        y: String,
    },
    /// Elgamal public key (algorithm 16).
    Elgamal {
        /// Prime modulus.
        p: String,
        /// Generator.
        g: String,
        /// Public key value.
        y: String,
    },
    /// ECDSA public key (algorithm 19).
    Ecdsa {
        /// OID identifying the elliptic curve.
        curve_oid: Vec<u8>,
        /// Encoded public point on the curve.
        public_key: String,
    },
    /// ECDH public key (algorithm 18).
    Ecdh {
        /// OID identifying the elliptic curve.
        curve_oid: Vec<u8>,
        /// Encoded public point on the curve.
        public_key: String,
        /// Key Derivation Function parameters.
        kdf_params: Vec<u8>,
    },
    /// EdDSA public key (legacy algorithm 22).
    EdDsa {
        /// OID identifying the curve (typically Ed25519).
        curve_oid: Vec<u8>,
        /// Encoded public key.
        public_key: String,
    },
    /// X25519 public key (algorithm 25, RFC 9580).
    X25519 {
        /// 32-byte public key.
        public_key: String,
    },
    /// Ed25519 public key (algorithm 27, RFC 9580).
    Ed25519 {
        /// 32-byte public key.
        public_key: String,
    },
    /// X448 public key (algorithm 26, RFC 9580).
    X448 {
        /// 56-byte public key.
        public_key: String,
    },
    /// Ed448 public key (algorithm 28, RFC 9580).
    Ed448 {
        /// 57-byte public key.
        public_key: String,
    },
    /// Unknown or unsupported algorithm.
    Unknown {
        /// Raw key material bytes.
        data: Vec<u8>,
    },
}

/// Parses a public key packet body.
///
/// This function is called for both Public Key (tag 6) and Public Subkey (tag 14)
/// packets, as they share the same format.
pub fn parse_public_key(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<PublicKeyPacket> {
    let body_start = stream.pos();
    let version_start = offset + stream.pos();
    let version = stream.octet()?;
    let version_end = offset + stream.pos();
    fields.push(Field::field(
        "Version",
        version.to_string(),
        (version_start, version_end),
    ));

    let packet = match version {
        6 => parse_public_key_v6(stream, version, fields, offset),
        _ => parse_public_key_v4(stream, version, fields, offset),
    }?;

    push_identity_fields(stream, body_start, version, fields, offset);
    Ok(packet)
}

/// Appends computed fingerprint and key ID fields for V4 and V6 keys.
///
/// The hashed region is the public key body (version octet through key
/// material), i.e. `stream` bytes `body_start..pos()` — for secret keys
/// this is called before any S2K/secret material is read, so the same
/// region applies. V3 (MD5) keys and unknown versions get no fields.
/// The fields' span is the hashed region, and their names carry a
/// "(computed)" marker since the values are derived, not on the wire.
fn push_identity_fields(
    stream: &ByteStream,
    body_start: usize,
    version: u8,
    fields: &mut Vec<Field>,
    offset: usize,
) {
    let body = &stream.all_bytes()[body_start..stream.pos()];
    let span = (offset + body_start, offset + stream.pos());

    let fingerprint: Vec<u8> = match version {
        4 => v4_fingerprint(body).to_vec(),
        6 => v6_fingerprint(body).to_vec(),
        _ => return,
    };
    let id = key_id(version, &fingerprint);

    fields.push(Field::field(
        "Fingerprint (computed)",
        to_hex(&fingerprint),
        span,
    ));
    fields.push(Field::field("Key ID (computed)", id, span));
}

/// Parses a V4 public key packet body.
fn parse_public_key_v4(
    stream: &mut ByteStream,
    version: u8,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<PublicKeyPacket> {
    let time_start = offset + stream.pos();
    let creation_time = stream.uint32()?;
    let time_end = offset + stream.pos();
    fields.push(Field::field(
        "Creation Time",
        format_timestamp(creation_time)?,
        (time_start, time_end),
    ));

    let algo_start = offset + stream.pos();
    let algorithm = stream.octet()?;
    let algo_end = offset + stream.pos();
    let algo_info = lookup_public_key_algorithm(algorithm);
    fields.push(Field::field(
        "Algorithm",
        algo_info.display(),
        (algo_start, algo_end),
    ));

    let key_material = match algorithm {
        1..=3 => parse_rsa_key(stream, fields, offset)?,
        16 => parse_elgamal_key(stream, fields, offset)?,
        17 => parse_dsa_key(stream, fields, offset)?,
        18 => parse_ecdh_key(stream, fields, offset)?,
        19 => parse_ecdsa_key(stream, fields, offset)?,
        22 => parse_eddsa_key(stream, fields, offset)?,
        25 => parse_x25519_key(stream, fields, offset)?,
        27 => parse_ed25519_key(stream, fields, offset)?,
        _ => {
            let data = stream.rest();
            KeyMaterial::Unknown { data }
        }
    };

    Ok(PublicKeyPacket {
        version,
        creation_time,
        algorithm,
        key_material,
    })
}

/// Parses a V6 public key packet body (RFC 9580).
///
/// V6 keys have:
/// - 4-byte creation time
/// - 1-byte algorithm
/// - 4-byte key material length (new in V6)
/// - Algorithm-specific key material
fn parse_public_key_v6(
    stream: &mut ByteStream,
    version: u8,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<PublicKeyPacket> {
    let time_start = offset + stream.pos();
    let creation_time = stream.uint32()?;
    let time_end = offset + stream.pos();
    fields.push(Field::field(
        "Creation Time",
        format_timestamp(creation_time)?,
        (time_start, time_end),
    ));

    let algo_start = offset + stream.pos();
    let algorithm = stream.octet()?;
    let algo_end = offset + stream.pos();
    let algo_info = lookup_public_key_algorithm(algorithm);
    fields.push(Field::field(
        "Algorithm",
        algo_info.display(),
        (algo_start, algo_end),
    ));

    // V6 has a 4-byte key material length field
    let len_start = offset + stream.pos();
    let key_material_len = stream.uint32()?;
    let len_end = offset + stream.pos();
    fields.push(Field::field(
        "Key Material Length",
        format!("{} bytes", key_material_len),
        (len_start, len_end),
    ));

    let key_material = match algorithm {
        1..=3 => parse_rsa_key(stream, fields, offset)?,
        16 => parse_elgamal_key(stream, fields, offset)?,
        17 => parse_dsa_key(stream, fields, offset)?,
        18 => parse_ecdh_key(stream, fields, offset)?,
        19 => parse_ecdsa_key(stream, fields, offset)?,
        22 => parse_eddsa_key(stream, fields, offset)?,
        25 => parse_x25519_key(stream, fields, offset)?,
        26 => parse_x448_key(stream, fields, offset)?,
        27 => parse_ed25519_key(stream, fields, offset)?,
        28 => parse_ed448_key(stream, fields, offset)?,
        _ => {
            let data = stream.rest();
            KeyMaterial::Unknown { data }
        }
    };

    Ok(PublicKeyPacket {
        version,
        creation_time,
        algorithm,
        key_material,
    })
}

fn parse_rsa_key(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<KeyMaterial> {
    let n_start = offset + stream.pos();
    let (n_bits, n) = stream.multi_precision_integer()?;
    let n_end = offset + stream.pos();
    fields.push(Field::field(
        "RSA n",
        format!("{} bits", n_bits),
        (n_start, n_end),
    ));

    let e_start = offset + stream.pos();
    let (e_bits, e) = stream.multi_precision_integer()?;
    let e_end = offset + stream.pos();
    fields.push(Field::field(
        "RSA e",
        format!("{} bits: {}", e_bits, e),
        (e_start, e_end),
    ));

    Ok(KeyMaterial::Rsa { n, e })
}

fn parse_dsa_key(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<KeyMaterial> {
    let p_start = offset + stream.pos();
    let (p_bits, p) = stream.multi_precision_integer()?;
    let p_end = offset + stream.pos();
    fields.push(Field::field(
        "DSA p",
        format!("{} bits", p_bits),
        (p_start, p_end),
    ));

    let q_start = offset + stream.pos();
    let (q_bits, q) = stream.multi_precision_integer()?;
    let q_end = offset + stream.pos();
    fields.push(Field::field(
        "DSA q",
        format!("{} bits", q_bits),
        (q_start, q_end),
    ));

    let g_start = offset + stream.pos();
    let (g_bits, g) = stream.multi_precision_integer()?;
    let g_end = offset + stream.pos();
    fields.push(Field::field(
        "DSA g",
        format!("{} bits", g_bits),
        (g_start, g_end),
    ));

    let y_start = offset + stream.pos();
    let (y_bits, y) = stream.multi_precision_integer()?;
    let y_end = offset + stream.pos();
    fields.push(Field::field(
        "DSA y",
        format!("{} bits", y_bits),
        (y_start, y_end),
    ));

    Ok(KeyMaterial::Dsa { p, q, g, y })
}

fn parse_elgamal_key(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<KeyMaterial> {
    let p_start = offset + stream.pos();
    let (p_bits, p) = stream.multi_precision_integer()?;
    let p_end = offset + stream.pos();
    fields.push(Field::field(
        "Elgamal p",
        format!("{} bits", p_bits),
        (p_start, p_end),
    ));

    let g_start = offset + stream.pos();
    let (g_bits, g) = stream.multi_precision_integer()?;
    let g_end = offset + stream.pos();
    fields.push(Field::field(
        "Elgamal g",
        format!("{} bits", g_bits),
        (g_start, g_end),
    ));

    let y_start = offset + stream.pos();
    let (y_bits, y) = stream.multi_precision_integer()?;
    let y_end = offset + stream.pos();
    fields.push(Field::field(
        "Elgamal y",
        format!("{} bits", y_bits),
        (y_start, y_end),
    ));

    Ok(KeyMaterial::Elgamal { p, g, y })
}

fn parse_ecdsa_key(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<KeyMaterial> {
    let oid_start = offset + stream.pos();
    let oid_len = stream.octet()? as usize;
    let curve_oid = stream.bytes(oid_len)?;
    let oid_end = offset + stream.pos();
    let curve_name = lookup_curve_oid(&curve_oid);
    fields.push(Field::field("Curve", curve_name, (oid_start, oid_end)));

    let pk_start = offset + stream.pos();
    let (pk_bits, public_key) = stream.multi_precision_integer()?;
    let pk_end = offset + stream.pos();
    fields.push(Field::field(
        "Public Key",
        format!("{} bits", pk_bits),
        (pk_start, pk_end),
    ));

    Ok(KeyMaterial::Ecdsa {
        curve_oid,
        public_key,
    })
}

fn parse_ecdh_key(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<KeyMaterial> {
    let oid_start = offset + stream.pos();
    let oid_len = stream.octet()? as usize;
    let curve_oid = stream.bytes(oid_len)?;
    let oid_end = offset + stream.pos();
    let curve_name = lookup_curve_oid(&curve_oid);
    fields.push(Field::field("Curve", curve_name, (oid_start, oid_end)));

    let pk_start = offset + stream.pos();
    let (pk_bits, public_key) = stream.multi_precision_integer()?;
    let pk_end = offset + stream.pos();
    fields.push(Field::field(
        "Public Key",
        format!("{} bits", pk_bits),
        (pk_start, pk_end),
    ));

    let kdf_start = offset + stream.pos();
    let kdf_len = stream.octet()? as usize;
    let kdf_params = stream.bytes(kdf_len)?;
    let kdf_end = offset + stream.pos();
    fields.push(Field::field(
        "KDF Parameters",
        format!("{} bytes", kdf_params.len()),
        (kdf_start, kdf_end),
    ));

    Ok(KeyMaterial::Ecdh {
        curve_oid,
        public_key,
        kdf_params,
    })
}

fn parse_eddsa_key(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<KeyMaterial> {
    let oid_start = offset + stream.pos();
    let oid_len = stream.octet()? as usize;
    let curve_oid = stream.bytes(oid_len)?;
    let oid_end = offset + stream.pos();
    let curve_name = lookup_curve_oid(&curve_oid);
    fields.push(Field::field("Curve", curve_name, (oid_start, oid_end)));

    let pk_start = offset + stream.pos();
    let (pk_bits, public_key) = stream.multi_precision_integer()?;
    let pk_end = offset + stream.pos();
    fields.push(Field::field(
        "Public Key",
        format!("{} bits", pk_bits),
        (pk_start, pk_end),
    ));

    Ok(KeyMaterial::EdDsa {
        curve_oid,
        public_key,
    })
}

fn parse_x25519_key(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<KeyMaterial> {
    let pk_start = offset + stream.pos();
    let public_key = stream.hex(32)?;
    let pk_end = offset + stream.pos();
    fields.push(Field::field(
        "Public Key",
        "256 bits (X25519)",
        (pk_start, pk_end),
    ));

    Ok(KeyMaterial::X25519 { public_key })
}

fn parse_ed25519_key(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<KeyMaterial> {
    let pk_start = offset + stream.pos();
    let public_key = stream.hex(32)?;
    let pk_end = offset + stream.pos();
    fields.push(Field::field(
        "Public Key",
        "256 bits (Ed25519)",
        (pk_start, pk_end),
    ));

    Ok(KeyMaterial::Ed25519 { public_key })
}

fn parse_x448_key(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<KeyMaterial> {
    let pk_start = offset + stream.pos();
    let public_key = stream.hex(56)?;
    let pk_end = offset + stream.pos();
    fields.push(Field::field(
        "Public Key",
        "448 bits (X448)",
        (pk_start, pk_end),
    ));

    Ok(KeyMaterial::X448 { public_key })
}

fn parse_ed448_key(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    offset: usize,
) -> Result<KeyMaterial> {
    let pk_start = offset + stream.pos();
    let public_key = stream.hex(57)?;
    let pk_end = offset + stream.pos();
    fields.push(Field::field(
        "Public Key",
        "456 bits (Ed448)",
        (pk_start, pk_end),
    ));

    Ok(KeyMaterial::Ed448 { public_key })
}