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
//! Signature subpacket parsing.
//!
//! This module parses the subpackets embedded in Signature packets.
//! Subpackets carry additional signature metadata like creation time,
//! key expiration, preferred algorithms, and issuer identification.

use crate::error::{Error, Result};
use crate::lookup::{
    lookup_compression_algorithm, lookup_hash_algorithm, lookup_key_flags,
    lookup_public_key_algorithm, lookup_revocation_reason, lookup_subpacket_type,
    lookup_symmetric_algorithm,
};
use crate::packet::Field;
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 signature subpacket.
#[derive(Debug, Clone)]
pub struct Subpacket {
    /// Subpacket type identifier.
    pub packet_type: u8,
    /// Whether this subpacket is critical (must be understood).
    pub critical: bool,
    /// The parsed subpacket data.
    pub data: SubpacketData,
}

/// The typed content of a signature subpacket.
///
/// Each variant corresponds to a specific subpacket type defined in
/// RFC 4880 and RFC 9580.
#[derive(Debug, Clone)]
pub enum SubpacketData {
    /// Signature creation time (type 2).
    SignatureCreationTime(u32),
    /// Signature expiration time as seconds after creation (type 3).
    SignatureExpirationTime(u32),
    /// Key expiration time as seconds after key creation (type 9).
    KeyExpirationTime(u32),
    /// Whether the certification is exportable (type 4).
    Exportable(bool),
    /// Trust signature level and amount (type 5).
    Trust {
        /// Trust level (0 = ordinary, 1 = introducer, etc.).
        level: u8,
        /// Trust amount (0-255).
        amount: u8,
    },
    /// Whether the signature is revocable (type 7).
    Revocable(bool),
    /// Preferred symmetric algorithms (type 11).
    PreferredSymmetric(Vec<u8>),
    /// Revocation key designation (type 12).
    RevocationKey {
        /// Revocation class.
        class: u8,
        /// Public-key algorithm of the revocation key.
        algo: u8,
        /// Fingerprint of the revocation key.
        fingerprint: String,
    },
    /// Issuer key ID (type 16).
    IssuerKeyId(String),
    /// Notation data (type 20).
    NotationData {
        /// Notation name.
        name: String,
        /// Notation value.
        value: String,
    },
    /// Preferred hash algorithms (type 21).
    PreferredHash(Vec<u8>),
    /// Preferred compression algorithms (type 22).
    PreferredCompression(Vec<u8>),
    /// Key server preferences (type 23).
    KeyServerPreferences(Vec<u8>),
    /// Preferred key server URL (type 24).
    PreferredKeyServer(String),
    /// Whether this is the primary user ID (type 25).
    PrimaryUserId(bool),
    /// Policy URI (type 26).
    PolicyUri(String),
    /// Key usage flags (type 27).
    KeyFlags(Vec<u8>),
    /// Signer's user ID (type 28).
    SignerUserId(String),
    /// Reason for revocation (type 29).
    RevocationReason {
        /// Reason code.
        code: u8,
        /// Human-readable reason string.
        reason: String,
    },
    /// Supported features (type 30).
    Features(Vec<u8>),
    /// Signature target (type 31).
    SignatureTarget {
        /// Public-key algorithm.
        algo: u8,
        /// Hash algorithm.
        hash_algo: u8,
        /// Hash of the target.
        hash: String,
    },
    /// Embedded signature (type 32).
    EmbeddedSignature(Vec<u8>),
    /// Issuer fingerprint (type 33).
    IssuerFingerprint {
        /// Key version.
        version: u8,
        /// Key fingerprint.
        fingerprint: String,
    },
    /// Preferred AEAD algorithms (type 34).
    PreferredAead(Vec<u8>),
    /// Intended recipient fingerprint (type 35).
    IntendedRecipient {
        /// Key version.
        version: u8,
        /// Recipient's key fingerprint.
        fingerprint: String,
    },
    /// Unknown or unsupported subpacket type.
    Unknown(Vec<u8>),
}

/// Parses subpackets from a stream.
///
/// # Arguments
///
/// * `stream` - Stream containing the subpacket data
/// * `fields` - Output field list
/// * `prefix` - Label prefix ("Hashed" or "Unhashed")
/// * `base_offset` - Byte offset for span calculation
pub fn parse_subpackets(
    stream: &mut ByteStream,
    fields: &mut Vec<Field>,
    prefix: &str,
    base_offset: usize,
) -> Result<Vec<Subpacket>> {
    let mut subpackets = Vec::new();
    let mut count = 0;

    while !stream.is_empty() {
        count += 1;
        let sp_start = base_offset + stream.pos();

        let len = stream.variable_length()?;
        if len == 0 {
            continue;
        }

        let type_byte = stream.octet()?;
        let critical = (type_byte & 0x80) != 0;
        let packet_type = type_byte & 0x7F;

        let data_len = len - 1;
        let mut sp_stream = stream.slice(stream.pos(), stream.pos() + data_len);
        stream.skip(data_len)?;
        let sp_end = base_offset + stream.pos();

        let type_info = lookup_subpacket_type(packet_type);
        let field_name = format!("{} #{}: {}", prefix, count, type_info.name);

        let (data, value) = parse_subpacket_data(packet_type, &mut sp_stream)?;

        fields.push(Field::subfield(field_name, value, (sp_start, sp_end)));

        subpackets.push(Subpacket {
            packet_type,
            critical,
            data,
        });
    }

    Ok(subpackets)
}

fn parse_subpacket_data(
    packet_type: u8,
    stream: &mut ByteStream,
) -> Result<(SubpacketData, String)> {
    let (data, value) = match packet_type {
        2 => {
            let time = stream.uint32()?;
            (
                SubpacketData::SignatureCreationTime(time),
                format_timestamp(time)?,
            )
        }
        3 => {
            let time = stream.uint32()?;
            (
                SubpacketData::SignatureExpirationTime(time),
                format_duration(time),
            )
        }
        4 => {
            let exportable = stream.octet()? != 0;
            (
                SubpacketData::Exportable(exportable),
                exportable.to_string(),
            )
        }
        5 => {
            let level = stream.octet()?;
            let amount = stream.octet()?;
            (
                SubpacketData::Trust { level, amount },
                format!("level={}, amount={}", level, amount),
            )
        }
        7 => {
            let revocable = stream.octet()? != 0;
            (SubpacketData::Revocable(revocable), revocable.to_string())
        }
        9 => {
            let time = stream.uint32()?;
            (
                SubpacketData::KeyExpirationTime(time),
                format_duration(time),
            )
        }
        11 => {
            let prefs = stream.rest();
            let names: Vec<String> = prefs
                .iter()
                .map(|&id| lookup_symmetric_algorithm(id).name)
                .collect();
            (SubpacketData::PreferredSymmetric(prefs), names.join(", "))
        }
        12 => {
            let class = stream.octet()?;
            let algo = stream.octet()?;
            let fingerprint = stream.hex(20)?;
            let algo_name = lookup_public_key_algorithm(algo).name;
            (
                SubpacketData::RevocationKey {
                    class,
                    algo,
                    fingerprint: fingerprint.clone(),
                },
                format!("{} ({})", fingerprint, algo_name),
            )
        }
        16 => {
            let key_id = stream.hex(8)?;
            (SubpacketData::IssuerKeyId(key_id.clone()), key_id)
        }
        20 => {
            let flags = stream.uint32()?;
            let name_len = stream.uint16()? as usize;
            let value_len = stream.uint16()? as usize;
            let name = stream.utf8(name_len)?;
            let value = if flags & 0x80000000 != 0 {
                stream.utf8(value_len)?
            } else {
                stream.hex(value_len)?
            };
            let display = format!("{}={}", name, value);
            (SubpacketData::NotationData { name, value }, display)
        }
        21 => {
            let prefs = stream.rest();
            let names: Vec<String> = prefs
                .iter()
                .map(|&id| lookup_hash_algorithm(id).name)
                .collect();
            (SubpacketData::PreferredHash(prefs), names.join(", "))
        }
        22 => {
            let prefs = stream.rest();
            let names: Vec<String> = prefs
                .iter()
                .map(|&id| lookup_compression_algorithm(id).name)
                .collect();
            (SubpacketData::PreferredCompression(prefs), names.join(", "))
        }
        23 => {
            let prefs = stream.rest();
            (
                SubpacketData::KeyServerPreferences(prefs.clone()),
                format!("{} bytes", prefs.len()),
            )
        }
        24 => {
            let server = stream.utf8(stream.remaining())?;
            (SubpacketData::PreferredKeyServer(server.clone()), server)
        }
        25 => {
            let primary = stream.octet()? != 0;
            (SubpacketData::PrimaryUserId(primary), primary.to_string())
        }
        26 => {
            let uri = stream.utf8(stream.remaining())?;
            (SubpacketData::PolicyUri(uri.clone()), uri)
        }
        27 => {
            let flags_data = stream.rest();
            let flags = if !flags_data.is_empty() {
                flags_data[0]
            } else {
                0
            };
            let flag_names = lookup_key_flags(flags);
            (SubpacketData::KeyFlags(flags_data), flag_names.join(", "))
        }
        28 => {
            let user_id = stream.utf8(stream.remaining())?;
            (SubpacketData::SignerUserId(user_id.clone()), user_id)
        }
        29 => {
            let code = stream.octet()?;
            let reason = stream.utf8(stream.remaining())?;
            let code_name = lookup_revocation_reason(code);
            (
                SubpacketData::RevocationReason {
                    code,
                    reason: reason.clone(),
                },
                format!("{}: {}", code_name, reason),
            )
        }
        30 => {
            let features = stream.rest();
            let mut feat_names = Vec::new();
            if !features.is_empty() {
                if features[0] & 0x01 != 0 {
                    feat_names.push("Modification Detection");
                }
                if features[0] & 0x02 != 0 {
                    feat_names.push("AEAD");
                }
                if features[0] & 0x04 != 0 {
                    feat_names.push("Version 5 Public Keys");
                }
            }
            (SubpacketData::Features(features), feat_names.join(", "))
        }
        31 => {
            let algo = stream.octet()?;
            let hash_algo = stream.octet()?;
            let hash = stream.rest_as_hex();
            let algo_name = lookup_public_key_algorithm(algo).name;
            let hash_name = lookup_hash_algorithm(hash_algo).name;
            (
                SubpacketData::SignatureTarget {
                    algo,
                    hash_algo,
                    hash: hash.clone(),
                },
                format!("{}/{}: {}", algo_name, hash_name, hash),
            )
        }
        32 => {
            let sig_data = stream.rest();
            (
                SubpacketData::EmbeddedSignature(sig_data.clone()),
                format!("{} bytes", sig_data.len()),
            )
        }
        33 => {
            let version = stream.octet()?;
            let fp_len = if version == 4 { 20 } else { 32 };
            let fingerprint = stream.hex(fp_len.min(stream.remaining()))?;
            (
                SubpacketData::IssuerFingerprint {
                    version,
                    fingerprint: fingerprint.clone(),
                },
                format!("v{}: {}", version, fingerprint),
            )
        }
        34 => {
            let prefs = stream.rest();
            (
                SubpacketData::PreferredAead(prefs.clone()),
                format!("{} algorithms", prefs.len()),
            )
        }
        35 => {
            let version = stream.octet()?;
            let fp_len = if version == 4 { 20 } else { 32 };
            let fingerprint = stream.hex(fp_len.min(stream.remaining()))?;
            (
                SubpacketData::IntendedRecipient {
                    version,
                    fingerprint: fingerprint.clone(),
                },
                format!("v{}: {}", version, fingerprint),
            )
        }
        _ => {
            let data = stream.rest();
            (
                SubpacketData::Unknown(data.clone()),
                format!("{} bytes", data.len()),
            )
        }
    };

    Ok((data, value))
}

fn format_duration(seconds: u32) -> String {
    if seconds == 0 {
        return "never expires".to_string();
    }

    let days = seconds / 86400;
    let years = days / 365;

    if years > 0 {
        format!("{} years", years)
    } else if days > 0 {
        format!("{} days", days)
    } else {
        format!("{} seconds", seconds)
    }
}