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
| from typing import List import argparse import pathlib import hashlib import struct import sys import zipfile import zlib
try: import zstandard except ImportError as exc: raise SystemExit("missing dependency: zstandard") from exc
try: from gmssl.sm4 import CryptSM4, SM4_DECRYPT except ImportError as exc: raise SystemExit("missing dependency: gmssl") from exc
DEXDATA_MAGIC = b"dexdata0" FDEX_MAGIC = b"fdex" CODEMAP_MAGIC = b"BBbb.dgc" DEFAULT_KEY = bytes([ 0x66, 0x97, 0x6C, 0xE8, 0x6D, 0x46, 0x38, 0xB0, 0x09, 0x5A, 0xA5, 0xD7, 0x0F, 0xCB, 0x9A, 0xA0, ])
def sm4_decrypt_ecb_nopad(key: bytes, ciphertext: bytes) -> bytes: sm4 = CryptSM4() sm4.set_key(key, SM4_DECRYPT) out = [] for i in range(0, len(ciphertext), 16): block = list(ciphertext[i:i + 16]) out += sm4.one_round(sm4.sk, block) return bytes(out)
def read_be32(buf: bytes, off: int) -> int: return struct.unpack_from(">I", buf, off)[0]
def write_uleb128(buf: bytearray, off: int, value: int) -> int: count = 0 while value >> 7: buf[off + count] = (value & 0x7F) | 0x80 value >>= 7 count += 1 if count == 4: buf[off + count] = value & 0x7F return count + 1 buf[off + count] = value & 0x7F return count + 1
def derive_key(package_name: str) -> bytes: key = bytearray(DEFAULT_KEY) salt = package_name.encode("utf-8") for i in range(min(0x10, len(salt))): key[i] ^= salt[i] return bytes(key)
def load_input_blob(path: pathlib.Path) -> bytes: data = path.read_bytes() if zipfile.is_zipfile(path): with zipfile.ZipFile(path, "r") as zf: if "classes.dex" not in zf.namelist(): raise SystemExit(f"{path} is zip/jar but has no classes.dex") data = zf.read("classes.dex") return data
def extract_dexdata_container(raw: bytes) -> bytes: start = raw.find(DEXDATA_MAGIC) if start < 0: raise SystemExit("dexdata0 not found")
return expand_stage1_payload(raw[start + 0x0C:])
def expand_stage1_payload(payload: bytes) -> bytes: copy_len = read_be32(payload, 0x00) compress_len = read_be32(payload, 0x04) compress_out_len = read_be32(payload, 0x08) comp_off = 0x0C + copy_len comp_end = comp_off + compress_len if comp_end > len(payload): raise SystemExit( f"invalid stage1 sizes: copy={copy_len:#x} comp={compress_len:#x} " f"out={compress_out_len:#x} payload={len(payload):#x}" ) comp = payload[comp_off:comp_end] out = zstandard.ZstdDecompressor().decompress(comp, max_output_size=compress_out_len) return payload[0x0C:0x0C + copy_len] + out
def extract_dexdata_container_from_fdex(raw: bytes) -> bytes: if not raw.startswith(b"dex\n") or len(raw) < 0x28: raise ValueError("not a dex file")
file_size = struct.unpack_from("<I", raw, 0x20)[0] if file_size < 0x28 or file_size > len(raw): raise ValueError("invalid dex file_size") if raw[file_size - 4:file_size] != FDEX_MAGIC: raise ValueError("fdex trailer not found")
table_off = struct.unpack_from("<I", raw, file_size - 8)[0] if table_off >= file_size - 8: raise ValueError("invalid fdex table offset")
count = struct.unpack_from("<I", raw, table_off)[0] entry = table_off + 4 for _ in range(count): if entry + 8 > file_size: break entry_size = struct.unpack_from("<I", raw, entry)[0] name_len = struct.unpack_from("<I", raw, entry + 4)[0] name_off = entry + 8 if entry_size < 8 + name_len + 4 or entry + entry_size > file_size: break
name = raw[name_off:name_off + name_len] if name == DEXDATA_MAGIC: payload_size = struct.unpack_from(">I", raw, name_off + name_len)[0] payload_off = name_off + name_len + 4 payload = raw[payload_off:payload_off + payload_size] if len(payload) != payload_size: raise SystemExit("dexdata0 payload truncated") return expand_stage1_payload(payload)
entry += entry_size
raise ValueError("dexdata0 fdex entry not found")
def load_stage1_container(raw: bytes) -> bytes: try: return extract_dexdata_container_from_fdex(raw) except ValueError: pass if DEXDATA_MAGIC in raw: return extract_dexdata_container(raw) return raw
def relocate_codeitems(dex: bytes) -> bytes: off = dex.rfind(CODEMAP_MAGIC) if off < 4: raise SystemExit("BBbb.dgc not found")
off1 = read_be32(dex, off - 4) code_map_start = off - 0x20 - off1 item_size = read_be32(dex, code_map_start + 0x08) itemdata_len = read_be32(dex, code_map_start + 0x0C) data_off = read_be32(dex, code_map_start + 0x10) item_count = itemdata_len // item_size
out = bytearray(dex) for i in range(item_count): item_off = code_map_start + 0x18 + item_size * i code_off = code_map_start + data_off + read_be32(out, item_off) base = read_be32(out, item_off + 0x10) write_uleb128(out, base, code_off)
out[0x0C:0x20] = hashlib.sha1(out[0x20:]).digest() checksum = zlib.adler32(out[0x0C:]) & 0xFFFFFFFF out[0x08:0x0C] = struct.pack("<I", checksum) return bytes(out)
def repair_dumped_dex_dir(in_dir: pathlib.Path, out_dir: pathlib.Path) -> None: files = sorted( in_dir.glob("dex_*.dex"), key=lambda p: int(p.name.split("_")[1]) if len(p.name.split("_")) > 2 else p.name, ) if not files: raise SystemExit(f"no dex_*.dex found in {in_dir}")
repaired = 0 copied = 0 for path in files: raw = path.read_bytes() out_path = out_dir / path.name if CODEMAP_MAGIC in raw: fixed = relocate_codeitems(raw) out_path.write_bytes(fixed) repaired += 1 print(f"[+] repaired {path.name} -> {out_path}") else: out_path.write_bytes(raw) copied += 1 print(f"[=] copied {path.name} -> {out_path}")
print(f"[+] total={len(files)} repaired={repaired} copied={copied}")
def split_and_decrypt_dexes(deccom: bytes, dex_count: int, key: bytes, decrypt_size: int) -> List[bytes]: table_off = 0x1000 - dex_count * 0x10 out = [] for i in range(dex_count): off = read_be32(deccom, table_off + 0x10 * i) size = read_be32(deccom, table_off + 0x10 * i + 4) if size == 0: continue start = 0x1000 + off end = start + size dex = deccom[start:end] if len(dex) != size: raise SystemExit(f"dex[{i}] truncated: expect {size:#x}, got {len(dex):#x}")
head_size = min(decrypt_size, len(dex)) if head_size % 16 != 0: head_size -= head_size % 16 if head_size <= 0: raise SystemExit(f"dex[{i}] too small to decrypt")
plain = sm4_decrypt_ecb_nopad(key, dex[:head_size]) + dex[head_size:] out.append(plain) return out
def main() -> int: parser = argparse.ArgumentParser(description="Recover dexes from Bangbang DexHelper container") parser.add_argument("input", nargs="?", help="shell dex or dumped .cache/classes.jar") parser.add_argument("--dumped-dir", help="directory containing already dumped dex_*.dex files") parser.add_argument("-p", "--package", default="com.chinamworld.main", help="package name used to derive SM4 key") parser.add_argument("-n", "--dex-count", type=int, default=10, help="number of embedded dex files") parser.add_argument("-o", "--out-dir", default="dexhelper_out", help="output directory") parser.add_argument("--decrypt-size", type=lambda x: int(x, 0), default=0x20000, help="SM4 decrypt size per dex") args = parser.parse_args()
out_dir = pathlib.Path(args.out_dir) out_dir.mkdir(parents=True, exist_ok=True)
if args.dumped_dir: repair_dumped_dex_dir(pathlib.Path(args.dumped_dir), out_dir) return 0
if not args.input: parser.error("input is required unless --dumped-dir is used")
in_path = pathlib.Path(args.input) raw = load_input_blob(in_path) deccom = load_stage1_container(raw) (out_dir / "deccom.bin").write_bytes(deccom)
key = derive_key(args.package) dexes = split_and_decrypt_dexes(deccom, args.dex_count, key, args.decrypt_size) if not dexes: raise SystemExit("no dex extracted")
for i, dex in enumerate(dexes): raw_path = out_dir / f"dex_{i}.dex" raw_path.write_bytes(dex) fixed = relocate_codeitems(dex) (out_dir / f"dex_out_{i}.dex").write_bytes(fixed) print(f"[+] wrote {raw_path}") print(f"[+] wrote {out_dir / f'dex_out_{i}.dex'}")
return 0
if __name__ == "__main__": sys.exit(main())
|