Skip to content

Add process-lifetime (session) blacklist via IOCTL_ADD_SESSION_BLACKLIST - #201

Merged
nefarius merged 4 commits into
nefarius:masterfrom
anagnorisis2peripeteia:feature/session-blacklist
Apr 28, 2026
Merged

nefarius merged 4 commits into
nefarius:masterfrom
anagnorisis2peripeteia:feature/session-blacklist

Conversation

@anagnorisis2peripeteia

@anagnorisis2peripeteia anagnorisis2peripeteia commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Adds IOCTL_ADD_SESSION_BLACKLIST (code 2056) and IOCTL_CLR_SESSION_BLACKLIST (code 2057)
  • Applications register device instance paths against their own process handle
  • When the registering process exits — for any reason (clean exit, crash, TerminateProcess, task kill) — HidHide automatically removes those entries via the existing OnSystemProcessChange callback
  • No watchdog process, no cleanup code required in the calling application

Motivation

The current blacklist is persistent (registry-backed), which is correct for permanent rules. But applications that want "hide this device while I'm running, release it when I exit" currently have no clean primitive for this — they must implement watchdog processes to handle crash cleanup, which adds complexity and can still leave devices hidden if the watchdog itself fails.

Moving this responsibility into the kernel is the right design: OnSystemProcessChange already fires reliably on all process terminations, including unexpected ones.

Use case

Input remappers like DS4Windows want to claim controllers exclusively for their session without permanently hiding them from other applications (Steam Input, OpenRGB, etc.). When the remapper exits, devices should become visible again automatically — no reboot, no manual HidHide Client interaction required.

This directly addresses several open requests:

Changes

Logic.h

  • New IOCTL codes IOCTL_ADD_SESSION_BLACKLIST / IOCTL_CLR_SESSION_BLACKLIST
  • SESSION_BLACKLIST_ENTRY struct (owner PID + device instance path)
  • sessionBlacklistHead (LIST_ENTRY) added to CONTROL_DEVICE_CONTEXT
  • SessionBlacklistCleanupForPid() declaration
  • OnControlDeviceIoAddSessionBlacklist() / OnControlDeviceIoClearSessionBlacklist() declarations

Logic.c

  • OnControlDeviceCreate: initialises sessionBlacklistHead
  • OnSystemProcessChange: calls SessionBlacklistCleanupForPid() on process exit
  • OnControlDeviceIoDeviceControl: dispatch cases for new IOCTLs
  • OnControlDeviceIoAddSessionBlacklist: walks MULTI_SZ input, allocates SESSION_BLACKLIST_ENTRY per path tagged with caller PID, builds into local list and splices atomically under lock
  • OnControlDeviceIoClearSessionBlacklist: explicit early release for calling process
  • SessionBlacklistCleanupForPid: walks session list under lock, removes and frees all entries for the given PID
  • OnControlDeviceContextCleanup: drains remaining session entries on driver unload
  • Blacklisted: checks session list after persistent list

Testing

Verified logic flow manually. Kernel build environment required for full testing — happy to iterate on review feedback.

Summary by CodeRabbit

Release Notes

  • New Features
    • Session-based device blacklisting: dynamically control which devices are hidden for the current session
    • Automatic cleanup of blacklist entries when processes terminate
    • Enhanced granular control over per-session device visibility management

Adds IOCTL_ADD_SESSION_BLACKLIST and IOCTL_CLR_SESSION_BLACKLIST.
Applications register device instance paths against their own process.
When the registering process exits for any reason, HidHide automatically
removes those entries via the existing OnSystemProcessChange callback.

This allows input remappers (e.g. DS4Windows) to claim controllers
exclusively for their session without permanently hiding them. Other
apps regain access automatically when the remapper exits, without
requiring a reboot or manual HidHide Client interaction.
@coderabbitai

coderabbitai Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5e73c3ba-cf1e-4cce-8dea-51b1d20d887b

📥 Commits

Reviewing files that changed from the base of the PR and between ce4140d and 62a5765.

📒 Files selected for processing (1)
  • HidHide/src/Logic.c
✅ Files skipped from review due to trivial changes (1)
  • HidHide/src/Logic.c

📝 Walkthrough

Walkthrough

Adds a per-process (session) blacklist to the control device: new IOCTLs to add/clear per-PID device-instance paths, per-PID cleanup on process exit, driver-unload draining of session entries, and access checks extended to consult the session blacklist alongside the persistent blacklist.

Changes

Cohort / File(s) Summary
Public API / Types
HidHide/src/Logic.h
Add SESSION_BLACKLIST_ENTRY, IOCTL_ADD_SESSION_BLACKLIST, IOCTL_CLR_SESSION_BLACKLIST, and declarations for OnControlDeviceIoAddSessionBlacklist, OnControlDeviceIoClearSessionBlacklist, SessionBlacklistCleanupForPid.
Implementation / IOCTL handlers
HidHide/src/Logic.c
Introduce sessionBlacklistHead in control context; implement OnControlDeviceIoAddSessionBlacklist (validate/parse caller MULTI_SZ, allocate per-entry deviceInstancePath, tag with caller PID, append under lock) and OnControlDeviceIoClearSessionBlacklist (validate empty buffer, remove entries for caller PID).
Access & cleanup logic
HidHide/src/Logic.c
Extend Blacklisted() to consult sessionBlacklistHead matches; add SessionBlacklistCleanupForPid called on process termination; driver unload drains/frees session blacklist entries with safe handling of a possibly-NULL s_criticalSectionLock.

Sequence Diagram(s)

sequenceDiagram
    participant App as User App
    participant Ctrl as Control Device
    participant Logic as Driver Logic
    participant Notif as Process Exit Notifier

    App->>Ctrl: IOCTL_ADD_SESSION_BLACKLIST (WCHAR MULTI_SZ)
    Ctrl->>Logic: Validate & parse MULTI_SZ -> allocate SESSION_BLACKLIST_ENTRY[] (tag entries with PID)
    Logic->>Logic: Acquire s_criticalSectionLock
    Logic->>Logic: Append entries to sessionBlacklistHead
    Logic->>Logic: Release s_criticalSectionLock

    App->>Ctrl: IOCTL_CLR_SESSION_BLACKLIST (empty buffer)
    Ctrl->>Logic: Validate request
    Logic->>Logic: Acquire s_criticalSectionLock
    Logic->>Logic: Remove/free entries matching caller PID
    Logic->>Logic: Release s_criticalSectionLock

    Notif->>Logic: Process exit(PID)
    Logic->>Logic: SessionBlacklistCleanupForPid(PID) — remove/free entries

    Note right of Logic: Blacklisted() checks persistent list, then sessionBlacklistHead
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I nibble strings and mark each path,
For every PID I keep my math,
I add, I clear, then tidy proud,
I hop away—no entries loud,
A little rabbit guard, unbowed. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main feature being added: a session-scoped (process-lifetime) blacklist accessible via a new IOCTL, which aligns with the core changes across both Logic.h and Logic.c files.
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.

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


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@HidHide/src/Logic.c`:
- Around line 644-671: SessionBlacklistCleanupForPid only deletes entries
matching a single PID so leftover SESSION_BLACKLIST_ENTRY allocations remain
when the control device is torn down; change the teardown path to drain all
entries (or extend SessionBlacklistCleanupForPid to treat a special value like
NULL/INVALID_PID as "delete all") and iterate the entire sessionBlacklistHead
removing each entry, calling WdfObjectDelete(sbe->deviceInstancePath) and
ExFreePoolWithTag(sbe, 'lBSH') for every node; ensure you still acquire and
release s_criticalSectionLock around the walk and use the same
CONTAINING_RECORD/RemoveEntryList/next pattern to avoid list corruption, and
call this new "drain all" behavior from OnControlDeviceContextCleanup/cleanup
code so no allocations remain after control-device teardown.
- Around line 604-618: The code currently inserts entry into
sessionBlacklistHead before ensuring all subsequent allocations succeed, risking
partial state on failure; change the flow so you fully allocate and initialize
entry (call ExAllocatePoolWithTag and WdfStringCreate and set ownerPid) before
taking s_criticalSectionLock and calling InsertTailList, or alternatively, if
you must insert incrementally, track inserted entries and on any later failure
acquire s_criticalSectionLock, remove those entries from sessionBlacklistHead,
free their WdfString and pool memory (using WdfObject/ExFreePoolWithTag), and
then return the error; use the existing symbols PSESSION_BLACKLIST_ENTRY,
ExAllocatePoolWithTag, WdfStringCreate, InsertTailList,
WdfWaitLockAcquire/WdfWaitLockRelease, and sessionBlacklistHead to locate and
implement the fix.
- Around line 587-620: The MULTI_SZ loop currently uses while (*current !=
L'\0') and wcslen(current) which can read past the IOCTL buffer; change the
parser to bound all reads by inputBufferLength: compute a remaining WCHAR count
(e.g. bytesLeft = inputBufferLength; remainingChars = bytesLeft / sizeof(WCHAR))
and in the loop ensure remainingChars >= 1, find the current string length using
a bounded search (wcsnlen or a manual scan) that will not exceed remainingChars,
return an error if no terminating NUL is found within remainingChars, and when
advancing current subtract (len+1) from remainingChars and add
(len+1)*sizeof(WCHAR) to the pointer; apply this to the code around buffer,
inputBufferLength, current, wcslen(current), and before calling
WdfStringCreate/ExAllocatePoolWithTag/InsertTailList to avoid overruns.
🪄 Autofix (Beta)

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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2071c392-0e7e-4ac5-baa1-b7a0a333b373

📥 Commits

Reviewing files that changed from the base of the PR and between fd9e3e4 and efd1856.

📒 Files selected for processing (2)
  • HidHide/src/Logic.c
  • HidHide/src/Logic.h

Comment thread HidHide/src/Logic.c Resolved
Comment thread HidHide/src/Logic.c Resolved
Comment thread HidHide/src/Logic.c Resolved
- OnControlDeviceContextCleanup: drain sessionBlacklistHead at driver
  unload to fix the memory leak when the list is non-empty
- OnControlDeviceIoAddSessionBlacklist: build entries into a local list
  first and splice atomically under lock, so the operation is all-or-
  nothing; previously a mid-loop allocation failure left partial state
- OnControlDeviceIoAddSessionBlacklist: replace unbounded wcslen with
  wcsnlen bounded by the IOCTL input buffer length; return
  STATUS_INVALID_PARAMETER for malformed input that has no null
  terminator within the buffer

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
HidHide/src/Logic.c (1)

601-603: ⚠️ Potential issue | 🟠 Major

Tighten MULTI_SZ validation to reject malformed payloads deterministically.

OnControlDeviceIoAddSessionBlacklist still accepts malformed buffer shapes (e.g., odd byte count or missing list terminator at end) and can return success after silently truncating input.

Suggested fix
     if (0 != outputBufferLength) LOG_AND_RETURN_NTSTATUS(L"Validation", STATUS_INVALID_PARAMETER);
     if (0 == inputBufferLength)  LOG_AND_RETURN_NTSTATUS(L"Validation", STATUS_INVALID_PARAMETER);
+    if ((inputBufferLength % sizeof(WCHAR)) != 0) LOG_AND_RETURN_NTSTATUS(L"Validation", STATUS_INVALID_PARAMETER);

@@
     while ((size_t)(current - buffer) < totalChars && *current != L'\0')
     {
@@
         current += len + 1;
     }

+    if (NT_SUCCESS(ntstatus))
+    {
+        // Ensure we stopped on the MULTI_SZ list terminator within bounds.
+        if (((size_t)(current - buffer) >= totalChars) || (*current != L'\0'))
+        {
+            ntstatus = STATUS_INVALID_PARAMETER;
+        }
+    }
+
     if (!NT_SUCCESS(ntstatus))
     {

Also applies to: 617-625, 653-669

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@HidHide/src/Logic.c` around lines 601 - 603, Tighten MULTI_SZ validation in
OnControlDeviceIoAddSessionBlacklist: in addition to existing output/input
length checks, verify inputBufferLength is a multiple of sizeof(WCHAR) and at
least 2*sizeof(WCHAR), and ensure the buffer ends with a double-NUL wchar (two
consecutive L'\0' at the end); if any check fails return
STATUS_INVALID_PARAMETER. Apply the same strict checks to the other MULTI_SZ
parsing blocks referenced around the 617-625 and 653-669 ranges so malformed
(odd byte-count or missing terminator) payloads are deterministically rejected
instead of being truncated or accepted.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@HidHide/src/Logic.c`:
- Around line 689-693: The handler currently only rejects non-zero
outputBufferLength but accepts and ignores inputBufferLength; add a symmetric
validation rejecting any non-zero input payload for the clear-session IOCTL by
checking if (0 != inputBufferLength) and returning the same failure path (use
LOG_AND_RETURN_NTSTATUS(L"Validation", STATUS_INVALID_PARAMETER)) so the
function (the IOCTL clear-session handler using variables
inputBufferLength/outputBufferLength and LOG_AND_RETURN_NTSTATUS) enforces both
input and output buffer constraints.
- Around line 79-90: OnControlDeviceContextCleanup currently calls
WdfWaitLockAcquire(s_criticalSectionLock) without checking that
s_criticalSectionLock was created; if WdfWaitLockCreate failed the NULL handle
causes a crash. Fix by guarding the lock usage: check s_criticalSectionLock !=
NULL before calling WdfWaitLockAcquire/WdfWaitLockRelease, and if NULL, proceed
to safely walk and free pControlDeviceContext->sessionBlacklistHead entries
(sessionBlacklistHead, SESSION_BLACKLIST_ENTRY, sbe) without acquiring the lock;
ensure the same removal and cleanup (RemoveEntryList, WdfObjectDelete,
ExFreePoolWithTag) still runs in that null-lock path.

---

Duplicate comments:
In `@HidHide/src/Logic.c`:
- Around line 601-603: Tighten MULTI_SZ validation in
OnControlDeviceIoAddSessionBlacklist: in addition to existing output/input
length checks, verify inputBufferLength is a multiple of sizeof(WCHAR) and at
least 2*sizeof(WCHAR), and ensure the buffer ends with a double-NUL wchar (two
consecutive L'\0' at the end); if any check fails return
STATUS_INVALID_PARAMETER. Apply the same strict checks to the other MULTI_SZ
parsing blocks referenced around the 617-625 and 653-669 ranges so malformed
(odd byte-count or missing terminator) payloads are deterministically rejected
instead of being truncated or accepted.
🪄 Autofix (Beta)

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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 871a2c9e-27a1-42ad-8dea-acd36269ef9f

📥 Commits

Reviewing files that changed from the base of the PR and between efd1856 and 1b059cf.

📒 Files selected for processing (1)
  • HidHide/src/Logic.c

Comment thread HidHide/src/Logic.c Resolved
Comment thread HidHide/src/Logic.c Resolved
- OnControlDeviceContextCleanup: guard WdfWaitLockAcquire/Release with
  NULL check on s_criticalSectionLock in case WdfWaitLockCreate failed
  during driver initialisation; drain proceeds locklessly in that path
- OnControlDeviceIoClearSessionBlacklist: add symmetric inputBufferLength
  validation (IOCTL takes no input and no output)
- OnControlDeviceIoAddSessionBlacklist: tighten MULTI_SZ upfront checks
  — reject if inputBufferLength is not a multiple of sizeof(WCHAR), less
  than 2*sizeof(WCHAR), or the buffer does not end with a double-NUL
@anagnorisis2peripeteia

Copy link
Copy Markdown
Contributor Author

All CodeRabbit comments addressed in the two follow-up commits:

ce4140d — second-pass fixes:

  • OnControlDeviceContextCleanup: WdfWaitLockAcquire/Release now guarded by s_criticalSectionLock != NULL check; drain proceeds locklessly if WdfWaitLockCreate failed during driver init
  • OnControlDeviceIoClearSessionBlacklist: symmetric validation added — now rejects both non-zero outputBufferLength and non-zero inputBufferLength
  • OnControlDeviceIoAddSessionBlacklist: upfront MULTI_SZ validation tightened — rejects inputBufferLength that is not a multiple of sizeof(WCHAR), less than 2*sizeof(WCHAR), or whose buffer does not end with a double-NUL

1b059cf — first-pass fixes (original three issues):

  • Memory leak in teardown: OnControlDeviceContextCleanup now drains sessionBlacklistHead
  • Partial state on failure: entries built into a local list first, spliced atomically with AppendTailList under lock only on full success
  • Buffer overrun: wcslen replaced with wcsnlen bounded by inputBufferLength

- Add missing _Use_decl_annotations_ to SessionBlacklistCleanupForPid
- Hoist all mid-function variable declarations to the top of each
  function block to match the declare-then-execute pattern used
  throughout Logic.c (OnControlDeviceIoAddSessionBlacklist,
  SessionBlacklistCleanupForPid, Blacklisted)
@anagnorisis2peripeteia

Copy link
Copy Markdown
Contributor Author

Style pass (62a5765) — reviewing the new code against the rest of Logic.c surfaced two conventions we weren't matching:

  1. SessionBlacklistCleanupForPid was missing _Use_decl_annotations_ — the only function in the file without it.
  2. All new functions had variable declarations scattered mid-function after executable statements. The codebase pattern throughout Logic.c is declare-all-locals-at-top-of-block, then execute. Fixed in OnControlDeviceIoAddSessionBlacklist, SessionBlacklistCleanupForPid, and Blacklisted.

No behavioural changes — purely bringing the code in line with the surrounding style.

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.

2 participants