-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathapktool
More file actions
executable file
·635 lines (586 loc) · 20.2 KB
/
Copy pathapktool
File metadata and controls
executable file
·635 lines (586 loc) · 20.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
#!/usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
import os
import sys
import glob
import zipfile
import functools
# fix sys path to include our lib
DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(0, DIR_PATH)
from atool.apk import sysresource
from atool.apk.axml import AXMLParser
from atool.apk.axml import ResourceParser
from atool.apk.axml import ResObject
TOOL_NAME = 'apktool'
COMMANDS = ['dumpapk', 'dumpxml', 'cat', 'resolve', 'resolve_string', 'catr', 'dump_dex', 'dex_sum', 'get_icon']
usage = '''usage: apktool <command> [args]
Type 'apktool <command> -h' for help of specific command.
Available commands:
dumpxml dump android binary xml
dumpapk dump all xml files in given apk file to current directory
cat dump specified xml from given apk file
catr dump R.java
resolve resolve resource name of given numeric id
resolve_string resolve value of given string id
dump_dex dump class name from dex file
'''
def get_cmd_path(cmd):
'''Get absolute path of given command with PATH environment'''
if cmd == "":
return None
path = os.environ.get("PATH")
if path == None:
path = os.environ.get("path")
if path == None:
return None
for p in path.split(':'):
f = p + "/" + cmd
if os.access(f, os.X_OK):
return f
return None
def cmp_version(v1, v2):
if v1 == v2:
return 0
a1 = v1.split(".")
a2 = v2.split(".")
while a1 or a2:
if not a1:
return -1
if not a2:
return 1
c1 = a1.pop(0)
c2 = a2.pop(0)
if c1.isdigit() and c2.isdigit():
tmp1 = int(c1)
tmp2 = int(c2)
return (tmp1 > tmp2) - (tmp1 < tmp2)
else:
return (c1 > c2) - (c1 < c2)
def get_android_jar(sdk_dir):
'''Get android system resource file (android.jar)'''
if not (os.path.isdir(sdk_dir + "/platforms")
and os.path.isfile(sdk_dir + "/tools/android")):
return None
prefix = sdk_dir + "/platforms/android-"
i = len(prefix)
platforms = glob.glob(prefix + "*")
if not platforms:
return None
vs = [item[i:] for item in platforms]
vs.sort(key=functools.cmp_to_key(cmp_version))
jar = prefix + vs[-1] + "/android.jar"
if os.path.isfile(jar):
return jar
else:
return None
def get_android_resource():
android = get_cmd_path("android")
if android:
android = os.path.realpath(android)
jar = None
if android:
sdk_dir = os.path.dirname(os.path.dirname(android))
jar = get_android_jar(sdk_dir)
if jar == None:
sdk_dir = os.environ.get("ANDROID_HOME")
if sdk_dir:
jar = get_android_jar(sdk_dir)
return jar
def dump_xml(cmd, argv):
usage = 'usage: %s %s <binary-xml> [<resources.arsc-or-.apk>]' % (TOOL_NAME, cmd)
detail = '''
Dump given xml file to stdout.
If resources file (typically resources.arsc extracted from the
same apk file) not specified, most xml attributes will be dumped
as numeric value.
System resources will be auto loaded (android sdk directory is
resolved by path of command 'android', then try environment
variable 'ANDROID_HOME'). If system resources can not be found,
most xml attributes will be dumped as numeric value.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print(usage)
print(detail)
sys.exit(0)
if len(argv) < 1 or len(argv) > 2:
print(usage, file=sys.stderr)
sys.exit(1)
restable = ResObject()
androidjar = get_android_resource()
if androidjar:
res = get_archived_resource(androidjar)
if res:
restable.update(res)
if len(argv) > 1:
try:
infile = open(argv[1], "rb")
indata = infile.read()
infile.close()
if len(indata) > 4 and indata[0:4] == '\x50\x4b\x03\x04':
res = get_archived_resource(argv[1])
if res:
restable.update(res)
else:
parser = ResourceParser(indata)
res = parser.parse_resources()
if res:
restable.update(res)
except Exception as e:
print("failed to process resource: ", e, file=sys.stderr)
infile = open(argv[0], "rb")
indata = infile.read()
infile.close()
parser = AXMLParser(indata)
parser.set_restable(restable)
(xml, ns) = parser.parsexml()
xml.dump(sys.stdout, ns)
def get_archived_resource(archive):
zfile = None
try:
try:
zfile = zipfile.ZipFile(archive, "r")
except Exception as e1:
print("failed to open zip archive:", archive, e1, file=sys.stderr)
return None
data = zfile.read("resources.arsc")
zfile.close()
zfile = None
parser = ResourceParser(data)
return parser.parse_resources()
except Exception as e:
if zfile:
zfile.close()
print("failed to process resources.arsc:", e, file=sys.stderr)
return None
def make_res_id(pkgid, typeid, entryid):
return ((0xff000000 & (pkgid << 24)) |
(0x00ff0000 & ((typeid) << 16)) |
(0x0000ffff & (entryid)) )
def dump_r(pkg, outfile=sys.stdout):
print("package %s\n" % (pkg.name), file=outfile)
print("public final class R {", file=outfile)
for tname in sorted(pkg.name_map.keys()):
t = pkg.name_map[tname]
print(" public static final class %s {" % (t.name), file=outfile)
for k in sorted(t.id_map.keys()):
e = t.id_map[k]
eid = make_res_id(pkg.id, t.id, e.id)
print(" public static final int %s = 0x%08x; // %d" % (e.name, eid, eid), file=outfile)
print(" }\n", file=outfile)
print("}", file=outfile)
def cat_r(cmd, argv):
usage = 'usage: %s %s <resources.arsc-or-.apk>' % (TOOL_NAME, cmd)
detail = '''
Dump R.java to stdout.
resources file or apk file must specified.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print(usage)
print(detail)
sys.exit(0)
if len(argv) != 1:
print(usage, file=sys.stderr)
sys.exit(1)
res = None
try:
infile = open(argv[0], "rb")
indata = infile.read()
infile.close()
if len(indata) > 4 and indata[0:4] == '\x50\x4b\x03\x04':
res = get_archived_resource(argv[1])
else:
parser = ResourceParser(indata)
res = parser.parse_resources()
if res == None or len(res.id_map) < 1:
print("no package in restable", file=std.err)
return
if len(res.id_map) != 1:
print("multiple package in restable", file=std.err)
return
ids = list(res.id_map.keys())
pkg = res.id_map[ids[0]]
dump_r(pkg)
except Exception as e:
print("failed to process resource: ", e, file=sys.stderr)
sys.exit(1)
def dump_apk(cmd, argv):
usage = 'usage: %s %s <file.apk>' % (TOOL_NAME, cmd)
detail = '''
Dump all xml files in given apk file into current directory.
System resources will be auto loaded (android sdk directory is
resolved by path of command 'android', then try environment
variable 'ANDROID_HOME'). If system resources can not be found,
most xml attributes will be dumped as numeric value.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print(usage)
print(detail)
sys.exit(0)
if len(argv) != 1:
print(usage, file=sys.stderr)
sys.exit(1)
apkfile = argv[0]
restable = ResObject()
androidjar = get_android_resource()
if androidjar:
# print >> sys.stderr, androidjar
res = get_archived_resource(androidjar)
if res:
restable.update(res)
infile = open(apkfile, "rb")
indata = infile.read(4)
infile.close()
if len(indata) < 4 or indata[0:4] != "\x50\x4b\x03\x04":
print("not a apk file: %s" % (apkfile), file=sys.stderr)
sys.exit(1)
res = get_archived_resource(apkfile)
if res:
restable.update(res)
zfile = zipfile.ZipFile(apkfile, "r")
zfile.getinfo("resources.arsc")
flist = zfile.namelist()
for fname in flist:
if not fname.endswith(".xml"):
continue
# if not (fname == 'AndroidManifest.xml' or fname.startswith("res/")):
# continue
data = zfile.read(fname)
fname = fname.lstrip("/")
print("processing", fname)
try:
parser = AXMLParser(data)
parser.set_restable(restable)
(xml, ns) = parser.parsexml()
dirname = os.path.dirname(fname)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname, 0o755)
outfile = open(fname, "wb")
xml.dump(outfile, ns)
outfile.close()
except Exception as e:
print(" Error:", e, file=sys.stderr)
zfile.close()
def cat_xml(cmd, argv):
usage = 'usage: %s %s <file.apk> [<name.xml>]' % (TOOL_NAME, cmd)
detail = '''
Dump specified xml file from given apk file, default to AndroidManifest.xml.
System resources will be auto loaded (android sdk directory is
resolved by path of command 'android', then try environment
variable 'ANDROID_HOME'). If system resources can not be found,
most xml attributes will be dumped as numeric value.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print(usage)
print(detail)
sys.exit(0)
if len(argv) < 1 or len(argv) > 2:
print(usage, file=sys.stderr)
sys.exit(1)
apkfile = argv[0]
zfile = zipfile.ZipFile(apkfile, "r")
if len(argv) > 1:
xmlfile = argv[1]
else:
xmlfile = 'AndroidManifest.xml'
data = zfile.read(xmlfile)
zfile.close()
if not data:
sys.exit(0)
restable = ResObject()
#androidjar = None
androidjar = get_android_resource()
if androidjar:
res = get_archived_resource(androidjar)
if res:
restable.update(res)
res = get_archived_resource(apkfile)
if res:
restable.update(res)
parser = AXMLParser(data)
parser.set_restable(restable)
(xml, ns) = parser.parsexml()
xml.dump(sys.stdout, ns)
def get_icon(cmd, argv):
usage = 'usage: %s %s <file.apk>' % (TOOL_NAME, cmd)
detail = '''
get icon file name from given apk file.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print(usage)
print(detail)
sys.exit(0)
if len(argv) != 1:
print(usage, file=sys.stderr)
sys.exit(1)
apkfile = argv[0]
zfile = zipfile.ZipFile(apkfile, "r")
xmlfile = 'AndroidManifest.xml'
data = zfile.read(xmlfile)
zfile.close()
if not data:
sys.exit(0)
restable = get_archived_resource(apkfile)
parser = AXMLParser(data)
parser.set_restable(restable)
(xml, ns) = parser.parsexml()
app_node = None
for c in xml.children:
if c.name == 'application':
app_node = c
break
if not app_node:
raise ValidationError("invalid apk, can not find 'application' in manifest")
name_attr = None
icon_attr = None
for attr in app_node.attributes:
if attr.name == 'android:label':
name_attr = attr
elif attr.name == 'android:icon':
icon_attr = attr
if icon_attr:
s = restable.get_entry_value(icon_attr.entry)
if s == None:
s = '?'
print("%s=%s, file: %s" % (icon_attr.name, icon_attr.value, s))
else:
print("icon file can not found")
def resolve_name(cmd, argv):
usage = 'usage: %s %s <numeric_id> [<apk_or_arsc>]' % (TOOL_NAME, cmd)
detail = '''
Resolve resource name of given id.
System resources will be auto loaded, optional apk file or resource file
will also be searched.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print(usage)
print(detail)
sys.exit(0)
if len(argv) < 1 or len(argv) > 2:
print(usage, file=sys.stderr)
sys.exit(1)
idstr = argv[0]
radix = 10
if idstr.startswith("0x") or idstr.startswith("0X"):
radix = 16
rid = 0
try:
rid = int(idstr, radix)
except:
print("invalid id, not a number: ", idstr, file=sys.stderr)
sys.exit(1)
if rid <= 0 or rid >= 0xffffffff:
print("invalid id: ", idstr, file=sys.stderr)
sys.exit(1)
restable = ResObject()
androidjar = get_android_resource()
if androidjar:
res = get_archived_resource(androidjar)
if res:
restable.update(res)
if len(argv) > 1:
try:
infile = open(argv[1], "rb")
indata = infile.read()
infile.close()
if len(indata) > 4 and indata[0:4] == "\x50\x4b\x03\x04":
m = get_archived_resource(argv[1])
else:
parser = ResourceParser(indata)
m = parser.parse_resources()
restable.update(m)
except Exception as e:
print("failed to process resource: ", e, file=sys.stderr)
parser = ResourceParser("")
parser.set_restable(restable)
result = parser.dereference_resource(rid)
if result == None:
print("can not resolve given id: 0x%08x" % (rid), file=sys.stderr)
sys.exit(1)
print("0x%08x %s %s %s" % (rid, result[0], result[1], result[2]))
def resolve_string(cmd, argv):
usage = 'usage: %s %s <apk_or_arsc> <string_name>' % (TOOL_NAME, cmd)
detail = '''
Resolve value of given string name.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print(usage)
print(detail)
sys.exit(0)
if len(argv) != 2:
print(usage, file=sys.stderr)
sys.exit(1)
string_name = argv[1]
res_file = argv[0]
try:
infile = open(res_file, "rb")
indata = infile.read()
infile.close()
if len(indata) > 4 and indata[0:4] == "\x50\x4b\x03\x04":
zfile = None
indata = None
try:
zfile = zipfile.ZipFile(res_file, 'r')
indata = zfile.read('resources.arsc')
zfile.close()
zfile = None
except Exception as e1:
print("failed to process resource: ", e1, file=sys.stderr)
return None
if indata:
parser = ResourceParser(indata)
restable = parser.parse_resources()
if not restable.name_map:
return None
package = list(restable.name_map.values())[0]
parser.set_restable(restable)
print(parser.resolve_string(package.name, string_name))
except Exception as e:
print("failed to process resource: ", e, file=sys.stderr)
return None
def dump_dex(cmd, argv):
usage = 'usage: %s %s <.dex-or-.apk>' % (TOOL_NAME, cmd)
detail = '''
Dump class names to stdout.
dex file or apk file must specified.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print(usage)
print(detail)
sys.exit(0)
if len(argv) != 1:
print(usage, file=sys.stderr)
sys.exit(1)
fname = argv[0]
try:
from atool.apk import dex
infile = open(fname, "rb")
indata = infile.read()
infile.close()
data = None
if len(indata) > 4 and indata[0:4] == '\x50\x4b\x03\x04':
zfile = zipfile.ZipFile(fname, "r")
flist = zfile.namelist()
for fname in flist:
if not fname.endswith(".dex"):
continue
data = zfile.read(fname)
(field_ids_size, method_ids_size, class_defs_size) = dex.parsedex(data, True)
print("--", fname, "--")
print(" field_size: %5d" % (field_ids_size))
print(" method_size: %5d" % (method_ids_size))
print(" classs_size: %5d" % (class_defs_size))
zfile.close()
elif len(indata) > 8 and data[0:8] == 'dex\n0350x00':
data = indata
print("field_size: %5d" % (field_ids_size))
print("method_size: %5d" % (method_ids_size))
print("classs_size: %5d" % (class_defs_size))
else:
print("input file is not dex or apk file", file=sys.stderr)
sys.exit(1)
if not data:
print("can not read dex data", file=sys.stderr)
sys.exit(1)
except Exception as e:
print("failed to dump class: ", e, file=sys.stderr)
sys.exit(1)
def dex_sum(cmd, argv):
usage = 'usage: %s %s <.dex-or-.apk>' % (TOOL_NAME, cmd)
detail = '''
Dump dex summary stdout.
dex file or apk file must specified.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print(usage)
print(detail)
sys.exit(0)
if len(argv) != 1:
print(usage, file=sys.stderr)
sys.exit(1)
fname = argv[0]
try:
infile = open(fname, "rb")
indata = infile.read()
infile.close()
data = None
if len(indata) > 4 and indata[0:4] == '\x50\x4b\x03\x04':
zfile = zipfile.ZipFile(fname, "r")
data = zfile.read("classes.dex")
zfile.close()
elif len(indata) > 8 and indata[0:8] == 'dex\n035\x00':
data = indata
else:
print("input file is not dex or apk file", file=sys.stderr)
sys.exit(1)
if not data:
print("can not read dex data", file=sys.stderr)
sys.exit(1)
if len(data) < 0x70:
error("incomplete header with size %d (min %d)" % (len(data), 0x70))
if data[0:8] != 'dex\n035\x00':
error("dex magic unmatch")
from struct import unpack
off = 56
(str_ids_size, str_ids_off, type_ids_size, type_ids_off) = unpack('<IIII', data[off:off+16])
off = 72
(proto_ids_size, proto_ids_off, field_ids_size, field_ids_off) = unpack('<IIII', data[off:off+16])
off = 88
(method_ids_size, method_ids_off) = unpack('<II', data[off:off+8])
off = 96
(class_defs_size, class_defs_off) = unpack('<II', data[off:off+8])
off = 104
(data_size, data_off) = unpack('<II', data[off:off+8])
va = (
('str_ids_size', str_ids_size),
('str_ids_off', str_ids_off),
('type_ids_size', type_ids_size),
('type_ids_off', type_ids_off),
('proto_ids_size', proto_ids_size),
('proto_ids_off', proto_ids_off),
('field_ids_size', field_ids_size),
('field_ids_off', field_ids_off),
('method_ids_size', method_ids_size),
('method_ids_off', method_ids_off),
('class_defs_size', class_defs_size),
('class_defs_off', class_defs_off),
('data_size', data_size),
('data_off', data_off)
)
for (k, v) in va:
if k.endswith('_off'):
print('%s\t : %d (0x%06x)' % (k, v, v))
else:
print('%s\t : %d' % (k, v))
except Exception as e:
print("failed to dump class: ", e, file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
if len(sys.argv) < 2:
print("no command specified, type 'apktool help' for usage.", file=sys.stderr)
sys.exit(1)
command = sys.argv[1]
argv = sys.argv[2:]
if command in ['-h', '-help', '--help', 'help']:
print(usage, end=' ')
sys.exit(0)
if command not in COMMANDS:
print("apktool: unknown command '%s'. See 'apktool help'." % (command), file=sys.stderr)
elif command == 'dumpxml':
dump_xml(command, argv)
elif command == 'dumpapk':
dump_apk(command, argv)
elif command == 'resolve':
resolve_name(command, argv)
elif command == 'resolve_string':
resolve_string(command, argv)
elif command == 'cat':
cat_xml(command, argv)
elif command == 'catr':
cat_r(command, argv)
elif command == 'dump_dex':
dump_dex(command, argv)
elif command == 'dex_sum':
dex_sum(command, argv)
elif command == 'get_icon':
get_icon(command, argv)