ssign-core 0.1.8

The Certum SimplySign cloud-signing pipeline behind ssign: OAuth login, card/cert fetch, remote signature, and local Authenticode/PKCS#7 assembly — the reusable half shared by the ssign CLI and the ssign-pkcs11 module.
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
//! Step 3b — the local Authenticode work, all cross-platform (no Windows APIs).
//!
//! - `pe_hash`  : Authenticode SHA-256 of a PE.
//! - `prepare`  : build the SpcIndirectData + signed attributes and return the
//!   SHA-256 that Certum must sign (over the signed attrs).
//! - `finalize` : wrap [attrs + signature + cert] into a PKCS#7 SignedData and
//!   splice it into the PE's certificate table.

use crate::asn1;
use anyhow::{anyhow, bail, Context, Result};
use aws_lc_rs::signature::{UnparsedPublicKey, RSA_PKCS1_2048_8192_SHA256};
use der::{Decode, Encode};
use sha2::{Digest, Sha256};
use std::path::Path;

// ---- OIDs -----------------------------------------------------------------
const OID_SHA256: &str = "2.16.840.1.101.3.4.2.1";
const OID_RSA: &str = "1.2.840.113549.1.1.1";
const OID_PKCS7_SIGNED_DATA: &str = "1.2.840.113549.1.7.2";
const OID_SPC_INDIRECT_DATA: &str = "1.3.6.1.4.1.311.2.1.4";
const OID_SPC_STATEMENT_TYPE: &str = "1.3.6.1.4.1.311.2.1.11";
const OID_SPC_SP_OPUS_INFO: &str = "1.3.6.1.4.1.311.2.1.12";
const OID_SPC_INDIVIDUAL: &str = "1.3.6.1.4.1.311.2.1.21";
const OID_CONTENT_TYPE: &str = "1.2.840.113549.1.9.3";
const OID_MESSAGE_DIGEST: &str = "1.2.840.113549.1.9.4";
const OID_SIGNING_TIME: &str = "1.2.840.113549.1.9.5";
const OID_TIMESTAMP_TOKEN: &str = "1.3.6.1.4.1.311.3.3.1";

/// The `SpcAttributeTypeAndOptionalValue` is identical for every PE signature
/// (SPC_PE_IMAGE_DATA + the "<<<Obsolete>>>" moniker); captured verbatim.
const SPC_ATTR_CONST: &[u8] = &[
    0x30, 0x34, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x0f, 0x30, 0x26,
    0x03, 0x02, 0x07, 0x80, 0xa0, 0x20, 0xa2, 0x1e, 0x80, 0x1c, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x3c,
    0x00, 0x4f, 0x00, 0x62, 0x00, 0x73, 0x00, 0x6f, 0x00, 0x6c, 0x00, 0x65, 0x00, 0x74, 0x00, 0x65,
    0x00, 0x3e, 0x00, 0x3e, 0x00, 0x3e,
];

/// SHA-256 of `data`.
pub fn sha256(data: &[u8]) -> [u8; 32] {
    let mut h = Sha256::new();
    h.update(data);
    h.finalize().into()
}

// ---- PE hashing -----------------------------------------------------------

fn u32le(b: &[u8], off: usize) -> Result<u32> {
    let s = b.get(off..off + 4).context("PE truncated")?;
    Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}

struct PeLayout {
    checksum_off: usize,
    sec_dir_entry_off: usize,
    cert_table_off: usize,
    cert_table_size: usize,
}

fn pe_layout(pe: &[u8]) -> Result<PeLayout> {
    if pe.get(..2) != Some(b"MZ") {
        bail!("not a PE (no MZ signature)");
    }
    let pe_off = u32le(pe, 0x3c)? as usize;
    if pe.get(pe_off..pe_off + 4) != Some(b"PE\0\0") {
        bail!("not a PE (no PE signature)");
    }
    let opt_off = pe_off + 24;
    let is_pe32plus = match pe.get(opt_off..opt_off + 2).context("PE truncated")? {
        [0x0b, 0x01] => false,
        [0x0b, 0x02] => true,
        _ => bail!("unknown optional-header magic"),
    };
    let checksum_off = opt_off + 64;
    let data_dir_off = opt_off + if is_pe32plus { 112 } else { 96 };
    let sec_dir_entry_off = data_dir_off + 4 * 8;
    Ok(PeLayout {
        checksum_off,
        sec_dir_entry_off,
        cert_table_off: u32le(pe, sec_dir_entry_off)? as usize,
        cert_table_size: u32le(pe, sec_dir_entry_off + 4)? as usize,
    })
}

/// Compute the Authenticode SHA-256 hash of a PE image.
pub fn pe_hash(pe: &[u8]) -> Result<[u8; 32]> {
    let l = pe_layout(pe)?;
    let (cert_start, cert_end) = if l.cert_table_size == 0 {
        (pe.len(), pe.len())
    } else {
        let cert_end = l
            .cert_table_off
            .checked_add(l.cert_table_size)
            .context("certificate table length overflows")?;
        if l.cert_table_off > pe.len() || cert_end > pe.len() {
            bail!("certificate table lies outside the PE file");
        }
        // The hash covers the headers up to the security directory entry and
        // then stops at the table: a table said to start inside the headers
        // would make that range run backwards.
        if l.cert_table_off < l.sec_dir_entry_off + 8 {
            bail!("certificate table overlaps the PE headers");
        }
        (l.cert_table_off, cert_end)
    };
    let mut h = Sha256::new();
    h.update(&pe[..l.checksum_off]);
    h.update(&pe[l.checksum_off + 4..l.sec_dir_entry_off]);
    h.update(&pe[l.sec_dir_entry_off + 8..cert_start]);
    if cert_end < pe.len() {
        h.update(&pe[cert_end..]);
    }
    // An unsigned file is zero-padded to an 8-byte boundary by embed() before the
    // certificate table is appended, and that padding falls inside the region
    // Windows hashes. It must be hashed here too, or every PE whose length is not
    // already a multiple of 8 gets a digest Windows disagrees with.
    if l.cert_table_size == 0 {
        let pad = (8 - (pe.len() % 8)) % 8;
        h.update(&[0u8; 8][..pad]);
    }
    Ok(h.finalize().into())
}

// ---- prepare / finalize ---------------------------------------------------

/// The Certum intermediates that issue SimplySign code signing certificates:
/// "Code Signing 2021 CA" (standard) and "Extended Validation Code Signing
/// 2021 CA" (EV). The one that issued the signing certificate is embedded, so
/// the chain to the (widely trusted) root is complete in the signature itself.
/// Windows does not fetch a missing intermediate for the UAC prompt, which
/// then shows "Unknown publisher".
const INTERMEDIATES_DER: &[&[u8]] = &[
    include_bytes!("certs/ccsca2021.der"),
    include_bytes!("certs/cevcsca2021.der"),
];

/// The embedded intermediate whose subject is `issuer_der` (the DER-encoded
/// issuer Name of the signing certificate), if any.
fn intermediate_for(issuer_der: &[u8]) -> Option<&'static [u8]> {
    INTERMEDIATES_DER.iter().copied().find(|der| {
        x509_cert::Certificate::from_der(der)
            .ok()
            .and_then(|c| c.tbs_certificate().subject().to_der().ok())
            .is_some_and(|subject| subject == issuer_der)
    })
}

/// Decode a PEM certificate to DER (pass-through if already DER).
pub fn pem_to_der(cert: &[u8]) -> Result<Vec<u8>> {
    if cert.starts_with(b"-----BEGIN") {
        let pem = std::str::from_utf8(cert).context("certificate PEM not UTF-8")?;
        Ok(der::Document::from_pem(pem)
            .context("decoding certificate PEM")?
            .1
            .into_vec())
    } else {
        Ok(cert.to_vec())
    }
}

/// Everything needed to finish a signature once Certum returns the RSA bytes.
pub struct Prepared {
    /// SHA-256 over the DER-encoded signed attributes — this is what Certum signs.
    pub to_be_signed: [u8; 32],
    /// The whole file bytes (an already-signed file is refused by `embed`).
    pe: Vec<u8>,
    /// SpcIndirectData eContent (full SEQUENCE).
    spc_indirect: Vec<u8>,
    /// Signed attributes, encoded as a SET OF (0x31) — hashed and embedded.
    signed_attrs_set: Vec<u8>,
}

/// Build the SpcIndirectData and signed attributes for `pe`, returning the
/// digest Certum must sign plus the context needed to finalize.
pub fn prepare(
    pe: &[u8],
    name: Option<&str>,
    url: Option<&str>,
    signing_time: &str,
) -> Result<Prepared> {
    let h_pe = pe_hash(pe)?;

    // SpcIndirectDataContent = SEQUENCE { SpcAttr(const), DigestInfo(sha256, H_pe) }
    let digest_info = asn1::seq(&[
        &asn1::seq(&[&asn1::oid(OID_SHA256), &asn1::null()]),
        &asn1::octet_string(&h_pe),
    ]);
    let mut spc_content = SPC_ATTR_CONST.to_vec();
    spc_content.extend_from_slice(&digest_info);
    let spc_indirect = asn1::tlv(0x30, &spc_content);
    // Authenticode quirk: messageDigest is the hash of the SEQUENCE *content*.
    let message_digest = sha256(&spc_content);

    // Signed attributes (each: SEQUENCE { OID, SET { value } }).
    let mut attrs: Vec<Vec<u8>> = vec![
        asn1::seq(&[
            &asn1::oid(OID_CONTENT_TYPE),
            &asn1::set(&[&asn1::oid(OID_SPC_INDIRECT_DATA)]),
        ]),
        asn1::seq(&[
            &asn1::oid(OID_SIGNING_TIME),
            &asn1::set(&[&asn1::utc_time(signing_time)]),
        ]),
        asn1::seq(&[
            &asn1::oid(OID_SPC_STATEMENT_TYPE),
            &asn1::set(&[&asn1::seq(&[&asn1::oid(OID_SPC_INDIVIDUAL)])]),
        ]),
        asn1::seq(&[
            &asn1::oid(OID_MESSAGE_DIGEST),
            &asn1::set(&[&asn1::octet_string(&message_digest)]),
        ]),
    ];
    if name.is_some() || url.is_some() {
        attrs.push(asn1::seq(&[
            &asn1::oid(OID_SPC_SP_OPUS_INFO),
            &asn1::set(&[&opus_info(name, url)]),
        ]));
    }
    // DER SET OF: members sorted ascending by their encoding.
    attrs.sort();
    let refs: Vec<&[u8]> = attrs.iter().map(|a| a.as_slice()).collect();
    let signed_attrs_set = asn1::set(&refs);

    Ok(Prepared {
        to_be_signed: sha256(&signed_attrs_set),
        pe: pe.to_vec(),
        spc_indirect,
        signed_attrs_set,
    })
}

/// SpcSpOpusInfo ::= SEQUENCE { programName [0] EXPLICIT SpcString OPTIONAL,
///                              moreInfo    [1] EXPLICIT SpcLink   OPTIONAL }
fn opus_info(name: Option<&str>, url: Option<&str>) -> Vec<u8> {
    let mut parts: Vec<Vec<u8>> = Vec::new();
    if let Some(n) = name {
        // programName = [0] { SpcString ascii = [1] IMPLICIT }
        parts.push(asn1::ctx(0, &asn1::ctx_prim(1, n.as_bytes())));
    }
    if let Some(u) = url {
        // moreInfo = [1] { SpcLink url = [0] IMPLICIT }
        parts.push(asn1::ctx(1, &asn1::ctx_prim(0, u.as_bytes())));
    }
    let refs: Vec<&[u8]> = parts.iter().map(|p| p.as_slice()).collect();
    asn1::seq(&refs)
}

/// Assemble the PKCS#7 SignedData with Certum's `signature` and splice it into
/// the PE; returns the signed image bytes.
pub fn finalize(
    prep: Prepared,
    signature: &[u8],
    cert_der: &[u8],
    timestamp_token: Option<&[u8]>,
) -> Result<Vec<u8>> {
    let cert = x509_cert::Certificate::from_der(cert_der).context("parsing signing certificate")?;
    let public_key = cert
        .tbs_certificate()
        .subject_public_key_info()
        .subject_public_key
        .raw_bytes();
    UnparsedPublicKey::new(&RSA_PKCS1_2048_8192_SHA256, public_key)
        .verify(&prep.signed_attrs_set, signature)
        .map_err(|_| anyhow!("the cloud signature does not verify with the signing certificate"))?;
    let issuer = cert
        .tbs_certificate()
        .issuer()
        .to_der()
        .context("encoding issuer")?;
    let serial = cert
        .tbs_certificate()
        .serial_number()
        .to_der()
        .context("encoding serial")?;
    let issuer_and_serial = asn1::seq(&[&issuer, &serial]);

    let sha256_algid = asn1::seq(&[&asn1::oid(OID_SHA256), &asn1::null()]);
    let rsa_algid = asn1::seq(&[&asn1::oid(OID_RSA), &asn1::null()]);

    // authenticatedAttributes as [0] IMPLICIT (0xa0) — same content we hashed.
    let auth_attrs_ctx = {
        // signed_attrs_set is 0x31|len|content; re-tag to 0xa0.
        let content = &prep.signed_attrs_set[1 + der_len_size(&prep.signed_attrs_set)..];
        asn1::ctx(0, content)
    };

    // unauthenticatedAttributes [1] IMPLICIT SET OF — carries the RFC3161 token.
    let unauth = timestamp_token.map(|tok| {
        let attr = asn1::seq(&[&asn1::oid(OID_TIMESTAMP_TOKEN), &asn1::set(&[tok])]);
        asn1::ctx(1, &attr)
    });

    let one = asn1::int_one();
    let sig_octet = asn1::octet_string(signature);
    let mut si_parts: Vec<&[u8]> = vec![
        &one,
        &issuer_and_serial,
        &sha256_algid,
        &auth_attrs_ctx,
        &rsa_algid,
        &sig_octet,
    ];
    if let Some(u) = &unauth {
        si_parts.push(u);
    }
    let signer_info = asn1::seq(&si_parts);

    // encapContentInfo = SEQUENCE { OID SPC_INDIRECT_DATA, [0] { SpcIndirectData } }
    let encap = asn1::seq(&[
        &asn1::oid(OID_SPC_INDIRECT_DATA),
        &asn1::ctx(0, &prep.spc_indirect),
    ]);

    // certificates [0] IMPLICIT SET OF: the leaf plus the Certum intermediate
    // that issued it, so the chain to the trusted root is complete.
    let mut certs = cert_der.to_vec();
    if let Some(intermediate) = intermediate_for(&issuer) {
        certs.extend_from_slice(intermediate);
    }

    let signed_data = asn1::seq(&[
        &asn1::int_one(),
        &asn1::set(&[&sha256_algid]),
        &encap,
        &asn1::ctx(0, &certs),
        &asn1::set(&[&signer_info]),
    ]);

    let pkcs7 = asn1::seq(&[
        &asn1::oid(OID_PKCS7_SIGNED_DATA),
        &asn1::ctx(0, &signed_data),
    ]);

    embed(prep.pe, &pkcs7)
}

/// Number of length octets in a DER TLV starting at `tlv[0]`.
fn der_len_size(tlv: &[u8]) -> usize {
    if tlv[1] < 0x80 {
        1
    } else {
        1 + (tlv[1] & 0x7f) as usize
    }
}

/// Splice a PKCS#7 blob into the PE's attribute certificate table.
fn embed(mut pe: Vec<u8>, pkcs7: &[u8]) -> Result<Vec<u8>> {
    let l = pe_layout(&pe)?;
    if l.cert_table_size != 0 {
        bail!("file already has a signature");
    }
    while !pe.len().is_multiple_of(8) {
        pe.push(0);
    }
    let table_off = pe.len();
    let win_cert_len = 8 + pkcs7.len();
    pe.extend_from_slice(&(win_cert_len as u32).to_le_bytes());
    pe.extend_from_slice(&[0x00, 0x02]); // wRevision  = WIN_CERT_REVISION_2_0
    pe.extend_from_slice(&[0x02, 0x00]); // wCertType  = WIN_CERT_TYPE_PKCS_SIGNED_DATA
    pe.extend_from_slice(pkcs7);
    while !(pe.len() - table_off).is_multiple_of(8) {
        pe.push(0);
    }
    let table_size = pe.len() - table_off;

    pe[l.sec_dir_entry_off..l.sec_dir_entry_off + 4]
        .copy_from_slice(&(table_off as u32).to_le_bytes());
    pe[l.sec_dir_entry_off + 4..l.sec_dir_entry_off + 8]
        .copy_from_slice(&(table_size as u32).to_le_bytes());

    let checksum = pe_checksum(&pe, l.checksum_off);
    pe[l.checksum_off..l.checksum_off + 4].copy_from_slice(&checksum.to_le_bytes());
    Ok(pe)
}

/// The PE image checksum (16-bit ones-complement sum + file length).
fn pe_checksum(pe: &[u8], checksum_off: usize) -> u32 {
    let mut sum: u64 = 0;
    let mut i = 0;
    while i + 1 < pe.len() {
        if i == checksum_off {
            i += 4; // the checksum field counts as zero
            continue;
        }
        let w = u16::from_le_bytes([pe[i], pe[i + 1]]) as u64;
        sum += w;
        sum = (sum & 0xffff) + (sum >> 16);
        i += 2;
    }
    if i < pe.len() {
        sum += pe[i] as u64;
        sum = (sum & 0xffff) + (sum >> 16);
    }
    sum = (sum & 0xffff) + (sum >> 16);
    (sum as u32) + pe.len() as u32
}

// ---- public helpers used by main ------------------------------------------

/// Authenticode SHA-256 of a file on disk.
pub fn digest(file: &Path) -> Result<[u8; 32]> {
    let bytes = std::fs::read(file).with_context(|| format!("reading {}", file.display()))?;
    pe_hash(&bytes)
}

/// Format a Unix timestamp as an ASN.1 UTCTime (`YYMMDDhhmmssZ`).
pub fn utc_time(unix: u64) -> String {
    // civil-from-days (Howard Hinnant's algorithm).
    let days = (unix / 86400) as i64;
    let secs = unix % 86400;
    let z = days + 719468;
    let era = z.div_euclid(146097);
    let doe = z.rem_euclid(146097);
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!(
        "{:02}{:02}{:02}{:02}{:02}{:02}Z",
        y.rem_euclid(100),
        m,
        d,
        secs / 3600,
        (secs % 3600) / 60,
        secs % 60
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    fn subject_der(cert_der: &[u8]) -> Vec<u8> {
        let cert = x509_cert::Certificate::from_der(cert_der).unwrap();
        cert.tbs_certificate().subject().to_der().unwrap()
    }

    fn issuer_der(cert_der: &[u8]) -> Vec<u8> {
        let cert = x509_cert::Certificate::from_der(cert_der).unwrap();
        cert.tbs_certificate().issuer().to_der().unwrap()
    }

    /// An EV certificate is issued by "Extended Validation Code Signing 2021
    /// CA", a standard one by "Code Signing 2021 CA": each must get its own
    /// issuer embedded, or Windows UAC shows "Unknown publisher".
    #[test]
    fn picks_the_intermediate_that_issued_the_certificate() {
        let standard: &[u8] = include_bytes!("certs/ccsca2021.der");
        let ev: &[u8] = include_bytes!("certs/cevcsca2021.der");
        assert_eq!(intermediate_for(&subject_der(standard)), Some(standard));
        assert_eq!(intermediate_for(&subject_der(ev)), Some(ev));
    }

    #[test]
    fn embeds_no_intermediate_for_a_foreign_issuer() {
        let cert_der = include_bytes!("../tests/fixtures/selftest_cert.der");
        assert_eq!(intermediate_for(&issuer_der(cert_der)), None);
    }

    #[test]
    fn pe_hash_covers_the_alignment_padding() {
        // embed() zero-pads an unsigned PE to an 8-byte boundary before appending
        // the certificate table, and Windows hashes that padding. Hashing the file
        // as it stands must therefore agree with hashing the padded bytes — if it
        // does not, every PE whose length is not already a multiple of 8 is signed
        // with a digest Windows rejects (Status: HashMismatch).
        let base = include_bytes!("../tests/fixtures/hello.exe");

        let mut odd = base.to_vec();
        odd.extend_from_slice(b"ABCDE");
        assert_ne!(
            odd.len() % 8,
            0,
            "fixture must not be 8-aligned for this test"
        );

        let mut padded = odd.clone();
        while !padded.len().is_multiple_of(8) {
            padded.push(0);
        }

        assert_eq!(pe_hash(&odd).unwrap(), pe_hash(&padded).unwrap());
    }

    #[test]
    fn rejects_certificate_table_outside_the_file() {
        let mut pe = vec![0u8; 0x200];
        pe[..2].copy_from_slice(b"MZ");
        pe[0x3c..0x40].copy_from_slice(&(0x80u32).to_le_bytes());
        pe[0x80..0x84].copy_from_slice(b"PE\0\0");
        pe[0x98..0x9a].copy_from_slice(&[0x0b, 0x01]);
        pe[0x118..0x11c].copy_from_slice(&(0xffff_fff0u32).to_le_bytes());
        pe[0x11c..0x120].copy_from_slice(&(0x20u32).to_le_bytes());
        assert!(pe_hash(&pe).is_err());
    }

    /// Found by fuzzing: a table offset inside the headers made pe_hash slice
    /// `pe[0x120..0]` and panic.
    #[test]
    fn rejects_a_certificate_table_inside_the_headers() {
        let mut pe = vec![0u8; 0x200];
        pe[..2].copy_from_slice(b"MZ");
        pe[0x3c..0x40].copy_from_slice(&(0x80u32).to_le_bytes());
        pe[0x80..0x84].copy_from_slice(b"PE\0\0");
        pe[0x98..0x9a].copy_from_slice(&[0x0b, 0x01]);
        pe[0x118..0x11c].copy_from_slice(&(0u32).to_le_bytes());
        pe[0x11c..0x120].copy_from_slice(&(0x20u32).to_le_bytes());
        assert!(pe_hash(&pe).is_err());
    }

    #[test]
    fn ignores_a_stale_certificate_offset_when_the_table_is_empty() {
        let mut pe = vec![0u8; 0x200];
        pe[..2].copy_from_slice(b"MZ");
        pe[0x3c..0x40].copy_from_slice(&(0x80u32).to_le_bytes());
        pe[0x80..0x84].copy_from_slice(b"PE\0\0");
        pe[0x98..0x9a].copy_from_slice(&[0x0b, 0x01]);
        pe[0x118..0x11c].copy_from_slice(&(0xffff_fff0u32).to_le_bytes());
        pe[0x11c..0x120].copy_from_slice(&(0u32).to_le_bytes());
        assert!(pe_hash(&pe).is_ok());
    }

    #[test]
    fn pe_hash_matches_osslsigncode() {
        let pe = include_bytes!("../tests/fixtures/hello.exe");
        assert_eq!(
            hex::encode_upper(pe_hash(pe).unwrap()),
            "BC17B1C98515D63F366BCD9F472054AE49CD5E839043265CE060B38B33CA2A43"
        );
    }

    #[test]
    fn message_digest_uses_sequence_content() {
        // Rebuild the SpcIndirectData for the fixture's known H_pe and check the
        // messageDigest matches what osslsigncode embedded.
        let h_pe = hex::decode("BC17B1C98515D63F366BCD9F472054AE49CD5E839043265CE060B38B33CA2A43")
            .unwrap();
        let digest_info = asn1::seq(&[
            &asn1::seq(&[&asn1::oid(OID_SHA256), &asn1::null()]),
            &asn1::octet_string(&h_pe),
        ]);
        let mut spc_content = SPC_ATTR_CONST.to_vec();
        spc_content.extend_from_slice(&digest_info);
        assert_eq!(
            hex::encode_upper(sha256(&spc_content)),
            "320623882B0DBD238471A6E7DC3C1F3177D2DD38C0DC166FB12109BA89698E4B"
        );
    }

    #[test]
    fn utc_time_format() {
        assert_eq!(utc_time(0), "700101000000Z");
        // 1783667881 == 2026-07-10 07:18:01 UTC (the fixture's signingTime).
        assert_eq!(utc_time(1783667881), "260710071801Z");
    }

    fn selftest_signature(prep: &Prepared) -> Vec<u8> {
        use rsa::pkcs8::DecodePrivateKey;
        use rsa::{Pkcs1v15Sign, RsaPrivateKey};
        let key = RsaPrivateKey::from_pkcs8_pem(include_str!("../tests/fixtures/selftest_key.pem"))
            .unwrap();
        key.sign(Pkcs1v15Sign::new::<Sha256>(), &prep.to_be_signed)
            .unwrap()
    }

    fn selftest_prep(signing_time: u64) -> Prepared {
        let pe = include_bytes!("../tests/fixtures/hello.exe");
        prepare(pe, Some("ssign"), None, &utc_time(signing_time)).unwrap()
    }

    #[test]
    fn embeds_a_signature_that_verifies() {
        let cert_der = include_bytes!("../tests/fixtures/selftest_cert.der");
        let prep = selftest_prep(1783667881);
        let signature = selftest_signature(&prep);
        let signed = finalize(prep, &signature, cert_der, None).unwrap();
        assert!(pe_layout(&signed).unwrap().cert_table_size > 0);
    }

    #[test]
    fn refuses_a_signature_with_a_flipped_byte() {
        let cert_der = include_bytes!("../tests/fixtures/selftest_cert.der");
        let prep = selftest_prep(1783667881);
        let mut signature = selftest_signature(&prep);
        signature[100] ^= 1;
        assert!(finalize(prep, &signature, cert_der, None).is_err());
    }

    #[test]
    fn refuses_a_valid_signature_over_other_attributes() {
        let cert_der = include_bytes!("../tests/fixtures/selftest_cert.der");
        let signature = selftest_signature(&selftest_prep(1783667881));
        let prep = selftest_prep(1783667882);
        assert!(finalize(prep, &signature, cert_der, None).is_err());
    }

    #[test]
    fn refuses_a_signature_from_another_key() {
        let other_cert: &[u8] = include_bytes!("certs/ccsca2021.der");
        let prep = selftest_prep(1783667881);
        let signature = selftest_signature(&prep);
        assert!(finalize(prep, &signature, other_cert, None).is_err());
    }

    /// End-to-end assembly check with a local self-signed key: prepare -> sign
    /// the digest ourselves (exactly as Certum would) -> finalize -> write a PE.
    /// Run with `cargo test -- --ignored`, then `osslsigncode verify` the output.
    #[test]
    #[ignore = "writes /tmp/ssign_selftest.exe for external osslsigncode verify"]
    fn selftest_assembles_verifiable_pe() {
        use rsa::pkcs8::DecodePrivateKey;
        use rsa::{Pkcs1v15Sign, RsaPrivateKey};

        let pe = include_bytes!("../tests/fixtures/hello.exe");
        let cert_der = include_bytes!("../tests/fixtures/selftest_cert.der");
        let key = RsaPrivateKey::from_pkcs8_pem(include_str!("../tests/fixtures/selftest_key.pem"))
            .unwrap();

        let prep = prepare(
            pe,
            Some("ssign selftest"),
            Some("https://github.com/Le-Syl21"),
            &utc_time(1783667881),
        )
        .unwrap();
        // Certum returns RSASSA-PKCS1-v1_5 over the signed-attrs digest; do the same.
        let signature = key
            .sign(Pkcs1v15Sign::new::<Sha256>(), &prep.to_be_signed)
            .unwrap();
        let ts = crate::timestamp::fetch("http://time.certum.pl/", &signature).ok();
        let signed = finalize(prep, &signature, cert_der, ts.as_deref()).unwrap();
        std::fs::write("/tmp/ssign_selftest.exe", &signed).unwrap();
        assert!(pe_layout(&signed).unwrap().cert_table_size > 0);
    }
}