envseal 0.3.13

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
//! Windows NTFS ACL helpers — the 0o600-equivalent for vault files.
//!
//! Unix `chmod 0o600` says "owner can read/write; nobody else can do
//! anything." On NTFS the same intent is expressed as a discretionary ACL
//! (DACL) containing exactly one access-allowed ACE for the file owner,
//! flagged `PROTECTED_DACL_SECURITY_INFORMATION` so it does not inherit
//! permissive entries from the parent directory.
//!
//! [`set_owner_only_dacl`] is the entry point. It is called by
//! [`super::rules::Policy::save`] / [`super::rules::Policy::save_signed`]
//! and (transitively) every vault file that needs to be owner-private.

#![cfg(windows)]

use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use std::ptr;

use windows_sys::Win32::Foundation::{
    CloseHandle, GetLastError, LocalFree, ERROR_INSUFFICIENT_BUFFER, ERROR_SUCCESS, GENERIC_ALL,
    HANDLE, HLOCAL, INVALID_HANDLE_VALUE,
};
use windows_sys::Win32::Security::Authorization::{
    SetEntriesInAclW, SetNamedSecurityInfoW, EXPLICIT_ACCESS_W, GRANT_ACCESS, NO_MULTIPLE_TRUSTEE,
    SE_FILE_OBJECT, TRUSTEE_IS_SID, TRUSTEE_IS_USER, TRUSTEE_W,
};
use windows_sys::Win32::Security::{
    GetTokenInformation, TokenUser, ACL, DACL_SECURITY_INFORMATION, NO_INHERITANCE,
    PROTECTED_DACL_SECURITY_INFORMATION, TOKEN_QUERY, TOKEN_USER,
};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};

use crate::error::Error;

/// Replace `path`'s DACL with one ACE that grants full access to the
/// current process owner only. The DACL is marked protected so the parent
/// directory's ACL does not re-introduce broader access.
pub fn set_owner_only_dacl(path: &Path) -> Result<(), Error> {
    let owner_sid = OwnerSid::current()?;

    // Build a single explicit access entry: GRANT, GENERIC_ALL, the owner's
    // SID, no inheritance.
    let explicit = EXPLICIT_ACCESS_W {
        grfAccessPermissions: GENERIC_ALL,
        grfAccessMode: GRANT_ACCESS,
        grfInheritance: NO_INHERITANCE,
        Trustee: TRUSTEE_W {
            pMultipleTrustee: ptr::null_mut(),
            MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
            TrusteeForm: TRUSTEE_IS_SID,
            TrusteeType: TRUSTEE_IS_USER,
            // The TRUSTEE form is `TRUSTEE_IS_SID`, so `ptstrName` is
            // reinterpreted as a SID pointer rather than a name string.
            // The function signature still types it as `*mut u16`.
            ptstrName: owner_sid.as_ptr() as *mut u16,
        },
    };

    // Build the ACL. SetEntriesInAclW allocates via LocalAlloc; we must
    // LocalFree it after we're done.
    let mut new_acl: *mut ACL = ptr::null_mut();
    let rc = unsafe { SetEntriesInAclW(1, &explicit, ptr::null_mut(), &mut new_acl) };
    if rc != ERROR_SUCCESS || new_acl.is_null() {
        return Err(Error::StorageIo(std::io::Error::other(format!(
            "SetEntriesInAclW failed: rc={rc}"
        ))));
    }
    let _acl_guard = LocalFreeOnDrop(new_acl.cast());

    // Apply the protected DACL to the file by name.
    let wide: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let info = DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION;
    let rc = unsafe {
        SetNamedSecurityInfoW(
            wide.as_ptr(),
            SE_FILE_OBJECT,
            info,
            ptr::null_mut(), // owner — leave as-is
            ptr::null_mut(), // group — leave as-is
            new_acl,         // dacl
            ptr::null_mut(), // sacl
        )
    };
    if rc != ERROR_SUCCESS {
        return Err(Error::StorageIo(std::io::Error::other(format!(
            "SetNamedSecurityInfoW({}) failed: rc={rc}",
            path.display()
        ))));
    }

    Ok(())
}

/// RAII wrapper around the current process owner's SID.
///
/// The `TOKEN_USER` buffer that holds the SID must outlive the
/// `EXPLICIT_ACCESS_W` that points into it.
struct OwnerSid {
    buffer: Vec<u8>,
}

impl OwnerSid {
    fn current() -> Result<Self, Error> {
        let mut token: HANDLE = INVALID_HANDLE_VALUE;
        let process = unsafe { GetCurrentProcess() };
        if unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) } == 0 {
            return Err(Error::StorageIo(last_os_error("OpenProcessToken")));
        }
        let _token_guard = HandleGuard(token);

        // Probe required size.
        let mut needed: u32 = 0;
        let probe =
            unsafe { GetTokenInformation(token, TokenUser, ptr::null_mut(), 0, &mut needed) };
        if probe == 0 {
            let err = unsafe { GetLastError() };
            if err != ERROR_INSUFFICIENT_BUFFER {
                return Err(Error::StorageIo(std::io::Error::other(format!(
                    "GetTokenInformation probe failed: rc={err}"
                ))));
            }
        }

        let mut buffer = vec![0u8; needed as usize];
        if unsafe {
            GetTokenInformation(
                token,
                TokenUser,
                buffer.as_mut_ptr().cast(),
                needed,
                &mut needed,
            )
        } == 0
        {
            return Err(Error::StorageIo(last_os_error("GetTokenInformation")));
        }

        Ok(Self { buffer })
    }

    /// Pointer to the SID inside the `TOKEN_USER` buffer.
    fn as_ptr(&self) -> *const std::ffi::c_void {
        // SAFETY: `GetTokenInformation(TokenUser, …)` returns a `TOKEN_USER`
        // structure starting at offset 0 of the buffer it filled. Its
        // alignment requirement matches the API contract; the buffer is
        // produced by a Windows API call rather than `Vec<u8>` reuse, so
        // the cast through a `*const u8` is necessary but the pointer is
        // sufficiently aligned in practice. We allow the lint here.
        #[allow(clippy::cast_ptr_alignment)]
        let token_user = self.buffer.as_ptr().cast::<TOKEN_USER>();
        unsafe { (*token_user).User.Sid.cast() }
    }
}

struct HandleGuard(HANDLE);
impl Drop for HandleGuard {
    fn drop(&mut self) {
        if self.0 != INVALID_HANDLE_VALUE {
            unsafe {
                let _ = CloseHandle(self.0);
            }
        }
    }
}

struct LocalFreeOnDrop(HLOCAL);
impl Drop for LocalFreeOnDrop {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe {
                LocalFree(self.0);
            }
        }
    }
}

fn last_os_error(label: &str) -> std::io::Error {
    let err = unsafe { GetLastError() };
    std::io::Error::other(format!("{label} failed: rc={err}"))
}

/// Create or open `path` for append with an **owner-only DACL applied
/// at creation time**, eliminating the post-open window in which a
/// freshly-created file briefly carried the inherited (often
/// permissive) parent-directory ACL. The handle is also returned with
/// a `FILE_FLAG_OPEN_REPARSE_POINT` post-open attribute check so a
/// hostile mid-race symlink cannot redirect the append.
///
/// Used by the audit log writer on Windows; the audit-key tmp-file
/// writer uses the same primitive so a same-user attacker cannot
/// race a read on the new key during the brief window the legacy
/// path left open.
///
/// # Errors
/// - [`Error::PolicyTampered`] if the resulting handle resolves to a
///   reparse point (junction, symlink, mount point, cloud-file).
/// - [`Error::StorageIo`] for any Win32 failure.
pub fn create_owner_only_append(path: &Path) -> Result<std::fs::File, Error> {
    use std::os::windows::io::FromRawHandle;
    use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE as INVALID_HV;
    use windows_sys::Win32::Security::SECURITY_DESCRIPTOR;
    use windows_sys::Win32::Storage::FileSystem::{
        CreateFileW, GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_APPEND_DATA,
        FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT,
        FILE_SHARE_READ, OPEN_ALWAYS, SYNCHRONIZE,
    };

    let owner_sid = OwnerSid::current()?;

    let explicit = EXPLICIT_ACCESS_W {
        grfAccessPermissions: GENERIC_ALL,
        grfAccessMode: GRANT_ACCESS,
        grfInheritance: NO_INHERITANCE,
        Trustee: TRUSTEE_W {
            pMultipleTrustee: ptr::null_mut(),
            MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
            TrusteeForm: TRUSTEE_IS_SID,
            TrusteeType: TRUSTEE_IS_USER,
            ptstrName: owner_sid.as_ptr() as *mut u16,
        },
    };
    let mut new_acl: *mut ACL = ptr::null_mut();
    let rc = unsafe { SetEntriesInAclW(1, &explicit, ptr::null_mut(), &mut new_acl) };
    if rc != ERROR_SUCCESS || new_acl.is_null() {
        return Err(Error::StorageIo(std::io::Error::other(format!(
            "SetEntriesInAclW failed: rc={rc}"
        ))));
    }
    let _acl_guard = LocalFreeOnDrop(new_acl.cast());

    // Build a self-contained absolute SECURITY_DESCRIPTOR pointing at
    // our DACL. We never serialize it; CreateFileW only needs a
    // valid pointer for the duration of the call.
    let mut sd: SECURITY_DESCRIPTOR = unsafe { std::mem::zeroed() };
    if unsafe {
        windows_sys::Win32::Security::InitializeSecurityDescriptor(
            std::ptr::from_mut(&mut sd).cast(),
            1, // SECURITY_DESCRIPTOR_REVISION
        )
    } == 0
    {
        return Err(Error::StorageIo(last_os_error(
            "InitializeSecurityDescriptor",
        )));
    }
    if unsafe {
        windows_sys::Win32::Security::SetSecurityDescriptorDacl(
            std::ptr::from_mut(&mut sd).cast(),
            1, // bDaclPresent
            new_acl,
            0, // not defaulted
        )
    } == 0
    {
        return Err(Error::StorageIo(last_os_error("SetSecurityDescriptorDacl")));
    }

    let sa = windows_sys::Win32::Security::SECURITY_ATTRIBUTES {
        nLength: u32::try_from(std::mem::size_of::<
            windows_sys::Win32::Security::SECURITY_ATTRIBUTES,
        >())
        .unwrap_or(0),
        lpSecurityDescriptor: std::ptr::from_mut(&mut sd).cast(),
        bInheritHandle: 0,
    };

    let wide: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let handle = unsafe {
        CreateFileW(
            wide.as_ptr(),
            // Append-only: the kernel forces every write to EOF
            // regardless of file pointer position. Matches Rust's
            // `OpenOptions::append(true)` access mask. Adding
            // GENERIC_WRITE (which also implies FILE_WRITE_DATA)
            // would let positioned writes overwrite earlier lines
            // — exactly the regression that lost line 1 in the
            // first test pass of this fix.
            FILE_APPEND_DATA | SYNCHRONIZE,
            FILE_SHARE_READ,
            // SAFETY: `sa` lives until CreateFileW returns; the
            // SECURITY_DESCRIPTOR it references lives in the same
            // stack frame and outlives the call.
            &sa,
            OPEN_ALWAYS,
            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
            std::ptr::null_mut(),
        )
    };
    if handle == INVALID_HV {
        return Err(Error::StorageIo(last_os_error("CreateFileW")));
    }

    // Post-open: refuse if the handle resolved to a reparse point.
    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
    if unsafe { GetFileInformationByHandle(handle, &mut info) } == 0 {
        unsafe {
            let _ = CloseHandle(handle);
        }
        return Err(Error::StorageIo(last_os_error(
            "GetFileInformationByHandle",
        )));
    }
    if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
        unsafe {
            let _ = CloseHandle(handle);
        }
        return Err(Error::PolicyTampered(format!(
            "refusing to append to '{}': path resolved to an NTFS reparse point",
            path.display()
        )));
    }

    // SAFETY: `handle` is a valid Win32 file handle returned by
    // CreateFileW; ownership transfers to the std::fs::File.
    Ok(unsafe { std::fs::File::from_raw_handle(handle.cast::<core::ffi::c_void>()) })
}

/// Create a NEW file with an owner-only DACL applied atomically.
///
/// Same security goal as `set_owner_only_dacl(path)` AFTER an
/// `OpenOptions::create_new(true)` — but without the brief
/// create-to-DACL race window where the file exists with the
/// parent's inherited (potentially permissive) ACL. Built for
/// `.seal` secret files (audit H3 follow-up): the filename leaks
/// the secret NAME even though AEAD protects the ciphertext, so
/// even a millisecond of "world-readable" status is too long.
///
/// Semantics:
/// - `CREATE_NEW` disposition: fails with `Error::SecretAlreadyExists`
///   (when `secret_name` is provided) or `StorageIo(AlreadyExists)`
///   if anything exists at the path, including a junction/symlink.
/// - `FILE_FLAG_OPEN_REPARSE_POINT` + post-open attribute check:
///   refuses to write through a reparse point even if `CREATE_NEW`
///   somehow handed us one.
/// - `SECURITY_ATTRIBUTES` owner-only DACL applied at create time —
///   the file never exists with any other ACL.
/// - Access mask: `GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE` so
///   the caller can both write the new content and read it back
///   for round-trip verification without re-opening.
///
/// # Errors
/// - [`Error::SecretAlreadyExists`] when the path already exists
///   and `secret_name` was provided.
/// - [`Error::PolicyTampered`] when the path is a reparse point.
/// - [`Error::StorageIo`] for any other Win32 failure.
#[allow(clippy::too_many_lines)]
pub fn create_owner_only_new(
    path: &Path,
    secret_name: Option<&str>,
) -> Result<std::fs::File, Error> {
    use std::os::windows::io::FromRawHandle;
    use windows_sys::Win32::Foundation::{ERROR_FILE_EXISTS, INVALID_HANDLE_VALUE as INVALID_HV};
    use windows_sys::Win32::Security::SECURITY_DESCRIPTOR;
    use windows_sys::Win32::Storage::FileSystem::{
        CreateFileW, GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, CREATE_NEW,
        FILE_ATTRIBUTE_NORMAL, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT,
        FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_SHARE_DELETE, FILE_SHARE_READ,
        FILE_SHARE_WRITE, SYNCHRONIZE,
    };

    let owner_sid = OwnerSid::current()?;
    let explicit = EXPLICIT_ACCESS_W {
        grfAccessPermissions: GENERIC_ALL,
        grfAccessMode: GRANT_ACCESS,
        grfInheritance: NO_INHERITANCE,
        Trustee: TRUSTEE_W {
            pMultipleTrustee: ptr::null_mut(),
            MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE,
            TrusteeForm: TRUSTEE_IS_SID,
            TrusteeType: TRUSTEE_IS_USER,
            ptstrName: owner_sid.as_ptr() as *mut u16,
        },
    };
    let mut new_acl: *mut ACL = ptr::null_mut();
    let rc = unsafe { SetEntriesInAclW(1, &explicit, ptr::null_mut(), &mut new_acl) };
    if rc != ERROR_SUCCESS || new_acl.is_null() {
        return Err(Error::StorageIo(std::io::Error::other(format!(
            "SetEntriesInAclW failed: rc={rc}"
        ))));
    }
    let _acl_guard = LocalFreeOnDrop(new_acl.cast());

    let mut sd: SECURITY_DESCRIPTOR = unsafe { std::mem::zeroed() };
    if unsafe {
        windows_sys::Win32::Security::InitializeSecurityDescriptor(
            std::ptr::from_mut(&mut sd).cast(),
            1,
        )
    } == 0
    {
        return Err(Error::StorageIo(last_os_error(
            "InitializeSecurityDescriptor",
        )));
    }
    if unsafe {
        windows_sys::Win32::Security::SetSecurityDescriptorDacl(
            std::ptr::from_mut(&mut sd).cast(),
            1,
            new_acl,
            0,
        )
    } == 0
    {
        return Err(Error::StorageIo(last_os_error("SetSecurityDescriptorDacl")));
    }

    let sa = windows_sys::Win32::Security::SECURITY_ATTRIBUTES {
        nLength: u32::try_from(std::mem::size_of::<
            windows_sys::Win32::Security::SECURITY_ATTRIBUTES,
        >())
        .unwrap_or(0),
        lpSecurityDescriptor: std::ptr::from_mut(&mut sd).cast(),
        bInheritHandle: 0,
    };

    let wide: Vec<u16> = path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let handle = unsafe {
        CreateFileW(
            wide.as_ptr(),
            FILE_GENERIC_READ | FILE_GENERIC_WRITE | SYNCHRONIZE,
            // Match Rust's stdlib OpenOptions default share mode:
            // R | W | DELETE. DELETE is critical for the
            // rename-over-existing path used by `Vault::store
            // (force=true)` — the destination file (a previously
            // stored .seal at the same name) must be openable for
            // rename while we hold the new tmp's handle. Without
            // FILE_SHARE_DELETE on either side the rename fails
            // with ERROR_SHARING_VIOLATION (32).
            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
            &sa,
            CREATE_NEW,
            FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT,
            std::ptr::null_mut(),
        )
    };
    if handle == INVALID_HV {
        let err = std::io::Error::last_os_error();
        // ERROR_FILE_EXISTS is a Win32 u32 constant; raw_os_error
        // returns i32. Compare numerically with a checked cast.
        if err.raw_os_error() == i32::try_from(ERROR_FILE_EXISTS).ok() {
            if let Some(name) = secret_name {
                return Err(Error::SecretAlreadyExists(name.to_string()));
            }
        }
        return Err(Error::StorageIo(err));
    }

    let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
    if unsafe { GetFileInformationByHandle(handle, &mut info) } == 0 {
        unsafe {
            let _ = CloseHandle(handle);
        }
        return Err(Error::StorageIo(last_os_error(
            "GetFileInformationByHandle",
        )));
    }
    if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 {
        unsafe {
            let _ = CloseHandle(handle);
        }
        return Err(Error::PolicyTampered(format!(
            "refusing to create '{}': path resolved to an NTFS reparse point",
            path.display()
        )));
    }

    Ok(unsafe { std::fs::File::from_raw_handle(handle.cast::<core::ffi::c_void>()) })
}