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
6 changes: 5 additions & 1 deletion docs/backends/bwrap/bubblewrap-backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,11 @@ backend-specific config block is needed.
### Process environment

The host environment is never inherited β€” the sandbox is built with
`--clearenv`, so host secrets can't leak into untrusted code.
`--clearenv`, so host secrets can't leak into untrusted code. `bwrap` itself is
also started with an empty environment, so the host environment can't be read
from `/proc/<pid>/environ` (for example `/proc/1/environ`) inside the sandbox.
The command's environment is passed to `bwrap` as `--clearenv` and `--setenv`
arguments.

**From schema 0.9** the child gets a default block of `PATH`
(`/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin`), `TERM`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -697,7 +697,10 @@ impl BubblewrapScriptRunner {

// 3. Spawn `bwrap`.
let mut command = Command::new(&bwrap);
command.args(&args);
// The confined command can read bwrap's exec-time environment through
// /proc, so bwrap must not inherit the host's. The command's own
// environment is passed as --clearenv/--setenv arguments.
command.env_clear().args(&args);
Comment thread
caarlos0 marked this conversation as resolved.
Resolved
Comment thread
caarlos0 marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium (reliability/correctness) - Apply the same environment rule to availability probes.

Attribution: newly_exposed_by_change - clearing the real launch here makes the unchanged native and Node probes test different execution conditions.

bwrap_version.rs:429-430 still runs bwrap --version with inherited variables, as does sdk/node/src/bwrap-probe-helper.ts:132-135. A resolved wrapper such as #!/bin/sh followed by exec "$REAL_BWRAP" "$@" therefore passes probing when the host supplies REAL_BWRAP, but fails when this launch clears it. Discovery/dry-run validation can report success and the actual run then fails after startup preparation. The test-wrapper repairs in this PR demonstrate the same dependency mechanism; ordinary distro binaries are not claimed to require these variables.

Fix: keep this env_clear(), clear the native version probe's environment too, and pass env: {} to the Node helper's bwrap spawn. Update environment-dependent probe fixtures and check that such a wrapper is rejected during probing rather than failing only during execution. This scenario was source-verified, not locally reproduced on Linux.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Declining for this PR. The scenario needs a bwrap that is a wrapper script reading host variables; no distro bwrap does, and the only wrappers like that were this repo's own test wrappers, which are fixed here. bwrap --version only checks that the binary runs, so passing the host environment there is not a sandbox exposure. Changing the native and Node probes is a separate behavior change; I can file it as its own issue if you want it tracked.

let pty = match stdio {
StdioMode::Pipes => {
command
Expand Down
12 changes: 8 additions & 4 deletions src/mxc-sdk/tests/streaming_bubblewrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -593,17 +593,22 @@ fn streaming_bubblewrap_cancels_without_parent_death_signal() {
let wrapper = directory.path().join("bwrap");

// Omit parent-death cleanup to hold the startup condition without a timing race.
// MXC starts bwrap with an empty environment, so the real path is written into
// the wrapper instead of being passed through a variable.
let real_bwrap = format!("'{}'", real_bwrap.to_string_lossy().replace('\'', r"'\''"));
std::fs::write(
&wrapper,
r#"#!/bin/sh
format!(
r#"#!/bin/sh
for arg in "$@"; do
shift
if [ "$arg" != "--die-with-parent" ]; then
set -- "$@" "$arg"
fi
done
exec "$MXC_TEST_REAL_BWRAP" "$@"
"#,
exec {real_bwrap} "$@"
"#
),
)
.expect("write bwrap wrapper");
std::fs::set_permissions(&wrapper, std::fs::Permissions::from_mode(0o700))
Expand All @@ -622,7 +627,6 @@ exec "$MXC_TEST_REAL_BWRAP" "$@"
"--test-threads=1",
])
.env(FIXTURE_ENV, "1")
.env("MXC_TEST_REAL_BWRAP", real_bwrap)
.env("PATH", path);
run_terminal_fixture(command);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,15 +118,20 @@ fn bubblewrap_streams_stdout() {
/// Bubblewrap runs with `--clearenv`, so the sandboxed child does *not* inherit
/// the launcher's environment even when `process.env` is empty. The refactor
/// should preserve this; if it ever turns RED the env model has drifted.
///
/// `bwrap` itself is the sandbox's PID 1 and the child can read its environment
/// from `/proc/1/environ`, so the launcher must start it with an empty
/// environment too.
#[test]
fn bubblewrap_clears_host_env_by_default() {
if !ready() {
return;
}
let marker = "CHAR_BWRAP_SHOULD_NOT_APPEAR_8a02f";
let command = r#"printf 'MARKER=[%s]\n' "$MXC_CHAR_MARKER"; if d=$(tr '\0' '\n' < /proc/1/environ); then printf 'PID1_LEAK=[%s]\n' "$(printf '%s\n' "$d" | grep -c '^MXC_CHAR_MARKER=')"; else echo 'PID1_LEAK=[unreadable]'; fi"#;
let result = run_platform_config_value(
"bwrap env clear",
&config("env-clear", "printf 'MARKER=[%s]\\n' \"$MXC_CHAR_MARKER\""),
&config("env-clear", command),
&[("MXC_CHAR_MARKER", marker)],
None,
);
Expand All @@ -136,6 +141,10 @@ fn bubblewrap_clears_host_env_by_default() {
out.contains("MARKER=[]"),
"expected cleared env (MARKER=[]); current Bubblewrap --clearenv behavior. Output:\n{out}"
);
assert!(
out.contains("PID1_LEAK=[0]"),
"expected the sandbox's /proc/1/environ to be readable without the host marker. Output:\n{out}"
);
assert!(
!out.contains(marker),
"host env marker leaked into the sandbox. Output:\n{out}"
Expand Down
12 changes: 12 additions & 0 deletions tests/configs/bwrap_env_host_environ.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"$schema": "../../schemas/stable/mxc-config.schema.1.0.0.json",
"version": "1.0.0",
"containerId": "CLI-bubblewrap-Env-host_environ",
"containment": "bubblewrap",
"process": {
"commandLine": "for f in /proc/[0-9]*/environ; do p=${f#/proc/}; p=${p%/environ}; if d=$(tr '\\0' '\\n' < \"$f\"); then echo \"READABLE_$p=[yes]\"; echo \"LEAK_$p=[$(printf '%s\\n' \"$d\" | grep -c '^MXC_LEAK_PROBE=')]\"; else echo \"READABLE_$p=[no]\"; fi; done; echo \"CONTROL_SELF=[$(cat /proc/self/environ | tr '\\0' '\\n' | grep -c '^FOO=bar$')]\"; echo \"FOO=[$FOO]\"; echo ENV_PROBE_DONE",
"cwd": "/tmp",
"env": ["FOO=bar"],
"timeout": 20000
}
}
20 changes: 20 additions & 0 deletions tests/scripts/run_bwrap_environment_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,24 @@ expect_ok "inheritDefaultEnv keeps the default HOME" "HOME=[/tmp]"
expect_ok "inheritDefaultEnv adds the caller's variable" "FOO=[bar]"
expect_ok "a caller entry overrides the same-named default" "TERM=[vt100]"

# `--clearenv` only changes the workload's environment. bwrap itself is the
# sandbox's PID 1 and keeps the environment it was started with, which the
# workload can read from /proc. The config sweeps every pid in the sandbox and
# counts only after a successful read, so a pid that cannot be read is reported
# as unreadable instead of passing with a zero count.
run_config bwrap_env_host_environ.json
expect_ok "the probe ran" "ENV_PROBE_DONE"
expect_ok "a supplied env reaches the command" "FOO=[bar]"
expect_ok "a successful read of the command's own environ holds the supplied env" "CONTROL_SELF=[1]"
expect_ok "the sandbox's pid 1 environ is readable" "READABLE_1=[yes]"
expect_ok "no host variable in the sandbox's pid 1 environ" "LEAK_1=[0]"
expect_absent "the host value itself does not appear" "BWRAP_HOST_ENV_LEAKED"
if grep -q 'READABLE_[0-9]*=\[no\]' <<<"$OUT"; then
fail "a sandbox pid's environ could not be read" "$OUT"
fi
if grep -q 'LEAK_[0-9]*=\[[1-9]' <<<"$OUT"; then
fail "a host variable is readable from /proc" "$OUT"
fi
pass "no sandbox pid exposes a host variable"

echo "All $PASS_COUNT Bubblewrap environment assertions passed."
31 changes: 21 additions & 10 deletions tests/scripts/run_bwrap_namespace_startup_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,6 @@ if [ "${1:-}" = "--user" ]; then
fi
exec "$REAL_UNSHARE" "$@"
SHIM
cat >"$WORK_DIR/shim/bwrap" <<'SHIM'
#!/bin/sh
if [ "${TEST_FAILURE:-}" = "bwrap" ] && [ "${1:-}" != "--version" ]; then
echo "test: bwrap network namespace refused" >&2
exit 1
fi
exec "$REAL_BWRAP" "$@"
SHIM
cat >"$WORK_DIR/shim/iptables-restore" <<'SHIM'
#!/bin/sh
if [ "${TEST_FAILURE:-}" = "rules" ] && [ "${1:-}" != "--version" ]; then
Expand All @@ -63,7 +55,24 @@ if [ "${TEST_FAILURE:-}" = "rules" ] && [ "${1:-}" != "--version" ]; then
fi
exec "$REAL_RESTORE" "$@"
SHIM
chmod +x "$WORK_DIR/shim/unshare" "$WORK_DIR/shim/bwrap" "$WORK_DIR/shim/iptables-restore"
chmod +x "$WORK_DIR/shim/unshare" "$WORK_DIR/shim/iptables-restore"

# MXC starts bwrap with an empty environment, so this shim cannot read the real
# path or the failure mode from variables. Each case gets its own copy with both
# written in.
write_bwrap_shim() {
local dir="$1" failure="$2"
mkdir -p "$dir"
cat >"$dir/bwrap" <<SHIM
#!/bin/sh
if [ "$failure" = "bwrap" ] && [ "\${1:-}" != "--version" ]; then
echo "test: bwrap network namespace refused" >&2
exit 1
fi
exec "$REAL_BWRAP" "\$@"
SHIM
chmod +x "$dir/bwrap"
}

for mode in proxy firewall; do
proxy=""
Expand Down Expand Up @@ -94,8 +103,10 @@ run_case() {
shift 3
local dir="$WORK_DIR/$label"
mkdir "$dir"
write_bwrap_shim "$dir/shim" "$failure"
local rc=0
TEST_LOG="$dir/unshare.log" TEST_PID="$dir/supervisor.pid" TEST_FAILURE="$failure" \
PATH="$dir/shim:$PATH" \
TEST_LOG="$dir/unshare.log" TEST_PID="$dir/supervisor.pid" TEST_FAILURE="$failure" \
timeout 30 "$LXC_EXEC" --experimental "$@" "$WORK_DIR/$mode.json" \
>"$dir/output" 2>&1 || rc=$?
echo "$rc" >"$dir/exit"
Expand Down
2 changes: 1 addition & 1 deletion tests/scripts/run_bwrap_resolver_isolation_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ from pathlib import Path
import sys
if '--version' not in sys.argv:
for value in sys.argv[1:]:
if value.startswith(os.environ['TMPDIR'] + '/mxc-bwrap-resolver-'):
if value.startswith({str(work / 'scratch')!r} + '/mxc-bwrap-resolver-'):
os.unlink(value)
os.symlink({str(work / 'ungranted-sentinel')!r}, value)
if '--file' in sys.argv:
Expand Down
Loading