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
13 changes: 9 additions & 4 deletions WINDOWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,13 @@ under development and is not a production-qualified security boundary:
Exclusive supervisor-mediated egress and live access revocation are unverified.
- The loopback exception can expose unrelated host-local services to workloads.
Treat the gateway host as trusted.
- Foreground main-process attachment and ConPTY resize are unavailable. Create
command workloads with `--detach`.
- A foreground `sandbox create -- <command>` without a terminal streams the
workload's stdout and stderr to the CLI and returns its exit code. An
interactive terminal (`--tty`) and ConPTY resize are unavailable; use
`--no-tty` or `--detach`.
Known limit: Windows `ssh.exe` (Win32-OpenSSH 9.5) does not exit after it
writes to a pipe, so redirect the CLI's stdout and stderr to files rather than
pipes when scripting a foreground create.
- Gateway exit ends sandbox workloads, and there is no restart recovery. When
the gateway process ends (a graceful stop with Ctrl-C, a crash, or a kill), the
sandbox processes it started end with it, workloads included. After the gateway
Expand Down Expand Up @@ -114,8 +119,8 @@ Configure `compute_driver = "mxc"` and use the matching
[Windows gateway configuration](https://github.com/NVIDIA/OpenShell/blob/windows/docs/how-it-works/gateways/configuration.mdx#configure-mxc)
and [example gateway TOML](https://github.com/NVIDIA/OpenShell/blob/windows/crates/openshell-driver-mxc/examples/mxc-gateway.toml).
Command-based sandbox creation requires administrator opt-in with
`allow_driver_config = true`, a workload command and working directory, and
`--detach`. Use a sandbox policy to grant the required filesystem and network
`allow_driver_config = true`, and a workload command and working directory. A
foreground create needs `--no-tty`; `--tty` is rejected. Use a sandbox policy to grant the required filesystem and network
access.

## Run additional commands and restart a sandbox
Expand Down
25 changes: 17 additions & 8 deletions crates/openshell-cli/src/ssh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ use miette::{IntoDiagnostic, Report, Result, WrapErr};
use nix::sys::signal::Signal;
use openshell_core::driver_mounts;
use openshell_core::forward::{
ForwardSpec, build_proxy_command, format_gateway_url, resolve_ssh_gateway, sandbox_ssh_args,
shell_escape, validate_ssh_session_response, write_forward_pid,
ForwardSpec, build_proxy_command, format_gateway_url, proxy_command_escape,
resolve_ssh_gateway, sandbox_ssh_args, shell_escape, validate_ssh_session_response,
write_forward_pid,
};
use openshell_core::proto::{
CreateSshSessionRequest, GetSandboxRequest, SandboxPhase, SshRelayTarget, TcpForwardFrame,
Expand Down Expand Up @@ -2126,13 +2127,13 @@ fn host_alias(name: &str, workspace: &str) -> String {

fn render_ssh_config(gateway: &str, name: &str, workspace: &str) -> String {
let exe = std::env::current_exe().expect("failed to resolve OpenShell executable");
let exe = shell_escape(&exe.to_string_lossy());
let exe = proxy_command_escape(&exe.to_string_lossy());

let proxy_cmd = format!(
"{exe} ssh-proxy --gateway-name {} --name {} --workspace {}",
shell_escape(gateway),
shell_escape(name),
shell_escape(workspace),
proxy_command_escape(gateway),
proxy_command_escape(name),
proxy_command_escape(workspace),
);
let host_alias = host_alias(name, workspace);
format!(
Expand Down Expand Up @@ -2790,9 +2791,17 @@ mod tests {
config.contains("Host openshell-demo.beta"),
"host alias should be workspace-qualified: {config}"
);
// The ProxyCommand arguments are quoted for the host platform (a POSIX shell, or the
// Windows command-line parser), so build the expectation the same way production does.
let expected = format!(
"--gateway-name {} --name {} --workspace {}",
proxy_command_escape("my-gw"),
proxy_command_escape("demo"),
proxy_command_escape("beta"),
);
assert!(
config.contains("--workspace beta"),
"ProxyCommand should include --workspace: {config}"
config.contains(&expected),
"ProxyCommand should carry the escaped gateway, name and workspace ({expected}): {config}"
);
}

Expand Down
98 changes: 88 additions & 10 deletions crates/openshell-core/src/forward.rs
Original file line number Diff line number Diff line change
Expand Up @@ -906,7 +906,7 @@ pub fn format_gateway_url(scheme: &str, host: &str, port: u16) -> String {
format!("{scheme}://{}:{port}", bracket_ipv6_host(host))
}

/// Shell-escape a value for use inside a `ProxyCommand` string.
/// POSIX shell-escape a value for use in command strings.
pub fn shell_escape(value: &str) -> String {
if value.is_empty() {
return "''".to_string();
Expand All @@ -923,11 +923,55 @@ pub fn shell_escape(value: &str) -> String {
format!("'{escaped}'")
}

/// Quote one argument for the Windows command-line parser used by
/// `CreateProcessW`-launched programs.
///
/// OpenSSH executes `ProxyCommand` directly on Windows instead of passing it
/// through `/bin/sh`. Always quoting each argument keeps executable paths with
/// spaces intact. Backslashes immediately before a quote or the closing quote
/// are doubled according to the Windows C runtime argument parsing rules.
#[cfg(any(windows, test))]
fn windows_command_line_escape(value: &str) -> String {
let mut escaped = String::with_capacity(value.len() + 2);
escaped.push('"');
let mut backslashes = 0;
for character in value.chars() {
if character == '\\' {
backslashes += 1;
continue;
}
let count = if character == '"' {
backslashes * 2 + 1
} else {
backslashes
};
escaped.extend(std::iter::repeat_n('\\', count));
backslashes = 0;
escaped.push(character);
}
escaped.extend(std::iter::repeat_n('\\', backslashes * 2));
escaped.push('"');
escaped
}

/// Escape one argument for the command-launch behavior OpenSSH uses for
/// `ProxyCommand` on the current host platform.
pub fn proxy_command_escape(value: &str) -> String {
#[cfg(not(windows))]
{
shell_escape(value)
}
#[cfg(windows)]
{
windows_command_line_escape(value)
}
}

/// Build the SSH `ProxyCommand` string used to tunnel to a sandbox.
///
/// Every interpolated argument is shell-escaped so that server-supplied values
/// (gateway URL, sandbox name, workspace, token, gateway name) cannot inject shell
/// metacharacters into the command that OpenSSH executes via `/bin/sh -c`.
/// On Unix, every interpolated argument is shell-escaped for the `/bin/sh -c`
/// invocation used by OpenSSH. On Windows, every argument is quoted for the
/// command line that OpenSSH launches through `CreateProcessW`.
pub fn build_proxy_command(
exe: &str,
gateway_url: &str,
Expand All @@ -938,12 +982,12 @@ pub fn build_proxy_command(
) -> String {
format!(
"{} ssh-proxy --gateway {} --sandbox {} --workspace {} --token {} --gateway-name {}",
shell_escape(exe),
shell_escape(gateway_url),
shell_escape(sandbox_name),
shell_escape(workspace),
shell_escape(token),
shell_escape(gateway_name),
proxy_command_escape(exe),
proxy_command_escape(gateway_url),
proxy_command_escape(sandbox_name),
proxy_command_escape(workspace),
proxy_command_escape(token),
proxy_command_escape(gateway_name),
)
}

Expand Down Expand Up @@ -1346,6 +1390,7 @@ mod tests {
}
}

#[cfg(not(windows))]
#[test]
fn build_proxy_command_escapes_shell_metacharacters() {
// Attacker-controlled values in every escapable position.
Expand All @@ -1369,6 +1414,7 @@ mod tests {
assert!(!outside_single_quotes(&cmd).contains('\n'));
}

#[cfg(not(windows))]
#[test]
fn build_proxy_command_empty_values_quote_rather_than_vanish() {
// An empty value must become `''` rather than disappearing — otherwise
Expand All @@ -1378,6 +1424,7 @@ mod tests {
assert!(cmd.contains("--workspace ''"));
}

#[cfg(not(windows))]
#[test]
fn build_proxy_command_safe_values_pass_through_unquoted() {
let cmd = build_proxy_command(
Expand Down Expand Up @@ -1411,8 +1458,39 @@ mod tests {
}
}

#[test]
fn windows_command_line_escape_round_trips_through_crt_parsing() {
assert_eq!(windows_command_line_escape(""), r#""""#);
assert_eq!(
windows_command_line_escape(r"C:\Program Files\openshell.exe"),
r#""C:\Program Files\openshell.exe""#
);
assert_eq!(windows_command_line_escape(r#"a"b"#), r#""a\"b""#);
assert_eq!(windows_command_line_escape(r#"a\"b"#), r#""a\\\"b""#);
assert_eq!(windows_command_line_escape(r"dir\"), r#""dir\\""#);
assert_eq!(windows_command_line_escape(r"a\b"), r#""a\b""#);
}

#[cfg(windows)]
#[test]
fn build_proxy_command_quotes_every_windows_argument() {
let cmd = build_proxy_command(
r"C:\Program Files\openshell.exe",
"gw",
"",
"ws & calc",
"tok",
"name",
);
assert_eq!(
cmd,
r#""C:\Program Files\openshell.exe" ssh-proxy --gateway "gw" --sandbox "" --workspace "ws & calc" --token "tok" --gateway-name "name""#
);
}

/// Helper: return the concatenation of characters that appear outside
/// POSIX single-quoted runs. Used by the metacharacter assertions above.
#[cfg(not(windows))]
fn outside_single_quotes(s: &str) -> String {
let mut out = String::new();
let mut inside = false;
Expand Down
6 changes: 3 additions & 3 deletions crates/openshell-driver-mxc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ branch's `MXC agent launched` acknowledgement only after native spawn succeeds.

The driver resolves its gateway endpoint and TLS server-name defaults from
generic gateway inputs. The host supervisor authenticates its gateway session
and retains main-process I/O. MXC has no foreground attachment adapter; create
command workloads with `--detach`. Preflight rejects foreground attachment
before provisioning. TCP readiness remains gated by authenticated session acceptance.
and retains main-process I/O. Foreground attachment without a terminal is served by the in-process SSH server
of the host supervisor; MXC has no ConPTY adapter, so preflight rejects a
foreground `--tty` request before provisioning. TCP readiness remains gated by authenticated session acceptance.

Windows boundary execution is implemented by the `openshell-mxc-boundary`
library behind the dedicated `openshell-windows-sandbox.exe`. The compute driver does not
Expand Down
36 changes: 26 additions & 10 deletions crates/openshell-driver-mxc/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,10 +304,10 @@ impl MxcComputeBackend {
if sandbox
.spec
.as_ref()
.is_some_and(|spec| spec.await_main_process_attachment)
.is_some_and(|spec| spec.await_main_process_attachment && spec.tty)
{
return Err(tonic::Status::failed_precondition(
"MXC does not support foreground attachment to the main process. Create the sandbox with --detach.",
"MXC does not support an interactive terminal for the main process. Create the sandbox with --no-tty or --detach.",
));
}
openshell_core::resource_admission::check_sandbox_driver_config(
Expand Down Expand Up @@ -1931,21 +1931,37 @@ mod tests {
}

#[tokio::test]
async fn foreground_attachment_is_rejected_before_provisioning() {
async fn foreground_terminal_attachment_is_rejected_before_provisioning() {
let (backend, mut sandbox, _dir) = preflight_fixture();
sandbox.spec.as_mut().unwrap().command =
vec!["cmd.exe".into(), "/c".into(), "exit 0".into()];
sandbox.spec.as_mut().unwrap().await_main_process_attachment = true;
let spec = sandbox.spec.as_mut().unwrap();
spec.command = vec!["cmd.exe".into(), "/c".into(), "exit 0".into()];
spec.await_main_process_attachment = true;
spec.tty = true;
let error = backend.validate_sandbox_create(&sandbox).unwrap_err();
assert_eq!(error.code(), tonic::Code::FailedPrecondition);
assert!(error.message().contains("--detach"));
assert!(error.message().contains("--no-tty"));
let error = backend.create_sandbox(&sandbox).await.unwrap_err();
assert_eq!(error.code(), tonic::Code::FailedPrecondition);
assert!(error.message().contains("foreground attachment"));
assert!(error.message().contains("interactive terminal"));
assert!(backend.get_sandbox(&sandbox.id).await.is_none());
assert!(!backend.config.state_dir.exists());
sandbox.spec.as_mut().unwrap().await_main_process_attachment = false;
assert!(backend.validate_sandbox_create(&sandbox).is_ok());
}

#[test]
fn non_terminal_foreground_and_detached_creates_are_admitted() {
let (backend, mut sandbox, _dir) = preflight_fixture();
let spec = sandbox.spec.as_mut().unwrap();
spec.command = vec!["cmd.exe".into(), "/c".into(), "exit 0".into()];
// Foreground without a terminal streams output over the SSH attachment.
for (await_attachment, tty) in [(true, false), (false, false), (false, true)] {
let spec = sandbox.spec.as_mut().unwrap();
spec.await_main_process_attachment = await_attachment;
spec.tty = tty;
assert!(
backend.validate_sandbox_create(&sandbox).is_ok(),
"await_main_process_attachment={await_attachment} tty={tty} must be admitted"
);
}
}

#[test]
Expand Down
7 changes: 4 additions & 3 deletions crates/openshell-supervisor-process/src/ssh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ pub async fn run_ssh_server(
_shared_socket: bool,
port_forward: Arc<dyn openshell_isolation_interface::contract::BoundaryLoopbackConnector>,
boundary_exec: Arc<dyn openshell_isolation_interface::contract::BoundaryExec>,
_main_session: Option<Arc<MainSession>>,
main_session: Option<Arc<MainSession>>,
host_key: PrivateKey,
) -> Result<()> {
let config = ssh_server_config(host_key);
Expand All @@ -507,13 +507,14 @@ pub async fn run_ssh_server(
let config = config.clone();
let port_forward = port_forward.clone();
let boundary_exec = boundary_exec.clone();
let main_session = main_session.clone();
tokio::spawn(async move {
if let Err(err) = handle_connection(
stream,
config,
port_forward,
boundary_exec,
None,
main_session,
SSH_PEER_TIMEOUT,
)
.await
Expand Down Expand Up @@ -1726,7 +1727,7 @@ async fn send_main_output(handle: &Handle, channel: ChannelId, event: MainOutput
MainOutput::Exit(code) => {
let eof = handle.eof(channel).await.is_ok();
let status = handle
.exit_status_request(channel, code.max(0).unsigned_abs())
.exit_status_request(channel, exit_code_to_wire(code))
.await
.is_ok();
let close = handle.close(channel).await.is_ok();
Expand Down
2 changes: 1 addition & 1 deletion crates/openshell-supervisor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -769,7 +769,7 @@ async fn run_sandbox_with_backend(
} = config;
// The current client attachment adapter is SSH; retaining a process's I/O
// internally does not make it reachable by a foreground client.
if await_main_process_attachment && (!cfg!(unix) || ssh_socket_path.is_none()) {
if await_main_process_attachment && ssh_socket_path.is_none() {
return Err(miette::miette!(
"foreground attachment to the main process requires a supported SSH access adapter; create the sandbox with --detach"
));
Expand Down
6 changes: 4 additions & 2 deletions docs/how-it-works/gateways/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1244,8 +1244,10 @@ for build prerequisites and runtime limitations.

The MXC driver is Windows-only and opt-in. It links into the gateway and invokes Microsoft MXC through `wxc-exec.exe`. The driver starts `openshell-supervisor --role=isolation-backend` on the host and `openshell-windows-sandbox.exe` inside each ProcessContainer. The standard authenticated Sandbox Protocol and supervisor session provide lifecycle, exec, forwarding, provider refresh, and network policy.

MXC does not support foreground attachment to the main process. Use `--detach`
when creating a command workload; foreground requests fail during preflight.
MXC supports foreground attachment to the main process without a terminal: the
CLI streams the workload's stdout and stderr and exits with its exit code. An
interactive terminal is not supported, so a foreground request with `--tty`
fails during preflight. Use `--no-tty` or `--detach`.

The dedicated `openshell-windows-sandbox.exe` uses a Windows boundary library for process operations and forwarding. It replaces the generic sandbox binary in the Windows runtime pair; the supervisor remains a separate host process, not part of the compute driver. No separate supervisor-relay executable is required. Set `wxc_exec_path` to an absolute path; configuration preflight rejects an omitted or relative path. Existing MXC configurations that explicitly select `openshell-sandbox.exe` must update `sandbox_binary_path` to the Windows executable.

Expand Down
10 changes: 6 additions & 4 deletions skills/openshell-cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,11 @@ attachment and delete its sandbox after the service exits.
When supplying `--name`, use a portable DNS-1123 label: at most 63 lowercase alphanumeric or `-` characters, beginning and ending with an alphanumeric character. The Kubernetes driver rejects uppercase letters, underscores, dots, and other names that cannot become Kubernetes resource labels.

For native Windows MXC, supply the Windows command and absolute working
directory through `--driver-config-json` and use `--detach`. The gateway
administrator must enable caller driver configuration. Foreground attachment
is rejected before provisioning; `--no-tty` alone does not request detachment.
directory through `--driver-config-json`. The gateway administrator must enable
caller driver configuration. A foreground create with a command after `--`
streams the command's output to the CLI and returns its exit code; use
`--no-tty`, because an interactive terminal is rejected before provisioning.
Add `--detach` to run the command in the background.
Use `sandbox exec <name> --no-tty -- <executable> [args...]` for an additional
command. For shell builtins, pass a single command string after `cmd.exe /d /c`.
Use `sandbox start <name>` to relaunch a stopped, completed, or failed-main-process sandbox with its
Expand Down Expand Up @@ -327,7 +329,7 @@ Key flags:
- `--forward [BIND_ADDRESS:]PORT`: Forward a local port and keep the sandbox alive
- `--editor vscode|cursor`: Open a remote editor after creation and keep the sandbox alive

If the driver rejects foreground attachment during create validation, use `--detach`.
If the driver rejects an interactive terminal during create validation (MXC), use `--no-tty` or `--detach`.

`--detach` adds no attachment grace period. When the canonical process exits,
its terminal phase is reported immediately. A foreground create declares one
Expand Down
Loading