用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tools-only/X-Skills --skill api-fuzz-testing命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
正在显示 SKILL.md
| description | Fuzz test APIs with malformed inputs and edge cases |
| shortcut | fuzz |
Automated fuzz testing for REST APIs to discover vulnerabilities, crashes, and unexpected behavior through malformed inputs, boundary values, and random payloads. This command generates comprehensive fuzz test suites targeting injection attacks, input validation failures, and edge cases.
Why fuzz testing matters:
Alternatives considered:
This approach balances: Automation, coverage, security focus, and integration with CI/CD.
Use API fuzzing when:
Don't use when:
Identify Attack Surface
Generate Fuzz Inputs
Execute Fuzz Tests
Analyze Results
Remediate and Retest
// tests/api-fuzzer.test.js
const axios = require('axios');
const API_BASE = process.env.API_URL || 'http://localhost:3000';
// Fuzz input generators
const fuzzInputs = {
// String mutations
strings: [
'', // Empty
null,
undefined,
' ', // Whitespace
'A'.repeat(10000), // Very long
'A'.repeat(1000000), // Extremely long
'<script>alert(1)</script>', // XSS
'<img src=x onerror=alert(1)>', // XSS variant
'${7*7}', // Template injection
'{{7*7}}', // Template injection variant
'\x00', // Null byte
'\n\r\t', // Control characters
'../../etc/passwd', // Path traversal
'../../../etc/passwd', // Path traversal variant
'\\x41\\x42\\x43', // Hex encoding
],
// SQL injection payloads
sqlInjection: [
"' OR '1'='1",
"' OR '1'='1' --",
,
,
,
,
,
,
],
: [
,
-,
,
,
-,
,
-,
,
.,
.,
.,
.,
,
],
: [
,
,
,
,
,
,
,
,
],
: [
{},
[],
{ : { : } },
{ : { : { : } } },
[[[[[]]]]]],
().(),
],
: [
,
,
,
,
,
,
,
],
};
(, {
(, {
(, () => {
( input fuzzInputs.) {
{
response = axios.(, {
: input,
: ,
}, { : });
(response.)..();
(response.).();
(response. >= ) {
(response.).();
}
} (error) {
(error. !== && error. !== ) {
error;
}
}
}
});
(, () => {
( payload fuzzInputs.) {
response = axios.(, {
: payload,
: payload,
}, { : });
(response.)..();
(response.).();
(response..) {
(response...())..();
}
}
});
(, () => {
( input fuzzInputs.) {
response = axios.(, {
: input,
: ,
: ,
}, { : });
(response.)..();
(input < || input > ) {
(response.).();
}
}
});
(, () => {
( input fuzzInputs.) {
response = axios.(, {
: input,
: ,
: ,
}, { : });
(response.)..();
}
});
});
(, {
(, () => {
idInputs = [
...fuzzInputs.,
...fuzzInputs.,
...fuzzInputs.,
];
( input idInputs) {
response = axios.(
,
{ : }
);
(response.)..();
([, ]).(response.);
}
});
});
(, {
(, () => {
( input fuzzInputs.) {
response = axios.(, {
: { : input },
: ,
});
(response.)..();
}
});
(, () => {
( payload fuzzInputs.) {
response = axios.(, {
: { : payload },
: ,
});
(response.)..();
(response. === ) {
(response..).();
}
}
});
});
});
# tests/test_api_fuzzer.py
import pytest
import requests
from typing import Any, List
import string
import random
API_BASE = "http://localhost:3000"
class FuzzInputGenerator:
"""Generate various fuzz inputs for API testing"""
@staticmethod
def string_mutations() -> List[Any]:
return [
"", # Empty
None,
" ", # Whitespace
"A" * 10000, # Very long
"<script>alert(1)</script>", # XSS
"${7*7}", # Template injection
"../../etc/passwd", # Path traversal
"\x00", # Null byte
]
@staticmethod
def sql_injection_payloads() -> List[str]:
return [
"' OR '1'='1",
"' OR '1'='1' --",
"1; DROP TABLE users--",
"admin'--",
]
@staticmethod
def number_mutations() -> []:
[
, -, ,
-,
(), (),
]
() -> :
chars = string.ascii_letters + string.digits + string.punctuation
.join(random.choice(chars) _ (length))
:
():
input_value FuzzInputGenerator.string_mutations():
response = requests.post(
,
json={: input_value, : },
timeout=
)
response.status_code < , \
response.status_code >= :
response.json()
():
payload FuzzInputGenerator.sql_injection_payloads():
response = requests.post(
,
json={: payload, : payload},
timeout=
)
response.status_code != , \
response.status_code >= :
error_text = response.text.lower()
error_text
error_text
():
value FuzzInputGenerator.number_mutations():
response = requests.post(
,
json={
: ,
: ,
: value
},
timeout=
)
response.status_code <
():
_ ():
random_data = {
: FuzzInputGenerator.generate_random_string(random.randint(, )),
: FuzzInputGenerator.generate_random_string(),
: random.randint(-, ),
}
response = requests.post(
,
json=random_data,
timeout=
)
response.status_code <
():
malicious_headers = {
: ,
: ,
: ,
}
response = requests.get(
,
headers=malicious_headers,
timeout=
)
response.status_code <
// .github/workflows/fuzz-tests.yml
name: API Fuzz Testing
on: [push, pull_request]
jobs:
fuzz:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Start API server
run: npm run start:test &
- name: Wait for API
run: npx wait-on http://localhost:3000/health
- name: Run fuzz tests
run: npm run test:fuzz
- name: Upload fuzz report
if: failure()
uses: actions/upload-artifact@v2
with:
name: fuzz-report
path: ./fuzz-report.html
// fuzzer/openapi-fuzzer.js
const SwaggerParser = require('@apidevtools/swagger-parser');
const axios = require('axios');
async function fuzzFromOpenAPI(specPath) {
const api = await SwaggerParser.validate(specPath);
for (const [path, methods] of Object.entries(api.paths)) {
for (const [method, operation] of Object.entries(methods)) {
if (method === 'get' || method === 'post') {
console.log(`Fuzzing ${method.toUpperCase()} ${path}`);
// Generate fuzz inputs based on parameters
const fuzzInputs = generateFuzzInputs(operation.parameters);
for (const input of fuzzInputs) {
const response = await axios[method](
`${api.servers[0].url}${path}`,
input,
{ validateStatus: }
);
(response. === ) {
.(, input);
}
}
}
}
}
}
() {
[
];
}
();
# fuzzer/continuous_fuzzer.py
import requests
import random
import json
from datetime import datetime
class ContinuousFuzzer:
"""Continuously fuzz API endpoints with mutations"""
def __init__(self, base_url: str, endpoints: list):
self.base_url = base_url
self.endpoints = endpoints
self.crashes = []
def mutate_string(self, s: str) -> str:
"""Mutate string with random changes"""
mutations = [
lambda x: x + chr(random.randint(0, 255)), # Append random char
lambda x: x[:len(x)//2], # Truncate
lambda x: x * 100, # Repeat
lambda x: x.replace('a', '<script>'), # XSS injection
lambda x: x + "' OR '1'='1", # SQL injection
]
return random.choice(mutations)(s)
def fuzz_endpoint(self, endpoint: str, method: str = ):
seed_data = {: , : }
_ ():
fuzzed_data = {}
key, value seed_data.items():
(value, ):
fuzzed_data[key] = .mutate_string(value)
:
fuzzed_data[key] = value
:
response = requests.request(
method,
,
json=fuzzed_data,
timeout=
)
response.status_code == :
.crashes.append({
: endpoint,
: fuzzed_data,
: response.text,
: datetime.now().isoformat()
})
requests.exceptions.Timeout:
.crashes.append({
: endpoint,
: fuzzed_data,
: ,
: datetime.now().isoformat()
})
():
time
start_time = time.time()
(time.time() - start_time) < (duration_minutes * ):
endpoint = random.choice(.endpoints)
.fuzz_endpoint(endpoint)
(, ) f:
json.dump(.crashes, f, indent=)
()
fuzzer = ContinuousFuzzer(
base_url=,
endpoints=[, , ]
)
fuzzer.run(duration_minutes=)
Common issues and solutions:
Problem: Fuzzer overwhelms API with requests
Problem: False positives (valid errors reported as crashes)
Problem: Fuzzer credentials get rate-limited or blocked
Problem: Fuzzing breaks production data
Problem: Can't reproduce crashes
// fuzzer.config.js
module.exports = {
target: {
baseUrl: process.env.API_URL || 'http://localhost:3000',
endpoints: [
{ path: '/api/users', method: 'POST' },
{ path: '/api/users/:id', method: 'GET' },
{ path: '/api/orders', method: 'POST' },
],
},
authentication: {
type: 'bearer', // 'bearer' | 'basic' | 'apiKey'
token: process.env.TEST_API_TOKEN,
},
fuzzing: {
iterations: 1000, // Tests per endpoint
timeout: 5000, // Request timeout (ms)
delay: 100, // Delay between requests (ms)
concurrent: 5, // Concurrent requests
},
inputs: {
strings: true, // Enable string fuzzing
numbers: true, // Enable number fuzzing
sqlInjection: true, // Enable SQL injection tests
: ,
: [
,
,
],
},
: {
: ,
: ,
: {
.(, crash);
},
},
: [
,
,
],
};
DO:
DON'T:
TIPS:
/scan-api-security - Comprehensive security scanning/validate-schemas - Schema validation testing/run-load-test - Performance testing under load/generate-rest-api - Generate APIs with built-in validation/implement-error-handling - Proper error handling to prevent info leaksOptimization strategies:
Security checklist:
Fuzzer hangs or times out:
No crashes found:
Too many false positives:
Can't reproduce crashes:
基于 SOC 职业分类