Repository navigation
Expand file tree
/
Copy pathparser.py
More file actions
452 lines (385 loc) · 17.2 KB
/
Copy pathparser.py
File metadata and controls
452 lines (385 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import os
import re
import json
from typing import Optional
class MiniAppAnalyzer:
"""对单个小程序目录执行静态分析,结果保存在 self.results 中。"""
# wx/qq API 调用模式:展示名 → 正则
API_PATTERNS = {
# 网络请求
"wx.request": r"wx\.request\s*\(",
"wx.uploadFile": r"wx\.uploadFile\s*\(",
"wx.downloadFile": r"wx\.downloadFile\s*\(",
"wx.connectSocket": r"wx\.connectSocket\s*\(",
"wx.sendSocketMessage": r"wx\.sendSocketMessage\s*\(",
# 本地存储
"wx.setStorage": r"wx\.setStorage(Sync)?\s*\(",
"wx.getStorage": r"wx\.getStorage(Sync)?\s*\(",
"wx.removeStorage": r"wx\.removeStorage(Sync)?\s*\(",
"wx.clearStorage": r"wx\.clearStorage(Sync)?\s*\(",
# 用户身份与授权
"wx.getUserInfo": r"wx\.getUserInfo\s*\(",
"wx.getUserProfile": r"wx\.getUserProfile\s*\(",
"wx.login": r"wx\.login\s*\(",
"wx.authorize": r"wx\.authorize\s*\(",
"wx.getSetting": r"wx\.getSetting\s*\(",
"wx.openSetting": r"wx\.openSetting\s*\(",
# 位置
"wx.getLocation": r"wx\.getLocation\s*\(",
"wx.chooseLocation": r"wx\.chooseLocation\s*\(",
"wx.openLocation": r"wx\.openLocation\s*\(",
# 媒体
"wx.chooseImage": r"wx\.chooseImage\s*\(",
"wx.previewImage": r"wx\.previewImage\s*\(",
"wx.chooseVideo": r"wx\.chooseVideo\s*\(",
"wx.chooseMessageFile": r"wx\.chooseMessageFile\s*\(",
"wx.startRecord": r"wx\.startRecord\s*\(",
# 页面导航与小程序互跳
"wx.navigateTo": r"wx\.navigateTo\s*\(",
"wx.redirectTo": r"wx\.redirectTo\s*\(",
"wx.reLaunch": r"wx\.reLaunch\s*\(",
"wx.switchTab": r"wx\.switchTab\s*\(",
"wx.navigateBack": r"wx\.navigateBack\s*\(",
"wx.navigateToMiniProgram": r"wx\.navigateToMiniProgram\s*\(",
# 支付
"wx.requestPayment": r"wx\.requestPayment\s*\(",
# 分享
"wx.shareAppMessage": r"wx\.shareAppMessage\s*\(",
"wx.showShareMenu": r"wx\.showShareMenu\s*\(",
"wx.updateShareMenu": r"wx\.updateShareMenu\s*\(",
# 剪贴板
"wx.setClipboardData": r"wx\.setClipboardData\s*\(",
"wx.getClipboardData": r"wx\.getClipboardData\s*\(",
# 系统信息
"wx.getSystemInfo": r"wx\.getSystemInfo(Sync)?\s*\(",
"wx.getNetworkType": r"wx\.getNetworkType\s*\(",
"wx.scanCode": r"wx\.scanCode\s*\(",
"wx.vibrateShort": r"wx\.vibrateShort\s*\(",
"wx.vibrateLong": r"wx\.vibrateLong\s*\(",
"wx.makePhoneCall": r"wx\.makePhoneCall\s*\(",
# 文件系统
"wx.getFileSystemManager": r"wx\.getFileSystemManager\s*\(",
"wx.saveFile": r"wx\.saveFile\s*\(",
"wx.openDocument": r"wx\.openDocument\s*\(",
# 云开发(任意 wx.cloud.* 调用)
"wx.cloud": r"wx\.cloud\.\w+",
# 激励/插屏广告
"wx.createRewardedVideoAd": r"wx\.createRewardedVideoAd\s*\(",
"wx.createInterstitialAd": r"wx\.createInterstitialAd\s*\(",
# 设备信息
"wx.getDeviceInfo": r"wx\.getDeviceInfo\s*\(",
"wx.getDeviceBenchmarkInfo": r"wx\.getDeviceBenchmarkInfo\s*\(",
# QQ 小程序专属 API
"qq.setShareInfo": r"qq\.setShareInfo\s*\(",
"qq.getUserInfo": r"qq\.getUserInfo\s*\(",
"qq.login": r"qq\.login\s*\(",
"qq.request": r"qq\.request\s*\(",
"qq.navigateTo": r"qq\.navigateTo\s*\(",
"qq.showShareMenu": r"qq\.showShareMenu\s*\(",
"qq.getSystemInfo": r"qq\.getSystemInfo\s*\(",
}
# 敏感信息模式:类型名 → 正则(多为带分组的 findall,取最后一个分组为值)
SENSITIVE_PATTERNS = {
"access_token": r'(access[_-]?token|accesstoken)["\s:=]+([A-Za-z0-9_\-\.]{20,})',
"api_key": r'(api[_-]?key|apikey)["\s:=]+([A-Za-z0-9_\-]{16,})',
"secret": r'(secret|appsecret|app_secret)["\s:=]+([A-Za-z0-9_\-]{16,})',
"app_id_embedded": r'(appid|app_id|appId|APPID)["\s:=]+["\'](wx[a-z0-9]{16,})["\']',
"url_with_token": r'(https?://[^\s"\']*[?&](token|access_token|key|secret)=[^\s"\'&]+)',
"phone_number": r'(phone|mobile|tel)["\s:=]+["\']?(1[3-9]\d{9})["\']?',
"email": r'([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})',
"ip_address": r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})',
"private_key_header": r'(-----BEGIN\s(?:RSA\s)?PRIVATE\sKEY-----)',
"jwt_token": r'(eyJ[A-Za-z0-9\-_]{10,}\.[A-Za-z0-9\-_]{10,}\.[A-Za-z0-9\-_]{10,})',
"database_url": r'(mysql|mongodb|postgresql|redis)://[^\s"\']+',
"authorization_header": r'[Aa]uthorization["\s:=]+["\']?(Bearer\s+[A-Za-z0-9\-_\.]+)',
}
# 通用 URL 提取:排除控制字符,长度 ≥ 6
URL_PATTERN = re.compile(
r'https?://[^\s"\'\\\x00-\x1f\x7f]{5,}',
re.IGNORECASE,
)
def __init__(self, app_info: dict):
# app_info 由 scanner.MiniAppScanner._parse_app_dir 生成
self.app_info = app_info
self.results = {
"api_calls": {}, # API 名 → {count, contexts[]}
"urls": {}, # 分类后的 URL 字典(api/cdn/docs/web/other)
"sensitive_findings": [], # 敏感信息命中列表
"permissions_analysis": {}, # 权限分析结果
"risk_score": 0, # 综合风险分(0-100)
"risk_factors": [], # 风险构成说明
}
def analyze(self) -> dict:
"""执行完整分析并返回结果字典。"""
# 1) 分析业务逻辑文件 app-service.js
service_path = os.path.join(
self.app_info.get("dir_path", ""), "app-service.js"
)
if os.path.exists(service_path):
self._analyze_service_js(service_path)
# 2) 权限分析(基于 app-config.json)
self._analyze_permissions()
# 3) 汇总风险评分
self._calculate_risk_score()
return self.results
def _analyze_service_js(self, path: str):
"""分析 app-service.js:API 调用、URL 提取、敏感信息匹配。"""
try:
with open(path, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
except Exception:
return
# ── API 调用统计:记录次数 + 每处调用前后上下文片段 ──
for api_name, pattern in self.API_PATTERNS.items():
matches = re.findall(pattern, content, re.IGNORECASE)
if matches:
contexts = []
for match in re.finditer(pattern, content, re.IGNORECASE):
start = max(0, match.start() - 50)
end = min(len(content), match.end() + 100)
ctx = content[start:end].replace("\n", " ").strip()
contexts.append(ctx[:150])
self.results["api_calls"][api_name] = {
"count": len(matches),
"contexts": contexts[:10],
}
# ── URL 提取与去重 ──
urls = self.URL_PATTERN.findall(content)
seen = set()
unique_urls = []
for url in urls:
# 去掉句尾被正则带上的标点/括号
url = url.rstrip(".,;:)}]\"'")
if url not in seen and len(url) < 500:
seen.add(url)
unique_urls.append(url)
# ── URL 按用途分类 ──
url_categories = {
"api": [],
"cdn": [],
"docs": [],
"web": [],
"other": [],
}
for url in unique_urls:
lower = url.lower()
if any(kw in lower for kw in ["/api/", "/rpc/", "/gateway/", "/v1/", "/v2/", "/v3/", "service"]):
url_categories["api"].append(url)
elif any(kw in lower for kw in ["cdn", "static", "assets", ".js", ".css", ".png", ".jpg"]):
url_categories["cdn"].append(url)
elif any(kw in lower for kw in ["docs.qq.com", "doc.qq.com", "docs"]):
url_categories["docs"].append(url)
elif any(kw in lower for kw in [".qq.com", ".tencent.com", ".weixin.qq.com", ".myqcloud.com"]):
url_categories["web"].append(url)
else:
url_categories["other"].append(url)
self.results["urls"] = url_categories
self.results["url_total"] = len(unique_urls)
# ── 敏感信息匹配:记录原始值并生成脱敏展示值 ──
for name, pattern in self.SENSITIVE_PATTERNS.items():
matches = re.findall(pattern, content, re.IGNORECASE)
if matches:
findings = []
for match in matches[:5]:
# findall 带分组时返回元组,取最后一个分组作为值
if isinstance(match, tuple):
match_str = str(match[-1]) if len(match) > 1 else str(match[0])
else:
match_str = str(match)
# 生成脱敏值:保留首尾各几位,中间用 *** 遮蔽
if len(match_str) > 8:
masked = match_str[:4] + "***" + match_str[-4:]
else:
masked = match_str[:2] + "***"
findings.append({"raw": match_str, "masked": masked})
self.results["sensitive_findings"].append({
"type": name,
"matches": findings,
})
def _analyze_permissions(self):
"""分析声明的权限 scope 与 requiredPrivateInfos,标记敏感项。"""
permissions = self.app_info.get("permissions", {})
required_private = self.app_info.get("required_private_infos", [])
analysis = {
"permissions_requested": list(permissions.keys()),
"permissions_detail": permissions,
"private_infos": required_private,
"concerns": [],
}
# 敏感 scope → 中文风险说明
sensitive_scopes = {
"scope.userLocation": "位置信息 - 可能追踪用户行踪",
"scope.userInfo": "用户信息 - 获取QQ昵称、头像等",
"scope.record": "录音 - 可能录制用户声音",
"scope.camera": "摄像头 - 可能拍照/录像",
"scope.writePhotosAlbum": "相册写入 - 可能保存图片",
"scope.userLocationBackground": "后台位置 - 持续追踪位置",
"scope.address": "通讯地址 - 获取用户地址",
"scope.invoiceTitle": "发票抬头 - 获取企业信息",
"scope.werun": "微信运动 - 获取健康数据",
}
for scope in permissions.keys():
if scope in sensitive_scopes:
analysis["concerns"].append({
"scope": scope,
"description": sensitive_scopes[scope],
})
# requiredPrivateInfos 中强制声明 getLocation 属于强敏感项
if "getLocation" in required_private:
analysis["concerns"].append({
"scope": "requiredPrivateInfos.getLocation",
"description": "强制要求获取位置信息",
})
self.results["permissions_analysis"] = analysis
def _calculate_risk_score(self):
"""按多项指标累加风险分(上限 100),并生成风险等级。"""
score = 0
factors = []
# API 种类数量
api_count = len(self.results["api_calls"])
if api_count > 30:
score += 20
factors.append("API调用种类多(>30)")
elif api_count > 15:
score += 10
factors.append("API调用种类较多(>15)")
# 敏感 API(读用户信息/位置/支付/剪贴板等)
sensitive_apis = [
"wx.getUserInfo", "wx.getLocation", "wx.login",
"wx.requestPayment", "wx.getClipboardData",
"wx.chooseImage", "wx.startRecord",
]
matched_sensitive = [
api for api in sensitive_apis
if api in self.results["api_calls"]
]
if matched_sensitive:
score += len(matched_sensitive) * 5
factors.append(f"使用敏感API: {', '.join(matched_sensitive)}")
# URL 数量
url_total = self.results.get("url_total", 0)
if url_total > 50:
score += 20
factors.append(f"包含大量URL({url_total}个)")
elif url_total > 20:
score += 10
factors.append(f"包含较多URL({url_total}个)")
# 敏感信息命中类型数
sens_count = len(self.results["sensitive_findings"])
if sens_count > 0:
score += sens_count * 10
types = [s["type"] for s in self.results["sensitive_findings"]]
factors.append(f"发现敏感信息: {', '.join(types)}")
# 第三方(非腾讯系)域名请求
other_urls = self.results.get("urls", {}).get("other", [])
if len(other_urls) > 5:
score += 10
factors.append("包含多个第三方域名请求")
# 权限数量
permissions = self.app_info.get("permissions", {})
if len(permissions) > 3:
score += 10
factors.append(f"请求{len(permissions)}项权限")
self.results["risk_score"] = min(score, 100)
self.results["risk_factors"] = factors
self.results["risk_level"] = (
"🔴 高风险" if score >= 60 else
"🟡 中等风险" if score >= 30 else
"🟢 低风险"
)
def analyze_fetch_data(fetch_data_path: str) -> list[dict]:
"""枚举 fetchData 目录下的小程序网络请求落盘文件,返回预览信息。
只读取小于 10MB 的文件、每个文件最多预览前 500 字符。
"""
findings = []
if not os.path.isdir(fetch_data_path):
return findings
for filename in os.listdir(fetch_data_path):
full = os.path.join(fetch_data_path, filename)
size = 0
try:
size = os.path.getsize(full)
if size < 10 * 1024 * 1024:
with open(full, "r", encoding="utf-8", errors="ignore") as f:
content = f.read(5000)
findings.append({
"file": filename,
"path": full,
"size": size,
"preview": content[:500],
"is_json": content.strip().startswith("{") or content.strip().startswith("["),
})
except Exception:
# 修复:size 需先初始化,否则读取失败时会 NameError
findings.append({
"file": filename,
"path": full,
"size": size,
"error": "无法读取",
})
return findings
def analyze_auth_data(auth_path: str) -> list[dict]:
"""枚举 auth 目录下的鉴权数据文件,返回内容预览。"""
findings = []
if not os.path.isdir(auth_path):
return findings
for entry in os.listdir(auth_path):
full = os.path.join(auth_path, entry)
if os.path.isfile(full):
try:
with open(full, "r", encoding="utf-8", errors="ignore") as f:
content = f.read(2000)
findings.append({
"file": entry,
"path": full,
"size": os.path.getsize(full),
"content_preview": content[:500],
})
except Exception:
pass
elif os.path.isdir(full):
findings.append({
"file": entry,
"path": full,
"type": "directory",
})
return findings
def analyze_local_storage(ls_path: str) -> list[dict]:
"""枚举 LocalStorage 目录下的存储文件,返回内容预览。"""
findings = []
if not os.path.isdir(ls_path):
return findings
for entry in os.listdir(ls_path):
full = os.path.join(ls_path, entry)
if os.path.isfile(full):
try:
with open(full, "r", encoding="utf-8", errors="ignore") as f:
content = f.read(5000)
findings.append({
"file": entry,
"path": full,
"size": os.path.getsize(full),
"preview": content[:500],
})
except Exception:
pass
return findings
def analyze_file_system(fs_path: str) -> list[dict]:
"""枚举小程序私有文件系统(fs),返回相对路径与元信息列表。"""
findings = []
if not os.path.isdir(fs_path):
return findings
for root, dirs, files in os.walk(fs_path):
# 每个目录最多取 50 个文件,避免超大目录拖慢界面
for f in files[:50]:
full = os.path.join(root, f)
rel = os.path.relpath(full, fs_path)
try:
findings.append({
"relative_path": rel,
"size": os.path.getsize(full),
"modified": os.path.getmtime(full),
})
except Exception:
pass
return findings