Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Changelog

- **Fixed** On Windows, cached tasks that run or spawn 32-bit (or other cross-architecture) programs, such as 32-bit `gpg.exe` during Git commit signing, no longer trigger a `RunDLL` error dialog or fail to start. The program runs untracked instead, and the run is reported as not cached with the untracked executable and architecture ([#1058](https://github.com/voidzero-dev/vite-task/pull/1058)).
- **Changed** When automatic file-access tracking cannot record everything a task did, the "Not cached" summary line now includes the specific reason (for example, that the tracking channel ran out of capacity or that installing the seccomp filter failed for a given executable) ([#1054](https://github.com/voidzero-dev/vite-task/pull/1054), [#1056](https://github.com/voidzero-dev/vite-task/pull/1056)).
- **Changed** Invalid remote cache endpoint URLs in `cache.remote.url` or `VP_REMOTE_CACHE_URL` (such as missing schemes, non-`http`/`https` schemes, or missing hosts) now fail upfront during configuration and planning instead of warning per task during execution, and `vp run --help` now documents `VP_REMOTE_CACHE`, `VP_REMOTE_CACHE_URL`, and `VP_REMOTE_CACHE_HEADER_<NAME>` ([#1048](https://github.com/voidzero-dev/vite-task/pull/1048)).
- **Changed** Removed `NEXT_*`, `VERCEL`, `VERCEL_*`, `USE_OUTPUT_FOR_EDGE_FUNCTIONS`, `NOW_BUILDER`, `VC_MICROFRONTENDS_CONFIG_FILE_NAME`, `GITHUB_*`, `ACTIONS_ID_TOKEN_REQUEST_URL`, `DOCKER_*`, `BUILDKIT_*`, `COMPOSE_*`, and `*_TOKEN` from the default untracked environment variables passed to cached tasks. Tasks that need any of these variables should declare them explicitly in `cache.env` or `cache.untrackedEnv` ([#1044](https://github.com/voidzero-dev/vite-task/pull/1044)).
Expand Down
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions crates/fspy/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ winapi = { workspace = true, features = ["winbase", "securitybaseapi", "handleap
wincode = { workspace = true }
winsafe = { workspace = true, features = ["kernel"] }

[target.'cfg(target_os = "windows")'.dev-dependencies]
winapi = { workspace = true, features = ["synchapi"] }

[target.'cfg(target_os = "macos")'.dev-dependencies]
tempfile = { workspace = true }

Expand Down
2 changes: 2 additions & 0 deletions crates/fspy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ On musl targets, only `seccomp_unotify`-based tracking is used (no preload libra

It uses [Detours](https://github.com/microsoft/Detours) to intercept file system calls. The implementation is in `src/windows`.

Only same-architecture processes can be injected with the preload DLL. When a tracked run launches a cross-architecture process (such as a 32-bit x86 binary on 64-bit Windows, or an emulated x64 binary from a native ARM64 process), `fspy` lets it run untracked and reports `TrackingIncomplete::UnsupportedProcessArchitecture` so the task result is not cached.

## Unified interface

The unified interface of `Command` is in `src/command.rs`.
Expand Down
49 changes: 48 additions & 1 deletion crates/fspy/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{ffi::OsString, path::PathBuf};
use std::{ffi::OsString, fmt, path::PathBuf};

#[derive(thiserror::Error, Debug)]
pub enum SpawnError {
Expand Down Expand Up @@ -31,6 +31,17 @@ pub enum SpawnError {
OsSpawn(std::io::Error),
}

/// Human-readable name for a Windows PE `IMAGE_FILE_MACHINE_*` constant.
const fn process_architecture_name(machine: u16) -> Option<&'static str> {
match machine {
0x014c => Some("32-bit x86"),
0x01c4 => Some("32-bit ARM"),
0x8664 => Some("x64"),
0xaa64 => Some("ARM64"),
_ => None,
}
}

/// A tracked process could not record a file access it went on to perform,
/// so the accesses collected for the run are a subset of what it really
/// touched.
Expand All @@ -54,6 +65,36 @@ pub enum TrackingIncomplete {
std::io::Error::from_raw_os_error(*.errno)
)]
SeccompInstallFailed { program: PathBuf, errno: i32 },

/// A spawned Windows process had a different processor architecture than
/// the tracker (for example, a 32-bit x86 child launched from a 64-bit
/// process), so it ran untracked.
#[error("{}", UnsupportedArchDisplay(.program.as_deref(), *.machine))]
UnsupportedProcessArchitecture { program: Option<PathBuf>, machine: u16 },
}

struct UnsupportedArchDisplay<'a>(Option<&'a std::path::Path>, u16);

impl fmt::Display for UnsupportedArchDisplay<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match (process_architecture_name(self.1), self.0) {
(Some(arch), Some(path)) => {
write!(f, "cannot track {arch} process `{}`", path.display())
}
(Some(arch), None) => write!(f, "cannot track {arch} process"),
(None, Some(path)) => {
write!(
f,
"cannot track process `{}` (unsupported architecture 0x{:04x})",
path.display(),
self.1
)
}
(None, None) => {
write!(f, "cannot track process (unsupported architecture 0x{:04x})", self.1)
}
}
}
}

impl From<fspy_shared::ipc::TrackingLoss<'_>> for TrackingIncomplete {
Expand All @@ -65,6 +106,12 @@ impl From<fspy_shared::ipc::TrackingLoss<'_>> for TrackingIncomplete {
errno,
}
}
fspy_shared::ipc::TrackingLoss::UnsupportedProcessArchitecture { program, machine } => {
Self::UnsupportedProcessArchitecture {
program: program.map(|p| PathBuf::from(p.to_cow_os_str().into_owned())),
machine,
}
}
}
}
}
46 changes: 46 additions & 0 deletions crates/fspy/src/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,50 @@ mod tests {
);
assert!(incomplete.to_string().contains("could not install seccomp filter"));
}

#[test]
fn channel_accesses_decodes_unsupported_process_architecture() {
let receiver = access_channel(1 << 30, Global).unwrap();
let sender = receiver.sender().unwrap();

#[cfg(unix)]
let raw = b"/windows/syswow64/cmd.exe";
#[cfg(unix)]
let program = IpcStr::from_bytes(raw);
#[cfg(windows)]
let raw: Vec<u16> = r"C:\Windows\SysWOW64\cmd.exe".encode_utf16().collect();
#[cfg(windows)]
let program = IpcStr::from_wide(&raw);

sender.report_loss(&TrackingLoss::UnsupportedProcessArchitecture {
program: Some(program),
machine: 0x014c,
});
drop(sender);

let Err(incomplete) = ChannelAccesses::try_from(receiver) else {
panic!("expected TrackingIncomplete");
};
let expected_path = PathBuf::from(program.to_cow_os_str().into_owned());
assert_eq!(
incomplete,
TrackingIncomplete::UnsupportedProcessArchitecture {
program: Some(expected_path),
machine: 0x014c,
}
);
assert!(incomplete.to_string().contains("cannot track 32-bit x86 process"));

let receiver_no_path = access_channel(1 << 30, Global).unwrap();
let sender_no_path = receiver_no_path.sender().unwrap();
sender_no_path.report_loss(&TrackingLoss::UnsupportedProcessArchitecture {
program: None,
machine: 0x014c,
});
drop(sender_no_path);
let Err(incomplete_no_path) = ChannelAccesses::try_from(receiver_no_path) else {
panic!("expected TrackingIncomplete");
};
assert_eq!(incomplete_no_path.to_string(), "cannot track 32-bit x86 process");
}
}
111 changes: 72 additions & 39 deletions crates/fspy/src/windows/mod.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
use std::{
ffi::{CStr, c_char},
ffi::{CStr, OsString, c_char},
io,
os::windows::{
ffi::OsStrExt,
ffi::{OsStrExt, OsStringExt},
io::{AsRawHandle, BorrowedHandle},
},
path::PathBuf,
sync::Arc,
};

use allocator_api2::alloc::Global;
use fspy_detours_sys::{DetourCopyPayloadToProcess, DetourUpdateProcessWithDll};
use fspy_shared::{
ipc::{PathAccess, access_channel},
windows::{PAYLOAD_ID, Payload},
ipc::{AccessReceiver, PathAccess, access_channel},
windows::{PAYLOAD_ID, Payload, query_process_image_name, unsupported_process_machine},
};
use futures_util::FutureExt;
use ntapi::{ntpsapi::NtResumeProcess, ntrtl::RtlNtStatusToDosError};
Expand All @@ -24,9 +26,17 @@ use winapi::{
use winsafe::co::{CP, WC};

use crate::{
ChildTermination, TrackedChild, command::Command, error::SpawnError, ipc::ChannelAccesses,
ChildTermination, TrackedChild,
command::Command,
error::{SpawnError, TrackingIncomplete},
ipc::ChannelAccesses,
};

enum TrackingState {
Channel(AccessReceiver<Global>),
Lost(TrackingIncomplete),
}

const INTERPOSE_CDYLIB: Artifact =
artifact!("fspy_preload", "CARGO_CDYLIB_FILE_FSPY_PRELOAD_WINDOWS");

Expand Down Expand Up @@ -89,16 +99,6 @@ impl SpyImpl {
let ansi_dll_path_with_nul = &self.ansi_dll_path_with_nul;
command.env("FSPY", "1");

let receiver = access_channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global)
.map_err(SpawnError::ChannelCreation)?;

let payload = Payload {
channel_conf: receiver.conf(),
ansi_dll_path_with_nul: ansi_dll_path_with_nul.to_bytes(),
};
let payload_bytes = wincode::serialize(&payload).unwrap();
let payload_len = payload_bytes.len().try_into().unwrap();

let mut command = command.into_tokio_command();
command.creation_flags(CREATE_SUSPENDED);
let mut child = command.spawn().map_err(SpawnError::OsSpawn)?;
Expand All @@ -110,27 +110,57 @@ impl SpyImpl {
let process = unsafe { BorrowedHandle::borrow_raw(child.raw_handle().unwrap()) };
let process_handle = process.try_clone_to_owned().map_err(SpawnError::OsSpawn)?;
let raw_process = process_handle.as_raw_handle().cast::<winapi::ctypes::c_void>();
let mut dll_paths = ansi_dll_path_with_nul.as_ptr().cast::<c_char>();
// SAFETY: raw_process is a valid handle to the suspended child process,
// dll_paths points to a valid null-terminated ANSI string.
let success = unsafe { DetourUpdateProcessWithDll(raw_process, &raw mut dll_paths, 1) };
if success != TRUE {
return Err(SpawnError::Injection(io::Error::last_os_error()));
}

// SAFETY: raw_process is valid, PAYLOAD_ID is a static GUID,
// payload_bytes is a valid buffer with the correct length.
let success = unsafe {
DetourCopyPayloadToProcess(
raw_process,
&PAYLOAD_ID,
payload_bytes.as_ptr().cast(),
payload_len,
)
};
if success != TRUE {
return Err(SpawnError::Injection(io::Error::last_os_error()));
}
// Skip DLL injection when the spawned process uses a different
// architecture (e.g. a 32-bit x86 binary on 64-bit Windows):
// resume it untracked and mark tracking incomplete instead of
// failing the spawn.
// SAFETY: `raw_process` is a valid handle to the suspended child process.
let tracking =
if let Some(machine) = unsafe { unsupported_process_machine(raw_process) } {
// SAFETY: `raw_process` is a valid handle to the suspended child process.
let program = unsafe { query_process_image_name(raw_process, Global) }
.map(|wide| PathBuf::from(OsString::from_wide(&wide)));
TrackingState::Lost(TrackingIncomplete::UnsupportedProcessArchitecture {
program,
machine,
})
} else {
let receiver = access_channel(crate::ipc::shm_capacity(), Global)
.map_err(SpawnError::ChannelCreation)?;

let payload = Payload {
channel_conf: receiver.conf(),
ansi_dll_path_with_nul: ansi_dll_path_with_nul.to_bytes(),
};
let payload_bytes = wincode::serialize(&payload).unwrap();
let payload_len = payload_bytes.len().try_into().unwrap();

let mut dll_paths = ansi_dll_path_with_nul.as_ptr().cast::<c_char>();
// SAFETY: raw_process is a valid handle to the suspended child process,
// dll_paths points to a valid null-terminated ANSI string.
let success =
unsafe { DetourUpdateProcessWithDll(raw_process, &raw mut dll_paths, 1) };
if success != TRUE {
return Err(SpawnError::Injection(io::Error::last_os_error()));
}

// SAFETY: raw_process is valid, PAYLOAD_ID is a static GUID,
// payload_bytes is a valid buffer with the correct length.
let success = unsafe {
DetourCopyPayloadToProcess(
raw_process,
&PAYLOAD_ID,
payload_bytes.as_ptr().cast(),
payload_len,
)
};
if success != TRUE {
return Err(SpawnError::Injection(io::Error::last_os_error()));
}

TrackingState::Channel(receiver)
};

// Resume using the process handle, without the nightly main-thread handle API.
// SAFETY: raw_process is a valid child process handle with PROCESS_SUSPEND_RESUME access.
Expand All @@ -144,10 +174,10 @@ impl SpyImpl {
)));
}

Ok(process_handle)
Ok((process_handle, tracking))
})();

let process_handle = preparation.inspect_err(|_| {
let (process_handle, tracking) = preparation.inspect_err(|_| {
// Do not leave a suspended process behind if tracking initialization fails.
let _ = child.start_kill();
})?;
Expand All @@ -169,8 +199,11 @@ impl SpyImpl {
};
// Close the ipc channel after the child has exited.
// We are not interested in path accesses from descendants after the main child has exited.
let path_accesses = ChannelAccesses::try_from(receiver)
.map(|ipc_accesses| PathAccessIterable { ipc_accesses });
let path_accesses = match tracking {
TrackingState::Channel(receiver) => ChannelAccesses::try_from(receiver)
.map(|ipc_accesses| PathAccessIterable { ipc_accesses }),
TrackingState::Lost(loss) => Err(loss),
};

io::Result::Ok(ChildTermination { status, path_accesses })
})
Expand Down
12 changes: 9 additions & 3 deletions crates/fspy/tests/untracked_fallback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,9 @@ fn static_binary_runs_untracked_when_injection_fails() {
let Err(AccessCloseError::Reported(report)) = receiver.close() else {
panic!("the channel did not report the untracked exec");
};
let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode();
let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode() else {
panic!("unexpected tracking loss variant");
};
assert_eq!(program, IpcStr::from_bytes(test_bin_path().as_os_str().as_bytes()));
assert_ne!(errno, 0);
}
Expand Down Expand Up @@ -107,7 +109,9 @@ fn execvp_fallback_keeps_path_search() {
let Err(AccessCloseError::Reported(report)) = receiver.close() else {
panic!("the channel did not report the untracked exec");
};
let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode();
let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode() else {
panic!("unexpected tracking loss variant");
};
assert_eq!(program, IpcStr::from_bytes(test_bin_path().as_os_str().as_bytes()));
assert_ne!(errno, 0);
}
Expand Down Expand Up @@ -166,7 +170,9 @@ fn posix_spawn_runs_untracked_when_injection_fails() {
let Err(AccessCloseError::Reported(report)) = receiver.close() else {
panic!("the channel did not report the untracked posix_spawn");
};
let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode();
let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode() else {
panic!("unexpected tracking loss variant");
};
assert_eq!(program, IpcStr::from_bytes(test_bin.as_os_str().as_bytes()));
assert_ne!(errno, 0);
}
Expand Down
Loading
Loading