Hardened memory-access and hardware-breakpoint driver for Linux, inspired by Cheat Engine's DBK on Windows. Kernel module + modern C++ userland API with process memory access, hardware debugging, native memory protection, and ELF mapping helpers. Research and educational use only.
- Kernel driver (
kernel/):/dev/snakedrv, process attach/detach, forced read/write, memory region enumeration, hardware breakpoints with thread inheritance, per-client event queues, physical memory access, and tracked pinned mappings. - Userland library (
userland/): typed C/C++ API (snakedrv.h,libsnakedrv.hpp) plus ELF mapping/injection helpers and remote symbol resolution. - Memory scanner (
libsnakedrv_scanner): Cheat Engine-style scans (exact/range/changed/pattern/float/string) with bloom filter acceleration and parallel scanning. - dlopen injection: inject any
.sointo a running process viadlopen— full C++ runtime, TLS, exception handling, and OpenGL support out of the box. - ImGui overlay: inject a Dear ImGui window into SDL2/OpenGL games (e.g. AssaultCube) with DYNAPI hook.
- Mapping lifetime: pinned allocations retain normal VMAs and belong to the opening client. Legacy VMA unlinking is unsupported in ABI 3.
- Automation (
deploy.sh): deps, build, install, load/unload, test, inject, SELinux policy, DKMS integration. - Security (
security/): udev rules, AppArmor profile, SELinux policy (v2.0 with kernel thread + unconfined_t support), Secure Boot signing.
- Linux kernel 6.1+ on x86_64
- Kernel headers matching the running kernel
- gcc, g++, make, cmake
- SDL2-devel, mesa-libGL-devel (for ImGui payload)
- DKMS recommended for kernel upgrades
- Secure Boot (optional):
mokutilandsign-module.sh
# Build everything (driver + library + tests + ImGui payload)
./deploy.sh build
# Install (kernel module, library, tools, SELinux policy)
sudo ./deploy.sh install
# Load the module
sudo ./deploy.sh load
# Check status
./deploy.sh statusInstall a new source checkout with sudo ./deploy.sh install (or use
./setup.sh). Both refresh the registered DKMS sources and build for the
running kernel and all installed kernels with development headers. DKMS
rebuilds the module automatically on later kernel upgrades; the matching
development headers must be installed.
To update from a signed GitHub release:
/usr/lib/snakeengine/snakedrv-updater --check
sudo /usr/lib/snakeengine/snakedrv-updater --latest
# Or choose a specific release:
sudo /usr/lib/snakeengine/snakedrv-updater 2.1.0--latest installs the latest stable release when invoked. Kernel upgrades
rebuild the registered sources; they do not download new GitHub releases.
The release version comes from userland/include/snakedrv.h. Update its
numeric version and SNAKEDRV_VERSION_STRING together before a release;
deploy.sh, DKMS staging, Make and CMake use that version. The ABI only
changes when the public interface becomes incompatible.
After reviewing and committing the release changes under your own Git identity,
and synchronizing main with origin/main:
bash scripts/version.sh --check-tag v2.1.0
git push origin main
git tag -a v2.1.0 -m "SnakeEngine driver 2.1.0"
git push origin v2.1.0The tag push runs .github/workflows/release.yml: validate the version,
compile the isolated DKMS sources on Ubuntu 24.04 and Fedora 44/45,
build the library/verifier and source archive, sign the artifacts,
verify the signed source archive with the shipped verifier, then publish
the GitHub Release. A failed validation blocks publication. The release
keeps the existing source-only format. Local installs, the updater, and
the optional native package templates use the same complete DKMS tree.
The workflow creates no Git commits and adds no contributor attribution. Use a new version/tag for subsequent fixes. A manual rerun must target the tag so its signing identity remains compatible with the updater:
gh workflow run release.yml --ref v2.1.0 -f tag=v2.1.0The recommended injection method uses dlopen for full runtime support:
# Inject a .so into a running process
sudo dlopen_inject <pid> /path/to/payload.so
# Or via deploy.sh
sudo ./deploy.sh inject <pid> /path/to/payload.soThe manual mapper requires an exported ManualMapEntry(void*). All mappings retain normal VMAs. In ABI 3, INJECT_STEALTH returns EOPNOTSUPP; pinned allocations are also visible and are released when their owning driver descriptor closes.
# Build the ImGui payload
./deploy.sh payload
# Launch a game and inject
assaultcube &
sleep 5
sudo dlopen_inject $(pgrep assaultcube) libpayload_dlopen.soThis injects a Dear ImGui overlay window into the game via SDL2 DYNAPI hook.
Driver::open() checks the loaded module ABI. Upgrade the module and SDK
as a matching pair; ABI 2 clients must be rebuilt for these lifetime semantics.
Breakpoint callbacks use preallocated per-client rings. They do not allocate,
acquire mutexes, walk mutable attachment lists, or execute SIMD instructions.
debugStats() / GET_DEBUG_STATS report queue capacity, queued events, dropped
events, and drops caused by lock contention. The default capacity is 256 and
new descriptors accept configured capacities from 1 to 4096. XMM fields are
not sampled by this callback.
Process-wide breakpoints inherit into subsequently created threads through perf's thread-only inheritance. Clearing a root event also removes its inherited events. Notification is the default; request a process stop explicitly:
auto bp = drv.setBreakpoint(address, snake::BreakpointType::Write,
snake::BreakpointLength::Byte8, 0, true);
auto stats = drv.debugStats();The last arguments select the thread (0 for the process) and stop-on-hit.
Stops are delivered as SIGSTOP outside the debug callback. Continue through
the driver when ready; detach/close also releases a stop owned by that client.
Driver::injectProtect() applies the target's native mprotect syscall,
including permission removal, page-table updates, subranges and the kernel's
normal permission checks. For another process the SDK pauses its threads via
ptrace, temporarily executes the syscall, restores instructions and registers,
and restores the prior stopped/running state. Existing trace owners are rejected.
The legacy kernel INJECT_PROTECT command returns EOPNOTSUPP, rather than
claiming success after changing only VMA flags. The SDK requires this response
after the driver's capability check before invoking its native implementation.
Cached scan results retain independent references for readers and are scoped to the owning descriptor and scan PID. Pinned mappings likewise retain reader references during explicit free or close. Timed-out allocation jobs retain their own context and mm reference, reclaim unclaimed mappings, and are drained before module unload. Arbitrary removal of VMAs from kernel tracking is disabled.
cmake -S userland -B /tmp/snakedrv-tests -DSNAKEDRV_BUILD_TESTS=ON
cmake --build /tmp/snakedrv-tests -j2
ctest --test-dir /tmp/snakedrv-tests --output-on-failure
# Requires matching boot image/headers, QEMU, cpio and CMake. No host module load.
python3 scripts/test-kernel-runtime.pyThe diskless guest exercises breakpoint inheritance, leader exit, stop-on-hit,
client isolation, event overflow, concurrent detach/registration, result-cache
read/free, pinned-page write/free, close cleanup, and delayed-worker unload.
It also tests actual R/RW/RX/PROT_NONE accesses and native-protection restoration.
TESTING=1 enables the guest-only worker-delay hook; production builds omit it.
These checks run in CI and gate source releases. Serial logs are retained as
CI artifacts. Kernel sanitizer coverage depends on the selected test kernel.
#include "libsnakedrv.hpp"
int main() {
snake::Driver drv;
drv.open();
drv.attach(target_pid);
// Read/write memory
uint32_t hp = drv.read<uint32_t>(health_addr);
drv.write(health_addr, 9999);
// Hardware breakpoint
auto bp = drv.setBreakpoint(addr,
snake::BreakpointType::ReadWrite,
snake::BreakpointLength::Byte4);
// Poll debug events
for (const auto& ev : drv.pollEvents(16))
printf("Hit at 0x%lx\n", ev.address);
drv.clearBreakpoint(*bp);
drv.detach();
}The driver ships a SELinux policy that allows operation under enforcing mode.
sudo ./deploy.sh install # installs policy automaticallycd security/
sudo dnf install selinux-policy-devel # Fedora
sudo make -f /usr/share/selinux/devel/Makefile snakeengine.pp
sudo semodule -i snakeengine.pp
sudo restorecon -Rv /dev/snakedrvgetenforce # should show "Enforcing"
sudo ./deploy.sh status # should work without setenforce 0The v2.0 policy covers:
unconfined_t(sudo processes) access to/dev/snakedrvioctlskernel_tthreads (snake_injector,snake_shadow) withexecmemforvm_mmap(PROT_EXEC)CAP_SYS_PTRACEandCAP_SYS_ADMINcapability checks- udev device node creation
- Boolean
snakeengine_can_trace_all(default: on)
kernel/ Kernel driver (snakedrv.ko)
snakedrv_main.c Core driver, IOCTLs, capability checks
snakedrv_scanner.c Memory scanner with bloom filter
snakedrv_backend_process.c Process memory backend
snakedrv_injector.c Allocation workers, thread hijack, pinned mappings
snakedrv_backend.h Backend abstraction (VFS-style vtable)
snakedrv_optimize.h Cache prefetch, huge page support
snakedrv_bloom.h Bloom filter for scan rescans
snakedrv_memory.h Slab caches, buffer pooling
snakedrv_benchmark.h Performance counters
userland/ C/C++ headers and library
include/snakedrv.h IOCTL definitions and ABI
include/libsnakedrv.hpp C++ driver API
include/snakedrv_elf.hpp ELF parser and relocation engine
src/libsnakedrv.cpp Driver implementation
src/snakedrv_injector.cpp Manual mapper + dlopen injector
security/ Security policies
snakeengine.te SELinux type enforcement (v2.0)
snakeengine.fc SELinux file contexts
snakeengine.apparmor AppArmor profile
99-snakedrv.rules udev rules
packaging/dkms/ DKMS configuration
deploy.sh Build, install, test, inject automation
sign-module.sh Secure Boot module signing (MOK)
- Runtime access requires membership in the
snakeenginegroup:sudo usermod -aG snakeengine $USER - All sensitive ioctls require
CAP_SYS_PTRACE; physical memory and injection requireCAP_SYS_ADMIN - SELinux policy v2.0 supports enforcing mode out of the box
- Keep
debug_levellow in production; increase only for debugging - If Secure Boot blocks loading, sign the module with
./sign-module.sh
- Bumped the driver ABI to 3 for per-client resource lifetimes and explicit rejection of legacy partial protection/VMA-unlinking operations.
- Replaced the global allocating breakpoint callback with preallocated client rings, immutable callback contexts, deferred notifications and loss counters.
- Serialized breakpoint updates, enabled thread-only inheritance, and added optional stop-on-hit with cleanup of inherited events and owned stops.
- Fixed concurrent result-cache and pinned-page release using independent references; close now releases the client's cached results and pinned mappings.
- Replaced stack-backed memory workers with owned workqueue jobs that remain valid after timeout and reclaim abandoned allocations before unload.
- Implemented complete SDK memory-protection changes through native mprotect, with thread, instruction, register and job-control restoration.
- Added native-permission tests and isolated QEMU kernel regression tests to CI.
- Fixed Fedora kernel builds by replacing the unavailable
strncpycall withstrscpyand including<linux/string.h>explicitly. - Unified release metadata and DKMS source staging across local installs, the updater and native packages; included the shared kernel ABI headers.
- Added Ubuntu/Fedora build checks before publication, complete package rendering, and verification of the signed tarball with the shipped verifier.
- Added updater
--latest, source/tag consistency checks, and updater self-refresh. Package upgrade hooks preserve the replacement driver. - Process-wide hardware breakpoints cover a snapshot of existing threads; data breakpoints report watchpoint events and the accessed address.
Driver update and source-install pipeline:
- Added a production source-release flow for
snakedrv-updater: GitHub tags now publishsnakeengine-driver-X.Y.Z.tar.gzplus a matching.sigstorebundle, checksum files, and a standalonesigstore-verifybinary. - Switched release signing to cosign's protobuf bundle format
(
--new-bundle-format) so the bundledsigstore-verifycan parse and verify release signatures. - Hardened
snakedrv-updaterinto a fail-closed updater: network timeouts, bounded Sigstore verification, fatalmodprobefailures, loaded-module verification, ABI verification,/dev/snakedrvverification, and clear error messages. - Fixed update ordering: the kernel module is now built, installed,
loaded, and validated before replacing
libsnakedrv.soand headers, preventing mixedlibsnakedrv/snakedrv.koABI states. - DKMS updates now remove stale
snakedrvversions and/usr/srctrees before registering the new version, avoiding stale source trees breaking later updates. - Added the source-install templates required by updater/deploy installs:
packaging/dkms/dkms.conf.in,packaging/pkgconfig/snakedrv.pc.in, andpackaging/cmake/SnakeDrvConfigVersion.cmake.in. - Added a package-free release workflow: no
nfpm, no.deb, no.rpm; releases publish only the signed source tarball and verifier assets.
Install and deployment tooling:
deploy.sh installnow installs the updater and verifier under/usr/lib/snakeengine/.deploy.sh statusreports update-tool installation state, loaded driver version/ABI, DKMS state, device state, and recent kernel logs.deploy.sh loadnow treats an already-loaded module as a state to validate instead of blindly runninginsmodand failing withFile exists.deploy.sh build/installno longer requires the localtests/ortests/payload_imgui/directories. They are optional developer assets; production source installs build the driver, userland library, and verifier without them.- Fixed the advertised
deploy.sh build-kernelcommand so it is accepted by the command parser and can be used for VM/kernel-only validation. deploy.shnow buildstools/sigstore-verifywith-buildvcs=false, making Go builds deterministic in source archives and temporary worktrees without reliable Git metadata.- The udev rule is now installed as a minimal root-owned
0644rule for/dev/snakedrvwith groupsnakeengine.
Kernel driver ABI and runtime validation:
- Introduced
SNAKEDRV_ABI_VERSIONand exposed the loaded ABI through driver info/module parameters so userland can reject unsupported kernels instead of failing later with mismatched IOCTL layouts. - Added runtime scanner ABI coverage for backend selection, scan options, first scan, next scan, result-set info, result retrieval, perf stats, reset, free, and detach paths.
- Fixed the scanner IOCTL header duplication issue by consolidating
SNAKEDRV_IOCTL_MAGICusage between core and scanner headers. - Added safer kernel scanner/result-set plumbing and ABI checks for the process backend.
Kernel safety fixes:
- Fixed the
injector_shadow_allocerror path so partially created shadow mappings are unmapped if later allocation steps fail. - Added validation for breakpoint target addresses before programming hardware breakpoints, avoiding arbitrary kernel-address breakpoints.
- Kept VMA stealth explicit and bounded; deferred VMA hiding remains disabled unless the target mapping can be handled safely.
Userland library and manual mapping:
- Hardened ELF symbol and relocation parsing in
userland/src/snakedrv_injector.cppwith stricter bounds checks. - Added local selftests for IOCTL ABI validation and manual-map ELF entry discovery.
manualMapLibrary()now has a concrete test path using a payload that exportsManualMapEntry.- Added installable pkg-config and CMake metadata for downstream driver consumers, with ABI checks in the generated CMake config.
- Installed headers now live under
include/snakedrv/, matching the installed library and generated metadata.
Cross-distro kernel build fixes (tested on Ubuntu 24.04 / kernel 6.17.0-20-generic in a VM, still working on Fedora 43 / kernel 6.19):
-
page->flagstype fix: the previousLINUX_VERSION_CODE >= 6.10guard aroundpage->flags.fwas wrong in both directions. Thememdesc_flags_tstruct wrapper landed later than 6.10 in mainline and distros cherry-pick it independently of the version bump. Replaced the#ifwith a version-independent*(unsigned long *)&page->flags— identical layout in both cases becausememdesc_flags_twraps a singleunsigned long. Fixeserror: request for member 'f' in something not a structure or unionon Ubuntu 6.17 and similar distros without the backport. -
Retpoline thunk flags propagated to out-of-tree builds: Ubuntu kernels with
CONFIG_MITIGATION_RETPOLINE=ysometimes fail to pass-mindirect-branch=thunk-extern -mindirect-branch-registerto external modules (especially when building from a shared folder on a VM), causingobjtool: indirect call found in MITIGATION_RETPOLINE builderrors on every function pointer call in the scanner and main driver.kernel/Makefilenow-includes the target kernel'sinclude/config/auto.confand re-adds the retpoline flags explicitly whenCONFIG_MITIGATION_RETPOLINE(or legacyCONFIG_RETPOLINE) is set, so gcc emits__x86_indirect_thunk_raxcalls instead of raw indirect calls. -
deploy.sh build-kerneltarget: new command that builds only the kernel module (skipping userland library, tests, and the ImGui payload). Useful for cross-testing the driver in a VM where the userland components aren't needed.
Kernel driver security hardening:
- Added
CAP_SYS_PTRACEgate on all debug/memory ioctls - Added
CAP_SYS_ADMINgate on physical memory, injection, and shadow memory ioctls - Fixed use-after-free in process detach: proper
atomic_dec_and_testrefcounting withkfreeon zero - Fixed integer overflow in
do_query_regions:check_mul_overflowbeforekvzalloc - Fixed
page->flagstype for kernel 6.10+ (memdesc_flags_tstruct wrapper) - Increased
d_pathbuffer from 256 toPATH_MAX(4096 bytes) - Added forward declaration for
cleanup_breakpointsto fix implicit function error
Injector improvements:
- Fixed unsafe
vm_flagsmanipulation: usesvm_flags_set()on kernel 6.3+ instead of UB pointer cast - Fixed maple tree VMA unlinking:
mas_set_range(vm_start, vm_end-1)for correct range coverage - Added
wait_for_completion_timeout(5s) on all worker threads instead of unbounded waits - Fixed thread hijack x86-64 ABI: RSP alignment handled by compiler (
-mincoming-stack-boundary=3) - Implemented shadow memory subsystem: pin-and-hide via
get_user_pages_remote+ VMA unlinking - Implemented
SHADOW_ALLOC,SHADOW_WRITE,SHADOW_FREEioctls (0x68-0x6A) - Shadow cleanup via
MAP_FIXED+vm_munmapto restore mm consistency on free - Transparent shadow read interception in
READ_MEMORYioctl handler
Scanner improvements:
- Hard cap on
scanner_create_result_set: max 10M results (160 MB) - Fixed parallel scan worker: separate
alloc_buf/scan_bufto preventkvfreeon aligned pointer - Added
get_unaligned()for safe unaligned memory access in scan loops - Added
linux/unaligned.h/asm/unaligned.hcompatibility for kernel 6.5+
Userland library:
- Fixed
MemoryRegion::end()overflow: saturates toUINT64_MAXinstead of wrapping - Added
static_assert(is_trivially_copyable_v<T>)onread<T>/write<T>templates - Fixed
readStringbounds: clampbytesReadtomaxLengthbefore null-terminator write - Fixed
DebugEventinstruction length: clamp tosizeof(k.instruction)to prevent over-read - Added exception safety in event loop thread (
try/catcharound callback) - Fixed
followPointerChainaddress overflow with__builtin_add_overflow - Made
resolve_importsstrict: returnsfalseon unresolved symbols instead of silent continue - Added
R_X86_64_64relocation type support inrelocate_base - Added
.init_arraydiscovery and execution via thread hijack - Implemented dlopen injection path in
ManualMapper(replaces manual mapping as default) - Added SDL2 DYNAPI jump table hook for render loop interception
SELinux policy v2.0:
- Added
unconfined_taccess tosnakedrv_device_t(fixesEPERMfor sudo operations) - Added
kernel_t execmemforvm_mmap(PROT_EXEC)in injector kernel threads - Added
sysadm_tandunconfined_service_tdevice access rules - Updated file contexts for
dlopen_injectandlibpayload_dlopen.so
Scripts:
deploy.shv2.0: addedset -o pipefail,trap cleanup,cd || dieguards,umask 022deploy.sh: new commandstest,inject,payload; installsdlopen_injectand payloaddeploy.sh: removed hardcoded SSH credentials, removed QEMU/VM referencesdeploy.sh: sanitizedPREFIXvariable, fixed unquoted expansionssign-module.sh: RSA 4096-bit keys, AES-256 encrypted private key,chmod 700/600sign-module.sh: cross-distrosign-filedetection (Fedora + Debian/Ubuntu)
- Manual map injector pipeline (alloc, relocate, write); VMA stealth remains disabled until deferred page-fault-safe hiding is implemented
- Improved remote symbol resolution and IFUNC handling for glibc
- GitHub Actions CI build and release workflows
- Documentation and wiki refresh
- Fixed AppArmor policy errors and improved profile compatibility
- Resolved objtool compilation errors (RETPOLINE) on newer kernels
- Added
sign-module.shfor Secure Boot module signing (MOK workflow)
- Initial public release
- Kernel module with privileged memory access and hardware breakpoints
- Userland library (C++ API)
- DKMS, udev, AppArmor, SELinux artifacts
- Automation script
deploy.sh
Contributions are welcome. Please keep kernel changes minimal and auditable.
GPL-2.0
This project is for educational and research use.