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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 Craton Software Company
use serde::Deserialize;
use std::fmt;
use std::path::{Path, PathBuf};

use crate::error::HsmError;

/// Minimum acceptable PBKDF2 iteration count to resist brute-force attacks.
#[cfg(debug_assertions)]
const MIN_PBKDF2_ITERATIONS: u32 = 1;
#[cfg(not(debug_assertions))]
const MIN_PBKDF2_ITERATIONS: u32 = 100_000;
/// Maximum acceptable PBKDF2 iteration count to prevent algorithmic DoS via
/// config-planted extreme values.
const MAX_PBKDF2_ITERATIONS: u32 = 10_000_000;
/// Minimum acceptable PIN length (NIST SP 800-63B recommends >= 6; we use 4
/// as an absolute floor so that downstream policy can tighten further).
const MIN_PIN_LENGTH: usize = 4;
/// Bounds for `max_failed_logins` to prevent DoS (too low) or brute-force
/// (too high).
const MIN_FAILED_LOGINS: u32 = 3;
const MAX_FAILED_LOGINS: u32 = 100;
/// Maximum PIN length to prevent memory-exhaustion via PBKDF2 on huge PINs.
const MAX_PIN_LENGTH: usize = 256;
/// Maximum sessions to prevent resource exhaustion.
const MAX_SESSIONS: u64 = 10_000;
/// Maximum slots to prevent OOM on initialization.
const MAX_SLOT_COUNT: usize = 256;
/// Maximum token label length (PKCS#11 CK_TOKEN_INFO.label is 32 bytes).
const MAX_LABEL_LENGTH: usize = 32;
/// Valid crypto backend identifiers.
const VALID_BACKENDS: &[&str] = &["rustcrypto", "awslc"];
/// Valid audit log levels.
const VALID_LOG_LEVELS: &[&str] = &["all", "crypto", "auth", "admin", "none"];
/// Relative path prefixes that could target sensitive directories.
const SENSITIVE_PATH_PREFIXES: &[&str] = &[".git", ".ssh", ".gnupg", ".aws", ".config", ".env"];

#[derive(Debug, Deserialize, Clone, Default)]
pub struct HsmConfig {
    #[serde(default)]
    pub token: TokenConfig,
    #[serde(default)]
    pub security: SecurityConfig,
    #[serde(default)]
    pub audit: AuditConfig,
    #[serde(default)]
    pub algorithms: AlgorithmConfig,
}

#[derive(Debug, Deserialize, Clone)]
pub struct TokenConfig {
    #[serde(default = "default_label")]
    pub label: String,
    #[serde(default = "default_storage_path")]
    pub storage_path: PathBuf,
    #[serde(default = "default_max_sessions")]
    pub max_sessions: u64,
    #[serde(default = "default_max_rw_sessions")]
    pub max_rw_sessions: u64,
    /// If true, token objects (CKA_TOKEN=true) are persisted to disk
    /// via EncryptedStore. Session objects are never persisted.
    /// Default: false (in-memory only, matching legacy behavior).
    #[serde(default)]
    pub persist_objects: bool,
    /// Number of slots to create. Default: 1 (backward compatible).
    /// Each slot gets its own independent token.
    #[serde(default = "default_slot_count")]
    pub slot_count: usize,
    /// Token serial number (16-char string, space-padded).
    /// Should be unique per deployment. Default: "0000000000000001".
    #[serde(default = "default_serial_number")]
    pub serial_number: String,
}

#[derive(Deserialize, Clone)]
pub struct SecurityConfig {
    #[serde(default = "default_pin_min")]
    pub pin_min_length: usize,
    #[serde(default = "default_pin_max")]
    pub pin_max_length: usize,
    #[serde(default = "default_max_failed")]
    pub max_failed_logins: u32,
    #[serde(default = "default_pbkdf2_iterations")]
    pub pbkdf2_iterations: u32,
}

// Custom Debug to avoid leaking security parameters in logs/panics.
impl fmt::Debug for SecurityConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SecurityConfig")
            .field("pin_min_length", &"[REDACTED]")
            .field("pin_max_length", &"[REDACTED]")
            .field("max_failed_logins", &"[REDACTED]")
            .field("pbkdf2_iterations", &"[REDACTED]")
            .finish()
    }
}

#[derive(Debug, Deserialize, Clone)]
pub struct AuditConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default = "default_audit_path")]
    pub log_path: PathBuf,
    #[serde(default = "default_log_level")]
    pub log_level: String,
}

#[derive(Debug, Deserialize, Clone)]
pub struct AlgorithmConfig {
    #[serde(default)]
    pub allow_weak_rsa: bool,
    #[serde(default)]
    pub allow_sha1_signing: bool,
    #[serde(default = "default_true")]
    pub enable_pqc: bool,
    /// Crypto backend: "rustcrypto" (default) or "awslc".
    /// Only effective when the corresponding feature is compiled in.
    #[serde(default = "default_crypto_backend")]
    pub crypto_backend: String,
    /// When true, only FIPS 140-3 approved algorithms are permitted.
    /// Non-approved mechanisms (e.g., EdDSA, SHA-1 signing) are blocked.
    /// PQC mechanisms are also blocked (not yet FIPS-approved).
    #[serde(default)]
    pub fips_approved_only: bool,
    /// When true, secret keys produced by key derivation (`C_DeriveKey`,
    /// the daemon `DeriveKey` RPC) whose template leaves `CKA_SENSITIVE` /
    /// `CKA_EXTRACTABLE` unset default to non-sensitive and extractable, so
    /// callers that read the derived secret back without asking for it
    /// (e.g. Java SunPKCS11 `KeyAgreement`) work without extra configuration.
    ///
    /// Default false: derived keys are sensitive and non-extractable unless
    /// the template says otherwise. Not permitted with `fips_approved_only`.
    #[serde(default)]
    pub derived_keys_extractable_by_default: bool,
}

impl AlgorithmConfig {
    /// Effective default for derived keys: extractable (and non-sensitive)
    /// only when enabled and the token is not in FIPS-approved mode.
    pub fn derived_keys_default_extractable(&self) -> bool {
        self.derived_keys_extractable_by_default && !self.fips_approved_only
    }
}

impl Default for TokenConfig {
    fn default() -> Self {
        Self {
            label: default_label(),
            storage_path: default_storage_path(),
            max_sessions: default_max_sessions(),
            max_rw_sessions: default_max_rw_sessions(),
            persist_objects: false,
            slot_count: default_slot_count(),
            serial_number: default_serial_number(),
        }
    }
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            pin_min_length: default_pin_min(),
            pin_max_length: default_pin_max(),
            max_failed_logins: default_max_failed(),
            pbkdf2_iterations: default_pbkdf2_iterations(),
        }
    }
}

impl Default for AuditConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            log_path: default_audit_path(),
            log_level: default_log_level(),
        }
    }
}

impl Default for AlgorithmConfig {
    fn default() -> Self {
        Self {
            allow_weak_rsa: false,
            allow_sha1_signing: false,
            enable_pqc: true,
            crypto_backend: default_crypto_backend(),
            fips_approved_only: false,
            derived_keys_extractable_by_default: false,
        }
    }
}

fn default_label() -> String {
    "Craton HSM Token 0".to_string()
}
/// Relative fallback used by `default_storage_path` when the platform
/// default system directory does not exist. Kept as a constant so tests
/// and other callers can refer to it without duplicating the literal.
const RELATIVE_STORAGE_FALLBACK: &str = "craton_hsm_store";

/// Default storage path for the encrypted token store.
///
/// Picks a platform-appropriate absolute system directory when it exists at
/// startup:
///   - Unix:    `/var/lib/craton-hsm/store`
///   - Windows: `%PROGRAMDATA%\craton-hsm\store`
///
/// If that directory is not present we deliberately do *not* try to create
/// it — provisioning system directories is a deployment concern, not a
/// library concern. Instead we fall back to the legacy CWD-relative
/// `craton_hsm_store` and emit a `tracing::warn!` so operators notice that
/// a non-stable default is in use.
fn default_storage_path() -> PathBuf {
    if let Some(system_default) = platform_default_storage_dir() {
        // Use the system directory only when its parent exists, so we do not
        // hand out a path the daemon cannot create on first run. We check the
        // parent rather than the leaf so a fresh install that has the parent
        // (e.g. `/var/lib/craton-hsm`) provisioned but no `store` subdir yet
        // still gets the stable absolute default.
        let parent_exists = system_default.parent().map(|p| p.is_dir()).unwrap_or(false);
        if parent_exists {
            return system_default;
        }
        tracing::warn!(
            "default storage parent directory '{}' does not exist — falling back to relative '{}' \
             (a process-CWD-relative store is a privesc foothold; configure storage_path \
             explicitly or provision the system directory)",
            system_default.display(),
            RELATIVE_STORAGE_FALLBACK
        );
    }
    PathBuf::from(RELATIVE_STORAGE_FALLBACK)
}

/// Canonicalize the deepest existing prefix of `path` and append the
/// remaining non-existent tail components verbatim.
///
/// `std::fs::canonicalize` fails if any component does not exist, but we
/// need to validate paths whose leaf (and possibly the last few directories)
/// have not been created yet — `storage_path` on first run is exactly that
/// shape. We walk from the leaf up, find the deepest ancestor that exists,
/// canonicalize *that*, and stitch the non-existent suffix back on.
///
/// On any unexpected error we fall back to returning the original path —
/// the caller's other checks (raw-component `..` scan, symlink walk) still
/// run, so this never weakens validation.
fn canonicalize_deepest_existing(path: &Path) -> PathBuf {
    // Walk up ancestors looking for the first one that exists. `ancestors()`
    // yields the path itself first, then its parent, then grandparent, …,
    // ending with the root (or "" for empty/relative-only paths).
    for ancestor in path.ancestors() {
        if ancestor.as_os_str().is_empty() {
            continue;
        }
        if let Ok(canon) = std::fs::canonicalize(ancestor) {
            // Strip the existing-prefix from the original path; whatever
            // remains is the not-yet-created suffix we append back on.
            if let Ok(suffix) = path.strip_prefix(ancestor) {
                let mut out = canon;
                out.push(suffix);
                return out;
            }
            return canon;
        }
    }
    path.to_path_buf()
}

/// Resolve the platform-default absolute storage directory.
///
/// Returns `None` on platforms where we do not have a sensible system-wide
/// default (so callers fall back to the relative path).
fn platform_default_storage_dir() -> Option<PathBuf> {
    #[cfg(unix)]
    {
        Some(PathBuf::from("/var/lib/craton-hsm/store"))
    }
    #[cfg(windows)]
    {
        std::env::var_os("PROGRAMDATA").map(|pd| {
            let mut p = PathBuf::from(pd);
            p.push("craton-hsm");
            p.push("store");
            p
        })
    }
    #[cfg(not(any(unix, windows)))]
    {
        None
    }
}
fn default_max_sessions() -> u64 {
    100
}
fn default_max_rw_sessions() -> u64 {
    10
}
fn default_pin_min() -> usize {
    8
}
fn default_pin_max() -> usize {
    64
}
fn default_max_failed() -> u32 {
    10
}
fn default_pbkdf2_iterations() -> u32 {
    if cfg!(debug_assertions) {
        1
    } else {
        600_000
    }
}
fn default_true() -> bool {
    true
}
fn default_audit_path() -> PathBuf {
    PathBuf::from("craton_hsm_audit.jsonl")
}
fn default_log_level() -> String {
    "all".to_string()
}
fn default_crypto_backend() -> String {
    "rustcrypto".to_string()
}
fn default_slot_count() -> usize {
    1
}
fn default_serial_number() -> String {
    "0000000000000001".to_string()
}

impl HsmConfig {
    /// Load configuration, returning an error if the config file exists but is
    /// invalid or fails validation. Falls back to defaults only when no config
    /// file is present.
    pub fn load() -> Result<Self, HsmError> {
        // In FIPS mode, use hardcoded secure defaults — never read from filesystem
        // to prevent an attacker from planting a permissive config file.
        #[cfg(feature = "fips")]
        {
            tracing::warn!(
                "FIPS mode active (compile-time, `--features fips`) — using hardcoded secure \
                 defaults and IGNORING craton_hsm.toml entirely, including persist_objects, \
                 storage_path, and all other settings. If you need persistence or other \
                 non-default settings in FIPS mode, build without the `fips` feature (note that \
                 `--all-features` includes it)."
            );
            if std::path::Path::new("craton_hsm.toml").exists() {
                tracing::warn!("craton_hsm.toml exists but is being ignored in FIPS mode");
            }
            return Ok(Self::fips_defaults());
        }

        #[cfg(not(feature = "fips"))]
        {
            if std::env::var("CRATON_HSM_FIPS").as_deref() == Ok("1") {
                // SECURITY WARNING: Environment-variable FIPS mode is ADVISORY ONLY.
                //
                // An attacker who can modify the process environment (e.g. via
                // /proc/pid/environ, LD_PRELOAD, or parent-process control) can:
                //   1. Unset CRATON_HSM_FIPS to disable FIPS mode entirely.
                //   2. Set CRATON_HSM_CONFIG to load a permissive configuration.
                //
                // For certified FIPS 140-3 compliance, you MUST compile with
                // `--features fips` which hardcodes secure defaults at compile time
                // and cannot be bypassed at runtime.
                //
                // This env-var path exists only as a convenience for development and
                // testing. Do NOT rely on it for production FIPS compliance.
                tracing::warn!(
                    "FIPS mode activated via CRATON_HSM_FIPS env var. \
                     SECURITY: env-var FIPS is ADVISORY ONLY — an attacker who can modify \
                     the process environment can bypass this entirely. For certified FIPS \
                     compliance, compile with `--features fips`."
                );
                if std::path::Path::new("craton_hsm.toml").exists() {
                    tracing::warn!("craton_hsm.toml exists but is being ignored in FIPS mode");
                }
                return Ok(Self::fips_defaults());
            }

            let config_path = std::env::var("CRATON_HSM_CONFIG")
                .unwrap_or_else(|_| "craton_hsm.toml".to_string());

            Self::validate_config_path(&config_path)?;

            let config = Self::load_from_path(&config_path)?;
            config.validate()?;
            Ok(config)
        }
    }

    /// FIPS-hardened defaults: audit enabled, no weak algorithms, approved-only.
    fn fips_defaults() -> Self {
        let mut config = Self::default();
        config.algorithms.fips_approved_only = true;
        config.algorithms.allow_weak_rsa = false;
        config.algorithms.allow_sha1_signing = false;
        config.algorithms.enable_pqc = false;
        config.audit.enabled = true;
        config
    }

    /// Validate that a filesystem path is safe.
    ///
    /// Accepts both absolute and CWD-relative paths. Absolute paths are
    /// required for production deployments (a CWD-relative store is a common
    /// privesc foothold), but relative paths are still honoured for
    /// backward compatibility and resolved against the process working
    /// directory by the consumer.
    ///
    /// Rejects:
    ///   * UNC paths (`\\server\share`, `//server/share`).
    ///   * Null bytes anywhere in the path string.
    ///   * `..` traversal components (checked both before and after
    ///     canonicalization of the deepest existing prefix).
    ///   * Any component that is a symlink — symlinks are a TOCTOU footgun
    ///     for security-sensitive state. Operators who need to relocate the
    ///     store should configure `storage_path` directly instead of
    ///     introducing a symlink the daemon must trust.
    ///   * First component matching a known sensitive directory
    ///     (`.git`, `.ssh`, …) for relative paths.
    ///
    /// `label` is used in error messages (e.g. "config path", "storage_path").
    fn validate_path_safety(path: &Path, label: &str) -> Result<(), Vec<String>> {
        let mut errors: Vec<String> = Vec::new();
        let path_str = path.to_string_lossy();

        if path_str.starts_with("\\\\") || path_str.starts_with("//") {
            errors.push(format!(
                "{} '{}' is a UNC path — not permitted",
                label, path_str
            ));
        }
        for component in path.components() {
            if let std::path::Component::ParentDir = component {
                errors.push(format!(
                    "{} '{}' contains '..' traversal component",
                    label, path_str
                ));
                break;
            }
        }
        if path_str.contains('\0') {
            errors.push(format!("{} contains null byte", label));
        }

        // Reject relative paths whose first component targets a known
        // sensitive directory. We only check this on relative paths because
        // an absolute path's first component is the root (`/` or `C:\`),
        // which is never a sensitive-name match.
        if path.is_relative() {
            if let Some(first) = path.components().next() {
                let first_str = first.as_os_str().to_string_lossy();
                for prefix in SENSITIVE_PATH_PREFIXES {
                    if first_str.eq_ignore_ascii_case(prefix) {
                        errors.push(format!(
                            "{} '{}' targets sensitive directory '{}'",
                            label, path_str, prefix
                        ));
                        break;
                    }
                }
            }
        }

        // Walk every ancestor that already exists and reject if any link in
        // the chain is a symlink. This covers the case where the leaf does
        // not exist yet (typical on first-run for storage_path) but a parent
        // does, as well as the existing-leaf case the old check handled.
        // We deliberately reject *any* symlink rather than trying to enforce
        // an allowed-root policy — operators can configure storage_path
        // directly to the real location.
        if let Err(sym_errs) = Self::reject_symlinks_on_path(path, label) {
            errors.extend(sym_errs);
        }

        // After resolving symlinks on the deepest existing prefix, ensure no
        // `..` survives. canonicalize collapses traversal, so a path that
        // canonicalizes to something different from its lexical join is a
        // sign of either symlinks (already caught) or weirdness we don't
        // want. The component-level `..` check above already rejects raw
        // traversal; this is a belt-and-braces sanity check.
        let canonical = canonicalize_deepest_existing(path);
        for component in canonical.components() {
            if let std::path::Component::ParentDir = component {
                errors.push(format!(
                    "{} '{}' canonicalizes to a path containing '..'",
                    label, path_str
                ));
                break;
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Reject the path if any existing component (the leaf or any ancestor)
    /// is a symlink. Non-existent tail components are skipped — they cannot
    /// be symlinks yet, and the deepest-existing-prefix is what
    /// canonicalization would resolve.
    fn reject_symlinks_on_path(path: &Path, label: &str) -> Result<(), Vec<String>> {
        let mut errors: Vec<String> = Vec::new();
        let mut acc = PathBuf::new();
        for component in path.components() {
            acc.push(component.as_os_str());
            // `symlink_metadata` does NOT follow the final component, which
            // is exactly what we want here — we're checking each step.
            match std::fs::symlink_metadata(&acc) {
                Ok(meta) if meta.file_type().is_symlink() => {
                    errors.push(format!(
                        "{} '{}' contains a symlink component at '{}' — not permitted",
                        label,
                        path.to_string_lossy(),
                        acc.display()
                    ));
                    // One error is enough; the path is rejected.
                    return Err(errors);
                }
                Ok(_) => {}
                Err(_) => {
                    // Component does not exist yet (or is unreadable). Stop
                    // walking — anything below this point cannot be a
                    // symlink on disk because it does not exist.
                    break;
                }
            }
        }
        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    /// Validate the config file path from CRATON_HSM_CONFIG env var.
    fn validate_config_path(path: &str) -> Result<(), HsmError> {
        let p = std::path::Path::new(path);
        if let Err(errs) = Self::validate_path_safety(p, "config path") {
            let msg = errs.join("; ");
            tracing::error!("Config path validation failed: {}", msg);
            return Err(HsmError::ConfigError(msg));
        }
        Ok(())
    }

    /// Check file permissions on the already-opened file to reject insecure
    /// ownership or write permissions, mitigating config-planting attacks.
    ///
    /// On Unix: rejects group-writable or world-writable files.
    /// On Windows: rejects files writable by the Everyone or Users groups.
    fn check_file_permissions(file: &std::fs::File, path: &str) -> Result<(), HsmError> {
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            let meta = file.metadata().map_err(|e| {
                HsmError::ConfigError(format!("cannot stat config file '{}': {}", path, e))
            })?;
            let mode = meta.mode();
            // Reject group-writable (0o020) or other-writable (0o002)
            if mode & 0o022 != 0 {
                tracing::error!(
                    "Config file '{}' has insecure permissions {:o} — \
                     must not be group- or world-writable",
                    path,
                    mode & 0o777
                );
                return Err(HsmError::ConfigError(format!(
                    "config file has insecure permissions ({:o}); \
                     must not be group- or world-writable",
                    mode & 0o777
                )));
            }
        }

        #[cfg(windows)]
        {
            Self::check_windows_permissions(file, path)?;
        }

        #[cfg(not(any(unix, windows)))]
        {
            let _ = (file, path);
        }

        Ok(())
    }

    /// Windows-specific permission check: reject files writable by broad groups.
    /// Uses the file's metadata to verify the read-only attribute as a baseline,
    /// and checks NTFS ACLs via icacls on the canonical path.
    #[cfg(windows)]
    fn check_windows_permissions(_file: &std::fs::File, path: &str) -> Result<(), HsmError> {
        // Check NTFS ACLs via icacls for broad write access.
        // Resolve the canonical path from the open handle to avoid TOCTOU on
        // the path string (the handle is already pinned to an inode).
        let canonical = match std::fs::canonicalize(path) {
            Ok(p) => p,
            Err(_) => {
                // If canonicalize fails, fall through — the file is already open.
                return Ok(());
            }
        };
        let output = std::process::Command::new("icacls")
            .arg(&canonical)
            .output();
        if let Ok(output) = output {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stdout_upper = stdout.to_uppercase();
            // Reject if Everyone, Users, or Authenticated Users have write/full access.
            let dangerous_principals =
                ["EVERYONE", "USERS", "AUTHENTICATED USERS", "BUILTIN\\USERS"];
            let dangerous_perms = ["(F)", "(M)", "(W)"];
            for line in stdout_upper.lines() {
                for principal in &dangerous_principals {
                    if line.contains(principal) {
                        for perm in &dangerous_perms {
                            if line.contains(perm) {
                                tracing::error!(
                                    "Config file '{}' has insecure ACL — {} has write access",
                                    path,
                                    principal
                                );
                                return Err(HsmError::ConfigError(format!(
                                    "config file has insecure permissions; \
                                     {} has write access — restrict to owner only",
                                    principal
                                )));
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Check that an already-opened file is not a symlink, using the file
    /// handle's metadata to avoid TOCTOU races.
    fn check_file_not_symlink(file: &std::fs::File, path: &str) -> Result<(), HsmError> {
        let meta = file.metadata().map_err(|e| {
            HsmError::ConfigError(format!("cannot stat config file '{}': {}", path, e))
        })?;

        // On Unix, also check via symlink_metadata on the path as a defense-in-depth
        // measure (the open fd is authoritative, but this catches broken symlinks).
        #[cfg(unix)]
        {
            if let Ok(link_meta) = std::fs::symlink_metadata(path) {
                if link_meta.file_type().is_symlink() {
                    tracing::error!(
                        "Config file '{}' is a symlink — not permitted for security files",
                        path
                    );
                    return Err(HsmError::ConfigError(
                        "config file is a symlink — not permitted".to_string(),
                    ));
                }
            }
        }

        let _ = meta;
        Ok(())
    }

    /// Load from a specific path. Returns defaults if the file does not exist.
    /// Returns an error if the file exists but cannot be parsed.
    ///
    /// Opens the file first, then performs permission and symlink checks on the
    /// open file descriptor to eliminate TOCTOU race conditions.
    pub fn load_from_path(path: &str) -> Result<Self, HsmError> {
        use std::io::Read;

        let file = match std::fs::File::open(path) {
            Ok(f) => f,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                tracing::info!("No config file at '{}' — using secure defaults", path);
                return Ok(Self::default());
            }
            Err(e) => {
                tracing::error!("Cannot read config file '{}': {}", path, e);
                return Err(HsmError::ConfigError(
                    "cannot read config file — check logs for details".to_string(),
                ));
            }
        };

        // All checks use the open file descriptor — no TOCTOU window.
        Self::check_file_not_symlink(&file, path)?;
        Self::check_file_permissions(&file, path)?;

        let mut content = String::new();
        let mut reader = std::io::BufReader::new(file);
        reader.read_to_string(&mut content).map_err(|e| {
            tracing::error!("Cannot read config file '{}': {}", path, e);
            HsmError::ConfigError("cannot read config file — check logs for details".to_string())
        })?;

        toml::from_str(&content).map_err(|e| {
            // Log full details internally; return sanitized error to caller
            tracing::error!(
                "Failed to parse config file '{}': {} — refusing to start with potentially \
                 misconfigured security parameters",
                path,
                e
            );
            HsmError::ConfigError(
                "failed to parse config file — check logs for details".to_string(),
            )
        })
    }

    /// Comprehensive validation of all security-critical configuration values.
    /// Called automatically by `load()`.
    pub fn validate(&self) -> Result<(), HsmError> {
        let mut errors: Vec<String> = Vec::new();

        // --- storage_path: reject absolute, traversal, UNC, null bytes, symlinks, sensitive dirs ---
        if let Err(path_errs) = Self::validate_path_safety(&self.token.storage_path, "storage_path")
        {
            errors.extend(path_errs);
        }

        // --- audit log_path: same checks ---
        if let Err(path_errs) = Self::validate_path_safety(&self.audit.log_path, "audit log_path") {
            errors.extend(path_errs);
        }

        // --- token label: PKCS#11 requires <= 32 bytes, printable ASCII only ---
        if self.token.label.is_empty() {
            errors.push("token label must not be empty".to_string());
        }
        if self.token.label.len() > MAX_LABEL_LENGTH {
            errors.push(format!(
                "token label '{}' exceeds {} bytes (PKCS#11 CK_TOKEN_INFO.label limit)",
                self.token.label, MAX_LABEL_LENGTH
            ));
        }
        if !self
            .token
            .label
            .bytes()
            .all(|b| b.is_ascii_graphic() || b == b' ')
        {
            errors.push("token label contains non-printable or non-ASCII characters".to_string());
        }

        // --- PIN length bounds ---
        if self.security.pin_min_length < MIN_PIN_LENGTH {
            errors.push(format!(
                "pin_min_length ({}) is below the minimum of {}",
                self.security.pin_min_length, MIN_PIN_LENGTH
            ));
        }
        if self.security.pin_max_length < self.security.pin_min_length {
            errors.push(format!(
                "pin_max_length ({}) is less than pin_min_length ({})",
                self.security.pin_max_length, self.security.pin_min_length
            ));
        }
        if self.security.pin_max_length > MAX_PIN_LENGTH {
            errors.push(format!(
                "pin_max_length ({}) exceeds the maximum of {} (risk of memory exhaustion during PIN hashing)",
                self.security.pin_max_length, MAX_PIN_LENGTH
            ));
        }

        // --- PBKDF2 iterations bounds ---
        if self.security.pbkdf2_iterations < MIN_PBKDF2_ITERATIONS {
            errors.push(format!(
                "pbkdf2_iterations ({}) is below the minimum of {}",
                self.security.pbkdf2_iterations, MIN_PBKDF2_ITERATIONS
            ));
        }
        if self.security.pbkdf2_iterations > MAX_PBKDF2_ITERATIONS {
            errors.push(format!(
                "pbkdf2_iterations ({}) exceeds the maximum of {} (risk of algorithmic DoS)",
                self.security.pbkdf2_iterations, MAX_PBKDF2_ITERATIONS
            ));
        }

        // --- max_failed_logins bounds ---
        if self.security.max_failed_logins < MIN_FAILED_LOGINS {
            errors.push(format!(
                "max_failed_logins ({}) is below the minimum of {} (risk of accidental lockout)",
                self.security.max_failed_logins, MIN_FAILED_LOGINS
            ));
        }
        if self.security.max_failed_logins > MAX_FAILED_LOGINS {
            errors.push(format!(
                "max_failed_logins ({}) exceeds the maximum of {} (risk of brute-force)",
                self.security.max_failed_logins, MAX_FAILED_LOGINS
            ));
        }

        // --- serial_number format (PKCS#11 requires 16-char space-padded) ---
        if self.token.serial_number.is_empty() {
            errors.push("serial_number must not be empty".to_string());
        }
        if self.token.serial_number.len() > 16 {
            errors.push(format!(
                "serial_number '{}' exceeds 16 characters",
                self.token.serial_number
            ));
        }
        if !self
            .token
            .serial_number
            .bytes()
            .all(|b| b.is_ascii_graphic() || b == b' ')
        {
            errors.push("serial_number contains non-printable or non-ASCII characters".to_string());
        }

        // --- session count bounds ---
        if self.token.max_sessions == 0 {
            errors.push("max_sessions must be at least 1".to_string());
        }
        if self.token.max_sessions > MAX_SESSIONS {
            errors.push(format!(
                "max_sessions ({}) exceeds the maximum of {} (risk of resource exhaustion)",
                self.token.max_sessions, MAX_SESSIONS
            ));
        }
        if self.token.max_rw_sessions == 0 {
            errors.push("max_rw_sessions must be at least 1".to_string());
        }
        if self.token.max_rw_sessions > self.token.max_sessions {
            errors.push(format!(
                "max_rw_sessions ({}) exceeds max_sessions ({})",
                self.token.max_rw_sessions, self.token.max_sessions
            ));
        }

        // --- slot_count sanity ---
        if self.token.slot_count == 0 {
            errors.push("slot_count must be at least 1".to_string());
        }
        if self.token.slot_count > MAX_SLOT_COUNT {
            errors.push(format!(
                "slot_count ({}) exceeds the maximum of {} (risk of resource exhaustion)",
                self.token.slot_count, MAX_SLOT_COUNT
            ));
        }

        // --- crypto_backend must be a known identifier ---
        if !VALID_BACKENDS.contains(&self.algorithms.crypto_backend.as_str()) {
            errors.push(format!(
                "crypto_backend '{}' is not recognized (valid: {:?})",
                self.algorithms.crypto_backend, VALID_BACKENDS
            ));
        }

        // --- log_level must be a known identifier ---
        if !VALID_LOG_LEVELS.contains(&self.audit.log_level.as_str()) {
            errors.push(format!(
                "audit log_level '{}' is not recognized (valid: {:?})",
                self.audit.log_level, VALID_LOG_LEVELS
            ));
        }

        // --- FIPS consistency: reject contradictory weak-algorithm flags ---
        if self.algorithms.fips_approved_only {
            if self.algorithms.allow_weak_rsa {
                errors.push(
                    "allow_weak_rsa cannot be true when fips_approved_only is enabled".to_string(),
                );
            }
            if self.algorithms.allow_sha1_signing {
                errors.push(
                    "allow_sha1_signing cannot be true when fips_approved_only is enabled"
                        .to_string(),
                );
            }
            if !self.audit.enabled {
                errors.push("audit must be enabled when fips_approved_only is active".to_string());
            }
            if self.algorithms.derived_keys_extractable_by_default {
                errors.push(
                    "derived_keys_extractable_by_default cannot be true when fips_approved_only is enabled"
                        .to_string(),
                );
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            let msg = errors.join("; ");
            tracing::error!("Configuration validation failed: {}", msg);
            Err(HsmError::ConfigError(msg))
        }
    }
}

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

    #[test]
    fn derived_keys_extractable_by_default_rejected_in_fips_mode() {
        let mut config = HsmConfig::default();
        config.algorithms.derived_keys_extractable_by_default = true;
        assert!(config.validate().is_ok());
        assert!(config.algorithms.derived_keys_default_extractable());

        config.algorithms.fips_approved_only = true;
        assert!(config.validate().is_err());
        // Even if validation were bypassed, FIPS mode forces it off.
        assert!(!config.algorithms.derived_keys_default_extractable());
    }

    /// Build a unique tempdir path so concurrent tests do not collide.
    ///
    /// On Unix we canonicalize the base so the symlink walk does not trip on
    /// platforms where `/var` or similar is itself a symlink (notably macOS,
    /// where `/var -> /private/var`). On Windows we deliberately *do not*
    /// canonicalize, because `std::fs::canonicalize` returns the extended-
    /// length `\\?\C:\…` form which our validator treats as a UNC path —
    /// real operators pass `C:\ProgramData\…` style paths, not the `\\?\`
    /// form, so the test should mirror that.
    fn unique_tempdir(tag: &str) -> PathBuf {
        #[cfg(unix)]
        let base = std::fs::canonicalize(std::env::temp_dir())
            .expect("temp_dir must exist and be canonicalizable");
        #[cfg(not(unix))]
        let base = std::env::temp_dir();
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let dir = base.join(format!(
            "craton-hsm-cfg-{}-{}-{}",
            tag,
            std::process::id(),
            nanos
        ));
        std::fs::create_dir_all(&dir).expect("can create tempdir");
        dir
    }

    #[test]
    fn absolute_path_with_no_symlinks_is_accepted() {
        // The whole point of this change: a stable absolute storage path
        // must validate cleanly.
        let dir = unique_tempdir("abs-ok");
        let leaf = dir.join("store");
        // Leaf does not exist; that's fine — first-run shape.
        let res = HsmConfig::validate_path_safety(&leaf, "storage_path");
        assert!(
            res.is_ok(),
            "expected absolute path to be accepted: {:?}",
            res
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[cfg(unix)]
    #[test]
    fn absolute_path_with_symlink_component_is_rejected() {
        use std::os::unix::fs::symlink;
        let dir = unique_tempdir("abs-symlink");
        // Real target dir and a symlink that points at it.
        let real = dir.join("real");
        std::fs::create_dir(&real).expect("create real");
        let link = dir.join("link");
        symlink(&real, &link).expect("create symlink");

        // Path that traverses the symlink: should be rejected.
        let candidate = link.join("store");
        let res = HsmConfig::validate_path_safety(&candidate, "storage_path");
        assert!(
            res.is_err(),
            "expected symlink-containing path to be rejected: {:?}",
            res
        );
        let errs = res.unwrap_err();
        assert!(
            errs.iter().any(|e| e.contains("symlink")),
            "expected a symlink-related error, got: {:?}",
            errs
        );

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn relative_path_is_still_accepted() {
        // Backwards compatibility: the legacy CWD-relative default must
        // continue to validate.
        let res =
            HsmConfig::validate_path_safety(Path::new(RELATIVE_STORAGE_FALLBACK), "storage_path");
        assert!(res.is_ok(), "expected relative default to pass: {:?}", res);
    }

    #[test]
    fn parent_dir_component_is_rejected() {
        // Raw `..` traversal is still rejected, regardless of whether the
        // path is absolute or relative.
        let res = HsmConfig::validate_path_safety(Path::new("../../etc/shadow"), "storage_path");
        assert!(res.is_err(), "expected '..' traversal to be rejected");
        let errs = res.unwrap_err();
        assert!(
            errs.iter().any(|e| e.contains("'..'")),
            "expected a traversal-related error, got: {:?}",
            errs
        );
    }

    #[cfg(unix)]
    #[test]
    fn absolute_path_with_parent_dir_is_rejected() {
        // `..` in an absolute path is also rejected.
        let res = HsmConfig::validate_path_safety(
            Path::new("/var/lib/craton-hsm/../passwd"),
            "storage_path",
        );
        assert!(
            res.is_err(),
            "expected absolute '..' traversal to be rejected"
        );
    }

    #[test]
    fn canonicalize_deepest_existing_handles_missing_leaf() {
        let dir = unique_tempdir("canon");
        let missing = dir.join("nope").join("deeper");
        let canon = canonicalize_deepest_existing(&missing);
        // The existing prefix must be canonicalized (i.e. resolved), and
        // the missing tail must be preserved verbatim.
        assert!(canon.ends_with("nope/deeper") || canon.ends_with("nope\\deeper"));
        let _ = std::fs::remove_dir_all(&dir);
    }
}