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
//! TOCTOU-free open that refuses to traverse symlinks (Unix) or
//! NTFS reparse points (Windows).
//!
//! # Audit C1 / H7
//!
//! `verify_not_symlink(path)` followed by `File::open(path)` is a
//! classic TOCTOU race: between the metadata check and the open,
//! an attacker can replace `path` with a junction / symlink and
//! redirect the read to attacker-controlled content. The previous
//! Windows code paths leaned on `verify_not_symlink` for the check
//! and then called `std::fs::read_to_string` / `File::open`, which
//! happily follows reparse points. The Unix paths used
//! `O_NOFOLLOW` and were already safe.
//!
//! The helpers below close that gap by performing the open and
//! the integrity check in one syscall (Unix `O_NOFOLLOW`) or by
//! opening with `FILE_FLAG_OPEN_REPARSE_POINT` and inspecting the
//! resulting handle's attributes (Windows). The handle is never
//! reachable for the caller without the check having succeeded.

use std::fs::File;
use std::io;
use std::path::Path;

use crate::error::Error;

/// Open `path` for read, refusing to traverse a symlink or reparse
/// point. The returned [`File`] is bound to the actual on-disk node
/// at the path — not to whatever a symlink might have pointed at.
///
/// # Errors
/// - [`Error::PolicyTampered`] if the path is a symlink or NTFS
///   reparse point.
/// - [`Error::StorageIo`] for any other I/O failure (file not
///   found, permission denied, …).
pub fn open_read_no_traverse(path: &Path) -> Result<File, Error> {
    open_read_no_traverse_inner(path).map_err(|e| match e {
        OpenError::Refused(msg) => Error::PolicyTampered(msg),
        OpenError::Io(io_err) => Error::StorageIo(io_err),
    })
}

enum OpenError {
    Refused(String),
    Io(io::Error),
}

#[cfg(unix)]
fn open_read_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    use std::os::unix::fs::OpenOptionsExt;
    let file = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open(path)
        .map_err(|e| {
            // ELOOP from O_NOFOLLOW maps to "is a symlink" — surface
            // that as a refusal, not as a generic I/O error.
            if e.raw_os_error() == Some(libc::ELOOP) {
                OpenError::Refused(format!(
                    "refusing to open '{}': path is a symlink (TOCTOU-free check)",
                    path.display()
                ))
            } else {
                OpenError::Io(e)
            }
        })?;
    Ok(file)
}

#[cfg(windows)]
fn open_read_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    use std::os::windows::fs::OpenOptionsExt;
    use std::os::windows::io::AsRawHandle;
    use windows_sys::Win32::Storage::FileSystem::{
        GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT,
        FILE_FLAG_OPEN_REPARSE_POINT,
    };

    // FILE_FLAG_OPEN_REPARSE_POINT instructs the kernel NOT to follow
    // the reparse point — instead, the open returns a handle to the
    // reparse-point file itself. We then inspect its attributes; if
    // it IS a reparse point we refuse.
    let file = std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
        .open(path)
        .map_err(OpenError::Io)?;

    // Inspect the handle's attributes — the open only confirmed the
    // open, not the type. GetFileInformationByHandle reads the
    // canonical attribute bits at the time of the call on the same
    // handle, eliminating the TOCTOU window.
    // SAFETY: `file` is a valid std::fs::File holding an OS file
    // handle; AsRawHandle returns it for the duration of the borrow.
    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
    let ok = unsafe {
        GetFileInformationByHandle(file.as_raw_handle().cast::<core::ffi::c_void>(), &mut info)
    };
    if ok == 0 {
        return Err(OpenError::Io(io::Error::last_os_error()));
    }
    if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
        return Err(OpenError::Refused(format!(
            "refusing to open '{}': path is an NTFS reparse point (junction, mount, \
             symlink, cloud-file). Reparse points silently redirect path resolution \
             and are not allowed in vault / .envseal paths.",
            path.display()
        )));
    }
    Ok(file)
}

#[cfg(not(any(unix, windows)))]
fn open_read_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    // Best-effort fallback: stat with symlink_metadata then open.
    // This DOES have a TOCTOU window — but on platforms where
    // neither O_NOFOLLOW nor FILE_FLAG_OPEN_REPARSE_POINT exists,
    // the OS itself doesn't support fully race-free no-follow opens.
    let meta = std::fs::symlink_metadata(path).map_err(OpenError::Io)?;
    if meta.file_type().is_symlink() {
        return Err(OpenError::Refused(format!(
            "refusing to open '{}': path is a symlink",
            path.display()
        )));
    }
    std::fs::File::open(path).map_err(OpenError::Io)
}

/// Open `path` for **append**, creating it with owner-only mode if
/// it doesn't exist, refusing to traverse a symlink or reparse
/// point. Used by the audit log writer so a same-user attacker
/// cannot win the TOCTOU race between `verify_not_symlink` and
/// `OpenOptions::open(create(true).append(true))` by planting a
/// symlink at the audit-log path between the two calls.
///
/// On Unix the create flags include `O_NOFOLLOW | O_EXCL`-via-
/// `O_CREAT` semantics; on a pre-existing file `O_NOFOLLOW`
/// rejects symlinks; on a fresh create the kernel won't traverse
/// even an attacker-planted symlink. On Windows we use
/// `FILE_FLAG_OPEN_REPARSE_POINT` on the open and then inspect
/// the resulting handle's attribute bits — same pattern as
/// [`open_read_no_traverse`].
///
/// # Errors
/// Same shape as [`open_read_no_traverse`].
pub fn open_append_no_traverse(path: &Path) -> Result<File, Error> {
    open_append_no_traverse_inner(path).map_err(|e| match e {
        OpenError::Refused(msg) => Error::PolicyTampered(msg),
        OpenError::Io(io_err) => Error::StorageIo(io_err),
    })
}

#[cfg(unix)]
fn open_append_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    use std::os::unix::fs::OpenOptionsExt;
    let file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .mode(0o600)
        .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open(path)
        .map_err(|e| {
            if e.raw_os_error() == Some(libc::ELOOP) {
                OpenError::Refused(format!(
                    "refusing to append to '{}': path is a symlink (TOCTOU-free check)",
                    path.display()
                ))
            } else {
                OpenError::Io(e)
            }
        })?;
    Ok(file)
}

#[cfg(windows)]
fn open_append_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    // CreateFileW with a SECURITY_ATTRIBUTES carrying an owner-only
    // DACL — the file is created (or extended) with the lockdown
    // ACL in place from byte 0, eliminating the post-open window
    // in which a freshly-created `audit.log` briefly carried the
    // inherited (often permissive) parent-directory ACL. Reparse-
    // point refusal happens on the same handle via the post-open
    // attribute check inside the helper.
    crate::policy::windows_acl::create_owner_only_append(path).map_err(|e| match e {
        crate::error::Error::PolicyTampered(msg) => OpenError::Refused(msg),
        crate::error::Error::StorageIo(io) => OpenError::Io(io),
        other => OpenError::Io(io::Error::other(format!(
            "create_owner_only_append: {other}"
        ))),
    })
}

#[cfg(not(any(unix, windows)))]
fn open_append_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    if let Ok(meta) = std::fs::symlink_metadata(path) {
        if meta.file_type().is_symlink() {
            return Err(OpenError::Refused(format!(
                "refusing to append to '{}': path is a symlink",
                path.display()
            )));
        }
    }
    std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .map_err(OpenError::Io)
}

/// Open `path` for **write+truncate**, refusing to traverse a
/// symlink or reparse point. Used by [`shred_file`] so a TOCTOU
/// race between `verify_not_symlink` and the subsequent open
/// cannot redirect a zero-fill to an attacker-chosen file.
///
/// Does NOT create the file if missing. Callers that want
/// "create if not exists" must use a different helper.
///
/// # Errors
/// `Error::PolicyTampered` if the path is a symlink / reparse
/// point; `Error::StorageIo` for any other I/O failure (file not
/// found, permission denied, etc).
pub fn open_write_no_traverse(path: &Path) -> Result<File, Error> {
    open_write_no_traverse_inner(path).map_err(|e| match e {
        OpenError::Refused(msg) => Error::PolicyTampered(msg),
        OpenError::Io(io_err) => Error::StorageIo(io_err),
    })
}

#[cfg(unix)]
fn open_write_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    use std::os::unix::fs::OpenOptionsExt;
    let file = std::fs::OpenOptions::new()
        .write(true)
        .truncate(true)
        .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open(path)
        .map_err(|e| {
            if e.raw_os_error() == Some(libc::ELOOP) {
                OpenError::Refused(format!(
                    "refusing to truncate '{}': path is a symlink",
                    path.display()
                ))
            } else {
                OpenError::Io(e)
            }
        })?;
    Ok(file)
}

#[cfg(windows)]
fn open_write_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    use std::os::windows::fs::OpenOptionsExt;
    use std::os::windows::io::AsRawHandle;
    use windows_sys::Win32::Storage::FileSystem::{
        GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT,
        FILE_FLAG_OPEN_REPARSE_POINT,
    };

    let file = std::fs::OpenOptions::new()
        .write(true)
        .truncate(true)
        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
        .open(path)
        .map_err(OpenError::Io)?;

    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
    let ok = unsafe {
        GetFileInformationByHandle(file.as_raw_handle().cast::<core::ffi::c_void>(), &mut info)
    };
    if ok == 0 {
        return Err(OpenError::Io(io::Error::last_os_error()));
    }
    if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
        return Err(OpenError::Refused(format!(
            "refusing to truncate '{}': path is an NTFS reparse point",
            path.display()
        )));
    }
    Ok(file)
}

#[cfg(not(any(unix, windows)))]
fn open_write_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    if let Ok(meta) = std::fs::symlink_metadata(path) {
        if meta.file_type().is_symlink() {
            return Err(OpenError::Refused(format!(
                "refusing to truncate '{}': path is a symlink",
                path.display()
            )));
        }
    }
    std::fs::OpenOptions::new()
        .write(true)
        .truncate(true)
        .open(path)
        .map_err(OpenError::Io)
}

/// Create a new file at `path`, refusing to overwrite anything that
/// already exists AND refusing to traverse a symlink or reparse point.
///
/// Critical for "drop a fresh file at a user-controlled path" flows
/// (git pre-commit hook install, alias snippet write, …) where an
/// attacker who can plant a dangling symlink at the target path
/// would otherwise redirect the write to their chosen file.
///
/// Semantics: returns an error if the file already exists, the path
/// is a symlink (even if dangling), or the parent directory does not
/// exist. Maps to `O_CREAT | O_EXCL | O_NOFOLLOW` on Unix and
/// `CREATE_NEW + FILE_FLAG_OPEN_REPARSE_POINT` (with a post-open
/// reparse-attribute check) on Windows.
///
/// # Errors
/// - [`Error::PolicyTampered`] if the path is a symlink / reparse
///   point or already exists.
/// - [`Error::StorageIo`] for any other I/O failure.
pub fn create_new_no_traverse(path: &Path) -> Result<File, Error> {
    create_new_no_traverse_inner(path).map_err(|e| match e {
        OpenError::Refused(msg) => Error::PolicyTampered(msg),
        OpenError::Io(io_err) => Error::StorageIo(io_err),
    })
}

#[cfg(unix)]
fn create_new_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    use std::os::unix::fs::OpenOptionsExt;
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open(path)
        .map_err(|e| match e.raw_os_error() {
            Some(libc::ELOOP) => OpenError::Refused(format!(
                "refusing to create '{}': path is a symlink",
                path.display()
            )),
            Some(libc::EEXIST) => OpenError::Refused(format!(
                "refusing to create '{}': file already exists \
                 (existing file may be a symlink — refusing to clobber)",
                path.display()
            )),
            _ => OpenError::Io(e),
        })
}

#[cfg(windows)]
fn create_new_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    use std::os::windows::fs::OpenOptionsExt;
    use std::os::windows::io::AsRawHandle;
    use windows_sys::Win32::Storage::FileSystem::{
        GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT,
        FILE_FLAG_OPEN_REPARSE_POINT,
    };

    // CREATE_NEW (= create_new) fails if anything exists at the path,
    // including a symlink/junction. FILE_FLAG_OPEN_REPARSE_POINT is
    // defense-in-depth: the post-open attribute check refuses if the
    // kernel ever hands us a reparse-point handle.
    let file = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
        .open(path)
        .map_err(|e| {
            if e.kind() == io::ErrorKind::AlreadyExists {
                OpenError::Refused(format!(
                    "refusing to create '{}': file already exists \
                     (existing file may be a reparse point — refusing to clobber)",
                    path.display()
                ))
            } else {
                OpenError::Io(e)
            }
        })?;

    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
    let ok = unsafe {
        GetFileInformationByHandle(file.as_raw_handle().cast::<core::ffi::c_void>(), &mut info)
    };
    if ok == 0 {
        return Err(OpenError::Io(io::Error::last_os_error()));
    }
    if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
        return Err(OpenError::Refused(format!(
            "refusing to create '{}': path is an NTFS reparse point",
            path.display()
        )));
    }
    Ok(file)
}

#[cfg(not(any(unix, windows)))]
fn create_new_no_traverse_inner(path: &Path) -> Result<File, OpenError> {
    std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map_err(OpenError::Io)
}

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

    #[test]
    fn opens_a_regular_file() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("plain.txt");
        std::fs::write(&path, b"hello").unwrap();
        let f = open_read_no_traverse(&path);
        assert!(f.is_ok(), "regular file open must succeed: {:?}", f.err());
    }

    #[cfg(unix)]
    #[test]
    fn refuses_a_symlink() {
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("real.txt");
        std::fs::write(&target, b"x").unwrap();
        let link = tmp.path().join("link.txt");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        let err = open_read_no_traverse(&link).expect_err("must refuse symlink");
        match err {
            Error::PolicyTampered(_) => {}
            other => panic!("expected PolicyTampered, got {other:?}"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn append_refuses_a_symlink() {
        // Audit-log writers must refuse to append to a symlink even
        // if the target already exists — a same-user attacker could
        // otherwise redirect forensic appends to /dev/null or to an
        // attacker-readable file.
        let tmp = tempfile::tempdir().unwrap();
        let target = tmp.path().join("real.log");
        std::fs::write(&target, b"").unwrap();
        let link = tmp.path().join("audit.log");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        let err = open_append_no_traverse(&link).expect_err("must refuse symlink on append");
        match err {
            Error::PolicyTampered(_) => {}
            other => panic!("expected PolicyTampered, got {other:?}"),
        }
    }

    #[test]
    fn append_creates_then_extends() {
        use std::io::Write;
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("audit.log");
        // First call creates.
        {
            let mut f = open_append_no_traverse(&path).unwrap();
            f.write_all(b"first\n").unwrap();
        }
        // Second call extends — must NOT truncate.
        {
            let mut f = open_append_no_traverse(&path).unwrap();
            f.write_all(b"second\n").unwrap();
        }
        let body = std::fs::read_to_string(&path).unwrap();
        assert_eq!(body, "first\nsecond\n");
    }
}