-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1198 lines (1035 loc) · 43.4 KB
/
main.py
File metadata and controls
1198 lines (1035 loc) · 43.4 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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import hashlib
import io
import json
import os
import shutil
import struct
import subprocess
import sys
import tempfile
import time
import zipfile
from pathlib import Path
try:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
_CRYPTO_OK = True
except ImportError:
_CRYPTO_OK = False
# Crypto constants - single source of truth (spec §11.1)
KDF_ITERATIONS = 120_000
KEY_LENGTH_BYTES = 32
SALT_SIZE = 16
IV_SIZE = 16
BLOCK_SIZE = 16
# Format constants
FORMAT_NAME = "apkv"
FORMAT_VERSION = 2
SENTINEL_ENTRY = ".apkv_enc"
MANIFEST_PLAIN = "manifest.json"
MANIFEST_ENC = "manifest.enc"
HEADER_JSON = "header.json"
ICON_PLAIN = "icon.webp"
ICON_ENC = "icon.enc"
PAYLOAD_ENC = "payload.enc"
ALLOWED_METHODS = {zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED}
STREAM_BUF = 65_536
def _require_crypto():
if not _CRYPTO_OK:
sys.exit(
"The 'cryptography' package is required for encrypted archives.\n"
"Install it with: pip install cryptography"
)
def _sha256_hex(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def _sha256_stream(fobj) -> str:
h = hashlib.sha256()
while True:
chunk = fobj.read(STREAM_BUF)
if not chunk:
break
h.update(chunk)
return h.hexdigest()
def _resolve_label(obj: dict, locale: str | None) -> str:
fallback = obj.get("label", "")
if not locale:
return fallback
labels = {k.lower(): v for k, v in (obj.get("labels") or {}).items()}
lc = locale.lower()
return labels.get(lc) or labels.get(lc.split("-")[0]) or fallback
def _check_zip_methods(zf: zipfile.ZipFile):
for info in zf.infolist():
if info.compress_type not in ALLOWED_METHODS:
print(
f"WARNING: entry '{info.filename}' uses compression method "
f"{info.compress_type} which is not permitted by the spec."
)
def _warn_version(v):
if v is not None and v != FORMAT_VERSION:
print(
f"WARNING: formatVersion is {v}, this tool implements v{FORMAT_VERSION}. "
"Known fields will be read but the archive may be partially incompatible."
)
def _derive_key(password: str, salt: bytes) -> bytes:
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=KEY_LENGTH_BYTES,
salt=salt,
iterations=KDF_ITERATIONS,
backend=default_backend(),
)
return kdf.derive(password.encode("utf-8"))
def _encrypt_blob(plaintext: bytes, password: str) -> bytes:
salt = os.urandom(SALT_SIZE)
iv = os.urandom(IV_SIZE)
key = _derive_key(password, salt)
padder = padding.PKCS7(BLOCK_SIZE * 8).padder()
padded = padder.update(plaintext) + padder.finalize()
enc = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()).encryptor()
return salt + iv + enc.update(padded) + enc.finalize()
def _encrypt_stream(src_file: Path, dest_stream, password: str):
# Streaming encryption for large payloads (spec §5.2).
# Writes salt + iv + ciphertext directly into dest_stream.
salt = os.urandom(SALT_SIZE)
iv = os.urandom(IV_SIZE)
key = _derive_key(password, salt)
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()).encryptor()
padder = padding.PKCS7(BLOCK_SIZE * 8).padder()
dest_stream.write(salt)
dest_stream.write(iv)
with src_file.open("rb") as f:
while True:
chunk = f.read(STREAM_BUF)
if not chunk:
break
dest_stream.write(cipher.update(padder.update(chunk)))
dest_stream.write(cipher.update(padder.finalize()))
dest_stream.write(cipher.finalize())
def _decrypt_blob(blob: bytes, password: str) -> bytes | None:
if len(blob) < SALT_SIZE + IV_SIZE + BLOCK_SIZE:
return None
salt = blob[:SALT_SIZE]
iv = blob[SALT_SIZE:SALT_SIZE + IV_SIZE]
ciphertext = blob[SALT_SIZE + IV_SIZE:]
key = _derive_key(password, salt)
dec = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend()).decryptor()
try:
padded = dec.update(ciphertext) + dec.finalize()
unpadder = padding.PKCS7(BLOCK_SIZE * 8).unpadder()
return unpadder.update(padded) + unpadder.finalize()
except Exception:
return None
def _verify_password(zf: zipfile.ZipFile, password: str) -> tuple[bool, dict | None]:
# spec §7: decrypt manifest.enc, check for format field
try:
blob = zf.read(MANIFEST_ENC)
except KeyError:
return False, None
plain = _decrypt_blob(blob, password)
if plain is None:
return False, None
try:
obj = json.loads(plain.decode("utf-8"))
if obj.get("format") == FORMAT_NAME:
return True, obj
except (json.JSONDecodeError, UnicodeDecodeError):
pass
return False, None
def _load_icon(path: str) -> bytes:
raw = Path(path).read_bytes()
try:
from PIL import Image
img = Image.open(io.BytesIO(raw)).convert("RGBA")
img = img.resize((192, 192), Image.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="WEBP", quality=80)
return buf.getvalue()
except ImportError:
if not path.lower().endswith(".webp"):
print(
"WARNING: icon is not .webp and Pillow is not installed. "
"Storing as-is. Install Pillow for automatic conversion."
)
return raw
def _normalize_icon(raw: bytes) -> bytes:
try:
from PIL import Image
img = Image.open(io.BytesIO(raw)).convert("RGBA")
img = img.resize((192, 192), Image.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="WEBP", quality=80)
return buf.getvalue()
except ImportError:
return raw
except Exception as e:
print(f"WARNING: icon conversion failed ({e}), storing raw bytes.")
return raw
def _write_plain(output: Path, manifest_bytes: bytes, apk_data: dict, icon_bytes: bytes | None):
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as zf:
zf.writestr(MANIFEST_PLAIN, manifest_bytes)
if icon_bytes:
zf.writestr(zipfile.ZipInfo(ICON_PLAIN), icon_bytes, compress_type=zipfile.ZIP_STORED)
for name, data in apk_data.items():
zf.writestr(zipfile.ZipInfo(name), data, compress_type=zipfile.ZIP_DEFLATED)
def _write_encrypted(
output: Path,
manifest: dict,
manifest_bytes: bytes,
apk_data: dict,
icon_bytes: bytes | None,
password: str,
now_ms: int,
):
header = {
"packageName": manifest["packageName"],
"versionName": manifest["versionName"],
"label": manifest["label"],
"encrypted": True,
"hasIcon": manifest["hasIcon"],
"exportedAt": now_ms,
}
if manifest.get("labels"):
header["labels"] = manifest["labels"]
if manifest.get("_comment"):
header["_comment"] = manifest["_comment"]
enc_manifest = _encrypt_blob(manifest_bytes, password)
enc_icon = _encrypt_blob(icon_bytes, password) if icon_bytes else None
# Build the inner payload ZIP to a temp file, then stream-encrypt it into
# the outer archive. This avoids loading the entire payload into memory
# at once, which matters for large apps (spec §5.2).
with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp:
tmp_path = Path(tmp.name)
try:
with zipfile.ZipFile(tmp_path, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True) as inner:
for name, data in apk_data.items():
inner.writestr(zipfile.ZipInfo(name), data, compress_type=zipfile.ZIP_DEFLATED)
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED, allowZip64=True) as zf:
zf.writestr(zipfile.ZipInfo(SENTINEL_ENTRY), b"")
zf.writestr(HEADER_JSON, json.dumps(header, indent=2, ensure_ascii=False).encode("utf-8"))
zf.writestr(zipfile.ZipInfo(MANIFEST_ENC), enc_manifest, compress_type=zipfile.ZIP_STORED)
if enc_icon:
zf.writestr(zipfile.ZipInfo(ICON_ENC), enc_icon, compress_type=zipfile.ZIP_STORED)
with zf.open(zipfile.ZipInfo(PAYLOAD_ENC), "w") as payload_entry:
_encrypt_stream(tmp_path, payload_entry, password)
finally:
tmp_path.unlink(missing_ok=True)
def cmd_pack(args):
apk_paths = [Path(p) for p in args.apks]
for p in apk_paths:
if not p.exists():
sys.exit(f"APK not found: {p}")
password = args.password
encrypted = bool(password)
if encrypted:
_require_crypto()
output = Path(args.output) if args.output else Path(f"{args.package}.apkv")
apk_data = {}
checksums = {}
total_size = 0
for p in apk_paths:
data = p.read_bytes()
apk_data[p.name] = data
checksums[p.name] = f"sha256:{_sha256_hex(data)}"
total_size += len(data)
is_split = args.is_split if args.is_split is not None else len(apk_paths) > 1
now_ms = int(time.time() * 1000)
manifest = {
"format": FORMAT_NAME,
"formatVersion": FORMAT_VERSION,
"packageName": args.package,
"versionName": args.version_name,
"versionCode": args.version_code,
"label": args.label,
"isSplit": is_split,
"splits": [p.name for p in apk_paths],
"encrypted": encrypted,
"hasIcon": bool(args.icon),
"exportedAt": now_ms,
"minSdkVersion": args.min_sdk,
"targetSdkVersion": args.target_sdk,
"checksums": checksums,
"totalSize": total_size,
}
if args.comment:
manifest["_comment"] = args.comment
if args.permissions:
manifest["permissions"] = args.permissions
manifest_bytes = json.dumps(manifest, indent=2, ensure_ascii=False).encode("utf-8")
icon_bytes = _load_icon(args.icon) if args.icon else None
if encrypted:
_write_encrypted(output, manifest, manifest_bytes, apk_data, icon_bytes, password, now_ms)
else:
_write_plain(output, manifest_bytes, apk_data, icon_bytes)
print(f"Created: {output} ({'encrypted' if encrypted else 'plain'})")
def cmd_unpack(args):
src = Path(args.file)
if not src.exists():
sys.exit(f"File not found: {src}")
dest = Path(args.output) if args.output else src.parent / src.stem
dest.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(src, "r") as zf:
_check_zip_methods(zf)
names = {i.filename for i in zf.infolist()}
if SENTINEL_ENTRY in names:
_unpack_encrypted(zf, names, dest, args)
else:
_unpack_plain(zf, dest, args)
def _unpack_plain(zf: zipfile.ZipFile, dest: Path, args):
manifest_bytes = zf.read(MANIFEST_PLAIN)
manifest = json.loads(manifest_bytes.decode("utf-8"))
_warn_version(manifest.get("formatVersion"))
checksums = manifest.get("checksums", {})
(dest / MANIFEST_PLAIN).write_bytes(manifest_bytes)
print(f"Extracted: {MANIFEST_PLAIN}")
for name in manifest.get("splits", []):
try:
data = zf.read(name)
except KeyError:
print(f"WARNING: declared split '{name}' not found in archive, skipping.")
continue
_write_and_verify(dest, name, data, checksums)
if manifest.get("hasIcon") and not args.no_icon:
try:
(dest / ICON_PLAIN).write_bytes(zf.read(ICON_PLAIN))
print(f"Extracted: {ICON_PLAIN}")
except KeyError:
pass
print(f"Done. Output: {dest}")
def _unpack_encrypted(zf: zipfile.ZipFile, names: set, dest: Path, args):
_require_crypto()
password = args.password
if not password:
import getpass
password = getpass.getpass("Password: ")
print("Verifying password...")
ok, manifest = _verify_password(zf, password)
if not ok:
sys.exit("Wrong password or corrupted archive.")
_warn_version(manifest.get("formatVersion"))
print("OK.")
manifest_bytes = json.dumps(manifest, indent=2, ensure_ascii=False).encode("utf-8")
(dest / MANIFEST_PLAIN).write_bytes(manifest_bytes)
print(f"Extracted: {MANIFEST_PLAIN}")
checksums = manifest.get("checksums", {})
if manifest.get("hasIcon") and ICON_ENC in names and not args.no_icon:
plain = _decrypt_blob(zf.read(ICON_ENC), password)
if plain:
(dest / ICON_PLAIN).write_bytes(plain)
print(f"Extracted: {ICON_PLAIN}")
else:
print("WARNING: could not decrypt icon.enc.")
print("Decrypting payload...")
payload_bytes = _decrypt_blob(zf.read(PAYLOAD_ENC), password)
if payload_bytes is None:
sys.exit("Failed to decrypt payload. Archive may be corrupted.")
try:
with zipfile.ZipFile(io.BytesIO(payload_bytes), "r") as inner:
for name in manifest.get("splits", []):
try:
data = inner.read(name)
except KeyError:
print(f"WARNING: '{name}' not in payload, skipping.")
continue
_write_and_verify(dest, name, data, checksums)
except zipfile.BadZipFile:
sys.exit("Decrypted payload is not a valid ZIP. Wrong password or corruption.")
finally:
# zero out the decrypted buffer (spec §10.3)
mv = memoryview(bytearray(payload_bytes))
for i in range(len(mv)):
mv[i] = 0
print(f"Done. Output: {dest}")
def _write_and_verify(dest: Path, name: str, data: bytes, checksums: dict):
(dest / name).write_bytes(data)
declared = checksums.get(name, "")
if declared.startswith("sha256:"):
actual = _sha256_hex(data)
if actual != declared[7:]:
print(
f"CHECKSUM MISMATCH: {name}\n"
f" declared: {declared}\n"
f" actual: sha256:{actual}"
)
else:
print(f"Extracted (OK): {name}")
return
print(f"Extracted: {name}")
def cmd_inspect(args):
src = Path(args.file)
if not src.exists():
sys.exit(f"File not found: {src}")
with zipfile.ZipFile(src, "r") as zf:
_check_zip_methods(zf)
names = {i.filename for i in zf.infolist()}
if SENTINEL_ENTRY in names:
if HEADER_JSON not in names:
sys.exit("header.json missing from encrypted archive.")
header = json.loads(zf.read(HEADER_JSON).decode("utf-8"))
label = _resolve_label(header, getattr(args, "locale", None))
print(f"Format : apkv v{FORMAT_VERSION} (encrypted)")
print(f"Package : {header.get('packageName')}")
print(f"Version : {header.get('versionName')}")
print(f"Label : {label}")
print(f"Has icon : {header.get('hasIcon')}")
_print_exported_at(header.get("exportedAt"))
print("(Full details require password — use the unpack command)")
else:
if MANIFEST_PLAIN not in names:
sys.exit("manifest.json not found — not a valid APKv archive.")
manifest = json.loads(zf.read(MANIFEST_PLAIN).decode("utf-8"))
_warn_version(manifest.get("formatVersion"))
label = _resolve_label(manifest, getattr(args, "locale", None))
print(f"Format : {manifest.get('format')} v{manifest.get('formatVersion')}")
print(f"Package : {manifest.get('packageName')}")
print(f"Version : {manifest.get('versionName')} (code {manifest.get('versionCode')})")
print(f"Label : {label}")
print(f"Min SDK : {manifest.get('minSdkVersion')}")
print(f"Target SDK : {manifest.get('targetSdkVersion')}")
print(f"Split : {manifest.get('isSplit')}")
print(f"Has icon : {manifest.get('hasIcon')}")
_print_exported_at(manifest.get("exportedAt"))
splits = manifest.get("splits", [])
print(f"APKs ({len(splits)}):")
for s in splits:
print(f" {s}")
if manifest.get("totalSize"):
print(f"Total size : {manifest['totalSize']:,} bytes (uncompressed)")
perms = manifest.get("permissions", [])
if perms:
if getattr(args, "verbose", False):
print(f"Permissions ({len(perms)}):")
for p in perms:
print(f" {p}")
else:
print(f"Permissions : {len(perms)} declared (--verbose to list)")
if manifest.get("checksums"):
print(f"Checksums : {len(manifest['checksums'])} declared")
def _print_exported_at(ts_ms):
if ts_ms:
import datetime
dt = datetime.datetime.fromtimestamp(ts_ms / 1000, tz=datetime.timezone.utc)
print(f"Exported at : {dt.isoformat()}")
def cmd_verify(args):
src = Path(args.file)
if not src.exists():
sys.exit(f"File not found: {src}")
with zipfile.ZipFile(src, "r") as zf:
names = {i.filename for i in zf.infolist()}
if SENTINEL_ENTRY in names:
_verify_encrypted(zf, names, args)
else:
_verify_plain(zf, names)
def _verify_plain(zf: zipfile.ZipFile, names: set):
if MANIFEST_PLAIN not in names:
sys.exit("manifest.json not found.")
manifest = json.loads(zf.read(MANIFEST_PLAIN).decode("utf-8"))
checksums = manifest.get("checksums", {})
if not checksums:
print("No checksums declared in manifest.json.")
return
_run_checksum_check(checksums, lambda name: zf.read(name), names)
def _verify_encrypted(zf: zipfile.ZipFile, names: set, args):
_require_crypto()
password = getattr(args, "password", None)
if not password:
import getpass
password = getpass.getpass("Password: ")
print("Verifying password...")
ok, manifest = _verify_password(zf, password)
if not ok:
sys.exit("Wrong password or corrupted archive.")
print("OK.")
checksums = manifest.get("checksums", {})
if not checksums:
print("No checksums declared in manifest.")
return
print("Decrypting payload...")
payload_bytes = _decrypt_blob(zf.read(PAYLOAD_ENC), password)
if payload_bytes is None:
sys.exit("Failed to decrypt payload.")
try:
with zipfile.ZipFile(io.BytesIO(payload_bytes), "r") as inner:
inner_names = {i.filename for i in inner.infolist()}
_run_checksum_check(checksums, lambda name: inner.read(name), inner_names)
except zipfile.BadZipFile:
sys.exit("Decrypted payload is not a valid ZIP.")
finally:
mv = memoryview(bytearray(payload_bytes))
for i in range(len(mv)):
mv[i] = 0
def _run_checksum_check(checksums: dict, read_fn, available_names: set):
all_ok = True
for apk_name, declared in checksums.items():
if apk_name not in available_names:
continue
if not declared.startswith("sha256:"):
print(f"SKIP {apk_name}: unknown checksum format")
continue
actual = _sha256_hex(read_fn(apk_name))
if actual == declared[7:]:
print(f"OK {apk_name}")
else:
print(f"FAIL {apk_name}")
print(f" declared: {declared}")
print(f" actual: sha256:{actual}")
all_ok = False
if all_ok:
print("All checksums passed.")
else:
print("\nWARNING: one or more checksums did not match.")
sys.exit(1)
def cmd_import(args):
src = Path(args.file)
if not src.exists():
sys.exit(f"File not found: {src}")
ext = src.suffix.lower()
out_path = Path(args.output) if args.output else src.with_suffix(".apkv")
if out_path == src:
out_path = src.with_name(src.stem + "_imported.apkv")
password = args.password
if password:
_require_crypto()
print(f"Source : {src}")
print(f"Output : {out_path}")
with tempfile.TemporaryDirectory() as tmpdir:
tmp = Path(tmpdir)
if ext == ".aab":
apks = _aab_to_apks(src, tmp, args)
_import_apks(apks, out_path, password, args, tmp)
elif ext == ".apks":
_import_apks(src, out_path, password, args, tmp)
elif ext == ".apkm":
_import_apkm(src, out_path, password, args, tmp)
elif ext == ".xapk":
_import_xapk(src, out_path, password, args, tmp)
elif ext == ".apkv":
_import_apkv(src, out_path, password, args)
else:
sys.exit(f"Unsupported source format '{ext}'. Supported: .apks .apkm .xapk .apkv .aab")
print(f"\nDone. Created: {out_path} ({'encrypted' if password else 'plain'})")
def _aab_to_apks(aab: Path, tmp: Path, args) -> Path:
print("Converting .aab to .apks via bundletool...")
bt = _find_bundletool(getattr(args, "bundletool", None))
out = tmp / (aab.stem + ".apks")
cmd = f'{bt} build-apks --bundle="{aab}" --output="{out}" --mode=universal'
ks = getattr(args, "keystore", None)
if ks:
cmd += (
f' --ks="{ks}"'
f' --ks-pass="pass:{getattr(args, "ks_pass", "android")}"'
f' --key-pass="pass:{getattr(args, "key_pass", "android")}"'
f' --ks-key-alias="{getattr(args, "ks_alias", "androiddebugkey")}"'
)
ret = subprocess.run(cmd, shell=True, capture_output=True, text=True)
if ret.returncode != 0:
print(ret.stdout)
print(ret.stderr)
sys.exit("bundletool failed.")
if not out.exists():
sys.exit("bundletool did not produce an .apks file.")
print(f" Produced: {out}")
return out
def _find_bundletool(hint: str | None) -> str:
if hint:
p = Path(hint)
if not p.exists():
sys.exit(f"bundletool not found at: {hint}")
if p.suffix.lower() == ".jar":
java = shutil.which("java")
if not java:
sys.exit("'java' not found on PATH, needed to run bundletool.jar.")
return f'java -jar "{p}"'
return str(p)
if shutil.which("bundletool"):
return "bundletool"
for search in [Path.cwd(), Path(__file__).parent]:
jar = search / "bundletool.jar"
if jar.exists():
java = shutil.which("java")
if not java:
sys.exit("'java' not found on PATH, needed to run bundletool.jar.")
return f'java -jar "{jar}"'
sys.exit(
"bundletool not found. Download from https://github.com/google/bundletool/releases "
"or pass --bundletool <path>."
)
def _import_apks(apks: Path, out: Path, password: str | None, args, tmp: Path):
print("Reading .apks...")
apk_data = {}
with zipfile.ZipFile(apks, "r") as zf:
for info in zf.infolist():
if not info.is_dir() and info.filename.lower().endswith(".apk"):
apk_data[Path(info.filename).name] = zf.read(info.filename)
if not apk_data:
sys.exit("No .apk entries found inside the .apks archive.")
base_key = next((k for k in apk_data if k.lower() == "base.apk"), next(iter(apk_data)))
meta = _meta_from_apk(apk_data[base_key], tmp)
pkg = _package_from_toc(apks)
if pkg:
meta["packageName"] = pkg
_finalize_and_write(meta, apk_data, out, password, args)
def _package_from_toc(apks: Path) -> str:
try:
with zipfile.ZipFile(apks, "r") as zf:
try:
data = zf.read("toc.pb")
except KeyError:
return ""
pos = 0
while pos < len(data):
tag, pos = _varint(data, pos)
wt = tag & 7
if wt == 0:
_, pos = _varint(data, pos)
elif wt == 1:
pos += 8
elif wt == 2:
length, pos = _varint(data, pos)
end = pos + length
if 4 <= length <= 200:
candidate = data[pos:end].decode("utf-8", errors="replace")
if "." in candidate and not candidate.startswith(".") \
and candidate.replace(".", "").replace("_", "").isalnum():
return candidate
pos = end
elif wt == 5:
pos += 4
else:
break
except Exception:
pass
return ""
def _varint(data: bytes, pos: int) -> tuple[int, int]:
result = shift = 0
while pos < len(data):
b = data[pos]; pos += 1
result |= (b & 0x7F) << shift
if not (b & 0x80):
break
shift += 7
return result, pos
def _import_apkm(apkm: Path, out: Path, password: str | None, args, tmp: Path):
print("Reading .apkm...")
apk_data = {}
meta = {}
icon_bytes = None
with zipfile.ZipFile(apkm, "r") as zf:
for info in zf.infolist():
low = info.filename.lower()
if low == "info.json":
try:
raw = zf.read(info.filename).decode("utf-8").strip().lstrip("\ufeff")
obj = json.loads(raw)
meta["packageName"] = obj.get("pname", "")
meta["versionName"] = obj.get("release_version", "")
meta["label"] = obj.get("app_name", "")
except Exception as e:
print(f"WARNING: could not parse info.json: {e}")
elif low == "icon.png" and icon_bytes is None:
icon_bytes = zf.read(info.filename)
elif low.endswith(".apk") and not info.is_dir():
apk_data[Path(info.filename).name] = zf.read(info.filename)
if not apk_data:
sys.exit("No .apk entries found inside the .apkm archive.")
if not meta.get("packageName"):
base_key = next((k for k in apk_data if k.lower() == "base.apk"), next(iter(apk_data)))
meta.update(_meta_from_apk(apk_data[base_key], tmp))
_finalize_and_write(meta, apk_data, out, password, args, icon_bytes=icon_bytes)
def _import_xapk(xapk: Path, out: Path, password: str | None, args, tmp: Path):
print("Reading .xapk...")
apk_data = {}
xmeta = {}
icon_bytes = None
with zipfile.ZipFile(xapk, "r") as zf:
for info in zf.infolist():
name = info.filename.replace("\\", "/").lstrip("/")
if name.lower() == "manifest.json" and not info.is_dir():
try:
xmeta = json.loads(zf.read(info.filename).decode("utf-8", errors="replace").lstrip("\ufeff"))
except Exception as e:
print(f"WARNING: could not parse xapk manifest: {e}")
split_files = {e.get("file", "").replace("\\", "/").lstrip("/") for e in xmeta.get("split_apks", [])}
icon_hint = xmeta.get("icon", "icon.png").replace("\\", "/").lstrip("/")
for info in zf.infolist():
if info.is_dir():
continue
name = info.filename.replace("\\", "/").lstrip("/")
low = name.lower()
if low.endswith(".apk") and (not split_files or name in split_files or Path(name).name in split_files):
apk_data[Path(name).name] = zf.read(info.filename)
if icon_bytes is None and (name == icon_hint or low in ("icon.png", "icon.webp")):
icon_bytes = zf.read(info.filename)
if not apk_data:
sys.exit("No .apk entries found inside the .xapk archive.")
meta = {
"packageName": xmeta.get("package_name", ""),
"versionName": xmeta.get("version_name", ""),
"versionCode": int(xmeta.get("version_code", 0) or 0),
"label": xmeta.get("name", ""),
"minSdk": int(xmeta.get("min_sdk_version", 0) or 0) or None,
"targetSdk": int(xmeta.get("target_sdk_version", 0) or 0) or None,
}
if not meta["packageName"]:
base_key = next((k for k in apk_data if k.lower() == "base.apk"), next(iter(apk_data)))
meta.update(_meta_from_apk(apk_data[base_key], tmp))
_finalize_and_write(meta, apk_data, out, password, args, icon_bytes=icon_bytes)
def _import_apkv(src: Path, out: Path, password: str | None, args):
print("Reading source .apkv...")
with zipfile.ZipFile(src, "r") as zf:
_check_zip_methods(zf)
names = {i.filename for i in zf.infolist()}
if SENTINEL_ENTRY in names:
_require_crypto()
src_pw = getattr(args, "source_password", None) or ""
if not src_pw:
import getpass
src_pw = getpass.getpass("Source .apkv password: ")
ok, manifest = _verify_password(zf, src_pw)
if not ok:
sys.exit("Wrong source password or corrupted archive.")
icon_bytes = None
if manifest.get("hasIcon") and ICON_ENC in names:
icon_bytes = _decrypt_blob(zf.read(ICON_ENC), src_pw)
payload = _decrypt_blob(zf.read(PAYLOAD_ENC), src_pw)
if payload is None:
sys.exit("Failed to decrypt payload.")
apk_data = {}
with zipfile.ZipFile(io.BytesIO(payload), "r") as inner:
for info in inner.infolist():
if not info.is_dir() and info.filename.lower().endswith(".apk"):
apk_data[info.filename] = inner.read(info.filename)
else:
manifest = json.loads(zf.read(MANIFEST_PLAIN).decode("utf-8"))
icon_bytes = zf.read(ICON_PLAIN) if manifest.get("hasIcon") and ICON_PLAIN in names else None
apk_data = {}
for split in manifest.get("splits", []):
try:
apk_data[split] = zf.read(split)
except KeyError:
print(f"WARNING: declared split '{split}' not found, skipping.")
meta = {
"packageName": manifest.get("packageName", ""),
"versionName": manifest.get("versionName", ""),
"versionCode": manifest.get("versionCode", 0),
"label": manifest.get("label", ""),
"minSdk": manifest.get("minSdkVersion", 21),
"targetSdk": manifest.get("targetSdkVersion", 34),
"permissions": manifest.get("permissions"),
}
_finalize_and_write(meta, apk_data, out, password, args, icon_bytes=icon_bytes)
def _finalize_and_write(
meta: dict,
apk_data: dict,
out: Path,
password: str | None,
args,
icon_bytes: bytes | None = None,
):
pkg = meta.get("packageName") or getattr(args, "package", None) or "unknown.package"
ver = meta.get("versionName") or getattr(args, "version_name", None) or "0"
code = int(meta.get("versionCode") or getattr(args, "version_code", None) or 0)
label = meta.get("label") or getattr(args, "label", None) or pkg
min_sdk = int(meta.get("minSdk") or getattr(args, "min_sdk", None) or 21)
tgt_sdk = int(meta.get("targetSdk") or getattr(args, "target_sdk", None) or 34)
perms = meta.get("permissions")
if getattr(args, "package", None): pkg = args.package
if getattr(args, "version_name", None): ver = args.version_name
if getattr(args, "version_code", None) is not None: code = args.version_code
if getattr(args, "label", None): label = args.label
if getattr(args, "min_sdk", None): min_sdk = args.min_sdk
if getattr(args, "target_sdk", None): tgt_sdk = args.target_sdk
if icon_bytes is None and meta.get("icon_bytes"):
icon_bytes = meta["icon_bytes"]
if icon_bytes:
icon_bytes = _normalize_icon(icon_bytes)
encrypted = bool(password)
checksums = {n: f"sha256:{_sha256_hex(d)}" for n, d in apk_data.items()}
total_size = sum(len(d) for d in apk_data.values())
now_ms = int(time.time() * 1000)
manifest = {
"_comment": f"Imported by apkv.py on {time.strftime('%Y-%m-%d')}",
"format": FORMAT_NAME,
"formatVersion": FORMAT_VERSION,
"packageName": pkg,
"versionName": ver,
"versionCode": code,
"label": label,
"isSplit": len(apk_data) > 1,
"splits": list(apk_data.keys()),
"encrypted": encrypted,
"hasIcon": icon_bytes is not None,
"exportedAt": now_ms,
"minSdkVersion": min_sdk,
"targetSdkVersion": tgt_sdk,
"checksums": checksums,
"totalSize": total_size,
}
if perms:
manifest["permissions"] = perms
manifest_bytes = json.dumps(manifest, indent=2, ensure_ascii=False).encode("utf-8")
print(f"\nPackage : {pkg}")
print(f"Version : {ver} (code {code})")
print(f"Label : {label}")
print(f"Splits : {len(apk_data)} ({', '.join(apk_data)})")
print(f"Min SDK : {min_sdk} Target SDK: {tgt_sdk}")
print(f"Icon : {'yes' if icon_bytes else 'no'}")
print(f"Encrypt : {'yes' if encrypted else 'no'}")
print()
if encrypted:
_write_encrypted(out, manifest, manifest_bytes, apk_data, icon_bytes, password, now_ms)
else:
_write_plain(out, manifest_bytes, apk_data, icon_bytes)
# Binary AndroidManifest.xml parser (AXML)
_ANDROID_ATTR_IDS = {
0x0101021B: "versionCode",
0x0101021C: "versionName",
0x0101020C: "minSdkVersion",
0x01010270: "targetSdkVersion",
0x01010001: "label",
0x01010002: "icon",
}
_ICON_DENSITY_ORDER = [
"mipmap-xxxhdpi", "mipmap-xxhdpi", "mipmap-xhdpi", "mipmap-hdpi", "mipmap-mdpi",
"mipmap-anydpi", "mipmap",
"drawable-xxxhdpi", "drawable-xxhdpi", "drawable-xhdpi", "drawable-hdpi",
"drawable-mdpi", "drawable-anydpi", "drawable",
]
_ICON_NAME_ORDER = [
"ic_launcher_round", "ic_launcher_foreground", "ic_launcher",
"app_icon", "icon", "launcher",
]
_AXML_MAGIC = 0x00080003
_STRING_POOL = 0x001C0001
_XML_START_EL = 0x00100102
_TYPE_STRING = 0x03
_TYPE_REF = 0x01
_TYPE_INT_DEC = 0x10
_TYPE_INT_HEX = 0x11
_TYPE_BOOL = 0x12
def _meta_from_apk(apk_bytes: bytes, tmp: Path) -> dict:
meta = {"packageName": "", "versionName": "", "versionCode": 0,
"label": "", "minSdk": 21, "targetSdk": 34, "icon_bytes": None}
try:
with zipfile.ZipFile(io.BytesIO(apk_bytes), "r") as zf:
try:
axml = zf.read("AndroidManifest.xml")
except KeyError:
return meta
meta.update(_parse_axml(axml))
if meta["icon_bytes"] is None:
meta["icon_bytes"] = _pick_icon(zf)
except Exception as e:
print(f"WARNING: could not parse APK metadata: {e}")
return meta
def _pick_icon(zf: zipfile.ZipFile) -> bytes | None:
best_d = best_n = float("inf")
best = None
for info in zf.infolist():
if info.is_dir():
continue
name = info.filename.replace("\\", "/").lstrip("/")
lower = name.lower()
if not lower.startswith("res/") or not (lower.endswith(".png") or lower.endswith(".webp")):
continue
parts = name.split("/")
if len(parts) < 3:
continue
folder = parts[1].lower()
fname = parts[-1].lower().rsplit(".", 1)[0]
try:
d = next(i for i, x in enumerate(_ICON_DENSITY_ORDER) if folder == x.lower())
except StopIteration:
continue
try:
n = next(i for i, x in enumerate(_ICON_NAME_ORDER) if fname == x.lower() or fname.startswith(x.lower()))
except StopIteration:
continue
if d < best_d or (d == best_d and n < best_n):
best_d, best_n, best = d, n, zf.read(info.filename)
return best
def _parse_axml(data: bytes) -> dict:
result = {}
if len(data) < 8 or struct.unpack_from("<I", data, 0)[0] != _AXML_MAGIC:
return result
strings = []
pos = 8
while pos + 8 <= len(data):
chunk_type = struct.unpack_from("<I", data, pos)[0]