envseal 0.3.8

Write-only secret vault with process-level access control — post-agent secret management
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
//! 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,
    /// 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); 7] {
        [
            ("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 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 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,
    ]
    .iter()
    .any(|c| c.is_fail());

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

/// 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 = std::fs::read_to_string(&hash_path)?.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 = std::fs::read_to_string(&legacy_path).unwrap_or_default();
            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;

    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 = std::fs::read_to_string(&hash_path)?.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() {
        if let Ok(content) = std::fs::read_to_string(&prev_tier_path) {
            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(meta) = std::fs::metadata(&flag_path) {
                let len = usize::try_from(meta.len()).unwrap_or(0);
                if len > 0 {
                    let _ = std::fs::write(&flag_path, vec![0u8; len]);
                }
            }
        }
        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 = format!("ENVSEAL_CTF{{{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 prev_tmp = prev_tier_path.with_extension("tmp");
    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 hash_tmp = hash_path.with_extension("tmp");
    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 })
}