automation: the control token file is private from the moment it is created

On Windows, create_token_file created the token file with its folder's
access list and only then restricted it to the user and SYSTEM. Another
local account that the folder lets read new files could open a handle in
between, and that handle keeps its read access after the list changes,
so it could read the token once it was written.

craft_platform::owner_only::create_private_file creates the file with an
owner-only security descriptor in the call that creates it, writes the
contents through that handle, and checks the result. The control token
file now uses it on Windows. Unix keeps mode 0600 at create, and losing
the create race to another process still reads the winner's file.
This commit is contained in:
dotCooCoo
2026-11-24 10:04:42 -08:00
parent 518f3c7775
commit c9c6010394
4 changed files with 110 additions and 17 deletions
+20 -16
View File
@@ -8,8 +8,11 @@
//! idle for [`IO_TIMEOUT`] is closed. Tokens are 64 hex characters in either case, kept
//! lower-cased by the server and compared in constant time with hex letters folded. None of this depends on the transport: the TCP server and a test channel share it.
#[cfg(not(windows))]
use std::fs::OpenOptions;
use std::io::{BufRead, Write};
use std::io::BufRead;
#[cfg(not(windows))]
use std::io::Write;
use std::path::Path;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
@@ -323,26 +326,27 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> {
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent).map_err(|e| AutomationError::Io(format!("{}: {e}", parent.display())))?;
}
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
// On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token
// is written, and a file that cannot be restricted is removed rather than left for the token to go into later.
// On Windows the file is created with an access list of its user and SYSTEM only, so it never has its folder's
// access list, and the token is written through the handle that created it.
#[cfg(windows)]
{
use craft_platform::owner_only;
if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) {
drop(file);
let _ = std::fs::remove_file(path);
return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display())));
owner_only::current_user_sid()
.and_then(|me| owner_only::create_private_file(path, &me, format!("{token}\n").as_bytes()))
.map_err(|e| AutomationError::Io(format!("{}: cannot create the control token file for its owner only: {e}", path.display())))
}
#[cfg(not(windows))]
{
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))
}
writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))
}
/// The server's token, lower-cased. Both given is
+6
View File
@@ -141,6 +141,12 @@ fn server_token_sources_and_validation() {
use std::os::unix::fs::PermissionsExt;
assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);
}
#[cfg(windows)]
{
use craft_platform::owner_only;
let sddl = owner_only::sddl_of(&file).unwrap();
assert_eq!(owner_only::foreign_access(&sddl, &owner_only::current_user_sid().unwrap()), None, "{sddl}");
}
assert_eq!(server_token(None, Some(&file)).unwrap(), created);
// An existing file's content is trimmed and lower-cased.
+1 -1
View File
@@ -23,7 +23,7 @@ pull in heavier dependencies.
| always | `watch::FileWatch` and `Changed`: open files that changed on disk. One worker thread (`craft-file-watch`) compares each file's metadata (`FileStamp`) every 250 ms and sleeps while nothing is watched; a changed file is reported once it has settled and, with `ReadPolicy::Whole`, looks complete. The app's own saves are recognised by `known_now`; `disk_differs` answers at Save time; `take_changes` runs on the frame the worker's `Wake` asks for. |
| always (native) | `default_app::make_default`: the Preferences button that makes the app the system default for its file types. Windows opens Settings › Default apps (`SettingsOpened`), Linux and BSD run `xdg-mime default` (`MadeDefault`, refused inside Flatpak or without an installed desktop entry), macOS answers `Unsupported`. `path_from_arg` and `rejoin_split_paths` read the paths a launcher hands the app. Only a button may call it. |
| always (native) | `temp::TempDir` and `TempFiles`: private temporary folders created exclusively with owner-only permissions (`0700`, files `0600`, `create_new`), named with the process id and a counter, removed on drop. |
| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. |
| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `create_private_file` creates a file with that access list from the start, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. |
| always | `PlatformText`: a user-visible message of a platform service (id, English text with `{name}` placeholders) that the app looks up in its own catalog. The open, clipboard, watch, default-app and temp services and craft-dialogs' save flow use it. No words table lists them yet, so the missing-translation list does not show them. |
| `screen` | Screen capture for the screen colour picker (`craft_platform::screen`). |
| `apple-events` | Apple Events requests on macOS (`open::apple_events`), through `fmv-macos-events`. |
+83
View File
@@ -205,6 +205,60 @@ pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<()
restricted
}
/// Create the file `path`, which must not exist yet, with user `me` (as for [`restrict_to_owner`])
/// as its owner and an access list of that user and SYSTEM only, given to Windows in the call that
/// creates the file, so the file never has its folder's access list, and write `contents` through
/// that handle, opened unshared. Then check the file's descriptor as [`restrict_to_owner`] does.
/// An existing `path` is an error of kind [`std::io::ErrorKind::AlreadyExists`] and is left as it
/// is. A file that was created but could not be written or checked is removed again. `contents`
/// reach PowerShell through its standard input, never as script text or an environment variable.
#[cfg(windows)]
pub fn create_private_file(path: &std::path::Path, me: &str, contents: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
/// The exit code the script ends with when the file already exists.
const EXISTS: i32 = 3;
// No double quotes: the command line would strip them. -2147024816 and -2147024713 are the
// HRESULTs of ERROR_FILE_EXISTS and ERROR_ALREADY_EXISTS.
const SCRIPT: &str = "$ErrorActionPreference = 'Stop'; \
$s = New-Object Security.AccessControl.FileSecurity; \
$s.SetSecurityDescriptorSddlForm('O:' + $env:CRAFT_ACL_USER + 'D:P(A;;FA;;;' + $env:CRAFT_ACL_USER + ')(A;;FA;;;SY)'); \
try { $fs = New-Object IO.FileStream -ArgumentList @($env:CRAFT_ACL_PATH, [IO.FileMode]::CreateNew, \
[Security.AccessControl.FileSystemRights]::Write, [IO.FileShare]::None, 4096, [IO.FileOptions]::None, $s) } \
catch { $e = $_.Exception; while ($e.InnerException) { $e = $e.InnerException }; \
if ($e.HResult -eq -2147024816 -or $e.HResult -eq -2147024713) { exit 3 }; throw }; \
try { [Console]::OpenStandardInput().CopyTo($fs); $fs.Flush($true); $fs.Dispose() } \
catch { $fs.Dispose(); [IO.File]::Delete($env:CRAFT_ACL_PATH); throw }";
let mut child = system_tool(POWERSHELL)
.args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT])
.env("CRAFT_ACL_PATH", path)
.env("CRAFT_ACL_USER", me)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()?;
// A script that stops before reading (the file exists) closes the pipe; its exit code says why.
let sent = child.stdin.take().map(|mut stdin| stdin.write_all(contents));
let out = child.wait_with_output()?;
if out.status.code() == Some(EXISTS) {
return Err(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "the file already exists"));
}
if !out.status.success() {
return Err(std::io::Error::other(format!(
"PowerShell could not create the file for its owner only: {}",
String::from_utf8_lossy(&out.stderr).trim()
)));
}
let checked = match sent {
Some(Ok(())) => sddl_of(path).and_then(|sddl| still_foreign(&sddl, me)),
Some(Err(e)) => Err(e),
None => Err(std::io::Error::other("PowerShell's standard input could not be opened")),
};
if checked.is_err() {
let _ = std::fs::remove_file(path);
}
checked
}
/// `Err` naming the problem when the descriptor read back after restricting still isn't `me`'s
/// alone, so a file that only looks restricted is never used as one.
#[cfg(any(test, windows))]
@@ -495,6 +549,35 @@ $n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256)
let _ = std::fs::remove_dir_all(&dir);
}
/// A file created by `create_private_file` in a folder that lets Users read what's in it is the
/// user's alone as soon as it exists, with nothing written to it yet; one created with contents
/// holds them, and an existing file is refused and left as it is.
#[cfg(windows)]
#[test]
fn a_private_file_is_private_from_the_start() {
let dir = std::env::temp_dir().join(format!("craft-owner-only-private-file-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap();
assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr));
let me = current_user_sid().unwrap();
let empty = dir.join("empty.token");
create_private_file(&empty, &user(), b"").unwrap();
let sddl = sddl_of(&empty).unwrap();
assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}");
assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}");
assert_eq!(std::fs::read(&empty).unwrap(), b"");
let file = dir.join("ctl.token");
create_private_file(&file, &user(), b"secret\n").unwrap();
let sddl = sddl_of(&file).unwrap();
assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}");
assert_eq!(std::fs::read(&file).unwrap(), b"secret\n");
let again = create_private_file(&file, &user(), b"other\n").unwrap_err();
assert_eq!(again.kind(), std::io::ErrorKind::AlreadyExists, "{again}");
assert_eq!(std::fs::read(&file).unwrap(), b"secret\n");
let _ = std::fs::remove_dir_all(&dir);
}
/// A folder may give its user Modify but not Full control, so a file created there doesn't let
/// its owner change the owner (no `WRITE_OWNER`). An owner can always replace the access list,
/// though, and the user's Full control on it then allows setting the owner.