Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -209,21 +209,26 @@ The container mounts system directories read-only to prevent the agent from modi

### Read-Only `.openclaw` Config

The `/sandbox/.openclaw` directory contains the OpenClaw gateway configuration, including auth tokens and CORS settings.
The container mounts it read-only while writable agent state (plugins, agent data) lives in `/sandbox/.openclaw-data` through symlinks.
The `/sandbox/.openclaw` directory contains the OpenClaw gateway configuration (model routing, CORS settings, channel config).
The gateway auth token is **not** stored in this directory — it is generated at container startup and passed via the `OPENCLAW_GATEWAY_TOKEN` environment variable only to the gateway process (which runs as the `gateway` user).
The token is also persisted to `/run/nemoclaw/gateway-token` (`gateway:gateway 0400`) for host-side reads.
The sandbox user (agent) cannot access the token: the file is owned by a different uid, the env var is only in the gateway process (`/proc/pid/environ` is uid-gated), and `no-new-privileges` prevents escalation.

The container mounts `.openclaw` read-only while writable agent state (plugins, agent data) lives in `/sandbox/.openclaw-data` through symlinks.

Multiple defense layers protect this directory:

- **DAC permissions.** Root owns the directory and `openclaw.json` with `chmod 444`, so the sandbox user cannot write to them.
- **Immutable flag.** The entrypoint applies `chattr +i` to the directory and all symlinks, preventing modification even if other controls fail.
- **Symlink validation.** At startup, the entrypoint verifies every symlink in `.openclaw` points to the expected `.openclaw-data` target. If any symlink points elsewhere, the container refuses to start.
- **Config integrity hash.** The build process pins a SHA256 hash of `openclaw.json`. The entrypoint verifies it at startup and refuses to start if the hash does not match.
- **Externalized gateway token.** The gateway auth token never appears in `openclaw.json`. It is generated at container startup, written to a gateway-user-only file, and passed to the gateway process via an environment variable that only the gateway process can see.

| Aspect | Detail |
|---|---|
| Default | The container mounts `/sandbox/.openclaw` as read-only, root-owned, immutable, and integrity-verified at startup. `/sandbox/.openclaw-data` remains writable. |
| Default | The container mounts `/sandbox/.openclaw` as read-only, root-owned, immutable, and integrity-verified at startup. `/sandbox/.openclaw-data` remains writable. The gateway auth token is stored separately at `/run/nemoclaw/gateway-token` (`gateway:gateway 0400`). |
| What you can change | Move `/sandbox/.openclaw` from `read_only` to `read_write` in the policy file. |
| Risk if relaxed | A writable `.openclaw` directory lets the agent modify its own gateway config: disabling CORS, changing auth tokens, or redirecting inference to an attacker-controlled endpoint. This is the single most dangerous filesystem change. |
| Risk if relaxed | A writable `.openclaw` directory lets the agent modify its own gateway config: disabling CORS or redirecting inference to an attacker-controlled endpoint. This is the single most dangerous filesystem change. |
| Recommendation | Never make `/sandbox/.openclaw` writable. |

### Writable Paths
Expand Down
16 changes: 11 additions & 5 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -221,11 +221,17 @@ ENV NEMOCLAW_MODEL=${NEMOCLAW_MODEL} \
WORKDIR /sandbox
USER sandbox

# Write the COMPLETE openclaw.json including gateway config and auth token.
# Write openclaw.json with gateway config but WITHOUT the real auth token.
# The gateway auth token is generated at container startup by the entrypoint
# and passed via OPENCLAW_GATEWAY_TOKEN env var only to the gateway process
# (running as 'gateway' user). The token is also persisted to
# /run/nemoclaw/gateway-token (gateway:gateway 0400) for host-side reads.
# The sandbox user (agent) cannot read the env var (/proc/pid/environ is
# uid-gated) or the file (wrong uid, no-new-privileges blocks escalation).
# See: scripts/nemoclaw-start.sh generate_gateway_token()
#
# This file is immutable at runtime (Landlock read-only on /sandbox/.openclaw).
# No runtime writes to openclaw.json are needed or possible.
# Build args (NEMOCLAW_MODEL, CHAT_UI_URL) customize per deployment.
# Auth token is generated per build so each image has a unique token.
#
# Temporary workaround for NemoClaw#1738: the OpenClaw Discord extension's
# gateway uses `ws` (via @buape/carbon), which ignores HTTPS_PROXY/HTTP_PROXY
Expand All @@ -238,7 +244,7 @@ USER sandbox
# Remove once OpenClaw lands an env-var-honouring fix for the Discord
# gateway equivalent to openclaw/openclaw#62878 (Slack Socket Mode).
RUN python3 -c "\
import base64, json, os, secrets; \
import base64, json, os; \
from urllib.parse import urlparse; \
proxy_url = f\"http://{os.environ['NEMOCLAW_PROXY_HOST']}:{os.environ['NEMOCLAW_PROXY_PORT']}\"; \
model = os.environ['NEMOCLAW_MODEL']; \
Expand Down Expand Up @@ -285,7 +291,7 @@ config = { \
'allowedOrigins': origins, \
}, \
'trustedProxies': ['127.0.0.1', '::1'], \
'auth': {'token': secrets.token_hex(32)} \
'auth': {'token': ''} \
} \
}; \
config.update({ \
Expand Down
13 changes: 9 additions & 4 deletions docs/security/best-practices.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,21 +229,26 @@ The container mounts system directories read-only to prevent the agent from modi

### Read-Only `.openclaw` Config

The `/sandbox/.openclaw` directory contains the OpenClaw gateway configuration, including auth tokens and CORS settings.
The container mounts it read-only while writable agent state (plugins, agent data) lives in `/sandbox/.openclaw-data` through symlinks.
The `/sandbox/.openclaw` directory contains the OpenClaw gateway configuration (model routing, CORS settings, channel config).
The gateway auth token is **not** stored in this directory — it is generated at container startup and passed via the `OPENCLAW_GATEWAY_TOKEN` environment variable only to the gateway process (which runs as the `gateway` user).
The token is also persisted to `/run/nemoclaw/gateway-token` (`gateway:gateway 0400`) for host-side reads.
The sandbox user (agent) cannot access the token: the file is owned by a different uid, the env var is only in the gateway process (`/proc/pid/environ` is uid-gated), and `no-new-privileges` prevents escalation.

The container mounts `.openclaw` read-only while writable agent state (plugins, agent data) lives in `/sandbox/.openclaw-data` through symlinks.

Multiple defense layers protect this directory:

- **DAC permissions.** Root owns the directory and `openclaw.json` with `chmod 444`, so the sandbox user cannot write to them.
- **Immutable flag.** The entrypoint applies `chattr +i` to the directory and all symlinks, preventing modification even if other controls fail.
- **Symlink validation.** At startup, the entrypoint verifies every symlink in `.openclaw` points to the expected `.openclaw-data` target. If any symlink points elsewhere, the container refuses to start.
- **Config integrity hash.** The build process pins a SHA256 hash of `openclaw.json`. The entrypoint verifies it at startup and refuses to start if the hash does not match.
- **Externalized gateway token.** The gateway auth token never appears in `openclaw.json`. It is generated at container startup, written to a gateway-user-only file, and passed to the gateway process via an environment variable that only the gateway process can see.

| Aspect | Detail |
|---|---|
| Default | The container mounts `/sandbox/.openclaw` as read-only, root-owned, immutable, and integrity-verified at startup. `/sandbox/.openclaw-data` remains writable. |
| Default | The container mounts `/sandbox/.openclaw` as read-only, root-owned, immutable, and integrity-verified at startup. `/sandbox/.openclaw-data` remains writable. The gateway auth token is stored separately at `/run/nemoclaw/gateway-token` (`gateway:gateway 0400`). |
| What you can change | Move `/sandbox/.openclaw` from `read_only` to `read_write` in the policy file. |
| Risk if relaxed | A writable `.openclaw` directory lets the agent modify its own gateway config: disabling CORS, changing auth tokens, or redirecting inference to an attacker-controlled endpoint. This is the single most dangerous filesystem change. |
| Risk if relaxed | A writable `.openclaw` directory lets the agent modify its own gateway config: disabling CORS or redirecting inference to an attacker-controlled endpoint. This is the single most dangerous filesystem change. |
| Recommendation | Never make `/sandbox/.openclaw` writable. |

### Writable Paths
Expand Down
112 changes: 49 additions & 63 deletions scripts/nemoclaw-start.sh
Original file line number Diff line number Diff line change
Expand Up @@ -465,66 +465,47 @@ PYSLACK
printf '[channels] Config hash recomputed after Slack token override\n' >&2
}

_read_gateway_token() {
python3 - <<'PYTOKEN'
import json
try:
with open('/sandbox/.openclaw/openclaw.json') as f:
cfg = json.load(f)
print(cfg.get('gateway', {}).get('auth', {}).get('token', ''))
except Exception:
print('')
PYTOKEN
}
# ── Gateway auth token (externalized) ──────────────────────────
# The gateway auth token is NOT stored in openclaw.json. It is generated
# at container startup by generate_gateway_token() and:
# 1. Written to /run/nemoclaw/gateway-token (gateway:gateway 0400)
# for host-side reads via openshell sandbox download.
# 2. Passed as OPENCLAW_GATEWAY_TOKEN env var only to the gateway
# process launch line (gosu gateway ...). OpenClaw reads this
# natively via its resolveGatewayCredentialsFromValues() path.
#
# The sandbox user (agent) cannot access the token:
# - The file is owned by gateway:gateway 0400 (wrong uid).
# - The env var is only in the gateway process (/proc/pid/environ
# is uid-gated, no-new-privileges blocks escalation).
#
# /run is tmpfs — the token file is regenerated on every container start.
GATEWAY_TOKEN_DIR="/run/nemoclaw"
GATEWAY_TOKEN_FILE="${GATEWAY_TOKEN_DIR}/gateway-token"

export_gateway_token() {
local token
token="$(_read_gateway_token)"
local marker_begin="# nemoclaw-gateway-token begin"
local marker_end="# nemoclaw-gateway-token end"

if [ -z "$token" ]; then
# Remove any stale marker blocks from rc files so revoked/old tokens
# are not re-exported in later interactive sessions.
unset OPENCLAW_GATEWAY_TOKEN
for rc_file in "${_SANDBOX_HOME}/.bashrc" "${_SANDBOX_HOME}/.profile"; do
if [ -f "$rc_file" ] && grep -qF "$marker_begin" "$rc_file" 2>/dev/null; then
local tmp
tmp="$(mktemp)"
awk -v b="$marker_begin" -v e="$marker_end" \
'$0==b{s=1;next} $0==e{s=0;next} !s' "$rc_file" >"$tmp"
cat "$tmp" >"$rc_file"
rm -f "$tmp"
fi
done
return
fi
export OPENCLAW_GATEWAY_TOKEN="$token"

# Persist to .bashrc/.profile so interactive sessions (openshell sandbox
# connect) also see the token — same pattern as the proxy config above.
# Shell-escape the token so quotes/dollars/backticks cannot break the
# sourced snippet or allow code injection.
local escaped_token
escaped_token="$(printf '%s' "$token" | sed "s/'/'\\\\''/g")"
local snippet
snippet="${marker_begin}
export OPENCLAW_GATEWAY_TOKEN='${escaped_token}'
${marker_end}"
generate_gateway_token() {
[ "$(id -u)" -eq 0 ] || {
printf '[SECURITY] generate_gateway_token requires root — skipping\n' >&2
return 1
}

for rc_file in "${_SANDBOX_HOME}/.bashrc" "${_SANDBOX_HOME}/.profile"; do
if [ -f "$rc_file" ] && grep -qF "$marker_begin" "$rc_file" 2>/dev/null; then
local tmp
tmp="$(mktemp)"
awk -v b="$marker_begin" -v e="$marker_end" \
'$0==b{s=1;next} $0==e{s=0;next} !s' "$rc_file" >"$tmp"
printf '%s\n' "$snippet" >>"$tmp"
cat "$tmp" >"$rc_file"
rm -f "$tmp"
elif [ -w "$rc_file" ] || [ -w "$(dirname "$rc_file")" ]; then
printf '\n%s\n' "$snippet" >>"$rc_file"
fi
done
mkdir -p "$GATEWAY_TOKEN_DIR"
chmod 755 "$GATEWAY_TOKEN_DIR"

python3 -c "import secrets; print(secrets.token_hex(32), end='')" \
>"$GATEWAY_TOKEN_FILE"

chown gateway:gateway "$GATEWAY_TOKEN_FILE"
chmod 400 "$GATEWAY_TOKEN_FILE"
printf '[token] Gateway auth token generated at %s (gateway:gateway 0400)\n' \
"$GATEWAY_TOKEN_FILE" >&2
}

_read_gateway_token() {
# Read the gateway token from the externalized file.
# Callable by root (entrypoint) and gateway user only.
# Returns the token on stdout; empty output means no token.
cat "$GATEWAY_TOKEN_FILE" 2>/dev/null || true
}

install_configure_guard() {
Expand Down Expand Up @@ -614,8 +595,8 @@ GUARD
printf '\n%s\n' "$snippet" >>"$rc_file"
fi
done
# Final lock after all rc-file mutations (export_gateway_token + this
# function) are complete so Landlock read_only enforcement holds.
# Final lock after all rc-file mutations are complete so Landlock
# read_only enforcement holds.
lock_rc_files "$_SANDBOX_HOME"
}

Expand Down Expand Up @@ -996,7 +977,9 @@ if [ "$(id -u)" -ne 0 ]; then
apply_model_override
apply_cors_override
apply_slack_token_override
export_gateway_token
# Non-root: no privilege separation, so we cannot isolate the token from
# the sandbox user. OpenClaw will auto-generate a token at gateway startup.
printf '[SECURITY] Non-root mode — gateway token not externalized (no privilege separation)\n' >&2
install_configure_guard
configure_messaging_channels
validate_openclaw_symlinks
Expand Down Expand Up @@ -1111,7 +1094,7 @@ verify_config_integrity /sandbox/.openclaw
apply_model_override
apply_cors_override
apply_slack_token_override
export_gateway_token
generate_gateway_token
install_configure_guard

# Inject messaging channel config if provider tokens are present.
Expand Down Expand Up @@ -1161,7 +1144,10 @@ validate_tmp_permissions "$_PROXY_FIX_SCRIPT"
# SECURITY: The sandbox user cannot kill this process because it runs
# under a different UID. The fake-HOME attack no longer works because
# the agent cannot restart the gateway with a tampered config.
nohup gosu gateway "$OPENCLAW" gateway run --port "${_DASHBOARD_PORT}" >/tmp/gateway.log 2>&1 &
# SECURITY: OPENCLAW_GATEWAY_TOKEN is passed only to the gateway process
# env — the sandbox user cannot read /proc/<pid>/environ (different uid).
OPENCLAW_GATEWAY_TOKEN="$(_read_gateway_token)" \
nohup gosu gateway "$OPENCLAW" gateway run --port "${_DASHBOARD_PORT}" >/tmp/gateway.log 2>&1 &
GATEWAY_PID=$!
echo "[gateway] openclaw gateway launched as 'gateway' user (pid $GATEWAY_PID)" >&2

Expand Down
2 changes: 1 addition & 1 deletion spark-install.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ The OpenClaw gateway includes a built-in web UI. Access it at:
http://127.0.0.1:18789/#token=<your-gateway-token>
```

Find your gateway token in `~/.openclaw/openclaw.json` under `gateway.auth.token` inside the sandbox.
The gateway token is printed by `nemoclaw onboard` at startup. It is stored at `/run/nemoclaw/gateway-token` inside the sandbox (readable only by root and the gateway user).

> **Important**: Use `127.0.0.1` (not `localhost`) — the gateway's origin check requires an exact match. External dashboards like Mission Control cannot currently connect due to the gateway resetting `controlUi.allowedOrigins` on every config reload (see [openclaw#49950](https://github.com/openclaw/openclaw/issues/49950)).

Expand Down
24 changes: 21 additions & 3 deletions src/lib/onboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6095,13 +6095,31 @@ function findOpenclawJsonPath(dir) {
}

/**
* Pull gateway.auth.token from the sandbox image via openshell sandbox download
* so onboard can print copy-paste Control UI URLs with #token= (same idea as nemoclaw-start.sh).
* Pull gateway auth token from the sandbox. The token lives at
* /run/nemoclaw/gateway-token (not in openclaw.json). Host-side
* openshell sandbox download runs as root and can read it.
*
* Falls back to openclaw.json for images that predate this change.
*/
function fetchGatewayAuthTokenFromSandbox(sandboxName) {
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-token-"));
try {
const destDir = `${tmpDir}${path.sep}`;

// Primary: externalized token file (gateway:gateway 0400, root can read)
const tokenFileResult = runOpenshell(
["sandbox", "download", sandboxName, "/run/nemoclaw/gateway-token", destDir],
{ ignoreError: true, stdio: ["ignore", "ignore", "ignore"] },
);
if (tokenFileResult.status === 0) {
const tokenPath = path.join(tmpDir, "gateway-token");
if (fs.existsSync(tokenPath)) {
const token = fs.readFileSync(tokenPath, "utf-8").trim();
if (token.length > 0) return token;
}
}

// Fallback: read from openclaw.json (pre-externalization images)
const result = runOpenshell(
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
["sandbox", "download", sandboxName, "/sandbox/.openclaw/openclaw.json", destDir],
{ ignoreError: true, stdio: ["ignore", "ignore", "ignore"] },
Expand Down Expand Up @@ -6284,7 +6302,7 @@ function printDashboard(sandboxName, model, provider, nimContainer = null, agent
console.log(` ${entry.label}: ${entry.url}`);
}
console.log(
` Token: nemoclaw ${sandboxName} connect → jq -r '.gateway.auth.token' /sandbox/.openclaw/openclaw.json`,
` Token: see /tmp/gateway.log inside the sandbox, or re-run onboard.`,
);
console.log(
` append #token=<token> to the URL, or see /tmp/gateway.log inside the sandbox.`,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Expand Down
Loading
Loading