Skip to main content

agentmux_common/
owner_only.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Files and folders only their own user may open: the place AgentMux Headless keeps its data and the key file that signs
5//! a browser in. On Linux and macOS that is a file mode (0700, 0600). Windows has access lists instead, and a profile
6//! folder can have been changed so that others are in them; this module reads a folder's list, says who besides the
7//! user, the system and the administrators is given access, and sets a list that gives it to the user and the system only.
8//!
9//! The reading of the list is plain text (its SDDL form), so it is the same code, and the same tests, on every platform.
10
11use std::path::Path;
12
13/// Who may be in a list besides the user: the system, the administrators, and the owner (as aliases and as SIDs). The
14/// administrators can always take a file they are denied, so listing them says nothing a check can use.
15const ALWAYS_ALLOWED: [&str; 8] = ["SY", "BA", "OW", "CO", "S-1-5-18", "S-1-5-32-544", "S-1-3-0", "S-1-3-4"];
16
17/// Someone a list lets in besides the user: what a person reads for them, and their SID, which is what removes them.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Other {
20    pub name: String,
21    pub sid: String,
22}
23
24/// What a person reads for the principals a list can name by alias, and the SID of each; any other is its own SID.
25pub fn say_who(principal: &str) -> Other {
26    let (name, sid) = match principal {
27        "WD" | "S-1-1-0" => ("Everyone", "S-1-1-0"),
28        "BU" | "S-1-5-32-545" => ("all Users of this computer", "S-1-5-32-545"),
29        "AU" | "S-1-5-11" => ("Authenticated Users", "S-1-5-11"),
30        "IU" | "S-1-5-4" => ("interactive users", "S-1-5-4"),
31        "NU" | "S-1-5-2" => ("network users", "S-1-5-2"),
32        "AN" | "S-1-5-7" => ("anonymous users", "S-1-5-7"),
33        "LG" => ("Guest", "S-1-5-32-546"),
34        other => (other, other),
35    };
36    Other { name: name.to_string(), sid: sid.to_string() }
37}
38
39/// Who besides `user_sid` (and the system, the administrators and the owner) the list in `sddl` allows to do anything
40/// to the object, each named once, in the order the list gives them. A denial is not an allowance, and an entry that
41/// gives no rights gives none. An empty answer is a list only the user (and those) can use.
42pub fn others_with_access(sddl: &str, user_sid: &str) -> Vec<Other> {
43    // An object with no list at all (a null list, which SDDL writes `D:NO_ACCESS_CONTROL` or leaves out) lets everyone in;
44    // an empty list (`D:`) lets nobody in.
45    let Some(dacl) = sddl.find("D:").map(|at| &sddl[at + 2..]) else { return vec![say_who("WD")] };
46    let dacl = dacl.split("S:").next().unwrap_or("");
47    if dacl.contains("NO_ACCESS_CONTROL") {
48        return vec![say_who("WD")];
49    }
50    let mut out: Vec<Other> = Vec::new();
51    for entry in dacl.split('(').skip(1) {
52        let body = entry.split(')').next().unwrap_or("");
53        let fields: Vec<&str> = body.split(';').collect();
54        let (kind, rights, principal) = (fields.first().copied().unwrap_or(""), fields.get(2).copied().unwrap_or(""), fields.get(5).copied().unwrap_or(""));
55        // `A` allowed, `OA` allowed for an object type, `XA` allowed with a condition, `ZA` a compound allowance.
56        let allows = matches!(kind, "A" | "OA" | "XA" | "ZA");
57        if !allows || rights.is_empty() || principal.is_empty() {
58            continue;
59        }
60        // SDDL writes the built-in administrator account (the user whose SID ends in -500) as `LA`, so that is the user too.
61        let is_the_user = principal.eq_ignore_ascii_case(user_sid) || (principal.eq_ignore_ascii_case("LA") && user_sid.ends_with("-500"));
62        if is_the_user || ALWAYS_ALLOWED.iter().any(|ok| ok.eq_ignore_ascii_case(principal)) {
63            continue;
64        }
65        let who = say_who(&principal.to_ascii_uppercase());
66        if !out.contains(&who) {
67            out.push(who);
68        }
69    }
70    out
71}
72
73/// What a person reads for an account Windows has no name for (one that was deleted, say), with the id that removes it.
74pub fn unnamed_account(sid: &str) -> String {
75    format!("an unnamed account (id {sid})")
76}
77
78/// The access list as SDDL text, which the user is `user_sid`: only the user and the system, nothing inherited.
79/// `folder` adds the rights to everything made inside it.
80pub fn private_sddl(user_sid: &str, folder: bool) -> String {
81    let inherit = if folder { "OICI" } else { "" };
82    format!("D:P(A;{inherit};FA;;;{user_sid})(A;{inherit};FA;;;SY)")
83}
84
85/// The list of a program folder the person's own login task runs from: the user, the system and the administrators, with
86/// nothing inherited from above (a profile can carry an entry for an account that no longer exists).
87pub fn program_folder_sddl(user_sid: &str) -> String {
88    format!("{}(A;OICI;FA;;;BA)", private_sddl(user_sid, true))
89}
90
91/// [`private_sddl`] for a file that also names `readers` (SIDs) with read rights: the one file a service writes and a person
92/// who is not its account must read (the key `agentmux open` proves itself to the server with).
93pub fn private_sddl_with_readers(user_sid: &str, folder: bool, readers: &[String]) -> String {
94    let mut out = private_sddl(user_sid, folder);
95    let inherit = if folder { "OICI" } else { "" };
96    for reader in readers {
97        out.push_str(&format!("(A;{inherit};{};;;{reader})", if folder { "0x1200a9" } else { "FR" }));
98    }
99    out
100}
101
102/// The accounts, besides the server's own, that may read its key file: the Windows service's installing person
103/// (`agentmux service install` names them, `service run` passes them on in this variable), who opens the browser with
104/// `agentmux open` from their own terminal.
105pub const KEY_READERS_ENV: &str = "AGENTMUX_KEY_READER_SIDS";
106
107/// Is `trustee`, as an access list names it (a SID, or an SDDL alias such as `LA`), one of the key `readers` (SIDs)? SDDL writes
108/// the built-in administrator account (the SID ending in -500) as `LA`, so that alias is the reader whose SID ends that way.
109pub fn is_key_reader(trustee: &str, readers: &[String]) -> bool {
110    readers.iter().any(|r| r.eq_ignore_ascii_case(trustee) || (trustee.eq_ignore_ascii_case("LA") && r.ends_with("-500")))
111}
112
113/// [`KEY_READERS_ENV`], as SIDs.
114pub fn key_readers() -> Vec<String> {
115    key_readers_of(std::env::var(KEY_READERS_ENV).ok().as_deref())
116}
117
118/// The accounts in a comma-separated value. Whitespace and empty entries are dropped, and so is anything that is not the SID of a
119/// person's own account, so a value another program put there cannot be spliced into an access list.
120fn key_readers_of(value: Option<&str>) -> Vec<String> {
121    value.unwrap_or("").split(',').map(str::trim).filter(|s| is_account_sid(s)).map(str::to_string).collect()
122}
123
124/// Is this the SID of one person's own account, as text: `S-1-5-21-<a>-<b>-<c>-<rid>` (a local or a domain account) or
125/// `S-1-12-1-<a>-<b>-<c>-<d>` (an account of an organisation's directory), every part digits only? A group, a well-known SID
126/// (Everyone, Authenticated Users, Users, Anonymous, the system, the administrators) and a built-in account that nobody signs in
127/// with (Guest and the like, relative ids 501 to 999) are not.
128pub fn is_account_sid(sid: &str) -> bool {
129    let digits = |s: &str| !s.is_empty() && s.len() <= 10 && s.chars().all(|c| c.is_ascii_digit());
130    if let Some(rest) = sid.strip_prefix("S-1-5-21-") {
131        let parts: Vec<&str> = rest.split('-').collect();
132        return parts.len() == 4 && parts.iter().all(|p| digits(p)) && parts[3].parse::<u64>().is_ok_and(|rid| rid == 500 || rid >= 1000);
133    }
134    if let Some(rest) = sid.strip_prefix("S-1-12-1-") {
135        let parts: Vec<&str> = rest.split('-').collect();
136        return parts.len() == 4 && parts.iter().all(|p| digits(p));
137    }
138    false
139}
140
141/// The words to a person whose folder lets others in: which folder, who, and the one command that fixes it: it stops what
142/// is inherited from above, takes away each of those named, and gives the folder to the person and the system.
143pub fn refusal(folder: &Path, others: &[Other], user: &str) -> String {
144    refusal_because(folder, others, user, "AgentMux Headless keeps your agents' data and its sign-in key there, so only you may")
145}
146
147/// `refusal` for a place kept for another reason, which is said in `why` (a sentence without its closing full stop).
148pub fn refusal_because(folder: &Path, others: &[Other], user: &str, why: &str) -> String {
149    let names: Vec<&str> = others.iter().map(|o| o.name.as_str()).collect();
150    let removals: String = others.iter().map(|o| format!(" /remove:g \"*{}\"", o.sid)).collect();
151    format!(
152        "{} can be opened by {} as well as you. {why}. To fix it, run: icacls \"{}\" /inheritance:r{removals} /grant:r \"{user}:(OI)(CI)F\" /grant:r \"SYSTEM:(OI)(CI)F\"",
153        folder.display(),
154        names.join(", "),
155        folder.display()
156    )
157}
158
159#[cfg(windows)]
160mod windows {
161    use std::os::windows::ffi::OsStrExt;
162    use std::path::Path;
163    use std::ptr::null_mut;
164
165    use windows_sys::Win32::Foundation::{CloseHandle, LocalFree, HANDLE};
166    use windows_sys::Win32::Security::Authorization::{
167        ConvertSecurityDescriptorToStringSecurityDescriptorW, ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW,
168        GetNamedSecurityInfoW, SetNamedSecurityInfoW, SDDL_REVISION_1, SE_FILE_OBJECT,
169    };
170    use windows_sys::Win32::Security::{
171        GetSecurityDescriptorDacl, GetTokenInformation, LookupAccountNameW, TokenElevation, TokenUser, DACL_SECURITY_INFORMATION,
172        OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, TOKEN_ELEVATION, TOKEN_QUERY, TOKEN_USER,
173    };
174    use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
175
176    fn wide(path: &Path) -> Vec<u16> {
177        path.as_os_str().encode_wide().chain(std::iter::once(0)).collect()
178    }
179
180    /// This process's user, as the text form of its SID.
181    pub fn user_sid() -> Option<String> {
182        // SAFETY: plain Win32 calls on this process's own token, closed on every path; the buffer is 8-byte aligned and as
183        // long as the call asked for.
184        unsafe {
185            let mut token: HANDLE = null_mut();
186            if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
187                return None;
188            }
189            let mut len = 0u32;
190            GetTokenInformation(token, TokenUser, null_mut(), 0, &mut len);
191            let mut buf = vec![0u64; (len as usize).div_ceil(8).max(1)];
192            let got = GetTokenInformation(token, TokenUser, buf.as_mut_ptr().cast(), len, &mut len) != 0;
193            CloseHandle(token);
194            if !got {
195                return None;
196            }
197            let user = &*(buf.as_ptr() as *const TOKEN_USER);
198            let mut text: *mut u16 = null_mut();
199            if ConvertSidToStringSidW(user.User.Sid, &mut text) == 0 || text.is_null() {
200                return None;
201            }
202            let n = (0..).take_while(|&i| *text.add(i) != 0).count();
203            let sid = String::from_utf16_lossy(std::slice::from_raw_parts(text, n));
204            LocalFree(text.cast());
205            Some(sid)
206        }
207    }
208
209    /// Is this process running with an administrator's full token (elevated)? A person who is an administrator but did not
210    /// choose "Run as administrator" is not.
211    pub fn is_elevated() -> bool {
212        // SAFETY: this process's own token, closed on every path; the buffer is the size the call asked for.
213        unsafe {
214            let mut token: HANDLE = null_mut();
215            if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
216                return false;
217            }
218            let mut elevation = TOKEN_ELEVATION { TokenIsElevated: 0 };
219            let mut len = 0u32;
220            let got = GetTokenInformation(token, TokenElevation, (&mut elevation as *mut TOKEN_ELEVATION).cast(), std::mem::size_of::<TOKEN_ELEVATION>() as u32, &mut len) != 0;
221            CloseHandle(token);
222            got && elevation.TokenIsElevated != 0
223        }
224    }
225
226    /// Does Windows say this SID is a user account (and not a group, an alias or anything else)?
227    pub fn sid_is_user(sid: &str) -> bool {
228        use windows_sys::Win32::Security::Authorization::ConvertStringSidToSidW;
229        use windows_sys::Win32::Security::{LookupAccountSidW, SidTypeUser};
230        let text: Vec<u16> = sid.encode_utf16().chain(std::iter::once(0)).collect();
231        // SAFETY: a NUL-terminated text that outlives the calls; the SID Windows allocates is freed here on every path; the name
232        // buffers are the sizes the first call asked for.
233        unsafe {
234            let mut raw: *mut std::ffi::c_void = null_mut();
235            if ConvertStringSidToSidW(text.as_ptr(), &mut raw) == 0 || raw.is_null() {
236                return false;
237            }
238            let (mut name_len, mut domain_len, mut kind) = (0u32, 0u32, 0i32);
239            LookupAccountSidW(null_mut(), raw, null_mut(), &mut name_len, null_mut(), &mut domain_len, &mut kind);
240            let mut name = vec![0u16; name_len.max(1) as usize];
241            let mut domain = vec![0u16; domain_len.max(1) as usize];
242            let found = LookupAccountSidW(null_mut(), raw, name.as_mut_ptr(), &mut name_len, domain.as_mut_ptr(), &mut domain_len, &mut kind) != 0;
243            LocalFree(raw);
244            found && kind == SidTypeUser
245        }
246    }
247
248    /// The SID, as text, of an account Windows knows by name (`NT SERVICE\AgentMuxHeadless` is one once that service exists).
249    pub fn account_sid(account: &str) -> Result<String, String> {
250        let name: Vec<u16> = account.encode_utf16().chain(std::iter::once(0)).collect();
251        // SAFETY: NUL-terminated names that outlive the calls, buffers of the sizes the first call asked for, and a text
252        // that is freed here on every path.
253        unsafe {
254            let (mut sid_len, mut domain_len, mut kind) = (0u32, 0u32, 0i32);
255            LookupAccountNameW(null_mut(), name.as_ptr(), null_mut(), &mut sid_len, null_mut(), &mut domain_len, &mut kind);
256            if sid_len == 0 {
257                return Err(format!("Windows has no account named {account}"));
258            }
259            let mut sid = vec![0u64; (sid_len as usize).div_ceil(8)];
260            let mut domain = vec![0u16; domain_len.max(1) as usize];
261            if LookupAccountNameW(null_mut(), name.as_ptr(), sid.as_mut_ptr().cast(), &mut sid_len, domain.as_mut_ptr(), &mut domain_len, &mut kind) == 0 {
262                return Err(format!("Windows has no account named {account}"));
263            }
264            let mut text: *mut u16 = null_mut();
265            if ConvertSidToStringSidW(sid.as_mut_ptr().cast(), &mut text) == 0 || text.is_null() {
266                return Err(format!("cannot write the SID of {account}"));
267            }
268            let n = (0..).take_while(|&i| *text.add(i) != 0).count();
269            let out = String::from_utf16_lossy(std::slice::from_raw_parts(text, n));
270            LocalFree(text.cast());
271            Ok(out)
272        }
273    }
274
275    /// The access list of a file or folder, as SDDL text.
276    pub fn sddl_of(path: &Path) -> Result<String, String> {
277        let name = wide(path);
278        let mut sd: PSECURITY_DESCRIPTOR = null_mut();
279        // SAFETY: `name` is NUL-terminated and outlives the calls; the descriptor and the text are LocalAlloc'd and freed
280        // here on every path.
281        unsafe {
282            let code = GetNamedSecurityInfoW(name.as_ptr(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, null_mut(), null_mut(), null_mut(), null_mut(), &mut sd);
283            if code != 0 || sd.is_null() {
284                return Err(format!("cannot read who may open {} (Windows error {code})", path.display()));
285            }
286            let mut text: *mut u16 = null_mut();
287            let ok = ConvertSecurityDescriptorToStringSecurityDescriptorW(sd, SDDL_REVISION_1, DACL_SECURITY_INFORMATION, &mut text, null_mut());
288            LocalFree(sd);
289            if ok == 0 || text.is_null() {
290                return Err(format!("cannot read who may open {}", path.display()));
291            }
292            let n = (0..).take_while(|&i| *text.add(i) != 0).count();
293            let out = String::from_utf16_lossy(std::slice::from_raw_parts(text, n));
294            LocalFree(text.cast());
295            Ok(out)
296        }
297    }
298
299    /// Give a file or folder an access list of the user and the system only, with nothing inherited from above; a folder's
300    /// list is what everything made inside it inherits.
301    pub fn restrict_to_user(path: &Path) -> Result<(), String> {
302        restrict_to_user_and_readers(path, &[])
303    }
304
305    /// [`restrict_to_user`], and the accounts in `readers` (SIDs) may read it too.
306    pub fn restrict_to_user_and_readers(path: &Path, readers: &[String]) -> Result<(), String> {
307        let user = user_sid().ok_or_else(|| "cannot find your Windows account".to_string())?;
308        apply_sddl(path, &super::private_sddl_with_readers(&user, path.is_dir(), readers))
309    }
310
311    /// Give a program folder the list of [`super::program_folder_sddl`]: only the user, the system and the administrators, nothing
312    /// inherited; what is inside it that inherits follows.
313    pub fn make_program_folder_private(path: &Path) -> Result<(), String> {
314        let user = user_sid().ok_or_else(|| "cannot find your Windows account".to_string())?;
315        apply_sddl(path, &super::program_folder_sddl(&user))
316    }
317
318    /// Replace a file or folder's access list with `sddl` (its DACL part), protected: nothing is inherited from above.
319    pub fn apply_sddl(path: &Path, sddl: &str) -> Result<(), String> {
320        let sddl: Vec<u16> = sddl.encode_utf16().chain(std::iter::once(0)).collect();
321        let mut name = wide(path);
322        let mut sd: PSECURITY_DESCRIPTOR = null_mut();
323        // SAFETY: both strings are NUL-terminated and outlive the calls; the descriptor is LocalAlloc'd and freed on every path; the
324        // list pointed into it is only used before that.
325        unsafe {
326            if ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.as_ptr(), SDDL_REVISION_1, &mut sd, null_mut()) == 0 || sd.is_null() {
327                return Err("cannot make the access list".to_string());
328            }
329            let (mut present, mut defaulted) = (0i32, 0i32);
330            let mut dacl = null_mut();
331            let got = GetSecurityDescriptorDacl(sd, &mut present, &mut dacl, &mut defaulted) != 0 && present != 0 && !dacl.is_null();
332            let code = if got {
333                SetNamedSecurityInfoW(name.as_mut_ptr(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, null_mut(), null_mut(), dacl, null_mut())
334            } else {
335                1
336            };
337            LocalFree(sd);
338            if code != 0 {
339                return Err(format!("cannot set who may open {} (Windows error {code})", path.display()));
340            }
341        }
342        Ok(())
343    }
344
345    /// Make a folder that has the access list `sddl` from the moment it exists, so nobody can put anything in it before the
346    /// list is set. Fails if the folder is already there (check `ErrorKind::AlreadyExists`).
347    pub fn create_dir_with_sddl(path: &Path, sddl: &str) -> std::io::Result<()> {
348        use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;
349        use windows_sys::Win32::Storage::FileSystem::CreateDirectoryW;
350        let text: Vec<u16> = sddl.encode_utf16().chain(std::iter::once(0)).collect();
351        let name = wide(path);
352        let mut sd: PSECURITY_DESCRIPTOR = null_mut();
353        // SAFETY: NUL-terminated strings that outlive the calls; the descriptor is LocalAlloc'd and freed on every path, after the
354        // call that reads it.
355        unsafe {
356            if ConvertStringSecurityDescriptorToSecurityDescriptorW(text.as_ptr(), SDDL_REVISION_1, &mut sd, null_mut()) == 0 || sd.is_null() {
357                return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "cannot make the access list"));
358            }
359            let attributes = SECURITY_ATTRIBUTES { nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32, lpSecurityDescriptor: sd, bInheritHandle: 0 };
360            let made = CreateDirectoryW(name.as_ptr(), &attributes) != 0;
361            let error = std::io::Error::last_os_error();
362            LocalFree(sd);
363            if made { Ok(()) } else { Err(error) }
364        }
365    }
366
367    /// Turn on a privilege this process's token has (an administrator's does, switched off).
368    fn enable_privilege(name: &str) -> bool {
369        use windows_sys::Win32::Security::{AdjustTokenPrivileges, LookupPrivilegeValueW, LUID_AND_ATTRIBUTES, SE_PRIVILEGE_ENABLED, TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES};
370        let name: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
371        // SAFETY: this process's own token, closed on every path; a NUL-terminated name that outlives the call.
372        unsafe {
373            let mut token: HANDLE = null_mut();
374            if OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &mut token) == 0 {
375                return false;
376            }
377            let mut privileges = TOKEN_PRIVILEGES { PrivilegeCount: 1, Privileges: [LUID_AND_ATTRIBUTES { Luid: std::mem::zeroed(), Attributes: SE_PRIVILEGE_ENABLED }] };
378            let found = LookupPrivilegeValueW(null_mut(), name.as_ptr(), &mut privileges.Privileges[0].Luid) != 0;
379            let done = found && AdjustTokenPrivileges(token, 0, &privileges, 0, null_mut(), null_mut()) != 0;
380            CloseHandle(token);
381            done
382        }
383    }
384
385    /// Make the administrators the owner of a file or folder and give them (and the system) full control of it, whatever its
386    /// list said before: what an administrator does to delete what a service made for its own account alone. Needs an elevated
387    /// token (it uses the right to take ownership and to restore).
388    ///
389    /// The change is made through a handle opened on the entry itself, never on what a link points to: `Ok(false)` says the entry
390    /// is a link (a junction or a symbolic link) and nothing was changed, so what an account that can still write there swaps in
391    /// between a check and this call is not followed.
392    pub fn take_over(path: &Path) -> Result<bool, String> {
393        use std::os::windows::io::FromRawHandle;
394        use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
395        use windows_sys::Win32::Security::Authorization::SetSecurityInfo;
396        use windows_sys::Win32::Security::GetSecurityDescriptorOwner;
397        use windows_sys::Win32::Storage::FileSystem::{
398            CreateFileW, GetFileInformationByHandle, BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
399            FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, READ_CONTROL, WRITE_DAC, WRITE_OWNER,
400        };
401        let _ = enable_privilege("SeTakeOwnershipPrivilege");
402        let _ = enable_privilege("SeRestorePrivilege");
403        let sddl: Vec<u16> = "O:BAD:P(A;OICI;FA;;;BA)(A;OICI;FA;;;SY)".encode_utf16().chain(std::iter::once(0)).collect();
404        let name = wide(path);
405        let mut sd: PSECURITY_DESCRIPTOR = null_mut();
406        // SAFETY: NUL-terminated strings that outlive the calls; the handle is owned by a `File` (closed on every path); the
407        // descriptor is LocalAlloc'd, read only before it is freed, and freed on every path.
408        unsafe {
409            let handle = CreateFileW(
410                name.as_ptr(),
411                READ_CONTROL | WRITE_OWNER | WRITE_DAC,
412                FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
413                null_mut(),
414                OPEN_EXISTING,
415                FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
416                null_mut(),
417            );
418            if handle == INVALID_HANDLE_VALUE {
419                return Err(format!("cannot open {}: {}", path.display(), std::io::Error::last_os_error()));
420            }
421            let held = std::fs::File::from_raw_handle(handle as _);
422            let mut info: BY_HANDLE_FILE_INFORMATION = std::mem::zeroed();
423            if GetFileInformationByHandle(handle, &mut info) == 0 {
424                return Err(format!("cannot read {}: {}", path.display(), std::io::Error::last_os_error()));
425            }
426            if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
427                return Ok(false);
428            }
429            if ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.as_ptr(), SDDL_REVISION_1, &mut sd, null_mut()) == 0 || sd.is_null() {
430                return Err("cannot make the access list".to_string());
431            }
432            let (mut owner, mut defaulted) = (null_mut(), 0i32);
433            let (mut present, mut dacl) = (0i32, null_mut());
434            let got = GetSecurityDescriptorOwner(sd, &mut owner, &mut defaulted) != 0 && !owner.is_null() && GetSecurityDescriptorDacl(sd, &mut present, &mut dacl, &mut defaulted) != 0 && present != 0;
435            let code = if got {
436                SetSecurityInfo(handle, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, owner, null_mut(), dacl, null_mut())
437            } else {
438                1
439            };
440            LocalFree(sd);
441            drop(held);
442            if code != 0 {
443                return Err(format!("cannot take over {} (Windows error {code})", path.display()));
444            }
445        }
446        Ok(true)
447    }
448
449    /// The owner and the access list of a file or folder, as SDDL text (`O:...D:...`).
450    pub fn owner_and_sddl_of(path: &Path) -> Result<String, String> {
451        let name = wide(path);
452        let mut sd: PSECURITY_DESCRIPTOR = null_mut();
453        // SAFETY: as `sddl_of`: a NUL-terminated name, and a descriptor and a text that are freed here on every path.
454        unsafe {
455            let info = OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION;
456            let code = GetNamedSecurityInfoW(name.as_ptr(), SE_FILE_OBJECT, info, null_mut(), null_mut(), null_mut(), null_mut(), &mut sd);
457            if code != 0 || sd.is_null() {
458                return Err(format!("cannot read who owns {} (Windows error {code})", path.display()));
459            }
460            let mut text: *mut u16 = null_mut();
461            let ok = ConvertSecurityDescriptorToStringSecurityDescriptorW(sd, SDDL_REVISION_1, info, &mut text, null_mut());
462            LocalFree(sd);
463            if ok == 0 || text.is_null() {
464                return Err(format!("cannot read who owns {}", path.display()));
465            }
466            let n = (0..).take_while(|&i| *text.add(i) != 0).count();
467            let out = String::from_utf16_lossy(std::slice::from_raw_parts(text, n));
468            LocalFree(text.cast());
469            Ok(out)
470        }
471    }
472
473    /// The name Windows gives an account, as `DOMAIN\name`; `None` for a SID it cannot name (an account that was deleted, or one
474    /// of another computer's).
475    pub fn account_name(sid: &str) -> Option<String> {
476        use windows_sys::Win32::Security::Authorization::ConvertStringSidToSidW;
477        use windows_sys::Win32::Security::LookupAccountSidW;
478        let text: Vec<u16> = sid.encode_utf16().chain(std::iter::once(0)).collect();
479        // SAFETY: a NUL-terminated text that outlives the calls; the SID Windows allocates is freed here on every path; the name
480        // buffers are the sizes the first call asked for.
481        unsafe {
482            let mut raw: *mut std::ffi::c_void = null_mut();
483            if ConvertStringSidToSidW(text.as_ptr(), &mut raw) == 0 || raw.is_null() {
484                return None;
485            }
486            let (mut name_len, mut domain_len, mut kind) = (0u32, 0u32, 0i32);
487            LookupAccountSidW(null_mut(), raw, null_mut(), &mut name_len, null_mut(), &mut domain_len, &mut kind);
488            let mut name = vec![0u16; name_len.max(1) as usize];
489            let mut domain = vec![0u16; domain_len.max(1) as usize];
490            let found = LookupAccountSidW(null_mut(), raw, name.as_mut_ptr(), &mut name_len, domain.as_mut_ptr(), &mut domain_len, &mut kind) != 0;
491            LocalFree(raw);
492            if !found {
493                return None;
494            }
495            let name = String::from_utf16_lossy(&name[..name_len as usize]);
496            let domain = String::from_utf16_lossy(&domain[..domain_len as usize]);
497            Some(if domain.is_empty() { name } else { format!("{domain}\\{name}") })
498        }
499    }
500
501    /// Who besides the user, the system and the administrators may open this file or folder, each by the name Windows gives the
502    /// account, or as an unnamed account with its id when Windows has none.
503    pub fn others_who_can_open(path: &Path) -> Result<Vec<super::Other>, String> {
504        let user = user_sid().ok_or_else(|| "cannot find your Windows account".to_string())?;
505        let mut others = super::others_with_access(&sddl_of(path)?, &user);
506        for other in &mut others {
507            if other.name == other.sid && other.sid.starts_with("S-1-") {
508                other.name = account_name(&other.sid).unwrap_or_else(|| super::unnamed_account(&other.sid));
509            }
510        }
511        Ok(others)
512    }
513}
514
515#[cfg(windows)]
516pub use windows::{account_name, account_sid, apply_sddl, make_program_folder_private, create_dir_with_sddl, is_elevated, sid_is_user, take_over, others_who_can_open, owner_and_sddl_of, restrict_to_user, restrict_to_user_and_readers, sddl_of, user_sid};
517
518#[cfg(test)]
519mod tests {
520    use super::*;
521
522    const USER: &str = "S-1-5-21-1111-2222-3333-1001";
523
524    #[test]
525    fn only_sids_are_taken_as_the_accounts_that_may_read_the_key() {
526        assert!(key_readers_of(None).is_empty());
527        assert_eq!(key_readers_of(Some(" S-1-5-21-1-2-3-1001 ,S-1-5-21-1-2-3-500,,")), vec!["S-1-5-21-1-2-3-1001", "S-1-5-21-1-2-3-500"]);
528        // A name, a trailing entry, or anything else that is not a SID is dropped.
529        assert!(key_readers_of(Some("Everyone,(A;;FA;;;WD),S-1-1-0)x,S-1-5-21-1;FA")).is_empty());
530    }
531
532    #[test]
533    fn only_the_sid_of_a_persons_own_account_is_one_that_may_read_the_key() {
534        for ok in ["S-1-5-21-3904905834-1961560920-3170238172-1001", "S-1-5-21-1-2-3-500", "S-1-5-21-1-2-3-1000", "S-1-12-1-1-2-3-4"] {
535            assert!(is_account_sid(ok), "{ok}");
536        }
537        for (bad, what) in [
538            ("S-1-1-0", "Everyone"),
539            ("S-1-5-11", "Authenticated Users"),
540            ("S-1-5-32-545", "Users"),
541            ("S-1-5-32-544", "the administrators"),
542            ("S-1-5-7", "Anonymous"),
543            ("S-1-5-18", "the system"),
544            ("S-1-5-4", "interactive users"),
545            ("S-1-5-21-1-2-3-513", "Domain Users"),
546            ("S-1-5-21-1-2-3-512", "Domain Admins"),
547            ("S-1-5-21-1-2-3-501", "Guest"),
548            ("S-1-5-21-1-2-3", "a domain, no account"),
549            ("S-1-5-21-1-2-3-1001-5", "too many parts"),
550            ("S-1-5-21-1-2-3-10a", "not digits"),
551            ("S-1-5-21-1-2-3-+1001", "a sign"),
552            ("S-1-12-1-1-2-3", "too few parts"),
553            ("S-1-5-80-1-2-3-4-5", "a service"),
554            ("Everyone", "a name"),
555            ("", "nothing"),
556        ] {
557            assert!(!is_account_sid(bad), "{what}: {bad}");
558        }
559    }
560
561    #[test]
562    fn a_file_list_can_name_readers_and_a_folder_list_gives_them_read_and_traverse() {
563        let readers = vec!["S-1-5-21-9-9-9-1001".to_string()];
564        assert_eq!(private_sddl_with_readers(USER, false, &readers), format!("D:P(A;;FA;;;{USER})(A;;FA;;;SY)(A;;FR;;;S-1-5-21-9-9-9-1001)"));
565        assert_eq!(private_sddl_with_readers(USER, true, &readers), format!("D:P(A;OICI;FA;;;{USER})(A;OICI;FA;;;SY)(A;OICI;0x1200a9;;;S-1-5-21-9-9-9-1001)"));
566        assert_eq!(private_sddl_with_readers(USER, false, &[]), private_sddl(USER, false));
567    }
568
569    #[test]
570    fn a_program_folder_list_is_the_user_the_system_and_the_administrators_and_nothing_inherited() {
571        let sddl = program_folder_sddl(USER);
572        assert_eq!(sddl, format!("D:P(A;OICI;FA;;;{USER})(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)"));
573        assert!(others_with_access(&sddl, USER).is_empty(), "nobody else is in it");
574        // The profile's own list, with an entry for an account that no longer exists, is what it replaces.
575        let profile = format!("D:AI(A;OICIID;0x1200a9;;;S-1-5-21-1-2-3-1005)(A;OICIID;FA;;;{USER})(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)");
576        assert_eq!(others_with_access(&profile, USER).len(), 1);
577        assert_eq!(unnamed_account("S-1-5-21-1-2-3-1005"), "an unnamed account (id S-1-5-21-1-2-3-1005)");
578    }
579
580    #[test]
581    fn a_default_profile_list_has_nobody_else() {
582        let sddl = format!("D:PAI(A;OICIID;FA;;;{USER})(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)");
583        assert!(others_with_access(&sddl, USER).is_empty());
584        // Owner and creator-owner entries, with the owner's rights empty, are the user's own.
585        assert!(others_with_access(&format!("D:P(A;;FA;;;{USER})(A;;;;;OW)(A;OICIIO;FA;;;CO)"), USER).is_empty());
586    }
587
588    #[test]
589    fn everyone_and_the_other_accounts_of_the_computer_are_named() {
590        let sddl = format!("D:AI(A;OICIID;FA;;;{USER})(A;OICIID;0x1200a9;;;WD)(A;OICIID;FR;;;BU)(A;OICIID;FA;;;S-1-5-21-1111-2222-3333-1002)");
591        let names = |sddl: &str| others_with_access(sddl, USER).into_iter().map(|o| o.name).collect::<Vec<_>>();
592        assert_eq!(names(&sddl), vec!["Everyone", "all Users of this computer", "S-1-5-21-1111-2222-3333-1002"]);
593        assert_eq!(names("D:(A;;GR;;;AU)(A;;GR;;;AU)"), vec!["Authenticated Users"], "each is named once");
594        assert_eq!(others_with_access("D:(A;;GR;;;WD)", USER), vec![Other { name: "Everyone".into(), sid: "S-1-1-0".into() }]);
595    }
596
597    #[test]
598    fn a_denial_an_empty_entry_and_an_audit_entry_give_nobody_access() {
599        let sddl = format!("D:P(D;;FA;;;WD)(A;;;;;WD)(A;;FA;;;{USER})S:(AU;SA;FA;;;WD)");
600        assert!(others_with_access(&sddl, USER).is_empty(), "{:?}", others_with_access(&sddl, USER));
601        assert!(others_with_access("D:", USER).is_empty(), "an empty list lets nobody in");
602        assert!(others_with_access("D:P", USER).is_empty());
603    }
604
605    #[test]
606    fn a_key_reader_is_found_by_its_sid_or_by_the_alias_sddl_gives_the_built_in_administrator() {
607        let admin = vec!["S-1-5-21-1111-2222-3333-500".to_string()];
608        let person = vec!["S-1-5-21-1111-2222-3333-1001".to_string()];
609        assert!(is_key_reader("S-1-5-21-1111-2222-3333-500", &admin));
610        assert!(is_key_reader("s-1-5-21-1111-2222-3333-1001", &person), "case does not matter");
611        assert!(is_key_reader("LA", &admin), "SDDL's name for the RID 500 account");
612        assert!(!is_key_reader("LA", &person), "LA is not a person whose SID does not end in -500");
613        assert!(!is_key_reader("S-1-1-0", &admin) && !is_key_reader("LA", &[]));
614    }
615
616    /// SDDL writes the built-in administrator account (RID 500) as `LA`: for that user it is the user, for anyone else it is not.
617    #[test]
618    fn the_built_in_administrator_is_the_user_only_when_it_is_the_user() {
619        let admin = "S-1-5-21-1111-2222-3333-500";
620        assert!(others_with_access("D:PAI(A;OICI;FA;;;LA)(A;OICI;FA;;;SY)", admin).is_empty());
621        let found = others_with_access("D:P(A;OICI;FA;;;LA)(A;OICI;FA;;;SY)", USER);
622        assert_eq!(found.len(), 1);
623        assert_eq!(found[0].sid, "LA");
624    }
625
626    /// An object with no access list at all is open to everyone, and is read as such.
627    #[test]
628    fn a_missing_access_list_is_open_to_everyone() {
629        let everyone = vec![Other { name: "Everyone".into(), sid: "S-1-1-0".into() }];
630        for sddl in ["", "O:BAG:BA", "D:NO_ACCESS_CONTROL", "D:P(A;;FA;;;SY)NO_ACCESS_CONTROL"] {
631            assert_eq!(others_with_access(sddl, USER), everyone, "{sddl:?}");
632        }
633    }
634
635    #[test]
636    fn the_users_own_sid_matches_whatever_its_case() {
637        assert!(others_with_access(&format!("D:P(A;;FA;;;{})", USER.to_lowercase()), USER).is_empty());
638    }
639
640    #[test]
641    fn the_private_list_is_the_user_and_the_system_and_nothing_inherited() {
642        let folder = private_sddl(USER, true);
643        assert_eq!(folder, format!("D:P(A;OICI;FA;;;{USER})(A;OICI;FA;;;SY)"));
644        assert_eq!(private_sddl(USER, false), format!("D:P(A;;FA;;;{USER})(A;;FA;;;SY)"));
645        assert!(others_with_access(&folder, USER).is_empty());
646    }
647
648    #[test]
649    fn the_refusal_names_the_folder_who_and_the_command() {
650        let others = others_with_access("D:(A;;GR;;;WD)(A;;GR;;;AU)", USER);
651        let said = refusal(Path::new(r"C:\Users\sam\.agentmux\channels\headless"), &others, r"HOME\sam");
652        assert!(said.contains(r"C:\Users\sam\.agentmux\channels\headless") && said.contains("Everyone, Authenticated Users"), "{said}");
653        assert!(said.contains(r#"icacls "C:\Users\sam\.agentmux\channels\headless" /inheritance:r /remove:g "*S-1-1-0" /remove:g "*S-1-5-11" /grant:r "HOME\sam:(OI)(CI)F" /grant:r "SYSTEM:(OI)(CI)F""#), "{said}");
654    }
655
656    /// Windows: a folder is read as private, then given to Everyone and read as not, then limited to the user and read as
657    /// private again, and what is made inside it afterwards is private too.
658    #[cfg(windows)]
659    #[test]
660    fn a_folder_that_lets_others_in_is_found_and_made_private() {
661        use windows_sys::Win32::Foundation::LocalFree;
662        use windows_sys::Win32::Security::Authorization::{ConvertStringSecurityDescriptorToSecurityDescriptorW, SetNamedSecurityInfoW, SDDL_REVISION_1, SE_FILE_OBJECT};
663        use windows_sys::Win32::Security::{GetSecurityDescriptorDacl, DACL_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION};
664        use std::os::windows::ffi::OsStrExt;
665
666        let outer = tempfile::tempdir().unwrap();
667        let dir = outer.path().join("channel");
668        std::fs::create_dir(&dir).unwrap();
669        let user = user_sid().expect("a user");
670        restrict_to_user(&dir).unwrap();
671        assert!(others_who_can_open(&dir).unwrap().is_empty(), "{}", sddl_of(&dir).unwrap());
672
673        // What is made inside a private folder is private: the folder's list is inherited.
674        let inner = dir.join("data");
675        std::fs::create_dir(&inner).unwrap();
676        std::fs::write(inner.join("srv-auth-key"), b"k").unwrap();
677        assert!(others_who_can_open(&inner).unwrap().is_empty(), "{}", sddl_of(&inner).unwrap());
678        assert!(others_who_can_open(&inner.join("srv-auth-key")).unwrap().is_empty(), "{}", sddl_of(&inner.join("srv-auth-key")).unwrap());
679
680        // Open it to Everyone (the damage the check is for).
681        let open: Vec<u16> = format!("D:P(A;OICI;FA;;;{user})(A;OICI;FA;;;SY)(A;OICI;FR;;;WD)").encode_utf16().chain(std::iter::once(0)).collect();
682        let mut name: Vec<u16> = dir.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
683        // SAFETY: NUL-terminated strings that outlive the calls; the descriptor is freed after the list is used.
684        unsafe {
685            let mut sd = std::ptr::null_mut();
686            assert_ne!(ConvertStringSecurityDescriptorToSecurityDescriptorW(open.as_ptr(), SDDL_REVISION_1, &mut sd, std::ptr::null_mut()), 0);
687            let (mut present, mut defaulted, mut dacl) = (0i32, 0i32, std::ptr::null_mut());
688            assert_ne!(GetSecurityDescriptorDacl(sd, &mut present, &mut dacl, &mut defaulted), 0);
689            let code = SetNamedSecurityInfoW(name.as_mut_ptr(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, std::ptr::null_mut(), std::ptr::null_mut(), dacl, std::ptr::null_mut());
690            LocalFree(sd);
691            assert_eq!(code, 0);
692        }
693        assert_eq!(others_who_can_open(&dir).unwrap().into_iter().map(|o| o.name).collect::<Vec<_>>(), vec!["Everyone".to_string()]);
694
695        restrict_to_user(&dir).unwrap();
696        assert!(others_who_can_open(&dir).unwrap().is_empty());
697        // A file is limited to the user too.
698        let key = outer.path().join("key");
699        std::fs::write(&key, b"k").unwrap();
700        restrict_to_user(&key).unwrap();
701        assert!(others_who_can_open(&key).unwrap().is_empty(), "{}", sddl_of(&key).unwrap());
702        // SDDL writes the built-in administrator account (RID 500, the CI runner's user) as `LA`.
703        let user_in_sddl = if user.ends_with("-500") { "LA" } else { user.as_str() };
704        assert!(!sddl_of(&key).unwrap().contains("WD") && sddl_of(&key).unwrap().contains(user_in_sddl), "{}", sddl_of(&key).unwrap());
705    }
706}