
Web应用渗透测试
测试方法论(OWASP测试指南)
1. 信息收集
- 指纹识别(技术栈、版本)
- 目录枚举
- 子域名发现
2. 配置管理
- 安全头审计
- TLS/SSL分析
- 错误处理
3. 认证测试
- 密码策略
- 默认凭据
- Token可预测性
4. 会话管理
- Cookie属性
- 会话固定
- CSRF
5. 输入验证
- XSS
- SQL注入
- XXE、SSRF
6. 业务逻辑
- 参数篡改
- 竞态条件

OWASP ZAP自动化扫描
from zapv2 import ZAPv2
import time
ZAP_API_KEY = 'your-api-key'
TARGET_URL = 'http://localhost:3000'
zap = ZAPv2(apikey=ZAP_API_KEY, proxies={'http': 'http://127.0.0.1:8080'})
# Spider to discover endpoints
print("[*] Starting spider...")
scan_id = zap.spider.scan(TARGET_URL, apikey=ZAP_API_KEY)
while int(zap.spider.status(scan_id)) < 100:
print(f" Spider: {zap.spider.status(scan_id)}%")
time.sleep(2)
print(f" Spider found {len(zap.spider.results())} URLs")
# Active scan
print("[*] Starting active scan...")
ascan_id = zap.ascan.scan(TARGET_URL, apikey=ZAP_API_KEY)
while int(zap.ascan.status(ascan_id)) < 100:
print(f" Active scan: {zap.ascan.status(ascan_id)}%")
time.sleep(5)
# Get alerts
alerts = zap.core.alerts(baseurl=TARGET_URL)
high = [a for a in alerts if a['risk'] == 'High']
medium = [a for a in alerts if a['risk'] == 'Medium']
print(f"\nResults: {len(high)} High, {len(medium)} Medium")
for alert in high:
print(f" HIGH: {alert['name']} at {alert['url']}")
print(f" {alert['description'][:100]}...")
# Generate HTML report
report = zap.core.htmlreport()
with open('zap-report.html', 'w') as f:
f.write(report)

SQLMap用法
# Basic SQL injection test
sqlmap -u "http://example.com/products?id=1" --dbs
# Test POST request
sqlmap -u "http://example.com/login" \
--data="username=admin&password=test" \
--dbs
# With session cookie
sqlmap -u "http://example.com/profile" \
--cookie="session=abc123" \
--tables -D users_db
# Extract data
sqlmap -u "http://example.com/products?id=1" \
-D mydb -T users \
--dump --batch
# Time-based blind injection
sqlmap -u "http://example.com/products?id=1" \
--technique=T --dbms=postgresql

Python安全测试脚本
import requests
from bs4 import BeautifulSoup
import re
class BasicSecurityTester:
def __init__(self, base_url: str):
self.base_url = base_url
self.session = requests.Session()
self.findings = []
def check_security_headers(self) -> list:
resp = self.session.get(self.base_url)
required_headers = {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': ['DENY', 'SAMEORIGIN'],
'Strict-Transport-Security': None,
'Content-Security-Policy': None,
}
missing = []
for header, expected in required_headers.items():
value = resp.headers.get(header)
if not value:
missing.append({'severity': 'medium', 'header': header, 'issue': 'missing'})
elif expected and (isinstance(expected, str) and value != expected or
isinstance(expected, list) and value not in expected):
missing.append({'severity': 'low', 'header': header, 'issue': f"value is '{value}'"})
return missing
def test_xss_reflection(self, url: str, param: str) -> bool:
"""Test for reflected XSS."""
payload = '<script>alert(1)</script>'
resp = self.session.get(url, params={param: payload})
return payload in resp.text # Check if reflected unencoded
def test_sql_injection(self, url: str, param: str) -> bool:
"""Basic SQL injection test."""
payloads = ["'", "1' OR '1'='1", "1; DROP TABLE users--"]
for payload in payloads:
try:
resp = self.session.get(url, params={param: payload})
# Look for SQL error messages
sql_errors = ['mysql_fetch', 'ORA-', 'PostgreSQL', 'syntax error']
if any(err.lower() in resp.text.lower() for err in sql_errors):
return True
except Exception:
pass
return False
def run_all_checks(self) -> dict:
results = {
'security_headers': self.check_security_headers(),
'findings': self.findings,
}
return results
CI中的持续安全测试
# .github/workflows/security-tests.yml
name: Security Tests
on:
push:
branches: [main]
jobs:
security-scan:
runs-on: ubuntu-latest
services:
app:
image: myapp:\${{ github.sha }}
ports:
- 3000:3000
steps:
- name: OWASP ZAP Scan
uses: zaproxy/action-baseline@v0.10.0
with:
target: 'http://localhost:3000'
rules_file_name: '.zap/rules.tsv'
fail_action: true
- name: Nuclei scan
run: |
nuclei -target http://localhost:3000 \
-severity critical,high \
-o nuclei-report.txt \
-exit-code 1
漏洞赏金检查清单
| 测试 |
工具 |
| IDOR |
手动 + Burp |
| SQL注入 |
SQLMap |
| XSS |
XSStrike |
| CSRF |
Burp Suite |
| 认证绕过 |
手动 |
| API测试 |
Postman + Burp |