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
| #!/usr/bin/env python3
"""
DEX 文件解析器 - 用于分析 Android DEX 文件结构
"""
import struct
import hashlib
import zlib
from dataclasses import dataclass
from typing import List, Optional
from pathlib import Path
@dataclass
class DexHeader:
"""DEX 文件头结构"""
magic: bytes
checksum: int
signature: bytes
file_size: int
header_size: int
endian_tag: int
link_size: int
link_off: int
map_off: int
string_ids_size: int
string_ids_off: int
type_ids_size: int
type_ids_off: int
proto_ids_size: int
proto_ids_off: int
field_ids_size: int
field_ids_off: int
method_ids_size: int
method_ids_off: int
class_defs_size: int
class_defs_off: int
data_size: int
data_off: int
@dataclass
class ClassDef:
"""类定义结构"""
class_idx: int
access_flags: int
superclass_idx: int
interfaces_off: int
source_file_idx: int
annotations_off: int
class_data_off: int
static_values_off: int
@dataclass
class MethodId:
"""方法 ID 结构"""
class_idx: int
proto_idx: int
name_idx: int
class DexParser:
"""DEX 文件解析器"""
# 访问标志常量
ACC_PUBLIC = 0x0001
ACC_PRIVATE = 0x0002
ACC_PROTECTED = 0x0004
ACC_STATIC = 0x0008
ACC_FINAL = 0x0010
ACC_SYNCHRONIZED = 0x0020
ACC_VOLATILE = 0x0040
ACC_BRIDGE = 0x0040
ACC_TRANSIENT = 0x0080
ACC_VARARGS = 0x0080
ACC_NATIVE = 0x0100
ACC_INTERFACE = 0x0200
ACC_ABSTRACT = 0x0400
ACC_STRICT = 0x0800
ACC_SYNTHETIC = 0x1000
ACC_ANNOTATION = 0x2000
ACC_ENUM = 0x4000
ACC_CONSTRUCTOR = 0x10000
ACC_DECLARED_SYNCHRONIZED = 0x20000
def __init__(self, dex_path: str):
self.dex_path = Path(dex_path)
with open(dex_path, 'rb') as f:
self.data = f.read()
self.header: Optional[DexHeader] = None
self.strings: List[str] = []
self.types: List[str] = []
self.class_defs: List[ClassDef] = []
self.method_ids: List[MethodId] = []
def parse(self) -> bool:
"""解析 DEX 文件"""
if not self._parse_header():
return False
self._parse_strings()
self._parse_types()
self._parse_method_ids()
self._parse_class_defs()
return True
def _parse_header(self) -> bool:
"""解析 DEX 头部"""
if len(self.data) < 112:
print("文件太小,不是有效的 DEX 文件")
return False
# 检查魔数
magic = self.data[0:8]
if not magic.startswith(b'dex\n'):
print(f"无效的魔数: {magic}")
return False
# 解析头部各字段
self.header = DexHeader(
magic=magic,
checksum=struct.unpack('<I', self.data[8:12])[0],
signature=self.data[12:32],
file_size=struct.unpack('<I', self.data[32:36])[0],
header_size=struct.unpack('<I', self.data[36:40])[0],
endian_tag=struct.unpack('<I', self.data[40:44])[0],
link_size=struct.unpack('<I', self.data[44:48])[0],
link_off=struct.unpack('<I', self.data[48:52])[0],
map_off=struct.unpack('<I', self.data[52:56])[0],
string_ids_size=struct.unpack('<I', self.data[56:60])[0],
string_ids_off=struct.unpack('<I', self.data[60:64])[0],
type_ids_size=struct.unpack('<I', self.data[64:68])[0],
type_ids_off=struct.unpack('<I', self.data[68:72])[0],
proto_ids_size=struct.unpack('<I', self.data[72:76])[0],
proto_ids_off=struct.unpack('<I', self.data[76:80])[0],
field_ids_size=struct.unpack('<I', self.data[80:84])[0],
field_ids_off=struct.unpack('<I', self.data[84:88])[0],
method_ids_size=struct.unpack('<I', self.data[88:92])[0],
method_ids_off=struct.unpack('<I', self.data[92:96])[0],
class_defs_size=struct.unpack('<I', self.data[96:100])[0],
class_defs_off=struct.unpack('<I', self.data[100:104])[0],
data_size=struct.unpack('<I', self.data[104:108])[0],
data_off=struct.unpack('<I', self.data[108:112])[0],
)
return True
def _read_uleb128(self, offset: int) -> tuple:
"""读取 ULEB128 编码的整数"""
result = 0
shift = 0
size = 0
while True:
byte = self.data[offset + size]
result |= (byte & 0x7f) << shift
size += 1
if (byte & 0x80) == 0:
break
shift += 7
return result, size
def _parse_strings(self):
"""解析字符串表"""
if not self.header:
return
self.strings = []
offset = self.header.string_ids_off
for i in range(self.header.string_ids_size):
# 读取字符串数据偏移
string_data_off = struct.unpack('<I', self.data[offset:offset+4])[0]
offset += 4
# 读取 ULEB128 编码的字符串长度
str_len, size = self._read_uleb128(string_data_off)
# 读取 MUTF-8 编码的字符串
str_start = string_data_off + size
str_bytes = self.data[str_start:str_start + str_len]
try:
self.strings.append(str_bytes.decode('utf-8', errors='replace'))
except:
self.strings.append(str_bytes.hex())
def _parse_types(self):
"""解析类型表"""
if not self.header:
return
self.types = []
offset = self.header.type_ids_off
for i in range(self.header.type_ids_size):
descriptor_idx = struct.unpack('<I', self.data[offset:offset+4])[0]
offset += 4
if descriptor_idx < len(self.strings):
self.types.append(self.strings[descriptor_idx])
else:
self.types.append(f"<invalid:{descriptor_idx}>")
def _parse_method_ids(self):
"""解析方法 ID 表"""
if not self.header:
return
self.method_ids = []
offset = self.header.method_ids_off
for i in range(self.header.method_ids_size):
class_idx = struct.unpack('<H', self.data[offset:offset+2])[0]
proto_idx = struct.unpack('<H', self.data[offset+2:offset+4])[0]
name_idx = struct.unpack('<I', self.data[offset+4:offset+8])[0]
offset += 8
self.method_ids.append(MethodId(class_idx, proto_idx, name_idx))
def _parse_class_defs(self):
"""解析类定义表"""
if not self.header:
return
self.class_defs = []
offset = self.header.class_defs_off
for i in range(self.header.class_defs_size):
class_def = ClassDef(
class_idx=struct.unpack('<I', self.data[offset:offset+4])[0],
access_flags=struct.unpack('<I', self.data[offset+4:offset+8])[0],
superclass_idx=struct.unpack('<I', self.data[offset+8:offset+12])[0],
interfaces_off=struct.unpack('<I', self.data[offset+12:offset+16])[0],
source_file_idx=struct.unpack('<I', self.data[offset+16:offset+20])[0],
annotations_off=struct.unpack('<I', self.data[offset+20:offset+24])[0],
class_data_off=struct.unpack('<I', self.data[offset+24:offset+28])[0],
static_values_off=struct.unpack('<I', self.data[offset+28:offset+32])[0],
)
offset += 32
self.class_defs.append(class_def)
def get_access_flags_str(self, flags: int) -> str:
"""将访问标志转换为可读字符串"""
result = []
if flags & self.ACC_PUBLIC: result.append("public")
if flags & self.ACC_PRIVATE: result.append("private")
if flags & self.ACC_PROTECTED: result.append("protected")
if flags & self.ACC_STATIC: result.append("static")
if flags & self.ACC_FINAL: result.append("final")
if flags & self.ACC_ABSTRACT: result.append("abstract")
if flags & self.ACC_INTERFACE: result.append("interface")
if flags & self.ACC_NATIVE: result.append("native")
return " ".join(result)
def verify_checksum(self) -> bool:
"""验证 Adler32 校验和"""
if not self.header:
return False
calculated = zlib.adler32(self.data[12:]) & 0xffffffff
return calculated == self.header.checksum
def verify_signature(self) -> bool:
"""验证 SHA-1 签名"""
if not self.header:
return False
calculated = hashlib.sha1(self.data[32:]).digest()
return calculated == self.header.signature
def print_header(self):
"""打印头部信息"""
if not self.header:
print("未解析头部")
return
h = self.header
print("=" * 60)
print("DEX 文件头信息")
print("=" * 60)
print(f"魔数: {h.magic}")
print(f"DEX 版本: {h.magic[4:7].decode()}")
print(f"校验和: 0x{h.checksum:08X} {'(有效)' if self.verify_checksum() else '(无效)'}")
print(f"SHA-1 签名: {h.signature.hex()}")
print(f"文件大小: {h.file_size} bytes ({h.file_size / 1024:.2f} KB)")
print(f"头部大小: {h.header_size} bytes")
print(f"字节序: {'小端' if h.endian_tag == 0x12345678 else '大端'}")
print("-" * 60)
print(f"字符串数量: {h.string_ids_size}")
print(f"类型数量: {h.type_ids_size}")
print(f"原型数量: {h.proto_ids_size}")
print(f"字段数量: {h.field_ids_size}")
print(f"方法数量: {h.method_ids_size}")
print(f"类定义数量: {h.class_defs_size}")
print("=" * 60)
def print_classes(self, limit: int = 20):
"""打印类列表"""
print(f"\n前 {limit} 个类:")
print("-" * 60)
for i, class_def in enumerate(self.class_defs[:limit]):
class_name = self.types[class_def.class_idx] if class_def.class_idx < len(self.types) else "?"
flags = self.get_access_flags_str(class_def.access_flags)
print(f" [{i:4d}] {flags} {class_name}")
def search_strings(self, keyword: str) -> List[tuple]:
"""搜索包含关键字的字符串"""
results = []
keyword_lower = keyword.lower()
for i, s in enumerate(self.strings):
if keyword_lower in s.lower():
results.append((i, s))
return results
def find_methods_by_name(self, name: str) -> List[tuple]:
"""按名称搜索方法"""
results = []
for i, method in enumerate(self.method_ids):
method_name = self.strings[method.name_idx] if method.name_idx < len(self.strings) else ""
if name.lower() in method_name.lower():
class_name = self.types[method.class_idx] if method.class_idx < len(self.types) else "?"
results.append((i, class_name, method_name))
return results
# 使用示例
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("用法: python dex_parser.py <dex文件路径> [搜索关键字]")
sys.exit(1)
parser = DexParser(sys.argv[1])
if not parser.parse():
sys.exit(1)
parser.print_header()
parser.print_classes()
# 如果提供了搜索关键字
if len(sys.argv) >= 3:
keyword = sys.argv[2]
print(f"\n搜索字符串: '{keyword}'")
results = parser.search_strings(keyword)
for idx, s in results[:20]:
print(f" [{idx}] {s[:80]}...")
print(f"\n搜索方法: '{keyword}'")
methods = parser.find_methods_by_name(keyword)
for idx, class_name, method_name in methods[:20]:
print(f" [{idx}] {class_name}->{method_name}")
|