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
| import os import zlib import shutil import hashlib import logging
from io import BufferedReader, BufferedRandom from zipfile import ZipFile
import click from cryptography.hazmat.primitives import padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
class QC: def __init__(self, apk, work_dir, key, out=None) -> None: """ param: apk: apk path to modify dir: work dir to save files in the process key: the aes ecb key to de/en-crypt dex """ self.work_path = self.clean_path(work_dir + '/') self.unzip_apk_path = self.clean_path(os.path.join(work_dir, os.path.basename(apk)[:-4])) self.original_path = self.clean_path(os.path.join(work_dir, 'original/')) self.decrypted_path = self.clean_path(os.path.join(work_dir, 'decrypted/')) self.baksmali_path = os.path.join(work_dir, 'baksmali/') self.updated_path = os.path.join(work_dir, 'updated/') self.encrypted_path = self.clean_path(os.path.join(work_dir, 'encrypted/'))
logging.info('Start Unpack apk') self.qcapk = ZipFile(apk, mode='r') self.qcapk.extract("classes.dex", path=self.unzip_apk_path) self.classes_path = os.path.join(self.unzip_apk_path, 'classes.dex') self.dex_dict = {}
self.key = key.encode('utf8')
self.outapk = self.work_path + out + '.apk' self.outzip = self.work_path + out + '.zip' shutil.copyfile(apk, self.outzip)
@staticmethod def clean_path(p): if os.path.exists(p): shutil.rmtree(p) os.mkdir(p) return p
@staticmethod def checksum(dexf: BufferedRandom): """ Update checksum of dex file
param: dexf: the file-object of dex file """ dexf.seek(8) sourceData = dexf.read(4) dexf.seek(12) checkdata = dexf.read() checksum = zlib.adler32(checkdata) checkBytes = (checksum & 0xffffffff).to_bytes(4, byteorder='little') logging.info("checksum: " + sourceData.hex() + " -> " + checkBytes.hex()) if dexf.writable and sourceData != checkBytes: dexf.seek(8) dexf.write(checkBytes)
@staticmethod def signature(dexf: BufferedRandom): """ Update signature of dex file
param: dexf: the file-object of dex file """ dexf.seek(12) sourceData = dexf.read(20) dexf.seek(32) sigdata = dexf.read() sha1 = hashlib.sha1() sha1.update(sigdata) sha2 = sha1.digest() logging.info("signature: " + sourceData.hex() + " -> " + sha2.hex()) if dexf.writable and sourceData != sha2: dexf.seek(12) dexf.write(sha2)
def splitdex(self, dexf: BufferedReader): """ Split original classes.dex file
param: dexf: the file-object of dex file """ dexf.seek(0x20) length = int.from_bytes(dexf.read(4), byteorder='little') dexf.seek(length - 4) index_length = int.from_bytes(dexf.read(4), byteorder='big') dexf.seek(length - 4 - index_length) _tmp = dexf.read(index_length).decode('utf8') info = "".join(_tmp[i] for i in range(1, len(_tmp), 2)) for di in info.split('-'): self.dex_dict[di.split('=')[0]] = int(di.split('=')[1]) dex_start = length - 4 - index_length for dex_name in self.dex_dict: dex_length = self.dex_dict[dex_name] dex_start = dex_start - dex_length with open(self.original_path + 'shell.dex', 'wb') as sf: dexf.seek(0) sf.write(dexf.read(dex_start)) for dex_name in self.dex_dict: dex_length = self.dex_dict[dex_name] with open(self.original_path + dex_name, 'wb') as cf: dexf.seek(dex_start) cf.write(dexf.read(dex_length)) dex_start = dex_start + dex_length
def decdex(self, dex_name: str): """ Decrypt dex
param: the dex name to be dec """ with open(self.original_path + dex_name, 'rb') as e: bencdata = e.read() decryptor = Cipher(algorithms.AES(self.key), modes.ECB()).decryptor() dexraw = decryptor.update(bencdata) + decryptor.finalize() unpadder = padding.PKCS7(128).unpadder() bdecdex = unpadder.update(dexraw) + unpadder.finalize() with open(self.decrypted_path + dex_name, 'wb') as d: d.write(bdecdex)
def encdex(self, dex_name: str): """ Encrypt dex
param: the dex name to be enc """ with open(self.updated_path + dex_name, 'rb') as e: bdecdata = e.read() padder = padding.PKCS7(128).padder() bpaddata = padder.update(bdecdata) + padder.finalize() encryptor = Cipher(algorithms.AES(self.key), modes.ECB()).encryptor() bencdex = encryptor.update(bpaddata) + encryptor.finalize() with open(self.encrypted_path + dex_name, 'wb') as d: return d.write(bencdex)
def repdex(self, dex_path, dex_name): """ Repair signature and checksum of dex
param: dex_path: the dex path dex_name: the dex name """ logging.info(f'Start Repair {dex_path + dex_name}') with open(dex_path + dex_name, 'r+b') as dexf: self.signature(dexf) self.checksum(dexf)
def baksmali(self): """ apply baksmali.jar, from decrypted_path to baksmali_path """ dec_name = self.work_path + 'decrypted' shutil.make_archive(dec_name, 'zip', self.decrypted_path) os.system(f'java -jar bin/apktool.jar d {dec_name}.zip -o {self.baksmali_path}')
def smali(self): """ apply smali.jar, from baksmali_path to updated_path """ bak_path = self.work_path + 'baksmali.zip' os.system(f'java -jar bin/apktool.jar b {self.baksmali_path} -o {bak_path}') shutil.unpack_archive(bak_path, self.updated_path, 'zip')
def write_out(self): """ merge all classes to one classes use the original encrypt type """ with open(self.work_path + 'classes.dex', 'w+b') as dexf: with open(self.original_path + 'shell.dex', 'rb') as sf: shell_length = dexf.write(sf.read()) for dex_name in self.dex_dict: dex_length = self.encdex(dex_name) self.dex_dict[dex_name] = dex_length with open(self.encrypted_path + dex_name, 'rb') as df: dexf.write(df.read()) dex_list = map(lambda x: x + '=' + str(self.dex_dict[x]), self.dex_dict) dex_index = ("." + ".".join(i for i in '-'.join(list(dex_list)))).encode('utf8') dexf.write(dex_index) index_length = len(dex_index).to_bytes(4, byteorder='big') dexf.write(index_length) dexf.seek(0x20) length = shell_length + sum(self.dex_dict.values()) + len(dex_index) + 4 dexf.write(length.to_bytes(4, byteorder='little')) self.repdex(self.work_path, 'classes.dex')
def pack_sign(self): """ Zip and Sign :return: """ shutil.move(self.work_path + 'classes.dex', 'classes.dex') logging.info(f'Start pack to {self.outapk}') os.system(f"bin\\7za d {self.outzip} classes.dex > nul") os.system(f"bin\\7za a {self.outzip} classes.dex > nul") os.rename(self.outzip, self.outapk) logging.info(f'Start sign {self.outapk}') os.system(f'apksigner.bat sign --ks bin/release.jks --ks-pass pass:123456 ' f'--min-sdk-version 22 {self.outapk}') shutil.move('classes.dex', self.work_path + 'classes.dex')
def break_dex(self): """ command d: splitdex + decrypt + baksmali """ with open(self.classes_path, 'rb') as cf: logging.info('Start Split original classes.dex') self.splitdex(cf) for dex_name in self.dex_dict: logging.info(f'Start Decrypt {dex_name}') self.decdex(dex_name) logging.info('Start Baksmali dex to smali') self.baksmali()
def replace(self): """ command r: replace ByteString.smali """ for dex_name in self.dex_dict: BS_path = f'{self.baksmali_path}smali_{dex_name[:-4]}/okio/ByteString.smali' if os.path.exists(BS_path): logging.info(f'Start Replace ByteString.smali of {dex_name}') os.remove(BS_path) shutil.copy('ByteString.smali', BS_path)
def build(self): """ command b: smali + encrypt + write + pack + sign """ logging.info('Start smali.jar to convert smali to dex') self.smali() for dex_name in self.dex_dict: logging.info(f'Start Decrypt {dex_name}') self.encdex(dex_name) logging.info('Start write out to classes.dex') self.write_out() logging.info('Start pack and sign the zip file') self.pack_sign()
@click.command() @click.option('-a', '--apk', help='the apk file path') @click.option('-d', '--dir', default='classes', help='the work directory') @click.option('-k', '--key', help='the aes ecb key') @click.option('-o', '--out', help='the output apk name') def run(apk, dir, key, out): xl = QC(apk, dir, key, out) xl.break_dex() xl.replace() xl.build()
if __name__ == '__main__': FORMAT = '%(levelname)s: %(message)s' logging.basicConfig(format=FORMAT, level=logging.INFO) run()
|