Skip to content

fix(security): drop unnecessary Linux capabilities at container startup - #917

Merged
cv merged 5 commits into
mainfrom
fix/cap-drop-797
Mar 25, 2026
Merged

cv merged 5 commits into
mainfrom
fix/cap-drop-797

Conversation

@ericksoa

@ericksoa ericksoa commented Mar 25, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Adds libcap2-bin to the Dockerfile (provides capsh)
  • Entrypoint (nemoclaw-start.sh) self-re-execs through capsh to drop 9 dangerous capabilities from the bounding set before any child processes launch: cap_net_raw, cap_dac_override, cap_sys_chroot, cap_fsetid, cap_setpcap, cap_setfcap, cap_mknod, cap_audit_write, cap_net_bind_service
  • Keeps only the 5 capabilities required for gosu privilege separation: cap_chown, cap_setuid, cap_setgid, cap_fowner, cap_kill
  • Adds e2e test verifying cap_net_raw is absent from the bounding set after entrypoint runs

Since OpenShell manages the container runtime (no --cap-drop flag on openshell sandbox create), the entrypoint handles capability dropping itself via capsh. This is defense-in-depth per CIS Docker Benchmark 5.3.

Thanks

Thanks to @BenediktSchackenberg for the thorough issue write-up and CIS benchmark references, and to @h-network for pushing back on docs-only approaches and keeping the bar high for a proper enforcement fix.

Fixes #797

Test plan

  • docker build succeeds with new libcap2-bin package
  • Container starts normally (entrypoint self-re-exec is transparent)
  • test/e2e-gateway-isolation.sh test 11 passes — cap_net_raw absent from bounding set
  • Existing tests 1–10 still pass (gosu, config integrity, symlinks, process isolation)
  • Gateway and sandbox processes function correctly with reduced capability set

Summary by CodeRabbit

  • Security

    • Enhanced application startup with reduced system-level privileges for improved security posture.
  • Tests

    • Added verification test to ensure privilege restrictions are properly enforced at runtime.

Use capsh to drop dangerous capabilities (CAP_NET_RAW, CAP_DAC_OVERRIDE,
CAP_SYS_CHROOT, etc.) from the bounding set at entrypoint startup.
OpenShell manages the container runtime so we cannot pass --cap-drop=ALL
to docker run; instead the entrypoint re-execs through capsh to strip
the bounding set before any child processes launch.

Keeps only the capabilities required for gosu privilege separation:
cap_chown, cap_setuid, cap_setgid, cap_fowner, cap_kill.

Fixes #797
@coderabbitai

coderabbitai Bot commented Mar 25, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 87544e01-c1c7-47db-8669-4e155b3e8925

📥 Commits

Reviewing files that changed from the base of the PR and between e1644a3 and 3d03d31.

📒 Files selected for processing (1)
  • Dockerfile.base
✅ Files skipped from review due to trivial changes (1)
  • Dockerfile.base

📝 Walkthrough

Walkthrough

Added Linux capability dropping to container startup. The Dockerfile installs libcap2-bin, the startup script wraps execution under capsh with specific capabilities dropped (if capsh available), and a test validates that cap_net_raw is successfully dropped from the bounding set.

Changes

Cohort / File(s) Summary
Capability Dropping Infrastructure
Dockerfile.base
Installed Debian package libcap2-bin (pinned version) to provide capsh for capability management.
Startup Script Capability Management
scripts/nemoclaw-start.sh
Added initialization logic that checks NEMOCLAW_CAPS_DROPPED env var; if unset, re-executes the script under capsh --drop= with a specific capability drop list. Falls back to warning if capsh unavailable. Inserted before existing self-invocation filtering logic.
Capability Verification Testing
test/e2e-gateway-isolation.sh
Added Test 12 that verifies cap_net_raw is absent from the process bounding set by reading /proc/self/status, converting CapBnd from hex to decimal, and checking that bit 13 is unset.

Sequence Diagram

sequenceDiagram
    participant start as nemoclaw-start.sh
    participant env as Environment
    participant capsh as capsh
    participant kernel as Kernel/Process

    start->>env: Check NEMOCLAW_CAPS_DROPPED
    env-->>start: Not set (first run)
    start->>capsh: exec capsh --drop=[list]<br/>-c 'exec /usr/local/bin/nemoclaw-start "$@"'
    capsh->>kernel: Apply capability drops<br/>(set NEMOCLAW_CAPS_DROPPED=1)
    kernel->>start: Re-execute script
    start->>env: Check NEMOCLAW_CAPS_DROPPED
    env-->>start: Already 1 (skip capsh)
    start->>start: Continue normal execution<br/>(with dropped caps)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 With capsh's magic, we drop and defend,
Net_raw and raw sockets must end,
Capabilities caged in the sandbox so tight,
Security strengthened, our container's just right! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: dropping unnecessary Linux capabilities at container startup, which is the core objective of all three modified files.
Linked Issues check ✅ Passed The PR successfully implements all coding requirements from issue #797: adds libcap2-bin, modifies entrypoint to drop nine unnecessary capabilities via capsh, retains five required capabilities, and adds e2e test verification.
Out of Scope Changes check ✅ Passed All changes directly support the linked issue objective to drop Linux capabilities. Dockerfile.base adds libcap2-bin, nemoclaw-start.sh implements capability dropping logic, and e2e test verifies the security implementation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/cap-drop-797

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
scripts/nemoclaw-start.sh (1)

32-45: Consider adding a fallback message when capsh is unavailable.

When capsh is not found (e.g., if libcap2-bin is removed), the script silently continues without dropping capabilities. For defense-in-depth visibility, consider logging a warning.

📝 Optional: Add warning when capsh is unavailable
 if [ "${NEMOCLAW_CAPS_DROPPED:-}" != "1" ] && command -v capsh >/dev/null 2>&1; then
   export NEMOCLAW_CAPS_DROPPED=1
   exec capsh \
     --drop=cap_net_raw \
     --drop=cap_dac_override \
     --drop=cap_sys_chroot \
     --drop=cap_fsetid \
     --drop=cap_setpcap \
     --drop=cap_setfcap \
     --drop=cap_mknod \
     --drop=cap_audit_write \
     --drop=cap_net_bind_service \
     -- -c 'exec /usr/local/bin/nemoclaw-start "$@"' -- "$@"
+elif [ "${NEMOCLAW_CAPS_DROPPED:-}" != "1" ]; then
+  echo "[SECURITY WARNING] capsh not available — running with default capabilities" >&2
 fi
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@scripts/nemoclaw-start.sh` around lines 32 - 45, The script currently skips
dropping capabilities silently when capsh is missing; update the block
referencing NEMOCLAW_CAPS_DROPPED and the capsh presence check to emit a clear
warning to stderr when command -v capsh fails (for example using echo >&2 or
printf to stderr) so operators see that capability dropping did not occur; keep
the existing behavior (only attempt capsh when present) and ensure the message
mentions capsh and NEMOCLAW_CAPS_DROPPED so it’s easy to locate in logs.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@scripts/nemoclaw-start.sh`:
- Around line 22-45: The capsh invocation in the startup guard (check of
NEMOCLAW_CAPS_DROPPED) uses multiple --drop= flags which is invalid; update the
exec capsh call in the block that exports NEMOCLAW_CAPS_DROPPED so it passes a
single --drop argument containing a comma-separated list of capabilities (e.g.
cap_net_raw,cap_dac_override,...cap_net_bind_service) to capsh, keeping the
trailing "-- -c 'exec /usr/local/bin/nemoclaw-start \"$@\"' -- \"$@\"" and
preserving the surrounding conditional and export of NEMOCLAW_CAPS_DROPPED.

In `@test/e2e-gateway-isolation.sh`:
- Around line 183-188: The comment incorrectly says "We read /proc/1/status"
while the code actually reads /proc/self/status; update the comment to state we
read /proc/self/status (or change the command to grep "^CapBnd:" /proc/1/status
if you prefer that behavior) so the comment matches the code that sets CAP_BND
via grep "^CapBnd:" /proc/self/status | awk "{print \$2}".

---

Nitpick comments:
In `@scripts/nemoclaw-start.sh`:
- Around line 32-45: The script currently skips dropping capabilities silently
when capsh is missing; update the block referencing NEMOCLAW_CAPS_DROPPED and
the capsh presence check to emit a clear warning to stderr when command -v capsh
fails (for example using echo >&2 or printf to stderr) so operators see that
capability dropping did not occur; keep the existing behavior (only attempt
capsh when present) and ensure the message mentions capsh and
NEMOCLAW_CAPS_DROPPED so it’s easy to locate in logs.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fa820330-a75d-4afa-890f-fe58a2b8757a

📥 Commits

Reviewing files that changed from the base of the PR and between 0d852d3 and 43bf6c4.

📒 Files selected for processing (3)
  • Dockerfile
  • scripts/nemoclaw-start.sh
  • test/e2e-gateway-isolation.sh

Comment thread scripts/nemoclaw-start.sh Resolved
Comment thread test/e2e-gateway-isolation.sh Resolved
- Fix package version to 1:2.66-4+deb12u2+b2 (actual bookworm version)
- Use comma-separated --drop= list per capsh man page
- Add warning when capsh is unavailable
- Fix /proc/1/status -> /proc/self/status comment typo in test

@BenediktSchackenberg BenediktSchackenberg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Solid fix — capsh bounding-set drop is the right approach for CIS 5.3 when the runtime doesn't expose --cap-drop. The re-exec guard with NEMOCLAW_CAPS_DROPPED is clean, and the fallback warning for missing capsh is a nice touch.

Two small things I noticed:

  1. The e2e test uses bash -c with nested arithmetic (\$((16#\$CAP_BND))) — might be fragile if the shell env changes. capsh --print and grepping for cap_net_raw in Bounding set could be simpler.
  2. Worth noting in the PR description that cap_dac_read_search is also kept (it's not in the drop list) — intentional? Some hardening guides flag it too.

(Note: please disregard my earlier empty approval — that was submitted by automation accidentally. I'm a contributor, not a maintainer, so that approval doesn't carry merge weight anyway.)

@cv
cv merged commit f4a68bf into main Mar 25, 2026
9 checks passed
@cv
cv deleted the fix/cap-drop-797 branch March 25, 2026 21:05
@h-network

Copy link
Copy Markdown

@ericksoa Thank you!

ericksoa added a commit that referenced this pull request Mar 25, 2026
capsh --drop needs CAP_SETPCAP in the effective set to modify the
bounding set. Dropping it causes "unable to raise CAP_SETPCAP for BSET
changes: Operation not permitted" and prevents the sandbox from starting.

Fixes install regression from #917.
ericksoa added a commit that referenced this pull request Mar 25, 2026
…929)

* fix(security): keep cap_setpcap so capsh can drop other capabilities

capsh --drop needs CAP_SETPCAP in the effective set to modify the
bounding set. Dropping it causes "unable to raise CAP_SETPCAP for BSET
changes: Operation not permitted" and prevents the sandbox from starting.

Fixes install regression from #917.

* fix(security): check for CAP_SETPCAP before attempting capability drop

capsh --drop requires CAP_SETPCAP in the bounding set. OpenShell's
sandbox runtime strips it, so the entrypoint crashes with "unable to
raise CAP_SETPCAP for BSET changes: Operation not permitted".

Check with capsh --has-p first; if unavailable, skip the drop since the
runtime is already restricting capabilities.
lakamsani pushed a commit to lakamsani/NemoClaw that referenced this pull request Apr 4, 2026
…up (NVIDIA#917)

* fix(security): drop unnecessary Linux capabilities at container startup

Use capsh to drop dangerous capabilities (CAP_NET_RAW, CAP_DAC_OVERRIDE,
CAP_SYS_CHROOT, etc.) from the bounding set at entrypoint startup.
OpenShell manages the container runtime so we cannot pass --cap-drop=ALL
to docker run; instead the entrypoint re-execs through capsh to strip
the bounding set before any child processes launch.

Keeps only the capabilities required for gosu privilege separation:
cap_chown, cap_setuid, cap_setgid, cap_fowner, cap_kill.

Fixes NVIDIA#797

* fix: correct libcap2-bin version pin and capsh comma-separated syntax

- Fix package version to 1:2.66-4+deb12u2+b2 (actual bookworm version)
- Use comma-separated --drop= list per capsh man page
- Add warning when capsh is unavailable
- Fix /proc/1/status -> /proc/self/status comment typo in test
lakamsani pushed a commit to lakamsani/NemoClaw that referenced this pull request Apr 4, 2026
…VIDIA#929)

* fix(security): keep cap_setpcap so capsh can drop other capabilities

capsh --drop needs CAP_SETPCAP in the effective set to modify the
bounding set. Dropping it causes "unable to raise CAP_SETPCAP for BSET
changes: Operation not permitted" and prevents the sandbox from starting.

Fixes install regression from NVIDIA#917.

* fix(security): check for CAP_SETPCAP before attempting capability drop

capsh --drop requires CAP_SETPCAP in the bounding set. OpenShell's
sandbox runtime strips it, so the entrypoint crashes with "unable to
raise CAP_SETPCAP for BSET changes: Operation not permitted".

Check with capsh --has-p first; if unavailable, skip the drop since the
runtime is already restricting capabilities.
cv pushed a commit that referenced this pull request Apr 29, 2026
…OVERRIDE drop (#2659)

## Summary

Fix the `test/e2e/test-runtime-overrides.sh` E2E crash at baseline
config capture. After PR #917 drops `CAP_DAC_OVERRIDE` via `capsh`, root
can no longer write to 444-mode config files. The three runtime override
functions (`apply_model_override`, `apply_cors_override`,
`apply_slack_token_override`) now temporarily relax permissions to 644
before writing and re-lock to 444 afterward, using `CAP_FOWNER` which is
retained by design.

## Related Issue

Fixes #2653

## Changes

- **`scripts/lib/sandbox-init.sh`**: Add `relax_config_for_write()` /
`lock_config_after_write()` shared helpers that `chmod 644`/`chmod 444`
with symlink guards
- **`scripts/nemoclaw-start.sh`**: Wrap python3 write + hash
recomputation in all three override functions with the new helpers
- **`scripts/nemoclaw-start.sh`**: Tighten `apply_model_override()`
trigger guard — only fire when `NEMOCLAW_MODEL_OVERRIDE` or
`NEMOCLAW_INFERENCE_API_OVERRIDE` is explicitly set (Dockerfile ENV
defaults no longer trigger spurious override runs)
- **`test/e2e/test-runtime-overrides.sh`**: Create timestamped log file
matching CI artifact glob `test-runtime-overrides-*.log`, replace all
`2>/dev/null` with `2>>"$LOG_FILE"`
- **`test/e2e/test-runtime-overrides.sh`**: Update tests 3-5, 9-11, 14
to pair standalone parameters with `NEMOCLAW_MODEL_OVERRIDE` (matching
the tightened trigger guard)

## Type of Change
- [x] Code change (feature, bug fix, or refactor)
- [ ] Code change with doc updates
- [ ] Doc only (prose changes, no code sample modifications)
- [ ] Doc only (includes code sample changes)

## Verification
- [ ] `npx prek run --all-files` passes
- [x] `npm test` passes
- [x] Tests added or updated for new or changed behavior
- [x] No secrets, API keys, or credentials committed
- [ ] Docs updated for user-facing behavior changes
- [ ] `make docs` builds without warnings (doc changes only)
- [ ] Doc pages follow the [style
guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md)
(doc changes only)
- [ ] New doc pages include SPDX header and frontmatter (new pages only)

## AI Disclosure
- [x] AI-assisted — tool: Claude Code (pi agent)

---
Signed-off-by: Julie Yaunches <[email protected]>

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Overrides now only apply when explicit override flags are set,
preventing unintended changes.
* Safer config writes: permissions are temporarily relaxed with strict
safety checks (rejecting unsafe targets, skipping missing files), clear
security errors on failure, recompute verification only on successful
writes, and permissions are always restored; write/hash failures are
surfaced.

* **Tests**
* Improved test logging with timestamped artifacts and preserved stderr;
runtime override tests updated to cover model-override scenarios.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Julie Yaunches <[email protected]>
DemianHeyGen pushed a commit to DemianHeyGen/NemoClaw that referenced this pull request Apr 30, 2026
…OVERRIDE drop (NVIDIA#2659)

## Summary

Fix the `test/e2e/test-runtime-overrides.sh` E2E crash at baseline
config capture. After PR NVIDIA#917 drops `CAP_DAC_OVERRIDE` via `capsh`, root
can no longer write to 444-mode config files. The three runtime override
functions (`apply_model_override`, `apply_cors_override`,
`apply_slack_token_override`) now temporarily relax permissions to 644
before writing and re-lock to 444 afterward, using `CAP_FOWNER` which is
retained by design.

## Related Issue

Fixes NVIDIA#2653

## Changes

- **`scripts/lib/sandbox-init.sh`**: Add `relax_config_for_write()` /
`lock_config_after_write()` shared helpers that `chmod 644`/`chmod 444`
with symlink guards
- **`scripts/nemoclaw-start.sh`**: Wrap python3 write + hash
recomputation in all three override functions with the new helpers
- **`scripts/nemoclaw-start.sh`**: Tighten `apply_model_override()`
trigger guard — only fire when `NEMOCLAW_MODEL_OVERRIDE` or
`NEMOCLAW_INFERENCE_API_OVERRIDE` is explicitly set (Dockerfile ENV
defaults no longer trigger spurious override runs)
- **`test/e2e/test-runtime-overrides.sh`**: Create timestamped log file
matching CI artifact glob `test-runtime-overrides-*.log`, replace all
`2>/dev/null` with `2>>"$LOG_FILE"`
- **`test/e2e/test-runtime-overrides.sh`**: Update tests 3-5, 9-11, 14
to pair standalone parameters with `NEMOCLAW_MODEL_OVERRIDE` (matching
the tightened trigger guard)

## Type of Change
- [x] Code change (feature, bug fix, or refactor)
- [ ] Code change with doc updates
- [ ] Doc only (prose changes, no code sample modifications)
- [ ] Doc only (includes code sample changes)

## Verification
- [ ] `npx prek run --all-files` passes
- [x] `npm test` passes
- [x] Tests added or updated for new or changed behavior
- [x] No secrets, API keys, or credentials committed
- [ ] Docs updated for user-facing behavior changes
- [ ] `make docs` builds without warnings (doc changes only)
- [ ] Doc pages follow the [style
guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md)
(doc changes only)
- [ ] New doc pages include SPDX header and frontmatter (new pages only)

## AI Disclosure
- [x] AI-assisted — tool: Claude Code (pi agent)

---
Signed-off-by: Julie Yaunches <[email protected]>

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **Bug Fixes**
* Overrides now only apply when explicit override flags are set,
preventing unintended changes.
* Safer config writes: permissions are temporarily relaxed with strict
safety checks (rejecting unsafe targets, skipping missing files), clear
security errors on failure, recompute verification only on successful
writes, and permissions are always restored; write/hash failures are
surfaced.

* **Tests**
* Improved test logging with timestamped artifacts and preserved stderr;
runtime override tests updated to cover model-override scenarios.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: Julie Yaunches <[email protected]>
@wscurran wscurran added the bug-fix PR fixes a bug or regression label Jun 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug-fix PR fixes a bug or regression

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[SECURITY] Dockerfile does not explicitly drop Linux capabilities

5 participants