envseal 0.3.14

Write-only secret vault with process-level access control — post-agent secret management
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
//! CTF (capture-the-flag) operations — built-in security challenge.
//!
//! Stores a sealed random flag and exposes its public verification
//! hash so anyone can verify a submitted flag without unlocking the
//! vault. Setup applies the Lockdown preset so the challenge exercises
//! the full security stack.
//!
//! Re-exported from [`super`] for backwards compatibility.

use std::path::{Path, PathBuf};

use crate::error::Error;
use crate::vault::Vault;

/// Result of CTF setup.
#[derive(Debug, Clone)]
pub struct CtfSetupResult {
    /// SHA-256 verification hash of the flag.
    pub hash: String,
    /// Path where the hash was saved.
    pub hash_path: PathBuf,
}

/// Result of CTF verification.
#[derive(Debug, Clone)]
pub enum CtfVerifyResult {
    /// Flag is correct.
    Correct {
        /// The submitted flag.
        flag: String,
        /// Its SHA-256 hash.
        hash: String,
    },
    /// Flag is incorrect.
    Incorrect {
        /// Hash of the submitted value.
        submitted_hash: String,
        /// Expected hash.
        expected_hash: String,
    },
}

/// CTF challenge status.
#[derive(Debug, Clone)]
pub enum CtfStatus {
    /// Challenge is active.
    Active {
        /// Verification hash.
        hash: String,
        /// Security tier.
        tier: String,
    },
    /// Flag exists but no verification hash.
    Partial,
    /// No challenge.
    Inactive,
}

/// Verdict for a single hardening check in [`CtfDoctorReport`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DoctorCheck {
    /// Check passed — this defense is engaged.
    Ok(String),
    /// Check failed — this defense is NOT engaged. Brings down the
    /// CTF integrity claim. Carries a remediation hint.
    Fail(String),
    /// Check is not applicable on this platform / build.
    NotApplicable(String),
}

impl DoctorCheck {
    /// Convenience: `true` iff this check is `Fail(_)`.
    #[must_use]
    pub fn is_fail(&self) -> bool {
        matches!(self, Self::Fail(_))
    }
}

/// Output of [`ctf_doctor`] — a publishable hardening report. Each
/// field is a single check; aggregate `is_ready` collapses the
/// per-check verdicts. The CLI prints this verbatim so judges /
/// attackers can audit every defense status in one command.
#[derive(Debug, Clone)]
pub struct CtfDoctorReport {
    /// Hardware-sealed master key backend (DPAPI / Secure Enclave / TPM /
    /// none).
    pub backend: DoctorCheck,
    /// Linux: `kernel.yama.ptrace_scope` value. `Ok` if ≥ 1.
    pub ptrace_scope: DoctorCheck,
    /// Windows: process DACL denies `PROCESS_VM_READ` to non-SYSTEM.
    pub windows_dacl: DoctorCheck,
    /// macOS: hardened-runtime entitlement engaged on the running
    /// binary (gates `task_for_pid`).
    pub macos_hardened_runtime: DoctorCheck,
    /// `LD_PRELOAD` / `LD_AUDIT` not present at exec time.
    pub no_ld_preload: DoctorCheck,
    /// Linux: `memfd_secret` is available — master key lives in
    /// memory unmapped from the kernel's page tables.
    pub memfd_secret: DoctorCheck,
    /// CTF challenge is currently set up.
    pub challenge_active: DoctorCheck,
    /// `audit.log` exists and its hash chain verifies end-to-end
    /// (no rotated-corruption sibling, no broken prev hash). A
    /// missing chain or corrupted history breaks the central
    /// "every attempt is on the record" claim of the challenge.
    pub audit_chain_intact: DoctorCheck,
    /// `audit.key` exists and the per-vault audit cipher is
    /// active. Pre-0.3.13 vaults that haven't yet logged any event
    /// will not have this; a missing audit.key for a vault that
    /// HAS audit history means an operator deleted the cipher and
    /// every event is back to plaintext.
    pub audit_encryption: DoctorCheck,
    /// FIDO2 third-factor enrolled. The challenge holds even when
    /// the attacker captures the passphrase; without FIDO2 the
    /// passphrase is the cryptographic ceiling.
    pub fido2_enrolled: DoctorCheck,
    /// Aggregate readiness: every applicable check is `Ok`.
    pub is_ready: bool,
}

impl CtfDoctorReport {
    /// All checks in display order — used by the CLI to render the
    /// report without hard-coding field names.
    #[must_use]
    pub fn checks(&self) -> [(&'static str, &DoctorCheck); 10] {
        [
            ("hardware-sealed master key", &self.backend),
            ("Linux ptrace_scope", &self.ptrace_scope),
            ("Windows process DACL", &self.windows_dacl),
            ("macOS hardened runtime", &self.macos_hardened_runtime),
            ("LD_PRELOAD / LD_AUDIT", &self.no_ld_preload),
            ("Linux memfd_secret", &self.memfd_secret),
            ("CTF challenge active", &self.challenge_active),
            ("audit-log chain intact", &self.audit_chain_intact),
            ("audit-event encryption", &self.audit_encryption),
            ("FIDO2 third-factor enrolled", &self.fido2_enrolled),
        ]
    }
}

/// Audit every defense the CTF claim depends on, on the current
/// platform, with the vault currently open. Returns a per-check
/// verdict and an aggregate `is_ready` boolean. Pure read; never
/// mutates vault state.
///
/// Intentionally non-failing on individual checks — a single
/// `Fail` does not abort the doctor, because the operator needs
/// to see EVERY exposed surface in one pass, not learn about them
/// one cargo-cult fix at a time.
#[allow(clippy::too_many_lines)]
pub fn ctf_doctor(root: &Path) -> CtfDoctorReport {
    // Apply process hardening so the DACL / PR_SET_DUMPABLE checks
    // below report the steady-state values they would have during a
    // live CTF (any vault-opening subcommand calls harden_process at
    // startup; the doctor must not under-report by skipping it).
    crate::guard::harden_process();

    let backend = {
        let b = crate::keychain::active_backend();
        if b == crate::vault::hardware::Backend::None {
            DoctorCheck::Fail(format!(
                "no hardware backend ({}) — master.key is decryptable on any \
                 machine that copies it. Install TPM 2.0 + tpm2-tools (Linux), \
                 use the default DPAPI (Windows), or sign with Secure Enclave \
                 entitlement (macOS).",
                b.name()
            ))
        } else {
            DoctorCheck::Ok(format!("backend = {}", b.name()))
        }
    };

    let ptrace_scope = if cfg!(target_os = "linux") {
        match crate::guard::check_ptrace_scope() {
            None => DoctorCheck::Ok("ptrace_scope ≥ 1 (same-UID ptrace blocked)".to_string()),
            Some(detail) => DoctorCheck::Fail(detail),
        }
    } else {
        DoctorCheck::NotApplicable("ptrace_scope is a Linux concept".to_string())
    };

    let windows_dacl = if cfg!(windows) {
        if crate::guard::vm_read_access_blocked() {
            DoctorCheck::Ok(
                "PROCESS_VM_READ denied — same-user ReadProcessMemory is blocked".to_string(),
            )
        } else {
            DoctorCheck::Fail(
                "process DACL still grants PROCESS_VM_READ to the owner — \
                 a same-user attacker can ReadProcessMemory the unlocked \
                 master key. harden_process() may have failed at startup."
                    .to_string(),
            )
        }
    } else {
        DoctorCheck::NotApplicable("Windows DACL hardening is Windows-only".to_string())
    };

    #[cfg(target_os = "macos")]
    let macos_hardened_runtime = match crate::guard::check_macos_hardened_runtime() {
        Ok(()) => {
            DoctorCheck::Ok("hardened runtime engaged — task_for_pid denied by default".to_string())
        }
        Err(detail) => DoctorCheck::Fail(detail),
    };
    #[cfg(not(target_os = "macos"))]
    let macos_hardened_runtime =
        DoctorCheck::NotApplicable("hardened runtime is a macOS concept".to_string());

    let no_ld_preload = match crate::guard::check_self_preload() {
        Ok(()) => DoctorCheck::Ok("no LD_PRELOAD / LD_AUDIT in startup environ".to_string()),
        Err(e) => DoctorCheck::Fail(e.to_string()),
    };

    let memfd_secret = if cfg!(target_os = "linux") {
        if crate::guard::test_memfd_secret() {
            DoctorCheck::Ok("memfd_secret available — master key in unmapped pages".to_string())
        } else {
            DoctorCheck::Fail(
                "memfd_secret unavailable (kernel < 5.14 or CONFIG_SECRETMEM=n) — \
                 master key falls back to mlock-only protection."
                    .to_string(),
            )
        }
    } else {
        DoctorCheck::NotApplicable("memfd_secret is a Linux 5.14+ feature".to_string())
    };

    let audit_chain_intact = check_audit_chain_intact(root);
    let audit_encryption = check_audit_encryption_active(root);
    let fido2_enrolled = check_fido2_enrolled(root);

    let challenge_active = match ctf_status(root) {
        Ok(CtfStatus::Active { hash, tier }) => {
            DoctorCheck::Ok(format!("challenge active (tier={tier}, hash={hash})"))
        }
        Ok(CtfStatus::Partial) => DoctorCheck::Fail(
            "ctf-flag exists but ctf-hash.txt is missing — verifier cannot \
             check submissions. Run `envseal ctf reset` and `envseal ctf start`."
                .to_string(),
        ),
        Ok(CtfStatus::Inactive) => {
            DoctorCheck::Fail("no challenge set up — run `envseal ctf start` first.".to_string())
        }
        Err(e) => DoctorCheck::Fail(format!("status check failed: {e}")),
    };

    // `is_ready` covers HARDENING only — `challenge_active` is a
    // state, not a defense. A machine can be fully hardened with no
    // challenge set up; the verdict in that state should read
    // "ready, no challenge" not "exposed".
    let is_ready = ![
        &backend,
        &ptrace_scope,
        &windows_dacl,
        &macos_hardened_runtime,
        &no_ld_preload,
        &memfd_secret,
        &audit_chain_intact,
        &audit_encryption,
        &fido2_enrolled,
    ]
    .iter()
    .any(|c| c.is_fail());

    CtfDoctorReport {
        backend,
        ptrace_scope,
        windows_dacl,
        macos_hardened_runtime,
        no_ld_preload,
        memfd_secret,
        challenge_active,
        audit_chain_intact,
        audit_encryption,
        fido2_enrolled,
        is_ready,
    }
}

/// Walk the audit log chain end-to-end and report whether it
/// verifies. We use the same streaming verifier the writer uses
/// before each append, but here we only read. Missing log file is
/// also a fail — a CTF with no audit history can't claim "every
/// attempt is on the record."
fn check_audit_chain_intact(root: &Path) -> DoctorCheck {
    let log_path = root.join("audit.log");
    if !log_path.exists() {
        return DoctorCheck::Fail(
            "audit.log missing — without a chained record of attempts, the CTF \
             integrity claim is unverifiable."
                .to_string(),
        );
    }
    // A `.corrupted-*` sibling means the chain rotated due to
    // tamper or partial-write — flag it for forensic attention even
    // if the new chain is clean.
    let rotated = std::fs::read_dir(root).ok().is_some_and(|rd| {
        rd.filter_map(Result::ok).any(|e| {
            e.file_name()
                .to_string_lossy()
                .starts_with("audit.log.corrupted-")
        })
    });
    // Use the parsed reader: if any line failed to parse, the
    // dropped_lines counter surfaces it without us re-implementing
    // chain math here.
    let parsed = crate::audit::read_last_parsed_at(root, usize::MAX);
    if parsed.dropped_lines > 0 {
        return DoctorCheck::Fail(format!(
            "audit.log has {} unparseable line(s) — chain verification cannot \
             complete, run `envseal audit verify` for details",
            parsed.dropped_lines
        ));
    }
    if rotated {
        return DoctorCheck::Fail(
            "audit.log.corrupted-* sibling exists — a previous tamper or \
             partial-write triggered chain rotation. Inspect the rotated file \
             before claiming CTF integrity."
                .to_string(),
        );
    }
    DoctorCheck::Ok(format!(
        "chain verifies, {} entries on the record",
        parsed.entries.len()
    ))
}

/// Whether the per-vault `audit.key` file is present. Pre-0.3.13
/// vaults have no audit.key and write plaintext events; 0.3.13+
/// vaults generate one on first append. A missing key for a vault
/// that DOES have an audit.log means an operator deleted the
/// cipher and history is back to plaintext — exactly the threat
/// the encryption layer was added for.
fn check_audit_encryption_active(root: &Path) -> DoctorCheck {
    let key_path = root.join("audit.key");
    let log_path = root.join("audit.log");
    if !log_path.exists() {
        // No audit log means no encryption gap can exist yet.
        return DoctorCheck::NotApplicable(
            "audit.log not yet created — first append will generate audit.key".to_string(),
        );
    }
    if !key_path.exists() {
        return DoctorCheck::Fail(
            "audit.log exists but audit.key is missing — events on disk are \
             plaintext (legacy or post-deletion). Run `envseal audit migrate` \
             once it ships, or rotate the audit log to start a fresh \
             encrypted chain."
                .to_string(),
        );
    }
    DoctorCheck::Ok("per-vault audit cipher active (0.3.13+)".to_string())
}

/// Whether the master.key carries a FIDO2 v3 envelope. The doctor
/// reads master.key and inspects its inner shape via
/// `keychain::fido2_unlock::fido2_status_at`. Fail-closed if the
/// vault doesn't exist (the CTF can't be defended at all).
fn check_fido2_enrolled(root: &Path) -> DoctorCheck {
    let mk_path = root.join("master.key");
    if !mk_path.exists() {
        return DoctorCheck::Fail(
            "no master.key found — vault is uninitialized, CTF cannot be defended".to_string(),
        );
    }
    #[cfg(feature = "fido2")]
    {
        match crate::keychain::fido2_unlock::fido2_status_at(&mk_path) {
            Ok(crate::keychain::fido2_unlock::Fido2Status::Enrolled { credential_id }) => {
                use sha2::Digest;
                let hash = format!("{:x}", sha2::Sha256::digest(&credential_id));
                DoctorCheck::Ok(format!(
                    "FIDO2 v3 envelope (cred {})",
                    &hash[..hash.len().min(8)]
                ))
            }
            Ok(_) => DoctorCheck::Fail(
                "vault uses passphrase-only wrapping — captured-passphrase + \
                 file-exfil attack still wins. Run `envseal fido2 enroll`."
                    .to_string(),
            ),
            Err(e) => DoctorCheck::Fail(format!("FIDO2 status check failed: {e}")),
        }
    }
    #[cfg(not(feature = "fido2"))]
    {
        let _ = mk_path;
        DoctorCheck::NotApplicable(
            "this build was compiled without the `fido2` feature".to_string(),
        )
    }
}

/// Default-vault wrapper for [`ctf_doctor`].
///
/// # Errors
/// Returns vault-discovery errors only; the doctor itself never fails.
pub fn ctf_doctor_default() -> Result<CtfDoctorReport, Error> {
    let root = super::vault_root()?;
    Ok(ctf_doctor(&root))
}

/// Check CTF status (no passphrase needed).
pub fn ctf_status(root: &Path) -> Result<CtfStatus, Error> {
    let hash_path = root.join("ctf-hash.txt");
    crate::guard::verify_not_symlink(&hash_path)?;
    let has_flag = super::secret_exists(root, "ctf-flag")?;

    if has_flag && hash_path.exists() {
        let hash = {
            use std::io::Read;
            // Cap at 64 KiB. ctf-hash.txt is one 64-char hex line.
            let f = crate::file::atomic_open::open_read_no_traverse(&hash_path)?;
            let mut s = String::new();
            f.take(64 * 1024).read_to_string(&mut s)?;
            s.trim().to_string()
        };

        // The security config is now AES-256-GCM sealed
        // (`security.sealed`) — we can't read the actual tier here
        // without the master key, and `ctf status` is documented as
        // a no-passphrase command. Fall back to plaintext grep if a
        // legacy `security.toml` happens to be present (vault not
        // yet migrated); otherwise report the file shape rather than
        // a guess. The previous code defaulted to "Standard" when
        // the legacy file was absent, which was actively misleading
        // after every fresh `ctf start` (which ALWAYS applies
        // Lockdown).
        let sealed_path = root.join("security.sealed");
        let legacy_path = root.join("security.toml");
        let tier = if legacy_path.exists() {
            let content = {
                use std::io::Read;
                match crate::file::atomic_open::open_read_no_traverse(&legacy_path) {
                    Ok(f) => {
                        let mut s = String::new();
                        let _ = f.take(1024 * 1024).read_to_string(&mut s);
                        s
                    }
                    Err(_) => String::new(),
                }
            };
            if content.contains("Lockdown") {
                "Lockdown".to_string()
            } else if content.contains("Hardened") {
                "Hardened".to_string()
            } else {
                "Standard".to_string()
            }
        } else if sealed_path.exists() {
            // We know a config is set; we can't see WHICH tier
            // without unlock. `ctf start` always sets Lockdown, so
            // unless the operator changed it via `envseal security
            // set` the tier is Lockdown. Surface that honestly.
            "(sealed — unlock with `envseal security show` to view)".to_string()
        } else {
            "Standard (default — no config saved)".to_string()
        };

        Ok(CtfStatus::Active { hash, tier })
    } else if has_flag {
        Ok(CtfStatus::Partial)
    } else {
        Ok(CtfStatus::Inactive)
    }
}

/// Verify a submitted CTF flag (no passphrase needed).
///
/// Rate limited: every call sleeps for `VERIFY_RATE_LIMIT` before
/// returning a verdict, regardless of correctness. Even though the
/// hash compare is constant-time and the SHA-256 image space is
/// computationally infeasible to brute-force, the artificial delay:
/// (a) makes scripted high-volume attempts visibly slow,
/// (b) caps the audit-log spam rate from automated guessers, and
/// (c) leaves a per-attempt forensic trail that distinguishes
/// "operator typed a guess" from "agent submitted 10 million
/// attempts."
///
/// Every attempt is audit-logged with the submitted hash (NEVER the
/// submitted plaintext — a wrong guess might still be sensitive to
/// the operator) and the verdict.
pub fn ctf_verify(root: &Path, submitted: &str) -> Result<CtfVerifyResult, Error> {
    use sha2::Digest;

    const MAX_FLAG_LEN: usize = 1024;
    if submitted.len() > MAX_FLAG_LEN {
        return Err(Error::CryptoFailure(format!(
            "submitted flag exceeds maximum length of {MAX_FLAG_LEN} bytes"
        )));
    }

    let hash_path = root.join("ctf-hash.txt");
    crate::guard::verify_not_symlink(&hash_path)?;

    if !hash_path.exists() {
        return Err(Error::CryptoFailure(
            "no CTF challenge is currently active. Run `envseal ctf start` to set one up."
                .to_string(),
        ));
    }

    let expected = {
        use std::io::Read;
        // Cap at 64 KiB. ctf-hash.txt is one 64-char hex line.
        let f = crate::file::atomic_open::open_read_no_traverse(&hash_path)?;
        let mut s = String::new();
        f.take(64 * 1024).read_to_string(&mut s)?;
        s.trim().to_string()
    };
    let submitted_hash = format!("{:x}", sha2::Sha256::digest(submitted.as_bytes()));
    let correct = crate::guard::constant_time_eq(submitted_hash.as_bytes(), expected.as_bytes());

    // Audit every attempt BEFORE the rate-limit sleep so even if
    // an attacker SIGKILLs the process during the sleep, the
    // attempt is recorded.
    let _ = crate::audit::log_required_at(
        root,
        &crate::audit::AuditEvent::SignalRecorded {
            tier: "Lockdown".to_string(),
            classification: format!(
                "info [ctf.verify.{verdict}] submitted_hash={submitted_hash}",
                verdict = if correct { "correct" } else { "incorrect" }
            ),
        },
    );

    std::thread::sleep(VERIFY_RATE_LIMIT);

    if correct {
        Ok(CtfVerifyResult::Correct {
            flag: submitted.to_string(),
            hash: submitted_hash,
        })
    } else {
        Ok(CtfVerifyResult::Incorrect {
            submitted_hash,
            expected_hash: expected,
        })
    }
}

/// Per-attempt sleep enforced by [`ctf_verify`]. 250ms is short
/// enough that an honest operator typing a guess feels nothing,
/// long enough that a million-shot scripted attack costs ~70 hours
/// of wall time per machine.
const VERIFY_RATE_LIMIT: std::time::Duration = std::time::Duration::from_millis(250);

/// Whether a CTF challenge is currently set up in the default vault.
///
/// # Errors
/// Returns vault-discovery errors only.
pub fn ctf_status_default() -> Result<CtfStatus, Error> {
    let root = super::vault_root()?;
    ctf_status(&root)
}

/// Verify a flag against the default vault's CTF state.
///
/// # Errors
/// `Error::SecretNotFound` if no challenge has been set up.
pub fn ctf_verify_default(submitted: &str) -> Result<CtfVerifyResult, Error> {
    let root = super::vault_root()?;
    ctf_verify(&root, submitted)
}

/// Set up a CTF challenge in the default vault. Refuses if `ctf-flag`
/// already exists (caller should run [`ctf_reset_default`] first).
///
/// # Errors
/// `Error::CryptoFailure` if a challenge is already active.
pub fn ctf_setup_default() -> Result<CtfSetupResult, Error> {
    let vault = Vault::open_default()?;
    if vault
        .list()?
        .iter()
        .any(|n| n.eq_ignore_ascii_case("ctf-flag"))
    {
        return Err(Error::CryptoFailure(
            "a CTF challenge already exists. Run `envseal ctf reset` first.".to_string(),
        ));
    }
    ctf_setup(&vault)
}

/// Tear down the default vault's CTF challenge: remove the hash file and
/// the sealed flag.
///
/// Returns `true` if a flag/hash existed and was removed, `false` if the
/// challenge wasn't set up.
///
/// # Errors
/// `Error::StorageIo` for filesystem failures during cleanup.
pub fn ctf_reset_default() -> Result<bool, Error> {
    let root = super::vault_root()?;
    let hash_path = root.join("ctf-hash.txt");
    let flag_path = root.join("vault").join("ctf-flag.seal");
    let prev_tier_path = root.join("ctf-prev-tier.txt");
    crate::guard::verify_not_symlink(&hash_path)?;
    crate::guard::verify_not_symlink(&flag_path)?;
    crate::guard::verify_not_symlink(&prev_tier_path)?;

    let mut removed = false;

    // Restore the pre-CTF tier if recorded. Best-effort — if the
    // marker file was deleted, the security config is left at
    // whatever `ctf start` set (Lockdown), and the operator can
    // fix it via `envseal security preset standard`. We don't fail
    // the reset for a missing marker because the flag/hash cleanup
    // is the more important half of this operation.
    if prev_tier_path.exists() {
        let content = {
            use std::io::Read;
            crate::file::atomic_open::open_read_no_traverse(&prev_tier_path)
                .and_then(|f| {
                    let mut s = String::new();
                    f.take(1024).read_to_string(&mut s)?;
                    Ok(s)
                })
                .unwrap_or_default()
        };
        let prev = content.trim();
        let restore_to = match prev {
            "Standard" => Some(crate::security_config::SecurityTier::Standard),
            "Hardened" => Some(crate::security_config::SecurityTier::Hardened),
            "Lockdown" => Some(crate::security_config::SecurityTier::Lockdown),
            _ => None,
        };
        if let Some(tier) = restore_to {
            // Reload + restore. Failure here doesn't fail the
            // reset — the operator can always fix the tier
            // manually via `envseal security preset <name>`.
            if let Ok(vault) = Vault::open_default() {
                if let Ok(mut config) =
                    crate::security_config::load_config(vault.root(), vault.master_key_bytes())
                {
                    config.apply_preset(tier);
                    let _ = crate::security_config::save_config(
                        vault.root(),
                        &config,
                        vault.master_key_bytes(),
                    );
                }
            }
        }
        let _ = std::fs::remove_file(&prev_tier_path);
        removed = true;
    }

    if hash_path.exists() {
        std::fs::remove_file(&hash_path).map_err(Error::StorageIo)?;
        removed = true;
    }
    if flag_path.exists() {
        // Open with O_NOFOLLOW to prevent TOCTOU symlink swap that
        // would cause us to zero out an attacker-chosen file.
        #[cfg(unix)]
        {
            use std::os::unix::fs::OpenOptionsExt;
            if let Ok(mut file) = std::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
                .open(&flag_path)
            {
                if let Ok(meta) = file.metadata() {
                    let len = usize::try_from(meta.len()).unwrap_or(0);
                    if len > 0 {
                        use std::io::{Seek, SeekFrom, Write};
                        let _ = file.seek(SeekFrom::Start(0));
                        let buf = [0u8; 8192];
                        let mut remaining = len;
                        while remaining > 0 {
                            let n = remaining.min(buf.len());
                            let _ = file.write_all(&buf[..n]);
                            remaining -= n;
                        }
                        let _ = file.sync_all();
                    }
                }
            }
        }
        #[cfg(not(unix))]
        {
            if let Ok(mut file) = crate::file::atomic_open::open_write_no_traverse(&flag_path) {
                if let Ok(meta) = file.metadata() {
                    let len = usize::try_from(meta.len()).unwrap_or(0);
                    if len > 0 {
                        use std::io::{Seek, SeekFrom, Write};
                        let _ = file.seek(SeekFrom::Start(0));
                        let buf = [0u8; 8192];
                        let mut remaining = len;
                        while remaining > 0 {
                            let n = remaining.min(buf.len());
                            let _ = file.write_all(&buf[..n]);
                            remaining -= n;
                        }
                        let _ = file.sync_all();
                    }
                }
            }
        }
        std::fs::remove_file(&flag_path).map_err(Error::StorageIo)?;
        removed = true;
    }
    Ok(removed)
}

/// Set up a CTF challenge (needs vault + passphrase).
///
/// Records the operator's pre-CTF tier in `ctf-prev-tier.txt` so
/// `ctf_reset` can restore it. Without this, `ctf start` would
/// silently park the entire vault in Lockdown forever — every
/// subsequent operation would carry Lockdown's 5-second approval
/// delay and challenge gate, which is hostile UX for a feature the
/// user thought was scoped to one CTF flag.
pub fn ctf_setup(vault: &Vault) -> Result<CtfSetupResult, Error> {
    use rand::RngCore;
    use sha2::Digest;
    use std::fmt::Write;

    // CTF integrity preflight — refuse to start a challenge whose
    // claimed defenses aren't actually engaged. Otherwise the
    // headline "nobody gets the flag out" is structurally false:
    //
    // 1. If the active hardware-seal backend is `None` (tier 3 —
    //    passphrase-only sealing), an attacker who copies
    //    `master.key` brute-forces it offline on their own
    //    hardware, no envseal process required. The whole sealed-
    //    on-this-device claim collapses.
    //
    // 2. On Linux, if `kernel.yama.ptrace_scope` is permissive
    //    (=0), any same-UID process can `process_vm_readv` envseal
    //    and grep memory for the master key while it's unlocked.
    //    `memfd_secret` (Linux 5.14+) blunts this for the master
    //    bytes, but the wrap key during unlock + per-secret
    //    plaintext during inject still flow through ordinary
    //    pages.
    //
    // Both checks abort BEFORE the flag is ever stored, so a
    // refused `ctf start` never leaves a half-set-up challenge
    // behind.
    let backend = crate::keychain::active_backend();
    if backend == crate::vault::hardware::Backend::None {
        return Err(Error::CryptoFailure(format!(
            "ctf start refused: vault is using tier 3 (passphrase-only) sealing — \
             no hardware backend ({}). The CTF integrity claim depends on \
             the master key being non-decryptable on any other machine. \
             Install the platform hardware backend (TPM 2.0 + tpm2-tools on \
             Linux, Secure Enclave on macOS, DPAPI is automatic on Windows) \
             and re-run.",
            backend.name()
        )));
    }
    if let Some(detail) = crate::guard::check_ptrace_scope() {
        return Err(Error::CryptoFailure(format!(
            "ctf start refused: ptrace scope is permissive — {detail}. \
             A permissive ptrace lets any same-UID process attach to envseal \
             and read the unlocked master key from memory. Run \
             `sudo sysctl kernel.yama.ptrace_scope=1` (or higher), confirm \
             with `cat /proc/sys/kernel/yama/ptrace_scope`, then re-run."
        )));
    }

    let mut bytes = [0u8; 32];
    rand::rngs::OsRng.fill_bytes(&mut bytes);
    let mut hex = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        let _ = write!(&mut hex, "{b:02x}");
    }
    let flag = {
        let f = format!("ENVSEAL_CTF{{{hex}}}");
        zeroize::Zeroizing::new(f)
    };
    zeroize::Zeroize::zeroize(&mut hex);

    let hash = format!("{:x}", sha2::Sha256::digest(flag.as_bytes()));

    vault
        .store("ctf-flag", flag.as_bytes(), false)
        .map_err(|e| match e {
            Error::SecretAlreadyExists(_) => Error::CryptoFailure(
                "a CTF challenge already exists. Run `envseal ctf reset` first.".to_string(),
            ),
            other => other,
        })?;

    let mut config = crate::security_config::load_config(vault.root(), vault.master_key_bytes())
        .unwrap_or_default();
    let old_tier = format!("{:?}", config.tier);

    // Persist the pre-CTF tier so `ctf_reset` can restore it. Stored
    // as plaintext (the value is just the tier name — public info
    // anyway, doctor reports it).
    let prev_tier_path = vault.root().join("ctf-prev-tier.txt");
    crate::guard::verify_not_symlink(&prev_tier_path)?;
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let prev_tmp =
        prev_tier_path.with_extension(format!("tmp.{pid}.{nanos}", pid = std::process::id()));
    std::fs::write(&prev_tmp, format!("{old_tier}\n")).map_err(Error::StorageIo)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&prev_tmp, std::fs::Permissions::from_mode(0o600))
            .map_err(Error::StorageIo)?;
    }
    std::fs::rename(&prev_tmp, &prev_tier_path).map_err(Error::StorageIo)?;

    config.apply_preset(crate::security_config::SecurityTier::Lockdown);
    crate::security_config::save_config(vault.root(), &config, vault.master_key_bytes())?;

    crate::audit::log_required_at(
        vault.root(),
        &crate::audit::AuditEvent::TierChanged {
            from: old_tier,
            to: format!("{:?}", config.tier),
        },
    )?;
    crate::audit::log_required_at(
        vault.root(),
        &crate::audit::AuditEvent::SecretStored {
            name: "ctf-flag".to_string(),
        },
    )?;

    let hash_path = vault.root().join("ctf-hash.txt");
    crate::guard::verify_not_symlink(&hash_path)?;
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let hash_tmp = hash_path.with_extension(format!("tmp.{pid}.{nanos}", pid = std::process::id()));
    std::fs::write(&hash_tmp, format!("{hash}\n")).map_err(Error::StorageIo)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&hash_tmp, std::fs::Permissions::from_mode(0o600))
            .map_err(Error::StorageIo)?;
    }
    std::fs::rename(&hash_tmp, &hash_path).map_err(Error::StorageIo)?;

    Ok(CtfSetupResult { hash, hash_path })
}