Skip to content

fix(cardwired): directly clean PID MAPS inside the bpf code - #158

Merged
luytan merged 2 commits into
mainfrom
ebpf-security
Aug 7, 2026
Merged

fix(cardwired): directly clean PID MAPS inside the bpf code#158
luytan merged 2 commits into
mainfrom
ebpf-security

Conversation

@luytan

@luytan luytan commented Aug 7, 2026

Copy link
Copy Markdown
Member

Description

Please include a summary of the changes and if applicable, a related issue.

If this PR introduce a new feature, explain your motivations

Fixes # (issue)

TODO

  • Copy-Paste this line

Checklist:

  • My code follows the style guidelines of this project (cargo fmt)
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the mdBook documentation
  • My changes generate no new warnings (clippy/clang)
  • New and existing unit tests pass locally with my changes (either use nix flake check or wait for the ci)

@coderabbitai

coderabbitai Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@luytan, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 21 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: e4b566f5-7704-46c6-aab9-f802d9923e8e

📥 Commits

Reviewing files that changed from the base of the PR and between 79194be and b43662f.

📒 Files selected for processing (1)
  • crates/cardwire-ebpf/src/main.rs
📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Added Smart Policy controls through the daemon’s D-Bus interface.
    • Processes can now be assigned default, allowed, or forced GPU access policies.
    • Added process status reporting, including the selected policy and GPU ID.
    • Registered the Smart Policy interface on the main Cardwire D-Bus path.
  • Improvements

    • Process policy state is automatically cleaned up when processes exit.
    • Simplified execution-event processing and policy map handling.

Walkthrough

Behold: the daemon now exposes SmartPolicyInterface over D-Bus, shares PID maps through EbpfBlocker, removes policy entries during eBPF process lifecycle events, and processes execution events without close-event handling.

Changes

Smart policy and PID lifecycle

Layer / File(s) Summary
eBPF PID lifecycle cleanup
crates/cardwire-ebpf/src/maps.rs, crates/cardwire-ebpf/src/main.rs
The close-event map is removed. Exec and main-thread exit handlers remove process IDs from the allowed and forced PID maps.
Shared PID map access
crates/cardwire-ebpf-userspace/src/lib.rs
EbpfBlocker stores asynchronously locked PID maps. Map accessors now receive an external mutable Ebpf reference.
Smart policy D-Bus interface
crates/cardwire-daemon/src/interface/smart.rs, crates/cardwire-daemon/src/interface/mod.rs, crates/cardwire-daemon/src/models.rs, crates/cardwire-daemon/src/daemon.rs
SmartPolicyInterface applies allow and force policies, reports process status, and is registered on the Cardwire D-Bus path.
Execution-only analyzer flow
crates/cardwire-daemon/src/analyzer/models.rs
CardwireAnalyzer removes close-ring state and close-event cleanup. Execution events use direct readiness polling.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DbusClient
  participant SmartPolicyInterface
  participant pid_map
  participant forced_map
  DbusClient->>SmartPolicyInterface: request_process_access(pid, policy, value)
  SmartPolicyInterface->>pid_map: update or remove allow entry
  SmartPolicyInterface->>forced_map: update or remove force entry
  SmartPolicyInterface-->>DbusClient: policy result or D-Bus error
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description retains the template without a change summary, issue reference, motivations, or completed checklist items. Add a concise change summary, related issue or justification, feature motivation if applicable, and complete the checklist accurately.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: direct cleanup of PID maps in the BPF code.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch ebpf-security

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

@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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
crates/cardwire-daemon/src/analyzer/models.rs (1)

41-50: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Restore expiry for reported_pids.

By the runes, removing close-event handling also removed the only cleanup for reported_pids. The set now grows for the daemon lifetime. A reused PID also suppresses reports for an unrelated process.

Keep process-exit cleanup, or replace this set with a bounded TTL cache.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/cardwire-daemon/src/analyzer/models.rs` around lines 41 - 50, Restore
cleanup for reported_pids in CardwireAnalyzer so entries are removed when their
processes exit, or replace the HashSet with a bounded TTL cache. Ensure reused
PIDs can be reported again and the collection cannot grow for the daemon’s
entire lifetime.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/cardwire-daemon/src/analyzer/models.rs`:
- Around line 131-143: Update the execution-ring readiness handling in run so
errors from exec_ring.ready_mut(Interest::READABLE).await are not discarded: use
the same reporting pattern as report_logger, log the failure, and return the
error from run. Preserve the existing readable-event processing for successful
readiness checks.

In `@crates/cardwire-daemon/src/interface/smart.rs`:
- Around line 37-40: Update the policy-key construction and insertion flow
around the visible `/proc/<pid>` existence check to use a stable
process-lifetime identifier, such as the process start identity, rather than PID
alone. Ensure the identifier is obtained and validated before map insertion, and
key authorization so PID reuse cannot inherit the previous process policy; do
not rely solely on `Path::new(...).exists()`.
- Around line 43-86: Update the policy transition handler around the
`"Default"`, `"Allow_dGPU"`, `"Force_dGPU"`, and `"Force_GPU"` branches to treat
`AyaMapError::KeyNotFound` from removals as success. Make `"Default"` remove the
PID from both maps, and introduce/use one shared transition lock held across
each branch’s complete removal and insertion so concurrent requests cannot leave
the PID in both maps.

In `@crates/cardwire-ebpf/src/main.rs`:
- Around line 463-464: Move removal of CW_ALLOWED_PID and CW_FORCED_PID entries
in crates/cardwire-ebpf/src/main.rs#L463-L464 before the is_cardwired,
whitelist, Smart-mode, and ring-buffer-reservation early returns so cleanup is
independent of event delivery. In the main-thread exit handling at
crates/cardwire-ebpf/src/main.rs#L485-L501, remove both map entries regardless
of whether Smart mode is active.

---

Outside diff comments:
In `@crates/cardwire-daemon/src/analyzer/models.rs`:
- Around line 41-50: Restore cleanup for reported_pids in CardwireAnalyzer so
entries are removed when their processes exit, or replace the HashSet with a
bounded TTL cache. Ensure reused PIDs can be reported again and the collection
cannot grow for the daemon’s entire lifetime.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 380d37bd-42d4-4c31-a511-82a1c9cc74bc

📥 Commits

Reviewing files that changed from the base of the PR and between 16b9672 and 79194be.

📒 Files selected for processing (8)
  • crates/cardwire-daemon/src/analyzer/models.rs
  • crates/cardwire-daemon/src/daemon.rs
  • crates/cardwire-daemon/src/interface/mod.rs
  • crates/cardwire-daemon/src/interface/smart.rs
  • crates/cardwire-daemon/src/models.rs
  • crates/cardwire-ebpf-userspace/src/lib.rs
  • crates/cardwire-ebpf/src/main.rs
  • crates/cardwire-ebpf/src/maps.rs
💤 Files with no reviewable changes (1)
  • crates/cardwire-ebpf/src/maps.rs

Comment thread crates/cardwire-daemon/src/analyzer/models.rs
Comment thread crates/cardwire-daemon/src/interface/smart.rs
Comment thread crates/cardwire-daemon/src/interface/smart.rs
Comment thread crates/cardwire-ebpf/src/main.rs Outdated
@luytan
luytan merged commit 7b1f539 into main Aug 7, 2026
7 checks passed
@luytan
luytan deleted the ebpf-security branch August 7, 2026 09:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant