FlowAnalyzer 0.4.0__tar.gz → 0.4.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flowanalyzer-0.4.2/FlowAnalyzer/FlowAnalyzer.py +440 -0
- flowanalyzer-0.4.2/FlowAnalyzer.egg-info/PKG-INFO +153 -0
- flowanalyzer-0.4.2/PKG-INFO +153 -0
- flowanalyzer-0.4.2/README.md +127 -0
- {FlowAnalyzer-0.4.0 → flowanalyzer-0.4.2}/setup.py +1 -1
- FlowAnalyzer-0.4.0/FlowAnalyzer/FlowAnalyzer.py +0 -334
- FlowAnalyzer-0.4.0/FlowAnalyzer.egg-info/PKG-INFO +0 -71
- FlowAnalyzer-0.4.0/PKG-INFO +0 -71
- FlowAnalyzer-0.4.0/README.md +0 -53
- {FlowAnalyzer-0.4.0 → flowanalyzer-0.4.2}/FlowAnalyzer/Path.py +0 -0
- {FlowAnalyzer-0.4.0 → flowanalyzer-0.4.2}/FlowAnalyzer/__init__.py +0 -0
- {FlowAnalyzer-0.4.0 → flowanalyzer-0.4.2}/FlowAnalyzer/logging_config.py +0 -0
- {FlowAnalyzer-0.4.0 → flowanalyzer-0.4.2}/FlowAnalyzer.egg-info/SOURCES.txt +0 -0
- {FlowAnalyzer-0.4.0 → flowanalyzer-0.4.2}/FlowAnalyzer.egg-info/dependency_links.txt +0 -0
- {FlowAnalyzer-0.4.0 → flowanalyzer-0.4.2}/FlowAnalyzer.egg-info/top_level.txt +0 -0
- {FlowAnalyzer-0.4.0 → flowanalyzer-0.4.2}/LICENSE +0 -0
- {FlowAnalyzer-0.4.0 → flowanalyzer-0.4.2}/setup.cfg +0 -0
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
import contextlib
|
|
2
|
+
import gzip
|
|
3
|
+
import os
|
|
4
|
+
import sqlite3
|
|
5
|
+
import subprocess
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Iterable, NamedTuple, Optional, Tuple
|
|
8
|
+
from urllib import parse
|
|
9
|
+
|
|
10
|
+
import ijson
|
|
11
|
+
|
|
12
|
+
from .logging_config import logger
|
|
13
|
+
from .Path import get_default_tshark_path
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Request:
|
|
18
|
+
__slots__ = ("frame_num", "header", "file_data", "full_uri", "time_epoch")
|
|
19
|
+
frame_num: int
|
|
20
|
+
header: bytes
|
|
21
|
+
file_data: bytes
|
|
22
|
+
full_uri: str
|
|
23
|
+
time_epoch: float
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class Response:
|
|
28
|
+
__slots__ = ("frame_num", "header", "file_data", "time_epoch", "_request_in")
|
|
29
|
+
frame_num: int
|
|
30
|
+
header: bytes
|
|
31
|
+
file_data: bytes
|
|
32
|
+
time_epoch: float
|
|
33
|
+
_request_in: Optional[int]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class HttpPair(NamedTuple):
|
|
37
|
+
request: Optional[Request]
|
|
38
|
+
response: Optional[Response]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class FlowAnalyzer:
|
|
42
|
+
"""
|
|
43
|
+
FlowAnalyzer 流量分析器 (智能缓存版)
|
|
44
|
+
特点:
|
|
45
|
+
1. Tshark -> Pipe -> ijson -> SQLite (无中间JSON文件)
|
|
46
|
+
2. 智能校验:自动比对 Filter 和文件修改时间,防止缓存错乱
|
|
47
|
+
3. 存储优化:数据库文件生成在流量包同级目录下
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(self, db_path: str):
|
|
51
|
+
"""
|
|
52
|
+
初始化 FlowAnalyzer
|
|
53
|
+
:param db_path: 数据库文件路径 (由 get_json_data 返回)
|
|
54
|
+
"""
|
|
55
|
+
# 路径兼容处理
|
|
56
|
+
if db_path.endswith(".json"):
|
|
57
|
+
possible_db = db_path + ".db"
|
|
58
|
+
if os.path.exists(possible_db):
|
|
59
|
+
self.db_path = possible_db
|
|
60
|
+
else:
|
|
61
|
+
self.db_path = db_path
|
|
62
|
+
else:
|
|
63
|
+
self.db_path = db_path
|
|
64
|
+
|
|
65
|
+
self.check_db_file()
|
|
66
|
+
|
|
67
|
+
def check_db_file(self):
|
|
68
|
+
"""检查数据库文件是否存在"""
|
|
69
|
+
if not os.path.exists(self.db_path):
|
|
70
|
+
raise FileNotFoundError(f"未找到数据文件或缓存数据库: {self.db_path},请先调用 get_json_data 生成。")
|
|
71
|
+
|
|
72
|
+
def generate_http_dict_pairs(self) -> Iterable[HttpPair]:
|
|
73
|
+
"""生成HTTP请求和响应信息的字典对 (SQL JOIN 高性能版)"""
|
|
74
|
+
if not os.path.exists(self.db_path):
|
|
75
|
+
return
|
|
76
|
+
|
|
77
|
+
with sqlite3.connect(self.db_path) as conn:
|
|
78
|
+
cursor = conn.cursor()
|
|
79
|
+
# 开启查询优化
|
|
80
|
+
cursor.execute("PRAGMA query_only = 1;")
|
|
81
|
+
|
|
82
|
+
# === 第一步:配对查询 ===
|
|
83
|
+
# 利用 SQLite 的 LEFT JOIN 直接匹配请求和响应
|
|
84
|
+
# 避免将所有数据加载到 Python 内存中
|
|
85
|
+
sql_pair = """
|
|
86
|
+
SELECT
|
|
87
|
+
req.frame_num, req.header, req.file_data, req.full_uri, req.time_epoch, -- 0-4 (Request)
|
|
88
|
+
resp.frame_num, resp.header, resp.file_data, resp.time_epoch, resp.request_in -- 5-9 (Response)
|
|
89
|
+
FROM requests req
|
|
90
|
+
LEFT JOIN responses resp ON req.frame_num = resp.request_in
|
|
91
|
+
ORDER BY req.frame_num ASC
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
cursor.execute(sql_pair)
|
|
95
|
+
|
|
96
|
+
# 流式遍历结果,内存占用极低
|
|
97
|
+
for row in cursor:
|
|
98
|
+
# 构建 Request 对象
|
|
99
|
+
# 注意处理 NULL 情况,虽然 requests 表理论上不为空,但防万一用 or b''
|
|
100
|
+
req = Request(frame_num=row[0], header=row[1] or b"", file_data=row[2] or b"", full_uri=row[3] or "", time_epoch=row[4])
|
|
101
|
+
|
|
102
|
+
resp = None
|
|
103
|
+
# 如果 row[5] (Response frame_num) 不为空,说明匹配到了响应
|
|
104
|
+
if row[5] is not None:
|
|
105
|
+
resp = Response(frame_num=row[5], header=row[6] or b"", file_data=row[7] or b"", time_epoch=row[8], _request_in=row[9])
|
|
106
|
+
|
|
107
|
+
yield HttpPair(request=req, response=resp)
|
|
108
|
+
|
|
109
|
+
# === 第二步:孤儿响应查询 ===
|
|
110
|
+
# 找出那些有 request_in 但找不到对应 Request 的响应包
|
|
111
|
+
sql_orphan = """
|
|
112
|
+
SELECT frame_num, header, file_data, time_epoch, request_in
|
|
113
|
+
FROM responses
|
|
114
|
+
WHERE request_in NOT IN (SELECT frame_num FROM requests)
|
|
115
|
+
"""
|
|
116
|
+
cursor.execute(sql_orphan)
|
|
117
|
+
|
|
118
|
+
for row in cursor:
|
|
119
|
+
resp = Response(frame_num=row[0], header=row[1] or b"", file_data=row[2] or b"", time_epoch=row[3], _request_in=row[4])
|
|
120
|
+
yield HttpPair(request=None, response=resp)
|
|
121
|
+
|
|
122
|
+
# =========================================================================
|
|
123
|
+
# 静态方法区域:包含校验逻辑和流式处理
|
|
124
|
+
# =========================================================================
|
|
125
|
+
|
|
126
|
+
@staticmethod
|
|
127
|
+
def get_json_data(file_path: str, display_filter: str, tshark_path: Optional[str] = None) -> str:
|
|
128
|
+
"""
|
|
129
|
+
获取数据路径 (智能校验版)。
|
|
130
|
+
|
|
131
|
+
逻辑:
|
|
132
|
+
1. 根据 PCAP 路径推算 DB 路径 (位于 PCAP 同级目录)。
|
|
133
|
+
2. 检查 DB 是否存在。
|
|
134
|
+
3. 检查 Filter 和文件元数据是否一致。
|
|
135
|
+
4. 若一致返回路径,不一致则重新解析。
|
|
136
|
+
"""
|
|
137
|
+
if not os.path.exists(file_path):
|
|
138
|
+
raise FileNotFoundError("流量包路径不存在:%s" % file_path)
|
|
139
|
+
|
|
140
|
+
# --- 修改处:获取流量包的绝对路径和所在目录 ---
|
|
141
|
+
abs_file_path = os.path.abspath(file_path)
|
|
142
|
+
pcap_dir = os.path.dirname(abs_file_path) # 获取文件所在的文件夹
|
|
143
|
+
base_name = os.path.splitext(os.path.basename(abs_file_path))[0]
|
|
144
|
+
|
|
145
|
+
# 将 db_path 拼接在流量包所在的目录下
|
|
146
|
+
db_path = os.path.join(pcap_dir, f"{base_name}.db")
|
|
147
|
+
# ----------------------------------------
|
|
148
|
+
|
|
149
|
+
# --- 校验环节 ---
|
|
150
|
+
if FlowAnalyzer._is_cache_valid(db_path, abs_file_path, display_filter):
|
|
151
|
+
logger.debug(f"缓存校验通过 (Filter匹配且文件未变),使用缓存: [{db_path}]")
|
|
152
|
+
return db_path
|
|
153
|
+
else:
|
|
154
|
+
logger.debug(f"缓存失效或不存在 (Filter变更或文件更新),开始重新解析...")
|
|
155
|
+
|
|
156
|
+
# --- 解析环节 ---
|
|
157
|
+
tshark_path = FlowAnalyzer.get_tshark_path(tshark_path)
|
|
158
|
+
FlowAnalyzer._stream_tshark_to_db(abs_file_path, display_filter, tshark_path, db_path)
|
|
159
|
+
|
|
160
|
+
return db_path
|
|
161
|
+
|
|
162
|
+
@staticmethod
|
|
163
|
+
def get_db_data(file_path: str, display_filter: str, tshark_path: Optional[str] = None) -> str:
|
|
164
|
+
"""
|
|
165
|
+
获取数据库路径 (get_json_data 的语义化别名)。
|
|
166
|
+
新项目建议使用此方法名,get_json_data 保留用于兼容旧习惯。
|
|
167
|
+
"""
|
|
168
|
+
return FlowAnalyzer.get_json_data(file_path, display_filter, tshark_path)
|
|
169
|
+
|
|
170
|
+
@staticmethod
|
|
171
|
+
def _is_cache_valid(db_path: str, pcap_path: str, current_filter: str) -> bool:
|
|
172
|
+
"""
|
|
173
|
+
检查缓存有效性:对比 Filter 字符串和文件元数据
|
|
174
|
+
"""
|
|
175
|
+
if not os.path.exists(db_path) or os.path.getsize(db_path) == 0:
|
|
176
|
+
return False
|
|
177
|
+
|
|
178
|
+
try:
|
|
179
|
+
current_mtime = os.path.getmtime(pcap_path)
|
|
180
|
+
current_size = os.path.getsize(pcap_path)
|
|
181
|
+
|
|
182
|
+
with sqlite3.connect(db_path) as conn:
|
|
183
|
+
cursor = conn.cursor()
|
|
184
|
+
cursor.execute("SELECT filter, pcap_mtime, pcap_size FROM meta_info LIMIT 1")
|
|
185
|
+
row = cursor.fetchone()
|
|
186
|
+
|
|
187
|
+
if not row:
|
|
188
|
+
return False
|
|
189
|
+
|
|
190
|
+
cached_filter, cached_mtime, cached_size = row
|
|
191
|
+
|
|
192
|
+
# 容差 0.1秒
|
|
193
|
+
if cached_filter == current_filter and cached_size == current_size and abs(cached_mtime - current_mtime) < 0.1:
|
|
194
|
+
return True
|
|
195
|
+
else:
|
|
196
|
+
logger.debug(f"校验失败: 缓存Filter={cached_filter} vs 当前={current_filter}")
|
|
197
|
+
return False
|
|
198
|
+
|
|
199
|
+
except sqlite3.OperationalError:
|
|
200
|
+
return False
|
|
201
|
+
except Exception as e:
|
|
202
|
+
logger.warning(f"缓存校验出错: {e},将重新解析")
|
|
203
|
+
return False
|
|
204
|
+
|
|
205
|
+
@staticmethod
|
|
206
|
+
def _stream_tshark_to_db(pcap_path: str, display_filter: str, tshark_path: str, db_path: str):
|
|
207
|
+
"""流式解析并存入DB,同时记录元数据"""
|
|
208
|
+
|
|
209
|
+
if os.path.exists(db_path):
|
|
210
|
+
os.remove(db_path)
|
|
211
|
+
|
|
212
|
+
with sqlite3.connect(db_path) as conn:
|
|
213
|
+
cursor = conn.cursor()
|
|
214
|
+
cursor.execute("PRAGMA synchronous = OFF")
|
|
215
|
+
cursor.execute("PRAGMA journal_mode = MEMORY")
|
|
216
|
+
|
|
217
|
+
cursor.execute("CREATE TABLE requests (frame_num INTEGER PRIMARY KEY, header BLOB, file_data BLOB, full_uri TEXT, time_epoch REAL)")
|
|
218
|
+
cursor.execute("CREATE TABLE responses (frame_num INTEGER PRIMARY KEY, header BLOB, file_data BLOB, time_epoch REAL, request_in INTEGER)")
|
|
219
|
+
|
|
220
|
+
# === 核心优化:增加索引,极大加速 SQL JOIN 配对 ===
|
|
221
|
+
cursor.execute("CREATE INDEX idx_resp_req_in ON responses(request_in)")
|
|
222
|
+
|
|
223
|
+
cursor.execute("""
|
|
224
|
+
CREATE TABLE meta_info (
|
|
225
|
+
id INTEGER PRIMARY KEY,
|
|
226
|
+
filter TEXT,
|
|
227
|
+
pcap_path TEXT,
|
|
228
|
+
pcap_mtime REAL,
|
|
229
|
+
pcap_size INTEGER
|
|
230
|
+
)
|
|
231
|
+
""")
|
|
232
|
+
conn.commit()
|
|
233
|
+
|
|
234
|
+
command = [
|
|
235
|
+
tshark_path,
|
|
236
|
+
"-r",
|
|
237
|
+
pcap_path,
|
|
238
|
+
"-Y",
|
|
239
|
+
f"({display_filter})",
|
|
240
|
+
"-T",
|
|
241
|
+
"json",
|
|
242
|
+
"-e",
|
|
243
|
+
"http.response.code",
|
|
244
|
+
"-e",
|
|
245
|
+
"http.request_in",
|
|
246
|
+
"-e",
|
|
247
|
+
"tcp.reassembled.data",
|
|
248
|
+
"-e",
|
|
249
|
+
"frame.number",
|
|
250
|
+
"-e",
|
|
251
|
+
"tcp.payload",
|
|
252
|
+
"-e",
|
|
253
|
+
"frame.time_epoch",
|
|
254
|
+
"-e",
|
|
255
|
+
"exported_pdu.exported_pdu",
|
|
256
|
+
"-e",
|
|
257
|
+
"http.request.full_uri",
|
|
258
|
+
]
|
|
259
|
+
|
|
260
|
+
logger.debug(f"执行 Tshark: {command}")
|
|
261
|
+
|
|
262
|
+
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(os.path.abspath(pcap_path)))
|
|
263
|
+
|
|
264
|
+
db_req_rows = []
|
|
265
|
+
db_resp_rows = []
|
|
266
|
+
BATCH_SIZE = 5000
|
|
267
|
+
|
|
268
|
+
try:
|
|
269
|
+
parser = ijson.items(process.stdout, "item")
|
|
270
|
+
|
|
271
|
+
with sqlite3.connect(db_path) as conn:
|
|
272
|
+
cursor = conn.cursor()
|
|
273
|
+
|
|
274
|
+
for packet in parser:
|
|
275
|
+
layers = packet.get("_source", {}).get("layers", {})
|
|
276
|
+
if not layers:
|
|
277
|
+
continue
|
|
278
|
+
|
|
279
|
+
try:
|
|
280
|
+
frame_num, request_in, time_epoch, full_uri, full_request = FlowAnalyzer.parse_packet_data(layers)
|
|
281
|
+
if not full_request:
|
|
282
|
+
continue
|
|
283
|
+
header, file_data = FlowAnalyzer.extract_http_file_data(full_request)
|
|
284
|
+
|
|
285
|
+
if layers.get("http.response.code"):
|
|
286
|
+
db_resp_rows.append((frame_num, header, file_data, time_epoch, request_in))
|
|
287
|
+
else:
|
|
288
|
+
db_req_rows.append((frame_num, header, file_data, full_uri, time_epoch))
|
|
289
|
+
|
|
290
|
+
if len(db_req_rows) >= BATCH_SIZE:
|
|
291
|
+
cursor.executemany("INSERT OR REPLACE INTO requests VALUES (?,?,?,?,?)", db_req_rows)
|
|
292
|
+
db_req_rows.clear()
|
|
293
|
+
if len(db_resp_rows) >= BATCH_SIZE:
|
|
294
|
+
cursor.executemany("INSERT OR REPLACE INTO responses VALUES (?,?,?,?,?)", db_resp_rows)
|
|
295
|
+
db_resp_rows.clear()
|
|
296
|
+
|
|
297
|
+
except Exception:
|
|
298
|
+
pass
|
|
299
|
+
|
|
300
|
+
if db_req_rows:
|
|
301
|
+
cursor.executemany("INSERT OR REPLACE INTO requests VALUES (?,?,?,?,?)", db_req_rows)
|
|
302
|
+
if db_resp_rows:
|
|
303
|
+
cursor.executemany("INSERT OR REPLACE INTO responses VALUES (?,?,?,?,?)", db_resp_rows)
|
|
304
|
+
|
|
305
|
+
pcap_mtime = os.path.getmtime(pcap_path)
|
|
306
|
+
pcap_size = os.path.getsize(pcap_path)
|
|
307
|
+
cursor.execute("INSERT INTO meta_info (filter, pcap_path, pcap_mtime, pcap_size) VALUES (?, ?, ?, ?)", (display_filter, pcap_path, pcap_mtime, pcap_size))
|
|
308
|
+
|
|
309
|
+
conn.commit()
|
|
310
|
+
|
|
311
|
+
except Exception as e:
|
|
312
|
+
logger.error(f"解析错误: {e}")
|
|
313
|
+
if process.poll() is None:
|
|
314
|
+
process.terminate()
|
|
315
|
+
finally:
|
|
316
|
+
if process.poll() is None:
|
|
317
|
+
process.terminate()
|
|
318
|
+
|
|
319
|
+
# --- 辅助静态方法 ---
|
|
320
|
+
|
|
321
|
+
@staticmethod
|
|
322
|
+
def parse_packet_data(packet: dict) -> Tuple[int, int, float, str, str]:
|
|
323
|
+
frame_num = int(packet["frame.number"][0])
|
|
324
|
+
request_in = int(packet["http.request_in"][0]) if packet.get("http.request_in") else frame_num
|
|
325
|
+
full_uri = parse.unquote(packet["http.request.full_uri"][0]) if packet.get("http.request.full_uri") else ""
|
|
326
|
+
time_epoch = float(packet["frame.time_epoch"][0])
|
|
327
|
+
|
|
328
|
+
if packet.get("tcp.reassembled.data"):
|
|
329
|
+
full_request = packet["tcp.reassembled.data"][0]
|
|
330
|
+
elif packet.get("tcp.payload"):
|
|
331
|
+
full_request = packet["tcp.payload"][0]
|
|
332
|
+
else:
|
|
333
|
+
full_request = packet["exported_pdu.exported_pdu"][0] if packet.get("exported_pdu.exported_pdu") else ""
|
|
334
|
+
return frame_num, request_in, time_epoch, full_uri, full_request
|
|
335
|
+
|
|
336
|
+
@staticmethod
|
|
337
|
+
def split_http_headers(file_data: bytes) -> Tuple[bytes, bytes]:
|
|
338
|
+
headerEnd = file_data.find(b"\r\n\r\n")
|
|
339
|
+
if headerEnd != -1:
|
|
340
|
+
return file_data[: headerEnd + 4], file_data[headerEnd + 4 :]
|
|
341
|
+
elif file_data.find(b"\n\n") != -1:
|
|
342
|
+
headerEnd = file_data.index(b"\n\n") + 2
|
|
343
|
+
return file_data[:headerEnd], file_data[headerEnd:]
|
|
344
|
+
return b"", file_data
|
|
345
|
+
|
|
346
|
+
@staticmethod
|
|
347
|
+
def dechunck_http_response(file_data: bytes) -> bytes:
|
|
348
|
+
"""解码分块TCP数据"""
|
|
349
|
+
if not file_data:
|
|
350
|
+
return b""
|
|
351
|
+
|
|
352
|
+
chunks = []
|
|
353
|
+
cursor = 0
|
|
354
|
+
total_len = len(file_data)
|
|
355
|
+
|
|
356
|
+
while cursor < total_len:
|
|
357
|
+
# 1. 寻找当前 Chunk Size 行的结束符 (\n)
|
|
358
|
+
newline_idx = file_data.find(b"\n", cursor)
|
|
359
|
+
if newline_idx == -1:
|
|
360
|
+
# 找不到换行符,说明格式不对,抛出异常让外层处理
|
|
361
|
+
raise ValueError("Not chunked data")
|
|
362
|
+
|
|
363
|
+
# 2. 提取并解析十六进制大小
|
|
364
|
+
size_line = file_data[cursor:newline_idx].strip()
|
|
365
|
+
|
|
366
|
+
# 处理可能的空行 (例如上一个 Chunk 后的 CRLF)
|
|
367
|
+
if not size_line:
|
|
368
|
+
cursor = newline_idx + 1
|
|
369
|
+
continue
|
|
370
|
+
|
|
371
|
+
# 这里不要捕获 ValueError,如果解析失败,直接抛出
|
|
372
|
+
# 说明这根本不是 chunk size,而是普通数据
|
|
373
|
+
chunk_size = int(size_line, 16)
|
|
374
|
+
|
|
375
|
+
# Chunk Size 为 0 表示传输结束
|
|
376
|
+
if chunk_size == 0:
|
|
377
|
+
break
|
|
378
|
+
|
|
379
|
+
# 3. 定位数据区域
|
|
380
|
+
data_start = newline_idx + 1
|
|
381
|
+
data_end = data_start + chunk_size
|
|
382
|
+
|
|
383
|
+
if data_end > total_len:
|
|
384
|
+
# 数据被截断,尽力读取
|
|
385
|
+
chunks.append(file_data[data_start:])
|
|
386
|
+
break
|
|
387
|
+
|
|
388
|
+
# 4. 提取数据
|
|
389
|
+
chunks.append(file_data[data_start:data_end])
|
|
390
|
+
|
|
391
|
+
# 5. 移动游标
|
|
392
|
+
cursor = data_end
|
|
393
|
+
# 跳过尾随的 \r 和 \n
|
|
394
|
+
while cursor < total_len and file_data[cursor] in (13, 10):
|
|
395
|
+
cursor += 1
|
|
396
|
+
|
|
397
|
+
return b"".join(chunks)
|
|
398
|
+
|
|
399
|
+
@staticmethod
|
|
400
|
+
def extract_http_file_data(full_request: str) -> Tuple[bytes, bytes]:
|
|
401
|
+
"""提取HTTP请求或响应中的文件数据 (修复版)"""
|
|
402
|
+
# 1. 基础校验
|
|
403
|
+
if not full_request:
|
|
404
|
+
return b"", b""
|
|
405
|
+
|
|
406
|
+
try:
|
|
407
|
+
# 转为二进制
|
|
408
|
+
raw_bytes = bytes.fromhex(full_request)
|
|
409
|
+
|
|
410
|
+
# 分割 Header 和 Body
|
|
411
|
+
header, file_data = FlowAnalyzer.split_http_headers(raw_bytes)
|
|
412
|
+
|
|
413
|
+
# 处理 Chunked 编码
|
|
414
|
+
with contextlib.suppress(Exception):
|
|
415
|
+
file_data = FlowAnalyzer.dechunck_http_response(file_data)
|
|
416
|
+
|
|
417
|
+
# 处理 Gzip 压缩
|
|
418
|
+
with contextlib.suppress(Exception):
|
|
419
|
+
if file_data.startswith(b"\x1f\x8b"):
|
|
420
|
+
file_data = gzip.decompress(file_data)
|
|
421
|
+
|
|
422
|
+
return header, file_data
|
|
423
|
+
|
|
424
|
+
except ValueError as e:
|
|
425
|
+
# 专门捕获 Hex 转换错误,并打印出来,方便你调试
|
|
426
|
+
# 如果你在控制台看到这个错误,说明 Tshark 输出的数据格式非常奇怪
|
|
427
|
+
logger.error(f"Hex转换失败: {str(e)[:100]}... 原数据片段: {full_request[:50]}")
|
|
428
|
+
return b"", b""
|
|
429
|
+
except Exception as e:
|
|
430
|
+
logger.error(f"解析HTTP数据未知错误: {e}")
|
|
431
|
+
return b"", b""
|
|
432
|
+
|
|
433
|
+
@staticmethod
|
|
434
|
+
def get_tshark_path(tshark_path: Optional[str]) -> str:
|
|
435
|
+
default_tshark_path = get_default_tshark_path()
|
|
436
|
+
use_path = tshark_path if tshark_path and os.path.exists(tshark_path) else default_tshark_path
|
|
437
|
+
if not use_path or not os.path.exists(use_path):
|
|
438
|
+
logger.critical("未找到 Tshark,请检查路径配置")
|
|
439
|
+
exit(-1)
|
|
440
|
+
return use_path
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: FlowAnalyzer
|
|
3
|
+
Version: 0.4.2
|
|
4
|
+
Summary: FlowAnalyzer是一个流量分析器,用于解析和处理tshark导出的JSON数据文件
|
|
5
|
+
Home-page: https://github.com/Byxs20/FlowAnalyzer
|
|
6
|
+
Author: Byxs20
|
|
7
|
+
Author-email: 97766819@qq.com
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.6
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: author
|
|
19
|
+
Dynamic: author-email
|
|
20
|
+
Dynamic: classifier
|
|
21
|
+
Dynamic: description
|
|
22
|
+
Dynamic: description-content-type
|
|
23
|
+
Dynamic: home-page
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
Dynamic: summary
|
|
26
|
+
|
|
27
|
+
# FlowAnalyzer
|
|
28
|
+
|
|
29
|
+
[](https://pypi.org/project/FlowAnalyzer/) [](LICENSE) 
|
|
30
|
+
|
|
31
|
+
**FlowAnalyzer** 是一个高效的 Python 流量分析库,基于 `Tshark` 进行底层解析。它专为处理大流量包(Large PCAP)设计,采用流式解析与 SQLite 缓存架构,彻底解决内存溢出问题,实现秒级二次加载。
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## 🚀 核心特性:智能缓存与流式架构
|
|
36
|
+
|
|
37
|
+
为了解决传统解析方式慢、内存占用高的问题,FlowAnalyzer 进行了核心架构升级:**流式解析 + SQLite 智能缓存**。
|
|
38
|
+
|
|
39
|
+
### 1. ⚡️ 高性能流式解析
|
|
40
|
+
- **极低内存占用**:不再将整个 JSON 读入内存。通过 `subprocess` 管道对接 Tshark 输出,结合 `ijson` 进行增量解析。
|
|
41
|
+
- **无中间文件**:解析过程中不生成体积巨大的临时 JSON 文件,直接入库。
|
|
42
|
+
|
|
43
|
+
### 2. 💾 智能缓存机制
|
|
44
|
+
- **自动缓存**:首次分析 `test.pcap` 时,会自动生成同级目录下的 `test.db`。
|
|
45
|
+
- **秒级加载**:二次分析时,直接读取 SQLite 数据库,跳过漫长的 Tshark 解析过程(速度提升 100 倍+)。
|
|
46
|
+
|
|
47
|
+
### 3. 🛡️ 智能校验 (Smart Validation)
|
|
48
|
+
为了防止“修改了过滤规则但误读旧缓存”的问题,内置了严格的元数据校验机制。每次运行时自动比对指纹:
|
|
49
|
+
|
|
50
|
+
| 校验项 | 说明 |
|
|
51
|
+
| :---------------------- | :----------------------------------------------------------- |
|
|
52
|
+
| **过滤规则 (Filter)** | 检查本次传入的 Tshark 过滤器(如 `http contains flag`)是否与缓存一致。 |
|
|
53
|
+
| **文件指纹 (Metadata)** | 检查原始 PCAP 文件的 **修改时间 (MTime)** 和 **文件大小 (Size)**。 |
|
|
54
|
+
|
|
55
|
+
- ✅ **命中缓存**:规则一致且文件未变 → **0秒等待,直接加载**。
|
|
56
|
+
- 🔄 **缓存失效**:规则变更或文件更新 → **自动重新解析并更新数据库**。
|
|
57
|
+
|
|
58
|
+
### 4. 性能对比
|
|
59
|
+
|
|
60
|
+
| 特性 | 旧版架构 | **新版架构 (FlowAnalyzer)** |
|
|
61
|
+
| :----------- | :---------------------------- | :---------------------------------- |
|
|
62
|
+
| **解析流程** | 生成巨大 JSON -> 全量读入内存 | Tshark流 -> 管道 -> ijson -> SQLite |
|
|
63
|
+
| **内存占用** | 极高 (易 OOM) | **极低 (内存稳定)** |
|
|
64
|
+
| **二次加载** | 需重新解析 | **直接读取 DB (0秒)** |
|
|
65
|
+
| **磁盘占用** | 巨大的临时 JSON 文件 | 轻量级 SQLite 文件 |
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## 📦 安装
|
|
70
|
+
|
|
71
|
+
请确保您的环境中已安装 Python 3 和 Tshark (Wireshark)。
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
# 安装 FlowAnalyzer 及其依赖 ijson
|
|
75
|
+
pip3 install FlowAnalyzer ijson
|
|
76
|
+
|
|
77
|
+
# 或者使用国内源加速
|
|
78
|
+
pip3 install FlowAnalyzer ijson -i https://pypi.org/simple
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## 🛠️ 快速上手
|
|
84
|
+
|
|
85
|
+
### 1. 基础使用
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from FlowAnalyzer import FlowAnalyzer
|
|
89
|
+
|
|
90
|
+
# 流量包路径
|
|
91
|
+
pcap_path = r"tests/demo.pcap"
|
|
92
|
+
# 过滤规则
|
|
93
|
+
display_filter = "http"
|
|
94
|
+
|
|
95
|
+
# 1. 获取数据库数据 (自动处理解析、缓存和校验)
|
|
96
|
+
# 返回的是生成的 .db 文件路径
|
|
97
|
+
db_path = FlowAnalyzer.get_db_data(pcap_path, display_filter)
|
|
98
|
+
# 兼容老的函数名 get_json_data
|
|
99
|
+
# db_path = FlowAnalyzer.get_json_data(pcap_path, display_filter)
|
|
100
|
+
|
|
101
|
+
# 2. 初始化分析器
|
|
102
|
+
analyzer = FlowAnalyzer(db_path)
|
|
103
|
+
|
|
104
|
+
# 3. 遍历 HTTP 流
|
|
105
|
+
print("[+] 开始分析 HTTP 流...")
|
|
106
|
+
for pair in analyzer.generate_http_dict_pairs():
|
|
107
|
+
if pair.request:
|
|
108
|
+
print(f"Frame: {pair.request.frame_num} | URI: {pair.request.full_uri}")
|
|
109
|
+
# 获取请求体数据
|
|
110
|
+
# print(pair.request.file_data)
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### 2. 配置 Tshark 路径
|
|
114
|
+
|
|
115
|
+
如果您的 `tshark` 不在系统环境变量中,程序可能会报错。您有两种方式进行配置:
|
|
116
|
+
|
|
117
|
+
**方法一:代码中指定 (推荐)**
|
|
118
|
+
|
|
119
|
+
在调用 `get_db_data` 时直接传入路径:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
tshark_ex = r"D:\Program Files\Wireshark\tshark.exe"
|
|
123
|
+
|
|
124
|
+
FlowAnalyzer.get_db_data(pcap_path, display_filter, tshark_path=tshark_ex)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
**方法二:修改默认配置**
|
|
128
|
+
|
|
129
|
+
如果安装目录固定,可以修改库文件中的默认路径:
|
|
130
|
+
找到 `python安装目录\Lib\site-packages\FlowAnalyzer\Path.py`,修改 `tshark_path` 变量。
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
## 📝 测试
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
$ git clone https://github.com/Byxs20/FlowAnalyzer.git
|
|
138
|
+
$ cd ./FlowAnalyzer/
|
|
139
|
+
$ python tests/demo.py
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
**运行预期结果:**
|
|
143
|
+
|
|
144
|
+
```text
|
|
145
|
+
[+] 正在处理第1个HTTP流!
|
|
146
|
+
序号: 2请求包, 请求头: b'POST /upload/php_eval_xor_base64.php HTTP/1.1 ...
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
## 📄 License
|
|
152
|
+
|
|
153
|
+
This project is licensed under the [MIT License](LICENSE).
|