Repository navigation
Add process-lifetime (session) blacklist via IOCTL_ADD_SESSION_BLACKLIST - #201
Conversation
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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
📝 WalkthroughWalkthroughAdds 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
HidHide/src/Logic.cHidHide/src/Logic.h
- 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
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
HidHide/src/Logic.c (1)
601-603:⚠️ Potential issue | 🟠 MajorTighten MULTI_SZ validation to reject malformed payloads deterministically.
OnControlDeviceIoAddSessionBlackliststill 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
📒 Files selected for processing (1)
HidHide/src/Logic.c
- 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
|
All CodeRabbit comments addressed in the two follow-up commits: ce4140d — second-pass fixes:
1b059cf — first-pass fixes (original three issues):
|
- 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)
|
Style pass (62a5765) — reviewing the new code against the rest of Logic.c surfaced two conventions we weren't matching:
No behavioural changes — purely bringing the code in line with the surrounding style. |
Summary
IOCTL_ADD_SESSION_BLACKLIST(code 2056) andIOCTL_CLR_SESSION_BLACKLIST(code 2057)TerminateProcess, task kill) — HidHide automatically removes those entries via the existingOnSystemProcessChangecallbackMotivation
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:
OnSystemProcessChangealready 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.hIOCTL_ADD_SESSION_BLACKLIST/IOCTL_CLR_SESSION_BLACKLISTSESSION_BLACKLIST_ENTRYstruct (owner PID + device instance path)sessionBlacklistHead(LIST_ENTRY) added toCONTROL_DEVICE_CONTEXTSessionBlacklistCleanupForPid()declarationOnControlDeviceIoAddSessionBlacklist()/OnControlDeviceIoClearSessionBlacklist()declarationsLogic.cOnControlDeviceCreate: initialisessessionBlacklistHeadOnSystemProcessChange: callsSessionBlacklistCleanupForPid()on process exitOnControlDeviceIoDeviceControl: dispatch cases for new IOCTLsOnControlDeviceIoAddSessionBlacklist: walks MULTI_SZ input, allocatesSESSION_BLACKLIST_ENTRYper path tagged with caller PID, builds into local list and splices atomically under lockOnControlDeviceIoClearSessionBlacklist: explicit early release for calling processSessionBlacklistCleanupForPid: walks session list under lock, removes and frees all entries for the given PIDOnControlDeviceContextCleanup: drains remaining session entries on driver unloadBlacklisted: checks session list after persistent listTesting
Verified logic flow manually. Kernel build environment required for full testing — happy to iterate on review feedback.
Summary by CodeRabbit
Release Notes