mirror of
https://github.com/zed-industries/zed.git
synced 2026-11-19 06:59:22 +01:00
sandbox: Sandbox Windows agent commands with PSEC instead of WSL
Run sandboxed terminal commands in a Windows Process Security Environment (an AppContainer) through a launcher mode of `zed.exe`, instead of under Bubblewrap in WSL. The PSEC bindings and launch sequence are adapted from MXC's PSEC backend. With sandboxing on, every agent command, sandboxed or not, runs in PowerShell, and the system prompt names that shell. The agent now picks the shell and passes it to `AcpThread::create_terminal`, and the prompt's shell moved from `ProjectContext` to the template so it is computed per request. The WSL sandbox code is now unreachable; it is removed in the next commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Generated
+16
-1
@@ -6350,6 +6350,16 @@ version = "0.5.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
|
||||
|
||||
[[package]]
|
||||
name = "flatbuffers"
|
||||
version = "25.12.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3"
|
||||
dependencies = [
|
||||
"bitflags 2.13.1",
|
||||
"rustc_version",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.8"
|
||||
@@ -15803,6 +15813,9 @@ name = "sandbox"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"dunce",
|
||||
"flatbuffers",
|
||||
"futures 0.3.34",
|
||||
"gpui",
|
||||
"http_proxy",
|
||||
@@ -15814,6 +15827,8 @@ dependencies = [
|
||||
"serde_json",
|
||||
"smol",
|
||||
"tempfile",
|
||||
"windows 0.62.2",
|
||||
"windows-core 0.62.2",
|
||||
"windows-registry 0.6.1",
|
||||
]
|
||||
|
||||
@@ -16172,7 +16187,7 @@ version = "2.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d43fb82d550b07e6f929a58d7d0935182602f48ddead875f5ee313c41c8f07fe"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"base64 0.23.1",
|
||||
"nohash-hasher",
|
||||
"num-traits",
|
||||
"serde_core",
|
||||
|
||||
@@ -633,6 +633,7 @@ env_logger = "0.11"
|
||||
etagere = "0.2"
|
||||
exec = "0.3.1"
|
||||
fancy-regex = "0.19"
|
||||
flatbuffers = "25.12"
|
||||
flume = { version = "0.12", default-features = false, features = ["async"] }
|
||||
font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "94b0f28166665e8fd2f53ff6d268a14955c82269", package = "zed-font-kit", version = "0.14.1-zed", default-features = false }
|
||||
foreign-types = "0.5"
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
> [!IMPORTANT]
|
||||
> Remove this line to confirm you've reviewed this PR before submitting.
|
||||
# Zed
|
||||
|
||||
[](https://zed.dev)
|
||||
|
||||
@@ -56,7 +56,7 @@ use text::Bias;
|
||||
use ui::App;
|
||||
use util::markdown::{MarkdownCodeBlock, MarkdownEscaped};
|
||||
use util::path_list::PathList;
|
||||
use util::{ResultExt, get_default_system_shell_preferring_bash, paths::PathStyle};
|
||||
use util::{ResultExt, paths::PathStyle};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(crate) enum MetadataUpdate {
|
||||
@@ -8307,6 +8307,7 @@ impl AcpThread {
|
||||
cwd: Option<PathBuf>,
|
||||
output_byte_limit: Option<u64>,
|
||||
sandbox_wrap: Option<SandboxWrap>,
|
||||
shell: String,
|
||||
cx: &mut Context<Self>,
|
||||
) -> Task<Result<Entity<Terminal>>> {
|
||||
let env = match &cwd {
|
||||
@@ -8341,13 +8342,6 @@ impl AcpThread {
|
||||
let terminal_id = terminal_id.clone();
|
||||
async move |_this, cx| {
|
||||
let env = env.await;
|
||||
let shell = project
|
||||
.update(cx, |project, cx| {
|
||||
project
|
||||
.remote_client()
|
||||
.and_then(|r| r.read(cx).default_system_shell())
|
||||
})
|
||||
.unwrap_or_else(|| get_default_system_shell_preferring_bash());
|
||||
|
||||
// The sandbox owns the network proxy (for restricted-network
|
||||
// policies) and injects the child's proxy env vars, returning
|
||||
@@ -8356,13 +8350,11 @@ impl AcpThread {
|
||||
#[cfg(target_os = "windows")]
|
||||
let (task_command, task_args, task_env, sandbox, spawn_cwd) =
|
||||
if sandbox_wrap.is_some() {
|
||||
let (task_command, task_args) = task::ShellBuilder::new(
|
||||
&Shell::Program("/bin/sh".to_string()),
|
||||
false,
|
||||
)
|
||||
.non_interactive()
|
||||
.redirect_stdin_to_dev_null()
|
||||
.build(Some(command.clone()), &args);
|
||||
let (task_command, task_args) =
|
||||
task::ShellBuilder::new(&Shell::Program(shell), is_windows)
|
||||
.non_interactive()
|
||||
.redirect_stdin_to_dev_null()
|
||||
.build(Some(command.clone()), &args);
|
||||
let wrap = cx.background_spawn(prepare_sandbox_wrap(
|
||||
task_command,
|
||||
task_args,
|
||||
@@ -8380,12 +8372,8 @@ impl AcpThread {
|
||||
)),
|
||||
)),
|
||||
};
|
||||
(task_command, task_args, task_env, sandbox, None)
|
||||
(task_command, task_args, task_env, sandbox, cwd.clone())
|
||||
} else {
|
||||
// No sandbox wrap means we're running unsandboxed, and
|
||||
// on Windows that deliberately changes the shell: the
|
||||
// sandboxed path runs under WSL's Linux bash, but this
|
||||
// fallback uses the host's `shell` against the native cwd.
|
||||
let mut builder = ShellBuilder::new(&Shell::Program(shell), is_windows);
|
||||
if headless {
|
||||
builder = builder.non_interactive();
|
||||
@@ -16911,6 +16899,7 @@ mod tests {
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
util::get_default_system_shell_preferring_bash(),
|
||||
cx,
|
||||
)
|
||||
})
|
||||
@@ -16940,6 +16929,7 @@ mod tests {
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
util::get_default_system_shell_preferring_bash(),
|
||||
cx,
|
||||
)
|
||||
})
|
||||
|
||||
@@ -3854,6 +3854,12 @@ impl ThreadEnvironment for NativeThreadEnvironment {
|
||||
Err(error) => return Task::ready(Err(error)),
|
||||
};
|
||||
}
|
||||
let shell = match self.thread.read_with(cx, |thread, cx| {
|
||||
crate::sandboxing::terminal_shell(thread.project().read(cx), cx)
|
||||
}) {
|
||||
Ok(shell) => shell,
|
||||
Err(error) => return Task::ready(Err(error)),
|
||||
};
|
||||
let task = self.acp_thread.update(cx, |thread, cx| {
|
||||
thread.create_terminal(
|
||||
command,
|
||||
@@ -3862,6 +3868,7 @@ impl ThreadEnvironment for NativeThreadEnvironment {
|
||||
cwd,
|
||||
output_byte_limit,
|
||||
sandbox_wrap,
|
||||
shell,
|
||||
cx,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -209,6 +209,37 @@ pub(crate) fn sandboxing_enabled_for_project(project: &Project, cx: &App) -> boo
|
||||
.allow_unsandboxed
|
||||
}
|
||||
|
||||
pub(crate) fn terminal_shell(project: &Project, cx: &App) -> String {
|
||||
#[cfg(target_os = "windows")]
|
||||
if sandboxing_enabled_for_project(project, cx) {
|
||||
|
||||
/// Git Bash is not yet compatible with the native Windows sandbox.
|
||||
/// Furthermore, packaged (MSIX) applications are not yet compatible either.
|
||||
/// So, we avoid selecting Git Bash or MSIX versions of PowerShell when the
|
||||
/// native Windows sandbox is enabled.
|
||||
let shell = util::get_windows_system_shell();
|
||||
let is_packaged = shell.to_ascii_lowercase().contains(r"\windowsapps\");
|
||||
if !is_packaged || sandbox::can_launch_packaged_apps() {
|
||||
return shell;
|
||||
}
|
||||
let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_string());
|
||||
return format!(r"{system_root}\System32\WindowsPowerShell\v1.0\powershell.exe");
|
||||
}
|
||||
project
|
||||
.remote_client()
|
||||
.and_then(|remote| remote.read(cx).default_system_shell())
|
||||
.unwrap_or_else(util::get_default_system_shell_preferring_bash)
|
||||
}
|
||||
|
||||
/// The name of the shell [`terminal_shell`] picks, for the system prompt.
|
||||
pub(crate) fn terminal_shell_name(project: &Project, cx: &App) -> String {
|
||||
util::shell::ShellKind::new(
|
||||
&terminal_shell(project, cx),
|
||||
project.path_style(cx).is_windows(),
|
||||
)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Whether agent-run terminal commands should be wrapped in an OS-level
|
||||
/// sandbox for this process. See module docs for the policy.
|
||||
pub(crate) fn sandboxing_enabled(cx: &App) -> bool {
|
||||
|
||||
@@ -59,8 +59,10 @@ pub struct SystemPromptTemplate<'a> {
|
||||
/// section describes the right one rather than advertising a `$TMPDIR`
|
||||
/// that doesn't behave as stated.
|
||||
pub is_linux: bool,
|
||||
/// Whether sandboxed terminal commands run through WSL on Windows.
|
||||
/// Whether the host is Windows.
|
||||
pub is_windows: bool,
|
||||
/// The shell terminal commands run in.
|
||||
pub shell: String,
|
||||
}
|
||||
|
||||
impl Template for SystemPromptTemplate<'_> {
|
||||
@@ -108,6 +110,7 @@ mod tests {
|
||||
sandboxing: false,
|
||||
is_linux: false,
|
||||
is_windows: false,
|
||||
shell: "bash".to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
@@ -141,6 +144,7 @@ mod tests {
|
||||
sandboxing: false,
|
||||
is_linux: false,
|
||||
is_windows: false,
|
||||
shell: "bash".to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
@@ -170,6 +174,7 @@ mod tests {
|
||||
sandboxing: false,
|
||||
is_linux: false,
|
||||
is_windows: false,
|
||||
shell: "bash".to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
@@ -203,6 +208,7 @@ mod tests {
|
||||
sandboxing: true,
|
||||
is_linux: false,
|
||||
is_windows: false,
|
||||
shell: "bash".to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
@@ -246,6 +252,7 @@ mod tests {
|
||||
sandboxing: true,
|
||||
is_linux: true,
|
||||
is_windows: false,
|
||||
shell: "bash".to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
@@ -279,12 +286,13 @@ mod tests {
|
||||
sandboxing: true,
|
||||
is_linux: false,
|
||||
is_windows: true,
|
||||
shell: "powershell".to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
||||
assert!(rendered.contains("commands run inside WSL under Bubblewrap"));
|
||||
assert!(rendered.contains("Protected Git metadata remains read-only"));
|
||||
assert!(rendered.contains("inside a Windows AppContainer sandbox"));
|
||||
assert!(rendered.contains("`.git` directories remain protected"));
|
||||
assert!(rendered.contains("do not use this on Windows"));
|
||||
assert!(rendered.contains("such requests are rejected"));
|
||||
assert!(rendered.contains("allow_all_hosts: true"));
|
||||
@@ -309,6 +317,7 @@ mod tests {
|
||||
sandboxing: true,
|
||||
is_linux: false,
|
||||
is_windows: false,
|
||||
shell: "bash".to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
@@ -331,6 +340,7 @@ mod tests {
|
||||
sandboxing: true,
|
||||
is_linux: false,
|
||||
is_windows: false,
|
||||
shell: "bash".to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
@@ -351,6 +361,7 @@ mod tests {
|
||||
sandboxing: false,
|
||||
is_linux: false,
|
||||
is_windows: false,
|
||||
shell: "bash".to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
@@ -369,6 +380,7 @@ mod tests {
|
||||
sandboxing: false,
|
||||
is_linux: false,
|
||||
is_windows: false,
|
||||
shell: "bash".to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
let rendered = template.render(&templates).unwrap();
|
||||
|
||||
@@ -160,28 +160,14 @@ The current project contains the following root directories:
|
||||
The `terminal` tool runs commands inside a sandbox with these permissions:
|
||||
|
||||
- Reads: any path on the filesystem is readable, including Git metadata.
|
||||
{{#if is_linux}}
|
||||
- Writes: `/tmp` is writable but is cleared between `terminal` calls{{#if worktrees}}. These project directories are also writable and persist across calls:
|
||||
{{#each worktrees}}
|
||||
- `{{abs_path}}`
|
||||
{{/each}}
|
||||
`.git` directories remain protected. Writes anywhere else on the filesystem are blocked.{{else}}. No project directories are currently writable.{{/if}}
|
||||
{{else}}
|
||||
{{#if is_windows}}
|
||||
- Execution: commands run inside WSL under Bubblewrap. Native Windows project paths are routed through WSL's `/mnt/<drive>/...` filesystem view.
|
||||
- Writes: `/tmp` inside WSL is writable but is cleared between `terminal` calls{{#if worktrees}}. These project directories are also writable and persist across calls:
|
||||
{{#each worktrees}}
|
||||
- `{{abs_path}}`
|
||||
{{/each}}
|
||||
Protected Git metadata remains read-only. Writes anywhere else on the WSL filesystem and mounted Windows drives are blocked.{{else}}. No project directories are currently writable.{{/if}}
|
||||
{{else}}
|
||||
- Writes: a per-thread temporary directory exposed via `$TMPDIR`, `$TMP`, and `$TEMP` is writable and persists across `terminal` calls in this thread{{#if worktrees}}, along with these project directories:
|
||||
- Execution: commands run inside a Windows AppContainer sandbox. Programs from MSYS2 or Cygwin (including Git Bash's suite of Unix tools) and apps from the Microsoft store may not work inside it. If one fails to start, rerun the command unsandboxed.
|
||||
{{/if}}
|
||||
- Writes: {{#if is_linux}}`/tmp` is writable but is cleared between `terminal` calls{{else}}{{#if is_windows}}a per-command temporary directory exposed via `%TEMP%` and `%TMP%` is writable but is removed after each `terminal` call{{else}}a per-thread temporary directory exposed via `$TMPDIR`, `$TMP`, and `$TEMP` is writable and persists across `terminal` calls in this thread{{/if}}{{/if}}{{#if worktrees}}. These project directories are also writable and persist across calls:
|
||||
{{#each worktrees}}
|
||||
- `{{abs_path}}`
|
||||
{{/each}}
|
||||
`.git` directories remain protected. Writes anywhere else on the filesystem are blocked.{{else}}. No project directories are currently writable.{{/if}}
|
||||
{{/if}}
|
||||
{{/if}}
|
||||
- Network: outbound network access is blocked.
|
||||
|
||||
{{#if is_windows}}
|
||||
|
||||
@@ -610,15 +610,10 @@ async fn test_thinking_allowed_when_model_cannot_disable_thinking(cx: &mut TestA
|
||||
|
||||
#[gpui::test]
|
||||
async fn test_system_prompt(cx: &mut TestAppContext) {
|
||||
let ThreadTest {
|
||||
fake,
|
||||
thread,
|
||||
project_context,
|
||||
..
|
||||
} = setup(cx, TestModel::Fake).await;
|
||||
let ThreadTest { fake, thread, .. } = setup(cx, TestModel::Fake).await;
|
||||
|
||||
project_context.update(cx, |project_context, _cx| {
|
||||
project_context.shell = "test-shell".into()
|
||||
let shell = thread.read_with(cx, |thread, cx| {
|
||||
crate::sandboxing::terminal_shell_name(thread.project().read(cx), cx)
|
||||
});
|
||||
thread.update(cx, |thread, _| thread.add_tool(EchoTool));
|
||||
thread
|
||||
@@ -643,7 +638,7 @@ async fn test_system_prompt(cx: &mut TestAppContext) {
|
||||
panic!("Expected text content");
|
||||
};
|
||||
assert!(
|
||||
system_prompt.contains("test-shell"),
|
||||
system_prompt.contains(&format!("Default Shell: {shell}")),
|
||||
"unexpected system message: {:?}",
|
||||
system_message
|
||||
);
|
||||
|
||||
@@ -4635,6 +4635,7 @@ impl Thread {
|
||||
),
|
||||
is_linux: cfg!(target_os = "linux"),
|
||||
is_windows: cfg!(target_os = "windows"),
|
||||
shell: crate::sandboxing::terminal_shell_name(self.project.read(cx), cx),
|
||||
}
|
||||
.render(&self.templates)
|
||||
.context("failed to build system prompt")
|
||||
|
||||
@@ -368,6 +368,11 @@ impl EditToolTest {
|
||||
sandboxing: false,
|
||||
is_linux: cfg!(target_os = "linux"),
|
||||
is_windows: cfg!(target_os = "windows"),
|
||||
shell: util::shell::ShellKind::new(
|
||||
&util::get_default_system_shell_preferring_bash(),
|
||||
cfg!(windows),
|
||||
)
|
||||
.to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
template.render(&templates)?
|
||||
|
||||
@@ -231,6 +231,11 @@ impl TerminalToolTest {
|
||||
sandboxing: false,
|
||||
is_linux: cfg!(target_os = "linux"),
|
||||
is_windows: cfg!(target_os = "windows"),
|
||||
shell: util::shell::ShellKind::new(
|
||||
&util::get_default_system_shell_preferring_bash(),
|
||||
cfg!(windows),
|
||||
)
|
||||
.to_string(),
|
||||
};
|
||||
template.render(&Templates::new())?
|
||||
};
|
||||
|
||||
@@ -203,6 +203,11 @@ impl WriteToolTest {
|
||||
sandboxing: false,
|
||||
is_linux: cfg!(target_os = "linux"),
|
||||
is_windows: cfg!(target_os = "windows"),
|
||||
shell: util::shell::ShellKind::new(
|
||||
&util::get_default_system_shell_preferring_bash(),
|
||||
cfg!(windows),
|
||||
)
|
||||
.to_string(),
|
||||
};
|
||||
let templates = Templates::new();
|
||||
template.render(&templates)?
|
||||
|
||||
@@ -161,9 +161,8 @@ pub struct SandboxedTerminalToolInput {
|
||||
#[cfg_attr(
|
||||
target_os = "windows",
|
||||
doc = "\nEvery path here must be an existing directory, given as a Windows drive \
|
||||
path (`C:\\...`) or a WSL absolute path (`/...`); a path that does not exist \
|
||||
cannot be granted. To write somewhere new, request write access to the nearest \
|
||||
existing parent directory."
|
||||
path (`C:\\...`); a path that does not exist cannot be granted. To write somewhere \
|
||||
new, request write access to the nearest existing parent directory."
|
||||
)]
|
||||
#[serde(default)]
|
||||
pub fs_write_paths: Vec<String>,
|
||||
@@ -185,15 +184,6 @@ pub struct SandboxedTerminalToolInput {
|
||||
/// needs behavior the sandbox can't grant on a per-permission basis,
|
||||
/// including commands that must write Git metadata.
|
||||
/// Requesting it triggers a user approval prompt.
|
||||
#[cfg_attr(
|
||||
target_os = "windows",
|
||||
doc = "\nOn Windows, running unsandboxed also switches the shell. Sandboxed \
|
||||
commands run under WSL's Linux bash; an unsandboxed command instead runs in the \
|
||||
host's default shell — Git Bash (or scoop's bash) when one is installed, otherwise \
|
||||
PowerShell/cmd. Path conventions change accordingly (e.g. `C:\\...` or `/c/...` \
|
||||
rather than WSL's `/mnt/c/...`), so a command written for the sandboxed shell may \
|
||||
behave differently here."
|
||||
)]
|
||||
#[serde(default)]
|
||||
pub unsandboxed: Option<bool>,
|
||||
/// A short justification for why this command needs the sandbox
|
||||
@@ -581,7 +571,6 @@ async fn run_terminal_tool(
|
||||
// what lets enforcement rebuild the grant via a verifying reopen rather than
|
||||
// re-resolving the requested path by string (closing a symlink TOCTOU). A
|
||||
// path that can't be resolved is dropped — fail-closed.
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
let write_paths: Vec<settings::GrantedWritePath> = write_paths
|
||||
.into_iter()
|
||||
.filter_map(|requested| match sandbox::resolve_canonical(&requested) {
|
||||
@@ -595,31 +584,6 @@ async fn run_terminal_tool(
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
#[cfg(target_os = "windows")]
|
||||
let write_paths: Vec<settings::GrantedWritePath> = {
|
||||
let Some(release) = wsl_zed_release.clone() else {
|
||||
return Err("Could not select a Linux Zed release for WSL sandboxing".to_string());
|
||||
};
|
||||
let mut resolved_paths = Vec::with_capacity(write_paths.len());
|
||||
for requested in write_paths {
|
||||
match sandbox::resolve_canonical_for_grant(requested.clone(), release.clone()).await {
|
||||
Ok(resolved) => {
|
||||
resolved_paths.push(settings::GrantedWritePath::resolved_on_fs(
|
||||
requested,
|
||||
resolved.canonical,
|
||||
resolved.on_windows_fs,
|
||||
));
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"could not resolve sandbox write path {} in WSL: {error:#}",
|
||||
requested.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
resolved_paths
|
||||
};
|
||||
|
||||
let request = crate::sandboxing::SandboxRequest {
|
||||
network,
|
||||
@@ -628,53 +592,6 @@ async fn run_terminal_tool(
|
||||
write_paths,
|
||||
};
|
||||
|
||||
// Before any escalation prompt: if this command's sandbox will contain a
|
||||
// path on a Windows drive (DrvFs) — from an explicit grant, a standing
|
||||
// grant, or the default project directory — its integrity guarantees are
|
||||
// weaker. When the warning is enabled, confirm with the user first. This
|
||||
// gate is transient (never persisted): on "Continue" the normal flow
|
||||
// (including any escalation prompt) proceeds; on "Abort" the command is
|
||||
// cancelled. It recurs until the warning is disabled in settings.
|
||||
//
|
||||
// The warning only makes sense when a WSL sandbox will actually wrap the
|
||||
// command, so it is skipped when the command is guaranteed to run without
|
||||
// one (`unsandboxed_floor`: the user already turned the sandbox off for
|
||||
// this thread) and when WSL is structurally absent (no registered distro —
|
||||
// sandbox creation is guaranteed to fail, and the creation-failure
|
||||
// fallback prompt handles that conversation instead).
|
||||
if sandboxing
|
||||
&& !want_unsandboxed
|
||||
&& !unsandboxed_floor
|
||||
&& persistent.warn_ntfs_grants
|
||||
&& sandbox::wsl_distro_registered()
|
||||
{
|
||||
let effective = event_stream.effective_sandbox_request(&request, &persistent);
|
||||
let contains_windows_fs = effective
|
||||
.write_paths
|
||||
.iter()
|
||||
.any(|granted| granted.on_windows_fs)
|
||||
|| cx.update(|cx| {
|
||||
let project = project.read(cx);
|
||||
working_dir
|
||||
.as_deref()
|
||||
.is_some_and(|path| sandbox::path_is_on_windows_drive(path))
|
||||
|| sandbox_worktree_writable_paths(project, cx)
|
||||
.iter()
|
||||
.any(|path| sandbox::path_is_on_windows_drive(path))
|
||||
});
|
||||
if contains_windows_fs
|
||||
&& let Err(error) = cx
|
||||
.update(|cx| event_stream.authorize_windows_fs_warning(cx))
|
||||
.await
|
||||
{
|
||||
// Carry the underlying error so a prompt-delivery failure is
|
||||
// distinguishable from a genuine user abort.
|
||||
return Ok(format!(
|
||||
"Command cancelled: the user declined to run a command whose sandbox writes to a Windows drive ({error})."
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if request.needs_escalation() {
|
||||
let reason = sandbox_input
|
||||
.reason
|
||||
@@ -944,41 +861,17 @@ async fn run_terminal_tool(
|
||||
// chose to run through), tell the agent so it can account for the weaker
|
||||
// isolation. Computed here — after the Windows fallback above may have set
|
||||
// the reason — so every affected command communicates the state.
|
||||
let sandbox_note = sandbox_not_applied.as_ref().map(|reason| {
|
||||
// Only the Windows-specific block below mutates this; on other
|
||||
// platforms the note is returned exactly as built.
|
||||
#[cfg_attr(not(target_os = "windows"), allow(unused_mut))]
|
||||
let mut note = match reason {
|
||||
acp_thread::SandboxNotAppliedReason::DisabledForThisThread => {
|
||||
"Note: this command ran WITHOUT an OS sandbox because the user allowed unsandboxed \
|
||||
let sandbox_note = sandbox_not_applied.as_ref().map(|reason| match reason {
|
||||
acp_thread::SandboxNotAppliedReason::DisabledForThisThread => {
|
||||
"Note: this command ran WITHOUT an OS sandbox because the user allowed unsandboxed \
|
||||
execution for the rest of this thread."
|
||||
.to_string()
|
||||
}
|
||||
acp_thread::SandboxNotAppliedReason::ErrorLinuxWsl(error) => format!(
|
||||
"Note: this command ran WITHOUT an OS sandbox because one could not be \
|
||||
created ({}).",
|
||||
error.user_facing_message()
|
||||
),
|
||||
};
|
||||
// On Windows, running without a sandbox also changes the interpreter:
|
||||
// the sandboxed path runs the command under WSL's Linux shell, but
|
||||
// every unsandboxed path that reaches here falls back to the host
|
||||
// shell (Git Bash, or PowerShell/cmd when no bash is installed) against
|
||||
// native Windows paths. The model writes commands for the WSL/Linux
|
||||
// sandbox, so the loss of isolation isn't the whole story — warn it
|
||||
// that the shell and path conventions differ too, or a command that
|
||||
// worked sandboxed may silently misbehave or fail here.
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
note.push(' ');
|
||||
note.push_str(
|
||||
"It also ran under the host shell (Git Bash, or PowerShell/cmd when no bash is \
|
||||
installed) instead of WSL's Linux shell, so the interpreter and path \
|
||||
conventions differ from the sandbox: Linux-only commands and `/mnt/...` paths \
|
||||
may fail. Rewrite the command for the host shell if it doesn't work.",
|
||||
);
|
||||
.to_string()
|
||||
}
|
||||
note
|
||||
acp_thread::SandboxNotAppliedReason::ErrorLinuxWsl(error) => format!(
|
||||
"Note: this command ran WITHOUT an OS sandbox because one could not be \
|
||||
created ({}).",
|
||||
error.user_facing_message()
|
||||
),
|
||||
});
|
||||
|
||||
let terminal_id = terminal.id(cx).map_err(|e| e.to_string())?;
|
||||
|
||||
@@ -15,9 +15,7 @@ use std::{
|
||||
time::Duration,
|
||||
};
|
||||
use text::LineEnding;
|
||||
use util::{
|
||||
ResultExt, get_default_system_shell_preferring_bash, rel_path::RelPath, shell::ShellKind,
|
||||
};
|
||||
use util::{ResultExt, rel_path::RelPath};
|
||||
|
||||
pub const RULES_FILE_NAMES: &[&str] = &[
|
||||
".rules",
|
||||
@@ -38,7 +36,6 @@ pub struct ProjectContext {
|
||||
pub has_rules: bool,
|
||||
pub os: String,
|
||||
pub arch: String,
|
||||
pub shell: String,
|
||||
// Similarly to `has_rules`, `has_skills` is a derived flag exposed
|
||||
// to the handlebars template (which can't do
|
||||
// `!skills.is_empty()`). These are `pub(crate)` so the only way to
|
||||
@@ -58,8 +55,6 @@ impl ProjectContext {
|
||||
has_rules,
|
||||
os: std::env::consts::OS.to_string(),
|
||||
arch: std::env::consts::ARCH.to_string(),
|
||||
shell: ShellKind::new(&get_default_system_shell_preferring_bash(), cfg!(windows))
|
||||
.to_string(),
|
||||
skills: Vec::new(),
|
||||
has_skills: false,
|
||||
}
|
||||
|
||||
@@ -74,7 +74,25 @@ gpui = { workspace = true, features = ["test-support"] }
|
||||
tempfile.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
base64.workspace = true
|
||||
dunce.workspace = true
|
||||
flatbuffers.workspace = true
|
||||
# Structural WSL-installed check (registered distros under HKCU\...\Lxss)
|
||||
# without spawning `wsl.exe`.
|
||||
smol.workspace = true
|
||||
windows = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Security",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System_Console",
|
||||
"Win32_System_Environment",
|
||||
"Win32_System_JobObjects",
|
||||
"Win32_System_LibraryLoader",
|
||||
"Win32_System_Threading",
|
||||
"Win32_System_WindowsProgramming",
|
||||
] }
|
||||
windows-core.workspace = true
|
||||
windows-registry.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
@@ -23,6 +23,8 @@ mod linux_bubblewrap;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos_seatbelt;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows_psec;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows_wsl;
|
||||
|
||||
@@ -37,6 +39,8 @@ pub use util::{
|
||||
resolve_canonical,
|
||||
};
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use windows_psec::can_launch_packaged_apps;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use windows_wsl::{ResolvedGrant, resolve_canonical_for_grant};
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
@@ -723,7 +727,7 @@ impl Sandbox {
|
||||
if matches!(policy.network, SandboxNetPolicy::Restricted { .. }) {
|
||||
return Err(unsupported_restricted_network_on_windows());
|
||||
}
|
||||
Ok(())
|
||||
windows_psec::check_available().map_err(map_anyhow_error)
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
|
||||
{
|
||||
@@ -746,7 +750,7 @@ impl Sandbox {
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
self.wrap_windows(command).await
|
||||
self.wrap_windows_psec(command)
|
||||
}
|
||||
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
|
||||
{
|
||||
@@ -998,6 +1002,44 @@ impl Sandbox {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn wrap_windows_psec(
|
||||
&mut self,
|
||||
command: &CommandAndArgs,
|
||||
) -> Result<WrappedCommand, SandboxError> {
|
||||
let writable_paths: Vec<&Path> = self
|
||||
.fs
|
||||
.writable_paths
|
||||
.iter()
|
||||
.map(HostFilesystemLocation::windows_canonical_path)
|
||||
.collect();
|
||||
let protected_paths: Vec<&Path> = self
|
||||
.fs
|
||||
.protected_paths
|
||||
.iter()
|
||||
.map(HostFilesystemLocation::windows_requested_path)
|
||||
.collect();
|
||||
|
||||
let spec = windows_psec::build_spec(
|
||||
self.fs.allow_fs_write,
|
||||
&writable_paths,
|
||||
&protected_paths,
|
||||
matches!(self.network, NetSetup::Unrestricted),
|
||||
)
|
||||
.map_err(map_anyhow_error)?;
|
||||
|
||||
let (program, args) =
|
||||
windows_psec::wrap_invocation(&spec, command.program.clone(), command.args.clone())
|
||||
.map_err(map_anyhow_error)?;
|
||||
|
||||
Ok(WrappedCommand {
|
||||
program,
|
||||
args,
|
||||
env: command.env.clone(),
|
||||
cwd: command.cwd.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn wrap_windows(
|
||||
&mut self,
|
||||
@@ -1085,6 +1127,8 @@ pub fn run_sandbox_launcher_if_invoked() {
|
||||
linux_bubblewrap::run_launcher_if_invoked();
|
||||
linux_bubblewrap::run_wsl_helper_if_invoked();
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
windows_psec::run_launcher_if_invoked();
|
||||
}
|
||||
|
||||
// The createability probe only needs to know whether a sandbox *can* be built
|
||||
|
||||
@@ -0,0 +1,623 @@
|
||||
//! Native Windows sandbox built on the Process Security Environment (PSEC) API.
|
||||
|
||||
use std::ffi::{CStr, OsStr, c_void};
|
||||
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use anyhow::{Context as _, Result, anyhow, ensure};
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use flatbuffers::{FlatBufferBuilder, VOffsetT};
|
||||
use windows::Win32::Foundation::{HANDLE, HANDLE_FLAG_INHERIT, SetHandleInformation, TRUE};
|
||||
use windows::Win32::Storage::FileSystem::{GetDriveTypeW, GetLogicalDrives};
|
||||
use windows::Win32::System::Console::{
|
||||
GetConsoleWindow, GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
|
||||
SetConsoleCtrlHandler,
|
||||
};
|
||||
use windows::Win32::System::Environment::GetCommandLineW;
|
||||
use windows::Win32::System::JobObjects::{
|
||||
JOB_OBJECT_LIMIT_BREAKAWAY_OK, JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK,
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
|
||||
QueryInformationJobObject,
|
||||
};
|
||||
use windows::Win32::System::LibraryLoader::{
|
||||
GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
|
||||
};
|
||||
use windows::Win32::System::Threading::{
|
||||
CREATE_BREAKAWAY_FROM_JOB, CREATE_NO_WINDOW, CreateProcessW, DeleteProcThreadAttributeList,
|
||||
EXTENDED_STARTUPINFO_PRESENT, GetExitCodeProcess, INFINITE, InitializeProcThreadAttributeList,
|
||||
LPPROC_THREAD_ATTRIBUTE_LIST, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, PROCESS_INFORMATION,
|
||||
STARTF_USESTDHANDLES, STARTUPINFOEXW, STARTUPINFOW, UpdateProcThreadAttribute,
|
||||
WaitForSingleObject,
|
||||
};
|
||||
use windows::Win32::System::WindowsProgramming::{DRIVE_FIXED, PROC_THREAD_ATTRIBUTE_INPUT};
|
||||
use windows_core::{BOOL, HRESULT, PCSTR, PCWSTR, PWSTR};
|
||||
|
||||
/// Argv flag that marks a re-exec of Zed as the PSEC launcher.
|
||||
pub(crate) const LAUNCHER_FLAG: &str = "--windows-sandbox-launcher";
|
||||
|
||||
/// Encode the crate's filesystem/network intent as a PSEC 1.0 FlatBuffer.
|
||||
///
|
||||
/// The layout follows the PSEC FlatBuffers schema:
|
||||
/// <https://github.com/microsoft/mxc/blob/main/external/windows-sdk/ProcessSecurityEnvironment.fbs>.
|
||||
pub(crate) fn build_spec(
|
||||
allow_fs_write: bool,
|
||||
writable_paths: &[&Path],
|
||||
protected_paths: &[&Path],
|
||||
allow_network: bool,
|
||||
) -> Result<Vec<u8>> {
|
||||
let roots = fixed_drive_roots();
|
||||
let mut read_write = Vec::new();
|
||||
if allow_fs_write {
|
||||
// A read-write grant on a volume root does not apply to anything
|
||||
// inside it, so grant each top-level directory instead.
|
||||
for root in &roots {
|
||||
read_write.extend(top_level_directories(root));
|
||||
}
|
||||
} else {
|
||||
for path in writable_paths {
|
||||
read_write.push(
|
||||
dunce::canonicalize(path)
|
||||
.with_context(|| format!("invalid writable path `{}`", path.display()))?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mut read_only = roots;
|
||||
for path in protected_paths {
|
||||
match dunce::canonicalize(path) {
|
||||
Ok(path) => read_only.push(path),
|
||||
// Like Bubblewrap, PSEC can only protect a path that exists when
|
||||
// the environment is created.
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(error) => {
|
||||
return Err(error)
|
||||
.with_context(|| format!("invalid protected path `{}`", path.display()));
|
||||
}
|
||||
}
|
||||
}
|
||||
log::debug!(
|
||||
"[sandbox] PSEC policy: read-write {read_write:?}, read-only {read_only:?}, network {allow_network}"
|
||||
);
|
||||
|
||||
// Vtable offsets (`4 + 2 * field index`) and enum values from the schema.
|
||||
const VERSION: VOffsetT = 4;
|
||||
const CAPABILITIES: VOffsetT = 6;
|
||||
const FS_READ_WRITE: VOffsetT = 12;
|
||||
const FS_READ_ONLY: VOffsetT = 14;
|
||||
const NETWORK_POLICY: VOffsetT = 18;
|
||||
const NETWORK_POLICY_EGRESS: VOffsetT = 6;
|
||||
const ENDPOINT_POLICY_DEFAULT_ACTION: VOffsetT = 4;
|
||||
const FILTER_ACTION_DENY: i8 = 0;
|
||||
const FILTER_ACTION_ALLOW: i8 = 1;
|
||||
|
||||
let mut builder = FlatBufferBuilder::with_capacity(1024);
|
||||
// Child objects must be finished before the table that refers to them is started.
|
||||
let mut path_vector = |paths: &[PathBuf]| {
|
||||
(!paths.is_empty()).then(|| {
|
||||
let paths: Vec<_> = paths
|
||||
.iter()
|
||||
.map(|path| builder.create_string(&path.to_string_lossy()))
|
||||
.collect();
|
||||
builder.create_vector(&paths)
|
||||
})
|
||||
};
|
||||
let read_write = path_vector(&read_write);
|
||||
let read_only = path_vector(&read_only);
|
||||
let capabilities =
|
||||
allow_network.then(|| builder.create_string("internetClient,privateNetworkClientServer"));
|
||||
|
||||
let egress = builder.start_table();
|
||||
let default_action = if allow_network {
|
||||
FILTER_ACTION_ALLOW
|
||||
} else {
|
||||
FILTER_ACTION_DENY
|
||||
};
|
||||
builder.push_slot(
|
||||
ENDPOINT_POLICY_DEFAULT_ACTION,
|
||||
default_action,
|
||||
FILTER_ACTION_DENY,
|
||||
);
|
||||
let egress = builder.end_table(egress);
|
||||
|
||||
let network_policy = builder.start_table();
|
||||
builder.push_slot_always(NETWORK_POLICY_EGRESS, egress);
|
||||
let network_policy = builder.end_table(network_policy);
|
||||
|
||||
let root = builder.start_table();
|
||||
// The inline `SchemaVersion { major: 1, minor: 0 }` struct: two
|
||||
// little-endian `uint16`s, written as one `u32`.
|
||||
builder.push_slot_always::<u32>(VERSION, 1);
|
||||
if let Some(capabilities) = capabilities {
|
||||
builder.push_slot_always(CAPABILITIES, capabilities);
|
||||
}
|
||||
if let Some(read_write) = read_write {
|
||||
builder.push_slot_always(FS_READ_WRITE, read_write);
|
||||
}
|
||||
if let Some(read_only) = read_only {
|
||||
builder.push_slot_always(FS_READ_ONLY, read_only);
|
||||
}
|
||||
builder.push_slot_always(NETWORK_POLICY, network_policy);
|
||||
let root = builder.end_table(root);
|
||||
builder.required(root, VERSION, "version");
|
||||
builder.finish(root, Some("PSEC"));
|
||||
Ok(builder.finished_data().to_vec())
|
||||
}
|
||||
|
||||
/// Wrap `program args` so it runs through the launcher under `spec`.
|
||||
pub(crate) fn wrap_invocation(
|
||||
spec: &[u8],
|
||||
program: String,
|
||||
args: Vec<String>,
|
||||
) -> Result<(String, Vec<String>)> {
|
||||
let launcher = std::env::current_exe().context("failed to resolve the Zed executable")?;
|
||||
let launcher = launcher
|
||||
.to_str()
|
||||
.ok_or_else(|| {
|
||||
anyhow!(
|
||||
"Zed executable path is not valid UTF-8: {}",
|
||||
launcher.display()
|
||||
)
|
||||
})?
|
||||
.to_string();
|
||||
let mut launcher_args = Vec::with_capacity(args.len() + 4);
|
||||
launcher_args.push(LAUNCHER_FLAG.to_string());
|
||||
launcher_args.push(URL_SAFE_NO_PAD.encode(spec));
|
||||
launcher_args.push(program);
|
||||
launcher_args.extend(args);
|
||||
Ok((launcher, launcher_args))
|
||||
}
|
||||
|
||||
pub(crate) fn check_available() -> Result<()> {
|
||||
ensure!(
|
||||
exports()?.supports_version(1, 0)?,
|
||||
"this Windows build does not support Process Security Environment 1.0"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// If this process was started as the launcher, run the sandboxed command and
|
||||
/// exit with its exit code. Returns normally otherwise.
|
||||
pub(crate) fn run_launcher_if_invoked() {
|
||||
if std::env::args_os().nth(1).as_deref() != Some(OsStr::new(LAUNCHER_FLAG)) {
|
||||
return;
|
||||
}
|
||||
let exit_code = match unsafe { GetCommandLineW().to_string() }
|
||||
.context("the command line is not valid UTF-16")
|
||||
.and_then(|command_line| run_launcher(&command_line))
|
||||
{
|
||||
Ok(exit_code) => exit_code as i32,
|
||||
Err(error) => {
|
||||
eprintln!("zed: failed to start the sandboxed command: {error:#}");
|
||||
126
|
||||
}
|
||||
};
|
||||
std::process::exit(exit_code);
|
||||
}
|
||||
|
||||
/// Run the command after `<launcher> <flag> <spec> ` under the encoded spec.
|
||||
fn run_launcher(command_line: &str) -> Result<u32> {
|
||||
let (_, rest) = command_line
|
||||
.split_once(LAUNCHER_FLAG)
|
||||
.context("missing launcher flag")?;
|
||||
let (spec, command) = rest
|
||||
.trim_start()
|
||||
.split_once(' ')
|
||||
.context("missing sandboxed command")?;
|
||||
let spec = URL_SAFE_NO_PAD
|
||||
.decode(spec)
|
||||
.context("malformed sandbox policy")?;
|
||||
|
||||
// Ctrl+C reaches every process attached to the console.
|
||||
// The launcher shouldn't exit on Ctrl+C so that it can report its exit code to Zed.
|
||||
unsafe extern "system" fn ignore_console_control(_: u32) -> BOOL {
|
||||
TRUE
|
||||
}
|
||||
unsafe { SetConsoleCtrlHandler(Some(ignore_console_control), true) }
|
||||
.context("failed to install the console control handler")?;
|
||||
|
||||
let environment = SecurityEnvironment::create(&spec)?;
|
||||
|
||||
// PSEC launch doesn't copy standard handles into the child by default, so pass them explicitly.
|
||||
let std_handles = [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE]
|
||||
.map(|kind| unsafe { GetStdHandle(kind) }.unwrap_or_default());
|
||||
let mut inherited_handles = Vec::new();
|
||||
for handle in std_handles {
|
||||
if handle.is_invalid() || handle.0.is_null() || inherited_handles.contains(&handle) {
|
||||
continue;
|
||||
}
|
||||
unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT.0, HANDLE_FLAG_INHERIT) }
|
||||
.context("failed to make a std handle inheritable")?;
|
||||
inherited_handles.push(handle);
|
||||
}
|
||||
|
||||
let attribute_count = 1 + u32::from(!inherited_handles.is_empty());
|
||||
let mut size = 0;
|
||||
// The sizing call always fails with `ERROR_INSUFFICIENT_BUFFER`; it only reports `size`.
|
||||
unsafe { InitializeProcThreadAttributeList(None, attribute_count, None, &mut size) }.ok();
|
||||
let mut attribute_storage = vec![0usize; size.div_ceil(std::mem::size_of::<usize>())];
|
||||
let attribute_list = LPPROC_THREAD_ATTRIBUTE_LIST(attribute_storage.as_mut_ptr().cast());
|
||||
unsafe {
|
||||
InitializeProcThreadAttributeList(Some(attribute_list), attribute_count, None, &mut size)
|
||||
}
|
||||
.context("failed to initialize the process attribute list")?;
|
||||
unsafe {
|
||||
UpdateProcThreadAttribute(
|
||||
attribute_list,
|
||||
0,
|
||||
// `ProcThreadAttributeSecurityEnvironment` (35).
|
||||
35 | PROC_THREAD_ATTRIBUTE_INPUT as usize,
|
||||
Some((&raw const environment.0).cast()),
|
||||
std::mem::size_of::<HANDLE>(),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
.context("failed to attach the process security environment")?;
|
||||
if !inherited_handles.is_empty() {
|
||||
unsafe {
|
||||
UpdateProcThreadAttribute(
|
||||
attribute_list,
|
||||
0,
|
||||
PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize,
|
||||
Some(inherited_handles.as_ptr().cast()),
|
||||
std::mem::size_of_val(inherited_handles.as_slice()),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
.context("failed to set the inherited handle list")?;
|
||||
}
|
||||
|
||||
let startup_info = STARTUPINFOEXW {
|
||||
StartupInfo: STARTUPINFOW {
|
||||
cb: std::mem::size_of::<STARTUPINFOEXW>() as u32,
|
||||
dwFlags: STARTF_USESTDHANDLES,
|
||||
hStdInput: std_handles[0],
|
||||
hStdOutput: std_handles[1],
|
||||
hStdError: std_handles[2],
|
||||
..Default::default()
|
||||
},
|
||||
lpAttributeList: attribute_list,
|
||||
};
|
||||
|
||||
let mut command_line = wide(command);
|
||||
let mut creation_flags = EXTENDED_STARTUPINFO_PRESENT;
|
||||
if unsafe { GetConsoleWindow() }.is_invalid() {
|
||||
creation_flags |= CREATE_NO_WINDOW;
|
||||
}
|
||||
|
||||
// To launch a packaged (MSIX) app with PSEC, the child process needs to break away from any job that's present.
|
||||
// The job might not allow breakaway; we'll only try if it's allowed.
|
||||
// https://github.com/microsoft/mxc/issues/1754
|
||||
if current_job_limits().is_some_and(|flags| flags & JOB_OBJECT_LIMIT_BREAKAWAY_OK.0 != 0) {
|
||||
creation_flags |= CREATE_BREAKAWAY_FROM_JOB;
|
||||
}
|
||||
|
||||
let mut process_information = PROCESS_INFORMATION::default();
|
||||
let created = unsafe {
|
||||
CreateProcessW(
|
||||
PCWSTR::null(),
|
||||
Some(PWSTR(command_line.as_mut_ptr())),
|
||||
None,
|
||||
None,
|
||||
!inherited_handles.is_empty(),
|
||||
creation_flags,
|
||||
None,
|
||||
PCWSTR::null(),
|
||||
&startup_info.StartupInfo,
|
||||
&mut process_information,
|
||||
)
|
||||
};
|
||||
unsafe { DeleteProcThreadAttributeList(attribute_list) };
|
||||
created.with_context(|| format!("failed to start `{command}` in the sandbox"))?;
|
||||
let process = unsafe { OwnedHandle::from_raw_handle(process_information.hProcess.0) };
|
||||
let _thread = unsafe { OwnedHandle::from_raw_handle(process_information.hThread.0) };
|
||||
|
||||
unsafe { WaitForSingleObject(HANDLE(process.as_raw_handle()), INFINITE) };
|
||||
let mut exit_code = 0u32;
|
||||
unsafe { GetExitCodeProcess(HANDLE(process.as_raw_handle()), &mut exit_code) }
|
||||
.context("failed to read the sandboxed command's exit code")?;
|
||||
Ok(exit_code)
|
||||
}
|
||||
|
||||
/// The limit flags of the job containing this process, or `None` outside a job.
|
||||
fn current_job_limits() -> Option<u32> {
|
||||
let mut limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
|
||||
unsafe {
|
||||
QueryInformationJobObject(
|
||||
None,
|
||||
JobObjectExtendedLimitInformation,
|
||||
(&raw mut limits).cast(),
|
||||
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
|
||||
None,
|
||||
)
|
||||
}
|
||||
.ok()?;
|
||||
Some(limits.BasicLimitInformation.LimitFlags.0)
|
||||
}
|
||||
|
||||
/// Whether the launcher can start a packaged (MSIX) app as the sandboxed command.
|
||||
pub fn can_launch_packaged_apps() -> bool {
|
||||
current_job_limits().is_none_or(|flags| {
|
||||
flags & (JOB_OBJECT_LIMIT_BREAKAWAY_OK.0 | JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK.0) != 0
|
||||
})
|
||||
}
|
||||
|
||||
fn fixed_drive_roots() -> Vec<PathBuf> {
|
||||
let drives = unsafe { GetLogicalDrives() };
|
||||
(0..26u8)
|
||||
.filter(|index| drives & (1 << index) != 0)
|
||||
.map(|index| format!("{}:\\", char::from(b'A' + index)))
|
||||
.filter(|root| {
|
||||
let root = wide(root);
|
||||
unsafe { GetDriveTypeW(PCWSTR(root.as_ptr())) == DRIVE_FIXED }
|
||||
})
|
||||
.map(PathBuf::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn top_level_directories(root: &Path) -> Vec<PathBuf> {
|
||||
let entries = match std::fs::read_dir(root) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"[sandbox] failed to list {} for writable grants: {error}",
|
||||
root.display()
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
entries
|
||||
.filter_map(|entry| entry.ok())
|
||||
// Junctions such as `C:\Documents and Settings` report as symlinks and
|
||||
// are skipped; their targets are granted directly.
|
||||
.filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
|
||||
.map(|entry| entry.path())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn wide(text: &str) -> Vec<u16> {
|
||||
text.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
|
||||
type RawExport = unsafe extern "system" fn() -> isize;
|
||||
type CreateProcessSecurityEnvironmentFn = unsafe extern "system" fn(
|
||||
sandbox_specification: *const c_void,
|
||||
sandbox_specification_size: u32,
|
||||
flags: u32,
|
||||
process_security_environment: *mut HANDLE,
|
||||
) -> HRESULT;
|
||||
type CloseProcessSecurityEnvironmentFn =
|
||||
unsafe extern "system" fn(process_security_environment: HANDLE);
|
||||
type IsProcessSecurityEnvironmentVersionSupportedFn =
|
||||
unsafe extern "system" fn(major: u32, available: *mut u8, minor: *mut u32) -> HRESULT;
|
||||
|
||||
/// The `processmodel.dll` exports, which only exist on recent Windows builds.
|
||||
struct Exports {
|
||||
create: CreateProcessSecurityEnvironmentFn,
|
||||
close: CloseProcessSecurityEnvironmentFn,
|
||||
version_supported: Option<IsProcessSecurityEnvironmentVersionSupportedFn>,
|
||||
}
|
||||
|
||||
fn exports() -> Result<&'static Exports> {
|
||||
static EXPORTS: OnceLock<Option<Exports>> = OnceLock::new();
|
||||
EXPORTS
|
||||
.get_or_init(|| unsafe {
|
||||
let dll = wide("processmodel.dll");
|
||||
let module =
|
||||
LoadLibraryExW(PCWSTR(dll.as_ptr()), None, LOAD_LIBRARY_SEARCH_SYSTEM32).ok()?;
|
||||
let export = |name: &CStr| GetProcAddress(module, PCSTR(name.as_ptr().cast()));
|
||||
Some(Exports {
|
||||
create: std::mem::transmute::<RawExport, CreateProcessSecurityEnvironmentFn>(
|
||||
export(c"CreateProcessSecurityEnvironment")?,
|
||||
),
|
||||
close: std::mem::transmute::<RawExport, CloseProcessSecurityEnvironmentFn>(
|
||||
export(c"CloseProcessSecurityEnvironment")?,
|
||||
),
|
||||
version_supported: export(c"IsProcessSecurityEnvironmentVersionSupported").map(
|
||||
|function| {
|
||||
std::mem::transmute::<RawExport, IsProcessSecurityEnvironmentVersionSupportedFn>(
|
||||
function,
|
||||
)
|
||||
},
|
||||
),
|
||||
})
|
||||
})
|
||||
.as_ref()
|
||||
.context("Process Security Environment is unavailable: processmodel.dll is missing or incomplete")
|
||||
}
|
||||
|
||||
impl Exports {
|
||||
fn supports_version(&self, major: u32, minor: u32) -> Result<bool> {
|
||||
// Builds that predate the version query only implement 1.0.
|
||||
let Some(version_supported) = self.version_supported else {
|
||||
return Ok(major == 1 && minor == 0);
|
||||
};
|
||||
let mut available = 0u8;
|
||||
let mut supported_minor = 0u32;
|
||||
unsafe { version_supported(major, &mut available, &mut supported_minor) }
|
||||
.ok()
|
||||
.context("IsProcessSecurityEnvironmentVersionSupported failed")?;
|
||||
Ok(available != 0 && supported_minor >= minor)
|
||||
}
|
||||
}
|
||||
|
||||
/// An open `HPROCESS_SECURITY_ENVIRONMENT`, closed on drop.
|
||||
struct SecurityEnvironment(HANDLE);
|
||||
|
||||
impl SecurityEnvironment {
|
||||
fn create(spec: &[u8]) -> Result<Self> {
|
||||
const TERMINATE_ON_CLOSE: u32 = 1;
|
||||
let size = u32::try_from(spec.len()).context("sandbox policy is too large")?;
|
||||
let mut handle = HANDLE::default();
|
||||
unsafe { (exports()?.create)(spec.as_ptr().cast(), size, TERMINATE_ON_CLOSE, &mut handle) }
|
||||
.ok()
|
||||
.context("CreateProcessSecurityEnvironment failed")?;
|
||||
Ok(Self(handle))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SecurityEnvironment {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(exports) = exports() {
|
||||
unsafe { (exports.close)(self.0) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Run `cmd /c <script>` through the launcher in-process. Returns `None`
|
||||
/// (skipping the test) when this host has no PSEC support.
|
||||
fn run_sandboxed(spec: &[u8], script: &str) -> Option<u32> {
|
||||
if let Err(error) = check_available() {
|
||||
eprintln!("skipping PSEC test: {error:#}");
|
||||
return None;
|
||||
}
|
||||
let command_line = format!(
|
||||
"zed.exe {LAUNCHER_FLAG} {} cmd.exe /c {script}",
|
||||
URL_SAFE_NO_PAD.encode(spec)
|
||||
);
|
||||
Some(run_launcher(&command_line).expect("launcher failed"))
|
||||
}
|
||||
|
||||
struct Layout {
|
||||
project: tempfile::TempDir,
|
||||
outside: tempfile::TempDir,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
fn new() -> Self {
|
||||
let layout = Self {
|
||||
project: tempfile::tempdir().unwrap(),
|
||||
outside: tempfile::tempdir().unwrap(),
|
||||
};
|
||||
std::fs::create_dir(layout.protected()).unwrap();
|
||||
std::fs::write(layout.protected().join("config"), "protected").unwrap();
|
||||
std::fs::write(layout.outside.path().join("secret.txt"), "outside").unwrap();
|
||||
layout
|
||||
}
|
||||
|
||||
fn protected(&self) -> PathBuf {
|
||||
self.project.path().join(".git")
|
||||
}
|
||||
|
||||
fn spec(&self, allow_fs_write: bool) -> Vec<u8> {
|
||||
build_spec(
|
||||
allow_fs_write,
|
||||
&[self.project.path()],
|
||||
&[&self.protected()],
|
||||
false,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restricted_policy_confines_writes_and_protects_paths() {
|
||||
let layout = Layout::new();
|
||||
let spec = layout.spec(false);
|
||||
let project = layout.project.path();
|
||||
let protected = layout.protected();
|
||||
let outside = layout.outside.path();
|
||||
|
||||
let Some(exit_code) = run_sandboxed(
|
||||
&spec,
|
||||
&format!("echo x> {}", project.join("a.txt").display()),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(exit_code, 0, "project should be writable");
|
||||
assert!(project.join("a.txt").exists());
|
||||
assert_eq!(
|
||||
run_sandboxed(&spec, "exit 7"),
|
||||
Some(7),
|
||||
"exit codes should pass through"
|
||||
);
|
||||
|
||||
// `%TEMP%` is expanded inside the sandbox, where PSEC points it at
|
||||
// the environment's own AppContainer folder.
|
||||
assert_eq!(
|
||||
run_sandboxed(&spec, r"echo x> %TEMP%\t.txt"),
|
||||
Some(0),
|
||||
"PSEC's temp dir should be writable"
|
||||
);
|
||||
assert_eq!(
|
||||
run_sandboxed(
|
||||
&spec,
|
||||
&format!("type {}", outside.join("secret.txt").display())
|
||||
),
|
||||
Some(0),
|
||||
"reads should be allowed everywhere"
|
||||
);
|
||||
assert_eq!(
|
||||
run_sandboxed(
|
||||
&spec,
|
||||
&format!("type {}", protected.join("config").display())
|
||||
),
|
||||
Some(0),
|
||||
"protected paths should stay readable"
|
||||
);
|
||||
|
||||
assert_ne!(
|
||||
run_sandboxed(
|
||||
&spec,
|
||||
&format!("echo x> {}", outside.join("b.txt").display())
|
||||
),
|
||||
Some(0)
|
||||
);
|
||||
assert!(
|
||||
!outside.join("b.txt").exists(),
|
||||
"outside should be read-only"
|
||||
);
|
||||
assert_ne!(
|
||||
run_sandboxed(
|
||||
&spec,
|
||||
&format!("echo x>> {}", protected.join("config").display())
|
||||
),
|
||||
Some(0)
|
||||
);
|
||||
assert_ne!(
|
||||
run_sandboxed(&spec, &format!("ren {} moved", protected.display())),
|
||||
Some(0)
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(protected.join("config")).unwrap(),
|
||||
"protected",
|
||||
"protected paths should not be writable or movable"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrestricted_policy_allows_writes_but_protects_paths() {
|
||||
let layout = Layout::new();
|
||||
let spec = layout.spec(true);
|
||||
let protected = layout.protected();
|
||||
let outside = layout.outside.path();
|
||||
|
||||
let Some(exit_code) = run_sandboxed(
|
||||
&spec,
|
||||
&format!("echo x> {}", outside.join("b.txt").display()),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
assert_eq!(exit_code, 0, "writes outside the project should be allowed");
|
||||
assert!(outside.join("b.txt").exists());
|
||||
|
||||
assert_ne!(
|
||||
run_sandboxed(
|
||||
&spec,
|
||||
&format!("echo x>> {}", protected.join("config").display())
|
||||
),
|
||||
Some(0)
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(protected.join("config")).unwrap(),
|
||||
"protected"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user