一键导入
zero-day-hunting-methodology
Systematic approach to discovering novel vulnerabilities through code analysis, fuzzing, and attack surface research
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Systematic approach to discovering novel vulnerabilities through code analysis, fuzzing, and attack surface research
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
| name | Zero-Day Hunting Methodology |
| description | Systematic approach to discovering novel vulnerabilities through code analysis, fuzzing, and attack surface research |
| when_to_use | When researching software for previously unknown vulnerabilities, analyzing complex codebases for security flaws, or building vulnerability research capabilities for bug bounty or security research |
| version | 1.0.0 |
| languages | c, c++, python, assembly |
Zero-day hunting is the systematic process of discovering previously unknown vulnerabilities in software. This requires combining multiple analysis techniques, deep understanding of common vulnerability classes, and methodical exploration of attack surfaces. Success comes from patience, persistence, and systematic methodology.
Core principle: Combine automated and manual analysis. Automated tools find low-hanging fruit; manual analysis finds complex logic flaws. Document everything.
Use this skill when:
Don't use when:
Goal: Choose promising targets and understand the attack surface.
Target Selection Criteria:
Complexity Indicators
Historical Vulnerability Indicators
# Check CVE databases
searchsploit "target software"
# Review past vulnerabilities
# - What vulnerability classes were found?
# - Were fixes complete or partial?
# - Pattern of similar bugs suggests more exist
Attack Surface Analysis
"""
Map the attack surface:
INPUT VECTORS:
- Network protocols (HTTP, custom binary protocols)
- File formats (images, documents, archives)
- Command-line arguments
- Environment variables
- IPC mechanisms (pipes, sockets, shared memory)
- Configuration files
TRUST BOUNDARIES:
- User input → Application
- Application → System calls
- Unprivileged → Privileged contexts
- Network → Local processing
- Untrusted data → Parser
INTERESTING CODE AREAS:
- Parsers and deserializers
- Cryptographic implementations
- Authentication and authorization
- Memory management
- Privileged operations
"""
Goal: Understand code structure and identify suspicious patterns through source code review.
Manual Code Review:
Vulnerability Pattern Recognition
// PATTERN 1: Buffer Overflow
// Look for unsafe functions with controllable size
char buffer[256];
strcpy(buffer, user_input); // ❌ No bounds check
char buffer[256];
strncpy(buffer, user_input, sizeof(buffer)-1); // ✓ Bounds checked
buffer[sizeof(buffer)-1] = '\0';
// PATTERN 2: Integer Overflow
size_t alloc_size = user_count * sizeof(struct item); // ❌ Can overflow
void *ptr = malloc(alloc_size); // Allocates small buffer, then overflow
// Better:
if (user_count > SIZE_MAX / sizeof(struct item)) {
return ERROR;
}
size_t alloc_size = user_count * sizeof(struct item);
// PATTERN 3: Use After Free
free(ptr);
// ... more code ...
ptr->field = value; // ❌ Use after free
// PATTERN 4: Format String
printf(user_input); // ❌ Format string vulnerability
printf("%s", user_input); // ✓ Safe
// PATTERN 5: Command Injection
char cmd[512];
sprintf(cmd, "ping %s", user_input); // ❌ Command injection
system(cmd);
// Better: Use execve with argument array
// PATTERN 6: Path Traversal
char filepath[256];
sprintf(filepath, "/var/data/%s", user_filename); // ❌ ../../../etc/passwd
FILE *f = fopen(filepath, "r");
// Better: Validate, sanitize, use realpath()
Automated Static Analysis
# Semgrep - pattern-based analysis
semgrep --config=auto /path/to/source/
# Cppcheck - C/C++ static analyzer
cppcheck --enable=all --inconclusive --std=c11 /path/to/source/
# CodeQL - semantic code analysis
codeql database create /tmp/db --language=cpp --source-root=/path/to/source/
codeql database analyze /tmp/db codeql/cpp-queries:codeql-suites/cpp-security-and-quality.qls
# Coverity, SonarQube (commercial but powerful)
Data Flow Analysis
"""
Trace untrusted input through the codebase:
1. Identify sources (user input points)
2. Identify sinks (dangerous operations)
3. Trace paths from sources to sinks
4. Check for validation/sanitization
Example trace:
[SOURCE] HTTP request parameter "filename"
→ parse_request()
→ extract_param("filename") // No validation
→ load_file(filename)
→ fopen(filename) // [SINK] File operation
FINDING: Path traversal vulnerability
- No validation between source and sink
- User controls filename directly
"""
Goal: Trigger vulnerabilities through runtime testing and intelligent input generation.
Fuzzing Strategies:
Coverage-Guided Fuzzing
# AFL++ (American Fuzzy Lop)
# Compile with instrumentation
export CC=afl-clang-fast
export CXX=afl-clang-fast++
./configure
make clean && make
# Create seed corpus
mkdir seeds
echo "valid input 1" > seeds/seed1.txt
echo "another valid input" > seeds/seed2.txt
# Run fuzzer
afl-fuzz -i seeds -o findings -m none -- ./target @@
# Monitor for crashes
# Triage crashes: unique, exploitable, duplicate?
Protocol Fuzzing
# Boofuzz - network protocol fuzzer
from boofuzz import *
def main():
session = Session(
target=Target(
connection=SocketConnection("target.com", 8080, proto='tcp')
)
)
# Define protocol structure
s_initialize("HTTP_REQUEST")
s_static("GET ")
s_string("/", name="path", fuzzable=True)
s_static(" HTTP/1.1\r\n")
s_static("Host: ")
s_string("target.com", name="host", fuzzable=True)
s_static("\r\n\r\n")
session.connect(s_get("HTTP_REQUEST"))
session.fuzz()
if __name__ == "__main__":
main()
Structured Fuzzing
# For file formats, use structure-aware fuzzers
# Honggfuzz with dictionaries
honggfuzz -i input_corpus/ -o output/ -- ./target_binary ___FILE___
# Libfuzzer for in-process fuzzing
# Compile with -fsanitize=fuzzer
clang++ -fsanitize=fuzzer,address target_fuzzer.cpp -o fuzzer
./fuzzer corpus/ -max_len=1024
Sanitizer Integration
# AddressSanitizer (ASan) - memory errors
export CFLAGS="-fsanitize=address -g"
export CXXFLAGS="-fsanitize=address -g"
make clean && make
# UndefinedBehaviorSanitizer (UBSan)
export CFLAGS="-fsanitize=undefined -g"
# MemorySanitizer (MSan) - uninitialized memory
export CFLAGS="-fsanitize=memory -g"
# Run tests or fuzzer with sanitizers
# They will detect and report issues
Goal: Confirm discovered issues are real vulnerabilities, not false positives.
Validation Steps:
Reproduce the Bug
#!/usr/bin/env python3
# reproduce_crash.py
import subprocess
# Minimal test case that triggers the bug
malicious_input = b"A" * 1000 # From fuzzer crash
# Reproduce
with open("crash_input.bin", "wb") as f:
f.write(malicious_input)
# Run target
result = subprocess.run(
["./target", "crash_input.bin"],
capture_output=True,
timeout=5
)
if result.returncode < 0:
print(f"[+] Crashed with signal {-result.returncode}")
print(f"[*] stderr: {result.stderr.decode()}")
Minimize Test Case
# AFL test case minimization
afl-tmin -i crash_sample -o minimized_crash -- ./target @@
# Manual minimization
# - Remove bytes while maintaining crash
# - Identify minimal triggering input
# - Understand what parts of input matter
Root Cause Analysis with Debugger
# GDB with ASAN/UBSAN reports
gdb ./target
(gdb) run crash_input.bin
# When crash occurs:
(gdb) bt # Backtrace
(gdb) info registers
(gdb) x/100x $rsp # Examine stack
# Identify:
# - Type of vulnerability (overflow, UAF, etc.)
# - Root cause (specific code location)
# - Exploitability (can attacker control execution?)
Exploitability Assessment
"""
Severity Classification:
CRITICAL:
- Remote Code Execution (RCE)
- Authentication bypass in privileged service
- SQL injection in sensitive database
HIGH:
- Local privilege escalation
- Information disclosure (passwords, keys)
- Denial of Service in critical service
MEDIUM:
- XSS, CSRF in web applications
- DoS in non-critical service
- Information disclosure (non-sensitive)
LOW:
- Minor information leaks
- DoS requiring local access
- Theoretical issues with no practical exploit
Exploitability Factors:
- Can attacker trigger remotely?
- Does attacker control any registers/memory?
- Are mitigations (ASLR, NX, etc.) bypassable?
- What privileges does vulnerable process have?
"""
Goal: Create demonstrable PoC and follow responsible disclosure process.
PoC Development:
Create Proof of Concept
#!/usr/bin/env python3
"""
Proof of Concept: Buffer Overflow in parse_header()
Target: Example HTTP Server v2.1.0
Type: Stack-based buffer overflow
Impact: Remote Code Execution
This PoC demonstrates the vulnerability by crashing the server.
For responsible disclosure, does not include exploit code.
"""
import socket
import sys
def create_poc():
# Trigger vulnerability without exploitation
payload = b"A" * 300 # Exceeds buffer, causes crash
request = b"GET / HTTP/1.1\r\n"
request += b"Host: " + payload + b"\r\n"
request += b"\r\n"
return request
def main():
if len(sys.argv) != 3:
print(f"Usage: {sys.argv[0]} <target_ip> <target_port>")
sys.exit(1)
target_ip = sys.argv[1]
target_port = int(sys.argv[2])
print(f"[*] Sending PoC to {target_ip}:{target_port}")
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target_ip, target_port))
s.send(create_poc())
s.close()
print("[+] PoC sent. Check if target crashed.")
except Exception as e:
print(f"[-] Error: {e}")
if __name__ == "__main__":
main()
Document the Vulnerability
# Vulnerability Report: Buffer Overflow in Example HTTP Server
## Summary
A stack-based buffer overflow exists in the parse_header() function
of Example HTTP Server versions 2.0.0 through 2.1.0, allowing remote
attackers to crash the service or potentially execute arbitrary code.
## Vulnerability Details
- **Type**: Stack-based buffer overflow (CWE-121)
- **Affected Versions**: 2.0.0 - 2.1.0
- **Fixed Version**: Not yet fixed
- **CVSS Score**: 9.8 (Critical)
- **Attack Vector**: Network (Remote)
- **Authentication**: None required
## Technical Description
The vulnerability exists in `src/http_parser.c` at line 234 in the
`parse_header()` function. The function uses `strcpy()` to copy the
HTTP Host header into a fixed 256-byte stack buffer without bounds
checking:
```c
void parse_header(char *header) {
char buffer[256];
strcpy(buffer, header); // Vulnerable line
// ... rest of function
}
An attacker can send an HTTP request with a Host header exceeding 256 bytes, causing a buffer overflow that overwrites the return address on the stack.
See attached poc_crash.py. This PoC demonstrates the crash but
does not include exploitation code.
python3 poc_crash.py 127.0.0.1 8080Replace strcpy() with bounds-checked alternative:
void parse_header(char *header) {
char buffer[256];
strncpy(buffer, header, sizeof(buffer) - 1);
buffer[sizeof(buffer) - 1] = '\0';
// ... rest of function
}
Discovered by: [Your Name] Contact: [your.email@example.com]
Responsible Disclosure Process:
Initial Contact
Subject: Security Vulnerability Report - Example HTTP Server
Dear Security Team,
I have discovered a security vulnerability in Example HTTP Server
that could allow remote code execution. I would like to report this
through your responsible disclosure program.
Please confirm receipt of this email and provide instructions for
submitting the detailed vulnerability report.
Thank you,
[Your Name]
Follow Timeline
Public Disclosure
1. Differential Testing
# Compare behavior of different implementations
# Inconsistencies may indicate bugs
def test_parsers():
test_inputs = generate_edge_cases()
for input_data in test_inputs:
result_a = parser_implementation_a(input_data)
result_b = parser_implementation_b(input_data)
if result_a != result_b:
print(f"Inconsistency found: {input_data}")
# Investigate which is correct
2. Symbolic Execution
# Use angr or other symbolic execution tools
# to explore program paths
python3 -c '
import angr
project = angr.Project("./target")
state = project.factory.entry_state()
simgr = project.factory.simulation_manager(state)
simgr.explore(find=0x401234, avoid=0x401500)
if simgr.found:
print("Found path:", simgr.found[0].posix.dumps(0))
'
3. Kernel Vulnerability Research
# Requires deep knowledge, use with caution
# syzkaller - kernel fuzzer
git clone https://github.com/google/syzkaller
# Configure for your kernel
# Run fuzzer
./bin/syz-manager -config my.cfg
# Analyze crashes, develop exploits
# Kernel vulns have high impact
Static Analysis:
Fuzzing:
Dynamic Analysis:
Binary Analysis:
| Mistake | Impact | Solution |
|---|---|---|
| Targeting wrong software | Wasted effort | Select based on complexity, exposure |
| Relying only on fuzzing | Miss logic flaws | Combine fuzzing with manual review |
| Not triaging crashes | False positives, duplicates | Analyze each crash, group similar |
| Premature disclosure | Vendor can't patch, users at risk | Follow 90-day disclosure timeline |
| Poor documentation | Can't reproduce/fix | Document thoroughly with PoC |
| Weaponizing exploits | Ethical/legal issues | Create PoCs only, not weaponized |
CRITICAL - Always follow these rules:
Authorization
Responsible Disclosure
Handle Data Responsibly
Know the Law
This skill works with:
Successful zero-day hunting should:
Systematic approach to analyzing compiled binaries, understanding program behavior, and identifying vulnerabilities without source code access
Methodical approach to finding security vulnerabilities through source code review and static analysis
Systematic methodology for developing reliable exploits from vulnerability discovery to weaponization
Building effective fuzzing harnesses to maximize code coverage and vulnerability discovery through automated input generation
Techniques for creating and adapting payloads for various exploitation scenarios, target environments, and evasion requirements
Systematic approach to discovering subdomains through passive and active reconnaissance techniques