craton-hsm 0.10.5

A production-grade PKCS#11 v3.0-compliant Software HSM written in Rust
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Craton Software Company
//! FIPS 140-3 Power-On Self-Tests (POST)
//!
//! These Known Answer Tests (KATs) run during C_Initialize before any
//! cryptographic service is available. If any test fails, the module
//! enters an error state and refuses all operations.
//!
//! # The KATs run against the configured backend
//!
//! [`run_post`] takes the `CryptoBackend` the module will actually use, and the
//! algorithm KATs are dispatched through it. This matters when a backend other
//! than the built-in RustCrypto one is selected: FIPS 140-3 requires a known-
//! answer test for each approved algorithm *the module implements*, and testing
//! a different implementation than the one in service establishes nothing about
//! it. Before this was wired through, an AWS-LC deployment self-tested
//! RustCrypto, so a broken or miscompiled AWS-LC would have passed POST.
//!
//! HMAC, SHA3, the PQC algorithms, and the RNG/DRBG health tests are not
//! backend-swapped, so those KATs call the shared implementations directly.
//!
//! KATs cover all approved algorithms:
//! - SHA-256, SHA-384, SHA-512, SHA3-256 (digest)
//! - HMAC-SHA256, HMAC-SHA384, HMAC-SHA512 (MAC)
//! - AES-256-GCM, AES-CBC, AES-CTR (symmetric encryption)
//! - ECDSA P-256 (asymmetric signature)
//! - ML-DSA-44 (post-quantum signature)
//! - ML-KEM-768 (post-quantum KEM)
//! - RNG health + continuous test (entropy source)

use crate::crypto::backend::CryptoBackend;
use crate::error::HsmResult;
use crate::pkcs11_abi::constants::{CKM_SHA256, CKM_SHA384, CKM_SHA512};

/// §9.4 software integrity test (HMAC-SHA256 over the module binary).
///
/// Split out from the algorithm KATs so it can keep running *first*, before
/// anything else at all. The KATs need the configured backend, which is only
/// known once the configuration has been read; this does not, and must not wait
/// for it.
pub fn run_post_integrity() -> HsmResult<()> {
    // Reset IV-reuse trackers and GCM counters so that the KATs can later run
    // deterministically with fixed IVs/nonces. Safe here because this runs on
    // initialization, before any user operation.
    crate::crypto::encrypt::reset_gcm_counters();
    crate::crypto::encrypt::reset_iv_trackers();

    if let Err(msg) = crate::crypto::integrity::check_integrity() {
        tracing::error!("POST: Software integrity test failed: {}", msg);
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

/// Run every algorithm known-answer test against `backend`.
///
/// `backend` must be the instance the module will actually serve requests with
/// — see the module documentation for why testing a different one proves
/// nothing. Call [`run_post_integrity`] first.
pub fn run_post_algorithms(backend: &dyn CryptoBackend) -> HsmResult<()> {
    // Digest KATs
    post_sha256_kat(backend)?;
    post_sha384_kat(backend)?;
    post_sha512_kat(backend)?;
    // SHA3 has no backend entry point; it is served by the shared
    // implementation regardless of the configured backend.
    post_sha3_256_kat()?;

    // MAC KATs
    post_hmac_sha256_kat()?;
    post_hmac_sha384_kat()?;
    post_hmac_sha512_kat()?;

    // Symmetric encryption KATs
    post_aes_gcm_kat(backend)?;
    post_aes_cbc_kat(backend)?;
    post_aes_ctr_kat(backend)?;

    // Asymmetric KATs — FIPS 140-3 IG §9.4 requires every approved
    // algorithm's KAT to run on every module initialization, regardless
    // of build profile. These are slow in unoptimized debug builds but
    // must NOT be skipped.
    post_rsa_pkcs1v15_kat(backend)?;
    post_ecdsa_p256_kat(backend)?;

    // PQC KATs
    post_ml_dsa_kat()?;
    post_ml_kem_kat()?;

    // RNG health + continuous test
    post_rng_health()?;

    // DRBG health
    post_drbg_health()?;

    Ok(())
}

/// Run the integrity test followed by every algorithm KAT.
///
/// Convenience wrapper for callers that already hold the backend and do not
/// need to interleave configuration loading between the two phases.
pub fn run_post(backend: &dyn CryptoBackend) -> HsmResult<()> {
    run_post_integrity()?;
    run_post_algorithms(backend)
}

// ============================================================================
// Digest KATs
// ============================================================================

/// SHA-256 KAT: hash "abc", compare against NIST digest.
fn post_sha256_kat(backend: &dyn CryptoBackend) -> HsmResult<()> {
    let result = backend.compute_digest(CKM_SHA256, b"abc")?;
    let expected: [u8; 32] = [
        0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22,
        0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00,
        0x15, 0xad,
    ];
    if result != expected {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

/// SHA-384 KAT: hash "abc", compare full 48-byte NIST digest.
fn post_sha384_kat(backend: &dyn CryptoBackend) -> HsmResult<()> {
    let result = backend.compute_digest(CKM_SHA384, b"abc")?;
    // NIST SHA-384("abc") — full 48-byte digest
    let expected: [u8; 48] = [
        0xcb, 0x00, 0x75, 0x3f, 0x45, 0xa3, 0x5e, 0x8b, 0xb5, 0xa0, 0x3d, 0x69, 0x9a, 0xc6, 0x50,
        0x07, 0x27, 0x2c, 0x32, 0xab, 0x0e, 0xde, 0xd1, 0x63, 0x1a, 0x8b, 0x60, 0x5a, 0x43, 0xff,
        0x5b, 0xed, 0x80, 0x86, 0x07, 0x2b, 0xa1, 0xe7, 0xcc, 0x23, 0x58, 0xba, 0xec, 0xa1, 0x34,
        0xc8, 0x25, 0xa7,
    ];
    if result != expected {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

/// SHA-512 KAT: hash "abc", compare full 64-byte NIST digest.
fn post_sha512_kat(backend: &dyn CryptoBackend) -> HsmResult<()> {
    let result = backend.compute_digest(CKM_SHA512, b"abc")?;
    // NIST SHA-512("abc") — full 64-byte digest
    let expected: [u8; 64] = [
        0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba, 0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41,
        0x31, 0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2, 0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55,
        0xd3, 0x9a, 0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8, 0x36, 0xba, 0x3c, 0x23, 0xa3,
        0xfe, 0xeb, 0xbd, 0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e, 0x2a, 0x9a, 0xc9, 0x4f,
        0xa5, 0x4c, 0xa4, 0x9f,
    ];
    if result != expected {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

/// SHA3-256 KAT: hash "abc", compare against NIST digest.
fn post_sha3_256_kat() -> HsmResult<()> {
    use sha3::{Digest, Sha3_256};
    let result = Sha3_256::digest(b"abc");
    // NIST SHA3-256("abc")
    let expected: [u8; 32] = [
        0x3a, 0x98, 0x5d, 0xa7, 0x4f, 0xe2, 0x25, 0xb2, 0x04, 0x5c, 0x17, 0x2d, 0x6b, 0xd3, 0x90,
        0xbd, 0x85, 0x5f, 0x08, 0x6e, 0x3e, 0x9d, 0x52, 0x5b, 0x46, 0xbf, 0xe2, 0x45, 0x11, 0x43,
        0x15, 0x32,
    ];
    if result.as_slice() != expected {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

// ============================================================================
// MAC KATs (all from RFC 4231 Test Case 2)
// ============================================================================

/// HMAC-SHA256 KAT: RFC 4231 test vector #2
fn post_hmac_sha256_kat() -> HsmResult<()> {
    use hmac::{Hmac, Mac};
    use sha2::Sha256;
    type HmacSha256 = Hmac<Sha256>;

    let key = b"Jefe";
    let data = b"what do ya want for nothing?";
    let expected: [u8; 32] = [
        0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24, 0x26, 0x08, 0x95, 0x75,
        0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27, 0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec,
        0x38, 0x43,
    ];

    let mut mac =
        HmacSha256::new_from_slice(key).map_err(|_| crate::error::HsmError::GeneralError)?;
    mac.update(data);
    let result = mac.finalize().into_bytes();
    if result.as_slice() != expected {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

/// HMAC-SHA384 KAT: RFC 4231 test vector #2 — full 48-byte MAC
fn post_hmac_sha384_kat() -> HsmResult<()> {
    use hmac::{Hmac, Mac};
    use sha2::Sha384;
    type HmacSha384 = Hmac<Sha384>;

    let key = b"Jefe";
    let data = b"what do ya want for nothing?";
    // RFC 4231 TC2 HMAC-SHA-384 — full 48 bytes
    let expected: [u8; 48] = [
        0xaf, 0x45, 0xd2, 0xe3, 0x76, 0x48, 0x40, 0x31, 0x61, 0x7f, 0x78, 0xd2, 0xb5, 0x8a, 0x6b,
        0x1b, 0x9c, 0x7e, 0xf4, 0x64, 0xf5, 0xa0, 0x1b, 0x47, 0xe4, 0x2e, 0xc3, 0x73, 0x63, 0x22,
        0x44, 0x5e, 0x8e, 0x22, 0x40, 0xca, 0x5e, 0x69, 0xe2, 0xc7, 0x8b, 0x32, 0x39, 0xec, 0xfa,
        0xb2, 0x16, 0x49,
    ];

    let mut mac =
        HmacSha384::new_from_slice(key).map_err(|_| crate::error::HsmError::GeneralError)?;
    mac.update(data);
    let result = mac.finalize().into_bytes();
    if result.as_slice() != expected {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

/// HMAC-SHA512 KAT: RFC 4231 test vector #2 — full 64-byte MAC
fn post_hmac_sha512_kat() -> HsmResult<()> {
    use hmac::{Hmac, Mac};
    use sha2::Sha512;
    type HmacSha512 = Hmac<Sha512>;

    let key = b"Jefe";
    let data = b"what do ya want for nothing?";
    // RFC 4231 TC2 HMAC-SHA-512 — full 64 bytes
    let expected: [u8; 64] = [
        0x16, 0x4b, 0x7a, 0x7b, 0xfc, 0xf8, 0x19, 0xe2, 0xe3, 0x95, 0xfb, 0xe7, 0x3b, 0x56, 0xe0,
        0xa3, 0x87, 0xbd, 0x64, 0x22, 0x2e, 0x83, 0x1f, 0xd6, 0x10, 0x27, 0x0c, 0xd7, 0xea, 0x25,
        0x05, 0x54, 0x97, 0x58, 0xbf, 0x75, 0xc0, 0x5a, 0x99, 0x4a, 0x6d, 0x03, 0x4f, 0x65, 0xf8,
        0xf0, 0xe6, 0xfd, 0xca, 0xea, 0xb1, 0xa3, 0x4d, 0x4a, 0x6b, 0x4b, 0x63, 0x6e, 0x07, 0x0a,
        0x38, 0xbc, 0xe7, 0x37,
    ];

    let mut mac =
        HmacSha512::new_from_slice(key).map_err(|_| crate::error::HsmError::GeneralError)?;
    mac.update(data);
    let result = mac.finalize().into_bytes();
    if result[..] != expected {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

// ============================================================================
// Symmetric encryption KATs
// ============================================================================

/// AES-256-GCM KAT: encrypt then decrypt roundtrip, plus verify the decryption
/// path independently with a known nonce to catch symmetric implementation bugs.
fn post_aes_gcm_kat(backend: &dyn CryptoBackend) -> HsmResult<()> {
    use aes_gcm::{
        aead::{Aead, KeyInit},
        Aes256Gcm, Key, Nonce,
    };

    // Part 1: roundtrip through the configured backend (catches gross failures).
    let key = [0x42u8; 32];
    let plaintext = b"FIPS POST AES-GCM self-test data";
    let ciphertext = backend.aes_256_gcm_encrypt(&key, plaintext)?;
    let decrypted = backend.aes_256_gcm_decrypt(&key, &ciphertext)?;
    if decrypted != plaintext {
        return Err(crate::error::HsmError::GeneralError);
    }

    // Part 2: fixed-nonce check of the shared AES-GCM primitive.
    //
    // This one cannot go through the backend: `aes_256_gcm_encrypt` generates
    // its own nonce by design (see `crypto/encrypt.rs`), so there is no entry
    // point that accepts a fixed nonce, and a deterministic vector needs one.
    // Part 1 above is what exercises the configured backend; this part guards
    // the shared primitive against a symmetric encrypt/decrypt bug.
    let kat_key = [0x00u8; 32];
    let kat_nonce = [0x00u8; 12];
    let kat_plaintext = b"";
    // AES-256-GCM(key=0x00*32, nonce=0x00*12, plaintext="") produces a 16-byte auth tag.
    // We verify by encrypting with known params and checking the tag is non-trivial.
    let aes_key = Key::<Aes256Gcm>::from_slice(&kat_key);
    let cipher = Aes256Gcm::new(aes_key);
    let nonce = Nonce::from_slice(&kat_nonce);
    let ct = cipher
        .encrypt(nonce, kat_plaintext.as_ref())
        .map_err(|_| crate::error::HsmError::GeneralError)?;
    // Verify the ciphertext (auth tag only for empty plaintext) is exactly 16 bytes
    // and is not all zeros (which would indicate a broken implementation)
    if ct.len() != 16 || ct.iter().all(|&b| b == 0) {
        return Err(crate::error::HsmError::GeneralError);
    }
    // Verify decryption of our known ciphertext succeeds
    let dt = cipher
        .decrypt(nonce, ct.as_ref())
        .map_err(|_| crate::error::HsmError::GeneralError)?;
    if !dt.is_empty() {
        return Err(crate::error::HsmError::GeneralError);
    }

    Ok(())
}

/// AES-256-CBC KAT: verify against hardcoded pre-computed ciphertext.
///
/// Uses a genuine known-answer test with a pre-computed expected ciphertext
/// that was generated and verified independently. This catches implementation
/// bugs that a roundtrip-only test or a circular self-comparison would miss.
fn post_aes_cbc_kat(backend: &dyn CryptoBackend) -> HsmResult<()> {
    let key = [0x55u8; 32];
    let iv = [0xAAu8; 16];
    let plaintext = b"FIPS POST AES-CBC test data!!!!"; // 31 bytes, tests PKCS#7 padding

    // Part 1: Known-answer test — compare against hardcoded expected ciphertext.
    // Pre-computed with a verified AES-256-CBC implementation (PKCS#7 padding).
    // 31 bytes plaintext + 1 byte PKCS#7 pad = 32 bytes = 2 AES blocks.
    let ciphertext = backend.aes_cbc_encrypt(&key, &iv, plaintext)?;
    let expected_ct: [u8; 32] = [
        0xb9, 0xf9, 0x93, 0x5b, 0xe0, 0x5d, 0x47, 0x0d, 0xe9, 0x8c, 0x11, 0x92, 0x18, 0xe5, 0xa9,
        0xc8, 0xf7, 0x31, 0x6a, 0xd6, 0x6d, 0xee, 0x0a, 0xd7, 0x1b, 0x1c, 0xb2, 0x1d, 0xa0, 0x32,
        0x2d, 0x30,
    ];
    if ciphertext != expected_ct {
        return Err(crate::error::HsmError::GeneralError);
    }

    // Part 2: Roundtrip — verify decryption recovers original plaintext
    let decrypted = backend.aes_cbc_decrypt(&key, &iv, &ciphertext)?;
    if decrypted != plaintext {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

/// AES-256-CTR KAT: verify against hardcoded pre-computed ciphertext.
///
/// Uses a genuine known-answer test with a pre-computed expected ciphertext
/// that was generated and verified independently. A roundtrip-only or circular
/// self-comparison test would miss symmetric bugs (e.g., XOR with wrong keystream).
fn post_aes_ctr_kat(backend: &dyn CryptoBackend) -> HsmResult<()> {
    let key = [0x77u8; 32];
    let iv = [0xBBu8; 16];
    let plaintext = b"FIPS POST AES-CTR self-test";

    // Part 1: Known-answer test — compare against hardcoded expected ciphertext.
    // Pre-computed with a verified AES-256-CTR (big-endian counter) implementation.
    let ciphertext = backend.aes_ctr_encrypt(&key, &iv, plaintext)?;
    let expected_ct: [u8; 27] = [
        0xf4, 0x1e, 0x8e, 0x60, 0x27, 0xfe, 0xb9, 0xb4, 0x1b, 0x89, 0x9f, 0x12, 0x84, 0xde, 0x34,
        0x03, 0x8b, 0x0d, 0x0d, 0xd6, 0xd1, 0x6d, 0x98, 0x23, 0xd8, 0x5b, 0x56,
    ];
    if ciphertext != expected_ct {
        return Err(crate::error::HsmError::GeneralError);
    }

    // Part 2: Roundtrip — CTR is symmetric, encrypting ciphertext recovers plaintext
    let decrypted = backend.aes_ctr_decrypt(&key, &iv, &ciphertext)?;
    if decrypted != plaintext {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

// ============================================================================
// Asymmetric KATs
// ============================================================================

/// Message covered by both RSA KAT paths below.
const RSA_KAT_MESSAGE: &[u8] = b"FIPS POST RSA PKCS#1 v1.5 self-test";

// Fixed RSA-2048 / SHA-256 PKCS#1 v1.5 verification vector.
//
// Generated once with `examples/gen_rsa_kat.rs` on a build with
// `insecure-rustcrypto-rsa-private-ops` enabled, then checked in so the verify
// KAT needs no private-key operation at run time. The private key was
// discarded; only the public parameters and the signature are retained, so
// nothing secret is embedded here.
// modulus 256 bytes, exponent 3 bytes, signature 256 bytes
const RSA_KAT_MODULUS: &[u8] = &[
    0xe9, 0x0c, 0x93, 0xbd, 0x1b, 0x25, 0x13, 0x6d, 0xc2, 0xf4, 0xc7, 0xda, 0x8c, 0x7b, 0xa0, 0xd0,
    0x0d, 0x77, 0xaa, 0xfd, 0x97, 0x0b, 0x36, 0x74, 0x52, 0x12, 0xcb, 0x3e, 0xf5, 0xf2, 0x6c, 0xa8,
    0x64, 0xc8, 0xd7, 0xdf, 0x62, 0x02, 0x0c, 0xa4, 0x1b, 0x57, 0xd7, 0x60, 0x61, 0x17, 0x4f, 0x92,
    0xb6, 0xa2, 0x97, 0x41, 0x34, 0xca, 0xb6, 0x7f, 0x43, 0x0a, 0xac, 0x8b, 0x29, 0x4e, 0x3f, 0x01,
    0x57, 0x84, 0x7f, 0xa7, 0x5d, 0x5d, 0x32, 0xd8, 0x5b, 0x3f, 0xdc, 0x00, 0x5f, 0x01, 0x3e, 0x8b,
    0xf0, 0x7a, 0x42, 0x4b, 0xd0, 0x80, 0x45, 0x5c, 0xdd, 0xb4, 0x73, 0x19, 0x27, 0xb6, 0x70, 0x53,
    0x1a, 0x74, 0x4c, 0xdc, 0x6d, 0xb0, 0x9e, 0x55, 0xc5, 0x0f, 0xa4, 0xe6, 0xd4, 0x6d, 0x32, 0xcd,
    0xf4, 0x7b, 0x91, 0x90, 0xbc, 0xa2, 0x5a, 0x1d, 0xf9, 0x65, 0xca, 0x41, 0x9e, 0x15, 0x7c, 0xf1,
    0xf5, 0x47, 0x1f, 0xaa, 0x98, 0xc0, 0x42, 0xc5, 0x9c, 0xb0, 0x24, 0x61, 0x30, 0x79, 0x68, 0x3b,
    0x79, 0x5d, 0x60, 0x52, 0x96, 0x03, 0x09, 0x45, 0x56, 0x49, 0x28, 0xa8, 0xd5, 0x64, 0x95, 0x1a,
    0x08, 0x8c, 0x85, 0xd6, 0xdf, 0x70, 0xca, 0xfc, 0xfb, 0x49, 0x44, 0xf2, 0xe9, 0xd2, 0x79, 0x1b,
    0xcb, 0x3e, 0x8b, 0xe0, 0xc2, 0x51, 0x32, 0x9c, 0x0d, 0x79, 0x28, 0x29, 0x50, 0x4a, 0x45, 0xed,
    0xb4, 0xa7, 0x26, 0x63, 0xa5, 0xd6, 0x09, 0xe0, 0x96, 0x5c, 0x8d, 0x26, 0xb6, 0x0c, 0xaf, 0x0b,
    0x04, 0xf3, 0xcb, 0xba, 0xe8, 0xb8, 0xd9, 0x7c, 0xca, 0x4c, 0x27, 0xf8, 0x5b, 0x06, 0x34, 0x13,
    0xd1, 0x84, 0x81, 0xea, 0x0a, 0x96, 0x02, 0xd6, 0xf0, 0x5e, 0x10, 0xd2, 0x17, 0x4c, 0xee, 0x7b,
    0xb7, 0xab, 0x4b, 0x1c, 0xe5, 0x40, 0xb3, 0x60, 0xee, 0xce, 0x40, 0x0d, 0xd5, 0x18, 0x5b, 0xdb,
];
const RSA_KAT_PUBLIC_EXPONENT: &[u8] = &[0x01, 0x00, 0x01];
const RSA_KAT_SIGNATURE: &[u8] = &[
    0x9b, 0xd1, 0x9c, 0x4f, 0x67, 0x4e, 0x27, 0x2a, 0x4e, 0x10, 0xc0, 0x31, 0xa0, 0xf6, 0x5d, 0x01,
    0x72, 0x6a, 0x2b, 0xb0, 0x17, 0x64, 0x14, 0x6a, 0x3a, 0x98, 0x07, 0x5f, 0xb2, 0x92, 0xde, 0xfc,
    0x44, 0xc0, 0x0d, 0xd7, 0xa2, 0x96, 0x6b, 0xc9, 0x32, 0x6a, 0xc1, 0x1b, 0x37, 0xa3, 0xf6, 0x1f,
    0xbe, 0x3f, 0x0c, 0x14, 0x33, 0x9a, 0xe4, 0x19, 0xb2, 0x68, 0x96, 0x05, 0x81, 0xd4, 0x6f, 0x44,
    0xab, 0x3b, 0x9e, 0x5d, 0x1d, 0x53, 0x1e, 0x71, 0x3a, 0x4b, 0xe2, 0x4a, 0x0a, 0x78, 0x74, 0x86,
    0xda, 0xb4, 0xa2, 0xb8, 0xc0, 0xf5, 0xa4, 0x8d, 0x70, 0x83, 0x69, 0xdb, 0x71, 0x7d, 0x15, 0xda,
    0x64, 0xed, 0x0d, 0x8c, 0xeb, 0x38, 0xcf, 0xe4, 0x41, 0x74, 0xf7, 0x22, 0x70, 0x09, 0xb6, 0xfe,
    0x7c, 0xf0, 0xcb, 0x55, 0xa0, 0xc3, 0xda, 0x13, 0x34, 0xec, 0xc1, 0x3b, 0xf1, 0xd7, 0x5b, 0x03,
    0x53, 0x84, 0x83, 0x9c, 0x55, 0x14, 0x1e, 0xcb, 0xe2, 0xf9, 0xee, 0x3b, 0xec, 0x39, 0xe7, 0xa2,
    0xba, 0x19, 0xbe, 0x92, 0xc8, 0x6c, 0xdc, 0x51, 0x84, 0xa0, 0xd9, 0x8a, 0xe9, 0x2f, 0xcb, 0xeb,
    0x55, 0x35, 0x56, 0xfb, 0x02, 0xac, 0xb0, 0x8d, 0x44, 0x5e, 0x6b, 0x1e, 0x3c, 0x6f, 0x88, 0x1f,
    0xc5, 0x93, 0x32, 0x1e, 0x64, 0xf4, 0x53, 0x4d, 0x23, 0xb4, 0x0e, 0x72, 0xca, 0xdd, 0x8e, 0x19,
    0xaa, 0x4f, 0x64, 0xaa, 0xed, 0x2a, 0x72, 0x79, 0x18, 0xba, 0xf7, 0x66, 0x54, 0x86, 0x5a, 0x80,
    0x9b, 0x86, 0x53, 0x89, 0xb3, 0xd3, 0x24, 0xe3, 0xf2, 0x57, 0xca, 0x45, 0xb5, 0x06, 0xa8, 0x33,
    0x00, 0x45, 0x05, 0x5e, 0x90, 0x30, 0xd8, 0x38, 0xb4, 0x54, 0x8c, 0x6e, 0xc1, 0x5d, 0x9f, 0xba,
    0xbb, 0xcd, 0x1b, 0xfd, 0xea, 0x11, 0x58, 0xfc, 0xf8, 0xdd, 0x2d, 0xf2, 0x98, 0xee, 0xb3, 0x49,
];

/// RSA PKCS#1 v1.5 known-answer test for RSA-2048 with SHA-256.
///
/// # Why this has two paths
///
/// Release builds refuse RustCrypto RSA **private-key** operations because the
/// `rsa` crate is subject to the Marvin timing attack (RUSTSEC-2023-0071); see
/// `require_rustcrypto_rsa_private_ops`. A KAT that unconditionally signs
/// therefore failed in every release build, which failed the POST, which failed
/// `C_Initialize`: the module could not start at all.
///
/// FIPS 140-3 requires a known-answer test for each approved security function
/// the module *provides*. When private-key operations are refused, RSA signature
/// generation is not a provided service and has no KAT to run; RSA signature
/// **verification** is still provided, and is covered here against a fixed
/// vector, including a negative case so that a verifier which accepts
/// everything cannot pass.
///
/// When private-key operations are available (debug builds, or an explicit
/// opt-in), the stronger generate-sign-verify roundtrip runs instead.
fn post_rsa_pkcs1v15_kat(backend: &dyn CryptoBackend) -> HsmResult<()> {
    // Ask the *backend* whether it provides RSA private-key operations, rather
    // than testing the build-time RustCrypto gate. A backend that provides them
    // (AWS-LC does) gets the stronger generate-sign-verify roundtrip against
    // its own implementation.
    if backend.supports_rsa_private_ops() {
        post_rsa_pkcs1v15_roundtrip_kat(backend)
    } else {
        post_rsa_pkcs1v15_verify_kat(backend)
    }
}

/// Full roundtrip: generate a key, sign, and verify.
fn post_rsa_pkcs1v15_roundtrip_kat(backend: &dyn CryptoBackend) -> HsmResult<()> {
    use crate::crypto::sign::HashAlg;
    let (priv_key, modulus, pub_exp) = backend.generate_rsa_key_pair(2048, false)?;
    let signature =
        backend.rsa_pkcs1v15_sign(priv_key.as_bytes(), RSA_KAT_MESSAGE, Some(HashAlg::Sha256))?;
    let valid = backend.rsa_pkcs1v15_verify(
        &modulus,
        &pub_exp,
        RSA_KAT_MESSAGE,
        &signature,
        Some(HashAlg::Sha256),
    )?;
    if !valid {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

/// Verify-only KAT against the fixed vector above.
///
/// Checks both directions: the valid signature must verify, and a signature
/// with one bit flipped must not. Without the negative case a verifier that
/// returned `true` unconditionally would pass.
fn post_rsa_pkcs1v15_verify_kat(backend: &dyn CryptoBackend) -> HsmResult<()> {
    use crate::crypto::sign::HashAlg;

    let valid = backend.rsa_pkcs1v15_verify(
        RSA_KAT_MODULUS,
        RSA_KAT_PUBLIC_EXPONENT,
        RSA_KAT_MESSAGE,
        RSA_KAT_SIGNATURE,
        Some(HashAlg::Sha256),
    )?;
    if !valid {
        tracing::error!("POST: RSA PKCS#1 v1.5 verify KAT rejected a valid signature");
        return Err(crate::error::HsmError::GeneralError);
    }

    let mut corrupted = RSA_KAT_SIGNATURE.to_vec();
    corrupted[0] ^= 0x01;
    let accepted = backend
        .rsa_pkcs1v15_verify(
            RSA_KAT_MODULUS,
            RSA_KAT_PUBLIC_EXPONENT,
            RSA_KAT_MESSAGE,
            &corrupted,
            Some(HashAlg::Sha256),
        )
        .unwrap_or(false);
    if accepted {
        tracing::error!("POST: RSA PKCS#1 v1.5 verify KAT accepted a corrupted signature");
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

/// ECDSA P-256 sign/verify roundtrip with generated key.
fn post_ecdsa_p256_kat(backend: &dyn CryptoBackend) -> HsmResult<()> {
    let (priv_key, pub_key) = backend.generate_ec_p256_key_pair()?;
    let message = b"FIPS POST ECDSA self-test";
    let signature = backend.ecdsa_p256_sign(priv_key.as_bytes(), message)?;
    let valid = backend.ecdsa_p256_verify(&pub_key, message, &signature)?;
    if !valid {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

// ============================================================================
// PQC KATs
// ============================================================================

/// ML-DSA-44 sign/verify roundtrip.
fn post_ml_dsa_kat() -> HsmResult<()> {
    use crate::crypto::pqc;
    let (sk, vk) = pqc::ml_dsa_keygen(pqc::MlDsaVariant::MlDsa44)?;
    let message = b"FIPS POST ML-DSA self-test";
    let signature = pqc::ml_dsa_sign(sk.as_bytes(), message, pqc::MlDsaVariant::MlDsa44)?;
    let valid = pqc::ml_dsa_verify(&vk, message, &signature, pqc::MlDsaVariant::MlDsa44)?;
    if !valid {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

/// ML-KEM-768 encapsulate/decapsulate roundtrip.
fn post_ml_kem_kat() -> HsmResult<()> {
    use crate::crypto::pqc;
    let (dk, ek) = pqc::ml_kem_keygen(pqc::MlKemVariant::MlKem768)?;
    let (ciphertext, shared_secret_enc) =
        pqc::ml_kem_encapsulate(&ek, pqc::MlKemVariant::MlKem768)?;
    let shared_secret_dec =
        pqc::ml_kem_decapsulate(dk.as_bytes(), &ciphertext, pqc::MlKemVariant::MlKem768)?;

    use subtle::ConstantTimeEq;
    let secrets_match: bool = shared_secret_enc.ct_eq(&shared_secret_dec).into();
    if !secrets_match {
        return Err(crate::error::HsmError::GeneralError);
    }
    Ok(())
}

// ============================================================================
// RNG Health + Continuous Test
// ============================================================================

/// RNG health test: generate 256 random bytes, verify not all zeros/identical.
/// Also performs a continuous RNG check (NIST SP 800-90B §4.3):
/// two consecutive draws must differ.
fn post_rng_health() -> HsmResult<()> {
    use rand::RngCore;

    let mut buf1 = vec![0u8; 256];
    rand::rngs::OsRng.fill_bytes(&mut buf1);

    // Check not all zeros
    if buf1.iter().all(|&b| b == 0) {
        return Err(crate::error::HsmError::GeneralError);
    }
    // Check not all same value
    let first = buf1[0];
    if buf1.iter().all(|&b| b == first) {
        return Err(crate::error::HsmError::GeneralError);
    }

    // Continuous RNG test: two consecutive 256-byte draws must differ
    let mut buf2 = vec![0u8; 256];
    rand::rngs::OsRng.fill_bytes(&mut buf2);
    if buf1 == buf2 {
        return Err(crate::error::HsmError::GeneralError);
    }

    Ok(())
}

/// HMAC_DRBG health test per SP 800-90A.
/// Instantiate DRBG, generate two consecutive outputs, verify they differ.
fn post_drbg_health() -> HsmResult<()> {
    let mut drbg = crate::crypto::drbg::HmacDrbg::new()?;

    let mut buf1 = [0u8; 32];
    drbg.generate(&mut buf1)?;

    // Output must not be all zeros
    if buf1.iter().all(|&b| b == 0) {
        return Err(crate::error::HsmError::GeneralError);
    }

    let mut buf2 = [0u8; 32];
    drbg.generate(&mut buf2)?;

    // Consecutive outputs must differ (continuous health test)
    if buf1 == buf2 {
        return Err(crate::error::HsmError::GeneralError);
    }

    Ok(())
}

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

    #[test]
    fn test_post_passes() {
        // Default `cargo test` build embeds the all-zero placeholder integrity
        // public key (no real CRATON_HSM_INTEGRITY_PUBLIC_KEY was set at build
        // time).  Opt in to the documented dev bypass so the integrity check
        // doesn't reject the test binary; this is exactly what the bypass env
        // var exists for.
        // SAFETY: env-var mutation is process-global, but this is a one-shot
        // setup that is safe to leave in place for the remainder of the test
        // process.
        unsafe { std::env::set_var("CRATON_HSM_INTEGRITY_BYPASS", "unsafe-dev-only") };
        // Whichever backend this build compiled; POST must pass against it.
        #[cfg(feature = "rustcrypto-backend")]
        let backend = crate::crypto::rustcrypto_backend::RustCryptoBackend;
        #[cfg(all(feature = "awslc-backend", not(feature = "rustcrypto-backend")))]
        let backend = crate::crypto::awslc_backend::AwsLcBackend;
        run_post(&backend).expect("POST self-tests should pass");
    }

    /// The KATs must pass against **AWS-LC specifically**, not just against
    /// whichever backend happens to be the default.
    ///
    /// This is the test that has teeth. It runs in a build where the RustCrypto
    /// backend is also compiled and is what `HsmCore` would select by default,
    /// so it cannot accidentally be exercising RustCrypto: it names the AWS-LC
    /// backend and asserts the algorithm KATs pass against that. Before the KATs
    /// took a backend, this assertion could not even be written -- `run_post()`
    /// had no way to be pointed at a particular implementation, which is exactly
    /// how an AWS-LC deployment ended up self-testing RustCrypto.
    #[test]
    #[cfg(feature = "awslc-backend")]
    fn post_algorithm_kats_pass_against_awslc() {
        // SAFETY: process-global env var; the integrity test is covered
        // separately and is not what this test is about.
        unsafe { std::env::set_var("CRATON_HSM_INTEGRITY_BYPASS", "unsafe-dev-only") };
        let backend = crate::crypto::awslc_backend::AwsLcBackend;
        run_post_algorithms(&backend).expect("algorithm KATs must pass against AWS-LC");
    }
}