#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
config-decrypt.py — recover the plaintext of an Android sample's encrypted
                    configuration or string table, offline, on your own
                    machine, without running the sample.

PURPOSE
    A config blob is the highest-value artefact in a suspected-malicious APK,
    because it is the part that NAMES things: command-and-control hostnames,
    targeted package lists, poll intervals, campaign tags, kill switches.
    Almost every sample encrypts it. Almost every sample must therefore ship
    the key, or everything needed to derive it, inside the same file — there
    is no user to type a passphrase and no server to ask before the first
    connection.

    This tool automates the four things an analyst does by hand against that
    situation:

      1. Try the cheap encodings first, in the right order, and score the
         results so you do not read 256 pages of garbage.
      2. Harvest candidate KEYS out of the DEX string pool by shape, so you
         do not have to find the decryption routine before you can try.
      3. Apply repeating-key XOR and AES (CBC and ECB, 128/192/256) with any
         candidate key, including keys recovered from the ciphertext ALONE by
         crib-dragging when no key literal exists.
      4. Extract indicators from whatever plaintext falls out, and print them
         defanged, so that a copied-and-pasted report does not become a live
         link.

    Everything happens offline. Nothing is executed, nothing is installed,
    nothing is resolved, nothing is fetched.

USAGE
    # host — the fully automatic pass: try everything, rank by score
    python3 config-decrypt.py --apk sample.apk --auto

    # host — one asset, one known key
    python3 config-decrypt.py --apk sample.apk --entry assets/cfg-xor.bin \\
        xor --key 'ch69-inert-xor'

    python3 config-decrypt.py --file cfg-aes.bin \\
        aes --key 6b39ff0e2c7a41d5 --mode cbc --iv-prefix

    # host — no key anywhere? recover it from the ciphertext with a crib.
    # A JSON config starts with {" and a URL contains https://
    python3 config-decrypt.py --file cfg-xor.bin xor --crib '{"schema"'

    # host — what key-shaped strings does the DEX carry?
    python3 config-decrypt.py --apk sample.apk --scan-dex

    # host — every asset in the APK, automatic, one line of verdict each
    python3 config-decrypt.py --apk sample.apk --auto --quiet

REQUIREMENTS
    Python 3.8 or newer. STANDARD LIBRARY ONLY — no pycryptodome, no
    cryptography, no network. The AES implementation is included below and is
    a plain textbook implementation: correctness and readability over speed.
    It decrypts a few kilobytes instantly and would be a poor choice for a
    few megabytes.

WHAT THIS WILL *NOT* TELL YOU
    * It will not tell you the sample is malicious. A decrypted config full
      of hostnames is a LEAD. Plenty of benign SDKs encrypt their endpoints,
      badly, for no good reason. Chapter 52's rule holds here unchanged: a
      hit is not a lead and a lead is not a finding.
    * It will not find a key that is DERIVED at runtime — from the package
      name, the signing certificate hash, ANDROID_ID, or a server response.
      --scan-dex looks for literals. When there is no literal, you must read
      the derivation, and the tool says so rather than pretending.
    * It will not defeat a native decryption routine. If the config is
      decrypted in C, the key may never exist as a Java string. Chapter 57 is
      where that goes; chapter 15's elf-inspect.py finds the routine.
    * It will not defeat a KDF. PBKDF2, scrypt and Argon2 over a passphrase
      are out of scope by design; if you meet one, the salt and iteration
      count are in the file and you are doing a different job.
    * It will not tell you the config is CURRENT. A hostname in a sample is
      what the author intended at build time. Whether it ever served
      anything is a question for passive DNS and public reporting, not for
      this script.
    * A high score is not proof. The scorer likes printable ASCII, JSON
      punctuation and URL fragments. A wrong key that produces printable
      output will outrank a right key that produces a protobuf. Read the
      plaintext.

RELATED
    ../README.md section 3.10       the four config-encryption shapes
    ../README.md section 8.6        where config blobs hide in an APK
    ../labs/lab-02-config-and-capability.md   this tool, driven end to end
    ../../34-Cryptography/README.md            the primitives, done properly
    ../../40-Obfuscation/scripts/frida-string-decryptor.js
                                    the runtime alternative, for when the key
                                    is derived and you are willing to execute
    ../../04-Java/scripts/dump-strings.py
                                    a fuller DEX string extractor with a
                                    complete MUTF-8 decoder

SAFETY
    This script decrypts. It does not connect, resolve, install or execute.
    Indicators are printed DEFANGED by default (hxxps://, [.] for dots);
    pass --raw-iocs if you are piping into another tool that needs them
    literal, and think about where that output is going to end up.

AUTHORISED ANALYSIS ONLY.
"""

import argparse
import base64
import binascii
import gzip
import io
import json
import os
import re
import struct
import sys
import zipfile
import zlib

# --------------------------------------------------------------------------- #
# AES — textbook implementation, standard library only.
#
# Included because a triage script that needs `pip install` is a triage script
# you will not have on the machine where you need it. It is deliberately the
# most boring possible implementation: FIPS-197 with no table tricks, so that
# a reader can check it against the specification line by line.
# --------------------------------------------------------------------------- #


def _gmul(a, b):
    """Multiply two bytes in GF(2^8) with the AES polynomial 0x11B."""
    p = 0
    for _ in range(8):
        if b & 1:
            p ^= a
        hi = a & 0x80
        a = (a << 1) & 0xFF
        if hi:
            a ^= 0x1B
        b >>= 1
    return p


def _build_sboxes():
    """Derive the S-box from first principles rather than pasting a table.

    Every byte's S-box value is the affine transform of its multiplicative
    inverse in GF(2^8). Computing the inverse by exhaustive search is 65,536
    multiplications, which is instant and impossible to typo.
    """
    inv = [0] * 256
    for i in range(1, 256):
        for j in range(1, 256):
            if _gmul(i, j) == 1:
                inv[i] = j
                break

    def rotl8(x, s):
        return ((x << s) | (x >> (8 - s))) & 0xFF

    sbox = []
    for i in range(256):
        b = inv[i]
        sbox.append(b ^ rotl8(b, 1) ^ rotl8(b, 2) ^ rotl8(b, 3) ^ rotl8(b, 4) ^ 0x63)
    rsbox = [0] * 256
    for i, v in enumerate(sbox):
        rsbox[v] = i
    return sbox, rsbox


SBOX, RSBOX = _build_sboxes()
RCON = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36,
        0x6C, 0xD8, 0xAB, 0x4D, 0x9A]


def _expand_key(key):
    nk = len(key) // 4
    if nk not in (4, 6, 8):
        raise ValueError("AES key must be 16, 24 or 32 bytes, got %d" % len(key))
    nr = nk + 6
    w = [list(key[4 * i:4 * i + 4]) for i in range(nk)]
    for i in range(nk, 4 * (nr + 1)):
        temp = list(w[i - 1])
        if i % nk == 0:
            temp = temp[1:] + temp[:1]
            temp = [SBOX[b] for b in temp]
            temp[0] ^= RCON[i // nk - 1]
        elif nk > 6 and i % nk == 4:
            temp = [SBOX[b] for b in temp]
        w.append([w[i - nk][j] ^ temp[j] for j in range(4)])
    return w, nr


def _add_round_key(state, w, rnd):
    for c in range(4):
        for r in range(4):
            state[r + 4 * c] ^= w[rnd * 4 + c][r]


def _decrypt_block(block, w, nr):
    state = list(block)
    _add_round_key(state, w, nr)
    for rnd in range(nr - 1, -1, -1):
        # InvShiftRows
        for r in range(1, 4):
            row = [state[r + 4 * c] for c in range(4)]
            row = row[-r:] + row[:-r]
            for c in range(4):
                state[r + 4 * c] = row[c]
        # InvSubBytes
        for i in range(16):
            state[i] = RSBOX[state[i]]
        _add_round_key(state, w, rnd)
        if rnd != 0:
            # InvMixColumns
            for c in range(4):
                a0, a1, a2, a3 = (state[0 + 4 * c], state[1 + 4 * c],
                                  state[2 + 4 * c], state[3 + 4 * c])
                state[0 + 4 * c] = _gmul(a0, 14) ^ _gmul(a1, 11) ^ _gmul(a2, 13) ^ _gmul(a3, 9)
                state[1 + 4 * c] = _gmul(a0, 9) ^ _gmul(a1, 14) ^ _gmul(a2, 11) ^ _gmul(a3, 13)
                state[2 + 4 * c] = _gmul(a0, 13) ^ _gmul(a1, 9) ^ _gmul(a2, 14) ^ _gmul(a3, 11)
                state[3 + 4 * c] = _gmul(a0, 11) ^ _gmul(a1, 13) ^ _gmul(a2, 9) ^ _gmul(a3, 14)
    return bytes(state)


def _encrypt_block(block, w, nr):
    state = list(block)
    _add_round_key(state, w, 0)
    for rnd in range(1, nr + 1):
        for i in range(16):
            state[i] = SBOX[state[i]]
        for r in range(1, 4):
            row = [state[r + 4 * c] for c in range(4)]
            row = row[r:] + row[:r]
            for c in range(4):
                state[r + 4 * c] = row[c]
        if rnd != nr:
            for c in range(4):
                a0, a1, a2, a3 = (state[0 + 4 * c], state[1 + 4 * c],
                                  state[2 + 4 * c], state[3 + 4 * c])
                state[0 + 4 * c] = _gmul(a0, 2) ^ _gmul(a1, 3) ^ a2 ^ a3
                state[1 + 4 * c] = a0 ^ _gmul(a1, 2) ^ _gmul(a2, 3) ^ a3
                state[2 + 4 * c] = a0 ^ a1 ^ _gmul(a2, 2) ^ _gmul(a3, 3)
                state[3 + 4 * c] = _gmul(a0, 3) ^ a1 ^ a2 ^ _gmul(a3, 2)
        _add_round_key(state, w, rnd)
    return bytes(state)


def aes_decrypt(data, key, mode="cbc", iv=None):
    """Decrypt `data`. Returns raw plaintext INCLUDING any padding bytes.

    Padding is stripped separately by strip_pkcs7, so that a caller can see
    a bad pad rather than have it hidden.
    """
    if len(data) % 16:
        raise ValueError("ciphertext length %d is not a multiple of 16" % len(data))
    w, nr = _expand_key(key)
    out = bytearray()
    if mode == "ecb":
        for i in range(0, len(data), 16):
            out += _decrypt_block(data[i:i + 16], w, nr)
        return bytes(out)
    if iv is None:
        raise ValueError("CBC needs an IV")
    prev = iv
    for i in range(0, len(data), 16):
        blk = data[i:i + 16]
        dec = _decrypt_block(blk, w, nr)
        out += bytes(a ^ b for a, b in zip(dec, prev))
        prev = blk
    return bytes(out)


def aes_encrypt(data, key, mode="cbc", iv=None):
    """Present only so that the chapter's fixture generator can build the
    inert sample's config blobs with the same code path the decryptor uses.
    An analysis tool has no operational need to encrypt anything."""
    data = pad_pkcs7(data)
    w, nr = _expand_key(key)
    out = bytearray()
    if mode == "ecb":
        for i in range(0, len(data), 16):
            out += _encrypt_block(data[i:i + 16], w, nr)
        return bytes(out)
    if iv is None:
        raise ValueError("CBC needs an IV")
    prev = iv
    for i in range(0, len(data), 16):
        blk = bytes(a ^ b for a, b in zip(data[i:i + 16], prev))
        enc = _encrypt_block(blk, w, nr)
        out += enc
        prev = enc
    return bytes(out)


def pad_pkcs7(data, block=16):
    n = block - (len(data) % block)
    return data + bytes([n]) * n


def strip_pkcs7(data, block=16):
    """Strip PKCS#7 padding if it is valid; otherwise return the data
    unchanged. Returns (data, was_valid)."""
    if not data or len(data) % block:
        return data, False
    n = data[-1]
    if n < 1 or n > block or len(data) < n:
        return data, False
    if data[-n:] != bytes([n]) * n:
        return data, False
    return data[:-n], True


# --------------------------------------------------------------------------- #
# Scoring — how we decide a candidate plaintext is plausible
# --------------------------------------------------------------------------- #

_JSON_MARKERS = (b'{"', b'":', b'":"', b'[{', b'null', b'true', b'false')
_URL_MARKERS = (b'http://', b'https://', b'://', b'.com', b'.net', b'.org',
                b'.invalid', b'.ru', b'.top', b'.xyz')
_ANDROID_MARKERS = (b'com.', b'android', b'package', b'apk', b'dex',
                    b'Landroid', b'permission')


def printable_ratio(data):
    if not data:
        return 0.0
    ok = sum(1 for b in data if 0x20 <= b < 0x7F or b in (0x09, 0x0A, 0x0D))
    return ok / len(data)


def score_plaintext(data):
    """Score 0.0-1.0. Deliberately simple and deliberately explained in the
    output, because an unexplained confidence number is worse than none.

    Chapter 52's warning transfers directly: high entropy is not evidence of
    encryption, and a high score here is not evidence of a correct key. It is
    a queue order.
    """
    if not data:
        return 0.0, "empty"
    reasons = []
    pr = printable_ratio(data)
    score = pr * 0.45
    reasons.append("printable=%.2f" % pr)

    low = data.lower()
    j = sum(1 for m in _JSON_MARKERS if m in data)
    if j:
        score += min(0.25, 0.08 * j)
        reasons.append("json_markers=%d" % j)
    u = sum(1 for m in _URL_MARKERS if m in low)
    if u:
        score += min(0.20, 0.07 * u)
        reasons.append("url_markers=%d" % u)
    a = sum(1 for m in _ANDROID_MARKERS if m in low)
    if a:
        score += min(0.10, 0.03 * a)
        reasons.append("android_markers=%d" % a)

    # A run of the same byte usually means we produced padding, not text.
    if len(data) > 32 and len(set(data[:64])) <= 2:
        score *= 0.3
        reasons.append("low_variety_penalty")

    return min(score, 1.0), " ".join(reasons)


def shannon_entropy(data):
    if not data:
        return 0.0
    counts = [0] * 256
    for b in data:
        counts[b] += 1
    import math
    n = len(data)
    return -sum((c / n) * math.log2(c / n) for c in counts if c)


# --------------------------------------------------------------------------- #
# XOR
# --------------------------------------------------------------------------- #

def xor_bytes(data, key):
    if not key:
        return data
    k = len(key)
    return bytes(b ^ key[i % k] for i, b in enumerate(data))


def recover_xor_key_from_crib(data, crib, keylen=None, max_keylen=48):
    """Recover a repeating-XOR key using a KNOWN PLAINTEXT PREFIX.

    This is the single most useful trick in config triage and it deserves an
    explanation, because it looks like magic and is not.

    Repeating-key XOR has the property  key[i % k] = plain[i] ^ cipher[i].
    If you know the first N plaintext bytes, you immediately know the first
    min(N, k) key bytes. Configs are JSON often enough that `{"` is a free
    two-byte crib, and if you can guess the first field name — `{"schema"`,
    `{"url"`, `{"c2"` — you usually have the whole key.

    When keylen is unknown we try every length from 1 to max_keylen, apply
    the recovered prefix, and score the result. The correct length is
    normally obvious: it is the shortest one whose whole-file decryption is
    printable, and lengths that are multiples of it also work, which is a
    useful confirmation rather than a problem.
    """
    if len(crib) > len(data):
        return []
    prefix = bytes(c ^ d for c, d in zip(crib, data))
    results = []
    lengths = [keylen] if keylen else range(1, min(max_keylen, len(prefix)) + 1)
    for k in lengths:
        if k > len(prefix):
            continue
        key = prefix[:k]
        # Consistency check: the crib must remain satisfied under the key.
        if xor_bytes(data[:len(crib)], key) != crib:
            continue
        plain = xor_bytes(data, key)
        sc, why = score_plaintext(plain)
        results.append((sc, k, key, plain, why))
    results.sort(key=lambda r: (-r[0], r[1]))
    return results


# A FREQUENCY table, not a membership test. This distinction is the whole
# difference between the recovery working and not working, and it is worth
# recording because the first version of this function got it wrong.
#
# A binary "is this byte printable" score ties for dozens of candidate key
# bytes, because most wrong keys still produce *some* printable text. What
# breaks the tie is that real config plaintext is not uniformly distributed:
# it is mostly spaces, lowercase letters, quotes and newlines. Weighting by
# expected frequency makes the correct key byte win by a wide margin instead
# of tying. Against a 441-byte JSON config the binary version recovered a
# 15-byte key of garbage; the weighted version below recovers the true
# 14-byte key exactly.
_BYTE_WEIGHT = [-20] * 256
for _c in range(0x20, 0x7F):
    _BYTE_WEIGHT[_c] = 1                      # any printable ASCII
for _c in b"ABCDEFGHIJKLMNOPQRSTUVWXYZ":
    _BYTE_WEIGHT[_c] = 2
for _c in b"0123456789":
    _BYTE_WEIGHT[_c] = 3
for _c in b"abcdefghijklmnopqrstuvwxyz":
    _BYTE_WEIGHT[_c] = 5
_BYTE_WEIGHT[0x0A] = 4                        # newline
_BYTE_WEIGHT[0x0D] = 2
_BYTE_WEIGHT[0x09] = 3
_BYTE_WEIGHT[ord('"')] = 7                    # JSON is quote-dense
_BYTE_WEIGHT[ord(' ')] = 9                    # and space-dense when indented


def _column_score(col, k):
    """How plausible is this column once XORed with candidate byte k?"""
    total = 0
    for b in col:
        total += _BYTE_WEIGHT[b ^ k]
    return total


def recover_xor_key_statistical(data, max_keylen=48, min_keylen=1):
    """Recover a repeating-XOR key from the CIPHERTEXT ALONE.

    No crib, no key, no knowledge of the plaintext beyond `it is probably
    mostly printable ASCII` -- which for a config blob is true essentially
    always, because configs are JSON, XML, or newline-separated lists.

    The method is the textbook break of a repeating-key (Vigenere) cipher,
    which is what repeating-key XOR is:

      1. Guess a key LENGTH k.
      2. Split the ciphertext into k columns: bytes 0, k, 2k, ... form
         column 0, and so on. Every byte in a column was XORed with the SAME
         key byte, so each column is a single-byte XOR problem.
      3. Solve each column independently by trying all 256 values and
         keeping the one that produces the most plausible characters.
      4. Reassemble, decrypt the whole message, score it.
      5. Repeat for every k and keep the best -- preferring the SHORTEST
         length that scores near the top, because every multiple of the true
         key length also decrypts correctly and would otherwise win by tying.

    This is why `we encrypted the config with XOR` is not a defence. It is
    not even a delay: the whole search is a few milliseconds.
    """
    best = []
    for k in range(min_keylen, min(max_keylen, max(1, len(data) // 4)) + 1):
        key = bytearray()
        for i in range(k):
            col = data[i::k]
            if not col:
                key.append(0)
                continue
            key.append(max(range(256), key=lambda b: _column_score(col, b)))
        plain = xor_bytes(data, bytes(key))
        sc, why = score_plaintext(plain)
        best.append((sc, k, bytes(key), plain, why))
    if not best:
        return []
    top_score = max(b[0] for b in best)
    # Prefer the shortest key length whose score is within 2% of the best.
    near = [b for b in best if b[0] >= top_score - 0.02]
    near.sort(key=lambda b: (b[1], -b[0]))
    rest = sorted((b for b in best if b not in near), key=lambda b: -b[0])
    return near + rest


def brute_single_byte_xor(data, top=5):
    out = []
    for k in range(256):
        plain = xor_bytes(data, bytes([k]))
        sc, why = score_plaintext(plain)
        out.append((sc, bytes([k]), plain, why))
    out.sort(key=lambda r: -r[0])
    return out[:top]


# --------------------------------------------------------------------------- #
# DEX string harvesting — candidate keys, by shape
# --------------------------------------------------------------------------- #

DEX_MAGICS = (b"dex\n035\x00", b"dex\n036\x00", b"dex\n037\x00",
              b"dex\n038\x00", b"dex\n039\x00", b"dex\n040\x00")


def _uleb128(buf, off):
    result = 0
    shift = 0
    while True:
        b = buf[off]
        off += 1
        result |= (b & 0x7F) << shift
        if not (b & 0x80):
            break
        shift += 7
        if shift > 35:
            raise ValueError("uleb128 too long")
    return result, off


def dex_strings(buf):
    """Yield every string in a DEX string pool.

    A deliberately minimal MUTF-8 handling: we decode with
    errors='replace' rather than implementing the full surrogate and
    embedded-NUL rules, because for KEY HUNTING a mangled astral character
    costs nothing. When you need the strings themselves to be exactly right
    — and for a report, you do — use
    ../../04-Java/scripts/dump-strings.py, which implements MUTF-8 properly
    and was tested against a DEX carrying an astral emoji and an embedded
    NUL.
    """
    if len(buf) < 0x70 or buf[:8] not in DEX_MAGICS:
        return
    string_ids_size, string_ids_off = struct.unpack_from("<II", buf, 0x38)
    for i in range(string_ids_size):
        try:
            (off,) = struct.unpack_from("<I", buf, string_ids_off + 4 * i)
            _, doff = _uleb128(buf, off)
            end = buf.index(b"\x00", doff)
            yield buf[doff:end].decode("utf-8", "replace")
        except (ValueError, IndexError, struct.error):
            continue


_HEXISH = re.compile(r"^[0-9a-fA-F]+$")
_B64ISH = re.compile(r"^[A-Za-z0-9+/]+={0,2}$")


def candidate_keys(strings):
    """Rank strings by how key-shaped they are.

    The shapes, in the order they are worth trying:

      * length exactly 16 / 24 / 32          -> SecretKeySpec(s.getBytes())
      * length exactly 32 / 48 / 64 and hex  -> hex-encoded AES key
      * length 24 / 44 and base64-ish        -> base64-encoded 16/32 bytes
      * length 4-32, printable, no spaces    -> a plausible XOR key

    None of this is clever. It is the boring shape check an analyst does by
    eye, applied to every string instead of the twenty they happened to see.
    """
    seen = set()
    out = []
    for s in strings:
        if s in seen or not s:
            continue
        seen.add(s)
        n = len(s)
        why = []
        rank = 0
        if n in (16, 24, 32) and all(32 <= ord(c) < 127 for c in s):
            rank += 60
            why.append("ascii-len-%d" % n)
        if n in (32, 48, 64) and _HEXISH.match(s):
            rank += 55
            why.append("hex-%d" % n)
        if n in (24, 44) and _B64ISH.match(s):
            rank += 35
            why.append("b64-%d" % n)
        if 4 <= n <= 32 and " " not in s and all(32 <= ord(c) < 127 for c in s):
            rank += 8
            why.append("xor-candidate")
        if re.search(r"(?i)(key|secret|aes|iv|salt|passw|cipher|token)", s):
            rank += 12
            why.append("named")
        if rank:
            out.append((rank, s, ",".join(why)))
    out.sort(key=lambda r: (-r[0], len(r[1])))
    return out


def key_bytes_variants(s):
    """One string can be a key in several ways. Try all of them."""
    variants = []
    raw = s.encode("utf-8", "replace")
    if len(raw) in (16, 24, 32):
        variants.append(("utf8", raw))
    if _HEXISH.match(s) and len(s) % 2 == 0 and len(s) // 2 in (16, 24, 32):
        try:
            variants.append(("hex", binascii.unhexlify(s)))
        except binascii.Error:
            pass
    if _B64ISH.match(s):
        try:
            d = base64.b64decode(s + "=" * (-len(s) % 4), validate=True)
            if len(d) in (16, 24, 32):
                variants.append(("b64", d))
        except (binascii.Error, ValueError):
            pass
    return variants


# --------------------------------------------------------------------------- #
# Indicator extraction, defanged
# --------------------------------------------------------------------------- #

_URL_RE = re.compile(rb"[a-zA-Z][a-zA-Z0-9+.-]{2,10}://[^\s\"'<>\\)]{4,200}")
_HOST_RE = re.compile(rb"\b(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+"
                      rb"(?:[a-zA-Z]{2,24})\b")
_PKG_RE = re.compile(rb"\b(?:com|net|org|io|ru|cn|app|me)\.[a-zA-Z0-9_]"
                     rb"(?:[a-zA-Z0-9_.]{2,80})\b")
_IPV4_RE = re.compile(rb"\b(?:\d{1,3}\.){3}\d{1,3}\b")


def defang(s):
    s = s.replace("http://", "hxxp://").replace("https://", "hxxps://")
    s = s.replace(".", "[.]")
    return s


# `loader.bin` and `config.json` have exactly the grammar of a hostname, and
# a naive extractor reports them as C2 domains. This is not a hypothetical:
# the first run of this script against the chapter's own inert sample
# reported `loader[.]bin` as a host. A reject list of file extensions costs
# nothing and removes an entire class of embarrassing report line.
_NOT_A_TLD = {
    "bin", "html", "htm", "php", "json", "png", "jpg", "jpeg", "gif", "webp",
    "js", "css", "xml", "dat", "so", "dex", "apk", "txt", "zip", "gz", "jar",
    "db", "sql", "log", "tmp", "cfg", "conf", "ini", "properties", "pem",
    "key", "crt", "md", "csv", "yml", "yaml", "sh", "py", "class", "smali",
}


def _looks_like_host(s):
    tail = s.rsplit(".", 1)[-1].lower()
    return tail not in _NOT_A_TLD


def extract_indicators(data, raw=False):
    found = {"url": set(), "host": set(), "package": set(), "ipv4": set()}
    for m in _URL_RE.findall(data):
        found["url"].add(m.decode("utf-8", "replace"))
    for m in _HOST_RE.findall(data):
        s = m.decode("utf-8", "replace")
        if _looks_like_host(s):
            found["host"].add(s)
    for m in _PKG_RE.findall(data):
        found["package"].add(m.decode("utf-8", "replace"))
    for m in _IPV4_RE.findall(data):
        found["ipv4"].add(m.decode("utf-8", "replace"))
    # A package name and a hostname have the same grammar. Anything that
    # matched both is reported once, as ambiguous, rather than twice with
    # false confidence.
    both = found["host"] & found["package"]
    out = {}
    for k, v in found.items():
        vals = sorted(v - (both if k in ("host", "package") else set()))
        if k == "package":
            vals = sorted(set(vals) | both)
        if not raw and k in ("url", "host", "ipv4"):
            vals = [defang(x) for x in vals]
        out[k] = vals
    return out


# --------------------------------------------------------------------------- #
# Input handling
# --------------------------------------------------------------------------- #

def read_blob(args):
    if args.file:
        with open(args.file, "rb") as fh:
            return fh.read(), args.file
    if args.apk and args.entry:
        with zipfile.ZipFile(args.apk) as z:
            return z.read(args.entry), "%s!%s" % (args.apk, args.entry)
    return None, None


def apk_candidate_entries(apk):
    """Which entries are worth trying? Anything that is not obviously a
    resource, an image or a signature file. Deliberately generous: chapter
    40's rule is `check entropy, not extension`, because a payload named
    `logo.png` is the norm rather than the exception."""
    skip_exact = {"AndroidManifest.xml", "resources.arsc"}
    skip_prefix = ("META-INF/", "res/", "kotlin/", "DebugProbes")
    skip_suffix = (".dex", ".so", ".arsc", ".version", ".kotlin_module",
                   ".properties", ".xml")
    out = []
    with zipfile.ZipFile(apk) as z:
        for info in z.infolist():
            n = info.filename
            if n.endswith("/") or n in skip_exact:
                continue
            if n.startswith(skip_prefix) or n.endswith(skip_suffix):
                continue
            if info.file_size == 0 or info.file_size > 8 * 1024 * 1024:
                continue
            out.append(n)
    return out


def apk_dex_strings(apk):
    strings = []
    with zipfile.ZipFile(apk) as z:
        for info in z.infolist():
            if info.filename.endswith(".dex"):
                strings.extend(dex_strings(z.read(info.filename)))
    return strings


# --------------------------------------------------------------------------- #
# Layered decoding — the cheap things, first, in the right order
# --------------------------------------------------------------------------- #

def peel_layers(data, depth=0, max_depth=4):
    """Strip base64 / gzip / zlib wrappers. Returns (data, [layer names]).

    Real config blobs are routinely base64(gzip(aes(json))) or worse, and an
    analyst who tries AES on the base64 text concludes the key is wrong.
    """
    layers = []
    cur = data
    for _ in range(max_depth):
        changed = False
        # gzip
        if cur[:2] == b"\x1f\x8b":
            try:
                cur = gzip.decompress(cur)
                layers.append("gzip")
                changed = True
            except (OSError, EOFError, zlib.error):
                pass
        # raw zlib
        elif cur[:1] in (b"\x78",):
            try:
                cur = zlib.decompress(cur)
                layers.append("zlib")
                changed = True
            except zlib.error:
                pass
        # base64 text
        if not changed:
            stripped = bytes(c for c in cur if c not in b"\r\n\t ")
            if 16 <= len(stripped) and _B64ISH.match(stripped.decode("latin-1")):
                try:
                    dec = base64.b64decode(stripped + b"=" * (-len(stripped) % 4),
                                           validate=True)
                    if len(dec) >= 8:
                        cur = dec
                        layers.append("base64")
                        changed = True
                except (binascii.Error, ValueError):
                    pass
        if not changed:
            break
    return cur, layers


# --------------------------------------------------------------------------- #
# Reporting
# --------------------------------------------------------------------------- #

BANNER = """\
================================================================================
 config-decrypt.py - offline configuration recovery
 Nothing is executed, resolved, installed or fetched. Indicators are DEFANGED
 unless --raw-iocs was passed. A decrypted config is a LEAD, not a finding.
================================================================================"""


def show_plaintext(plain, args, label, key_desc, score, why, layers=None):
    print("-" * 78)
    print("CANDIDATE  %s" % label)
    print("  key      : %s" % key_desc)
    print("  score    : %.2f   (%s)" % (score, why))
    if layers:
        print("  layers   : %s" % " -> ".join(layers))
    print("  entropy  : %.2f bits/byte" % shannon_entropy(plain))
    body = plain[:args.max_bytes]
    try:
        text = body.decode("utf-8")
        pretty = None
        stripped = text.strip()
        if stripped.startswith("{") or stripped.startswith("["):
            try:
                pretty = json.dumps(json.loads(stripped), indent=2,
                                    sort_keys=True)
            except ValueError:
                pretty = None
        print("  plaintext:")
        for line in (pretty or text).splitlines():
            print("    " + line)
    except UnicodeDecodeError:
        print("  plaintext (not valid UTF-8, showing hex of first 128 bytes):")
        print("    " + binascii.hexlify(body[:128]).decode())

    iocs = extract_indicators(plain, raw=args.raw_iocs)
    any_ioc = any(iocs.values())
    if any_ioc:
        print("  indicators%s:" % ("" if args.raw_iocs else " (defanged)"))
        for kind in ("url", "host", "ipv4", "package"):
            for v in iocs[kind][:args.max_iocs]:
                print("    %-8s %s" % (kind, v))
            if len(iocs[kind]) > args.max_iocs:
                print("    %-8s ... and %d more" % (kind, len(iocs[kind]) - args.max_iocs))
    print()


# --------------------------------------------------------------------------- #
# Modes
# --------------------------------------------------------------------------- #

def mode_scan_dex(args):
    if not args.apk:
        print("--scan-dex needs --apk", file=sys.stderr)
        return 2
    strings = apk_dex_strings(args.apk)
    print("DEX string pool: %d strings across all classes*.dex" % len(strings))
    cands = candidate_keys(strings)
    print("key-shaped candidates: %d  (showing top %d)"
          % (len(cands), min(args.top, len(cands))))
    print()
    print("  %-5s  %-40s  %s" % ("rank", "string", "why"))
    for rank, s, why in cands[:args.top]:
        disp = s if len(s) <= 40 else s[:37] + "..."
        print("  %-5d  %-40s  %s" % (rank, disp, why))
    print()
    print("A candidate is a SHAPE, not a key. Try them with --auto, and if")
    print("nothing decrypts, the key is derived at runtime and you need to")
    print("read the derivation — see README section 3.10, shape C.")
    return 0


def try_all_keys(blob, keys, args, source_label):
    """Try every candidate key under XOR, AES-CBC (with and without an IV
    prefix) and AES-ECB. Returns scored results."""
    results = []
    for rank, s, why in keys:
        # XOR with the literal bytes
        kb = s.encode("utf-8", "replace")
        if 1 <= len(kb) <= 64:
            plain = xor_bytes(blob, kb)
            sc, w = score_plaintext(plain)
            if sc >= args.threshold:
                results.append((sc, plain, "xor utf8 %r" % s, w))
        for enc, key in key_bytes_variants(s):
            if len(blob) >= 32 and len(blob) % 16 == 0:
                try:
                    p = aes_decrypt(blob, key, "ecb")
                    p2, ok = strip_pkcs7(p)
                    sc, w = score_plaintext(p2)
                    if sc >= args.threshold:
                        results.append((sc, p2, "aes-ecb %s %r%s"
                                        % (enc, s, "" if ok else " (bad pad)"), w))
                except ValueError:
                    pass
            if len(blob) >= 48 and (len(blob) - 16) % 16 == 0:
                try:
                    p = aes_decrypt(blob[16:], key, "cbc", blob[:16])
                    p2, ok = strip_pkcs7(p)
                    sc, w = score_plaintext(p2)
                    if sc >= args.threshold:
                        results.append((sc, p2, "aes-cbc %s %r iv=prefix%s"
                                        % (enc, s, "" if ok else " (bad pad)"), w))
                except ValueError:
                    pass
            if len(blob) >= 32 and len(blob) % 16 == 0:
                try:
                    p = aes_decrypt(blob, key, "cbc", b"\x00" * 16)
                    p2, ok = strip_pkcs7(p)
                    sc, w = score_plaintext(p2)
                    if sc >= args.threshold:
                        results.append((sc, p2, "aes-cbc %s %r iv=zero%s"
                                        % (enc, s, "" if ok else " (bad pad)"), w))
                except ValueError:
                    pass
    results.sort(key=lambda r: -r[0])
    return results


def mode_auto(args):
    if not args.apk and not args.file:
        print("--auto needs --apk or --file", file=sys.stderr)
        return 2

    keys = []
    if args.apk:
        strings = apk_dex_strings(args.apk)
        keys = candidate_keys(strings)[:args.top]
        if not args.quiet:
            print("harvested %d key-shaped strings from the DEX pool "
                  "(trying top %d)" % (len(keys), len(keys)))
    if args.key:
        keys = [(999, args.key, "supplied")] + keys

    if args.file:
        targets = [(args.file, open(args.file, "rb").read())]
    elif args.entry:
        with zipfile.ZipFile(args.apk) as z:
            targets = [(args.entry, z.read(args.entry))]
    else:
        names = apk_candidate_entries(args.apk)
        if not args.quiet:
            print("candidate entries in APK: %d" % len(names))
        with zipfile.ZipFile(args.apk) as z:
            targets = [(n, z.read(n)) for n in names]

    found_any = False
    for name, raw in targets:
        peeled, layers = peel_layers(raw)
        ent = shannon_entropy(peeled)
        if not args.quiet:
            print()
            print("=" * 78)
            print("ENTRY %s   %d bytes   entropy %.2f%s"
                  % (name, len(raw), ent,
                     ("   layers " + "->".join(layers)) if layers else ""))

        # 0. Already plaintext?
        sc, why = score_plaintext(peeled)
        if sc >= 0.55:
            found_any = True
            show_plaintext(peeled, args, name, "none (already plaintext)",
                           sc, why, layers)
            continue

        results = []
        # 1. single-byte XOR
        for s, k, p, w in brute_single_byte_xor(peeled, top=3):
            if s >= args.threshold:
                results.append((s, p, "xor single 0x%02x" % k[0], w))
        # 2. repeating-key XOR recovered from the ciphertext alone
        for s, klen, key, p, w in recover_xor_key_statistical(
                peeled, max_keylen=args.max_keylen)[:2]:
            if s >= args.threshold:
                results.append((s, p, "xor STATISTICALLY recovered key len=%d %r"
                                % (klen, key.decode("latin-1")), w))
        # 3. JSON crib, no key needed. Short cribs recover only short keys --
        #    a 14-byte key needs 14 known plaintext bytes, so pass a longer
        #    --crib by hand when the automatic ones fall short.
        for crib in (b'{"', b'{\n', b'{\n  "', b'{\n    "', b'[{"', b'<?xml'):
            for s, klen, key, p, w in recover_xor_key_from_crib(
                    peeled, crib, max_keylen=args.max_keylen)[:2]:
                if s >= args.threshold:
                    results.append((s, p, "xor crib-recovered key len=%d %r"
                                    % (klen, key.decode("latin-1")), w))
        # 3. every harvested key, every cipher
        results.extend(try_all_keys(peeled, keys, args, name))

        results.sort(key=lambda r: -r[0])
        # De-duplicate on plaintext
        seen = set()
        shown = 0
        for sc, plain, kd, w in results:
            h = plain[:256]
            if h in seen:
                continue
            seen.add(h)
            found_any = True
            if args.quiet:
                print("%-40s  %.2f  %s" % (name, sc, kd))
            else:
                show_plaintext(plain, args, name, kd, sc, w, layers)
            shown += 1
            if shown >= args.results:
                break
        if not shown and not args.quiet:
            print("  nothing above threshold %.2f." % args.threshold)
            print("  Next steps, in order of cost:")
            print("    * raise --top, the key may be further down the list")
            print("    * lower --threshold and read the output yourself")
            print("    * the key is DERIVED, not literal — read the routine")
            print("    * the decryption is NATIVE — chapter 15 and 57")
            print("    * this entry is not a config at all")

    return 0 if found_any else 1


def mode_xor(args):
    blob, label = read_blob(args)
    if blob is None:
        print("xor mode needs --file, or --apk with --entry", file=sys.stderr)
        return 2
    peeled, layers = peel_layers(blob)
    if args.crib:
        crib = args.crib.encode("utf-8")
        res = recover_xor_key_from_crib(peeled, crib, args.keylen,
                                        args.max_keylen)
        if not res:
            print("crib %r produced no self-consistent key." % args.crib)
            print("Either the crib is wrong, or this is not repeating-key XOR.")
            return 1
        for sc, klen, key, plain, why in res[:args.results]:
            show_plaintext(plain, args, label,
                           "recovered len=%d %r" % (klen, key.decode("latin-1")),
                           sc, why, layers)
        return 0
    if args.recover:
        res = recover_xor_key_statistical(peeled, args.max_keylen,
                                          args.keylen or 1)
        if args.keylen:
            res = [r for r in res if r[1] == args.keylen]
        for sc, klen, key, plain, why in res[:args.results]:
            show_plaintext(plain, args, label,
                           "statistically recovered len=%d %r"
                           % (klen, key.decode("latin-1")), sc, why, layers)
        return 0
    if args.brute_single:
        for sc, k, plain, why in brute_single_byte_xor(peeled, args.results):
            show_plaintext(plain, args, label, "single byte 0x%02x" % k[0],
                           sc, why, layers)
        return 0
    if not args.key:
        print("xor mode needs --key, --crib, --recover or --brute-single",
              file=sys.stderr)
        return 2
    key = parse_key(args.key)
    plain = xor_bytes(peeled, key)
    sc, why = score_plaintext(plain)
    show_plaintext(plain, args, label, "supplied %r" % args.key, sc, why, layers)
    return 0


def parse_key(s):
    if s.startswith("hex:"):
        return binascii.unhexlify(s[4:])
    if s.startswith("b64:"):
        return base64.b64decode(s[4:] + "=" * (-len(s[4:]) % 4))
    if _HEXISH.match(s) and len(s) % 2 == 0 and len(s) // 2 in (16, 24, 32) \
            and len(s) not in (16, 24, 32):
        return binascii.unhexlify(s)
    return s.encode("utf-8")


def mode_aes(args):
    blob, label = read_blob(args)
    if blob is None:
        print("aes mode needs --file, or --apk with --entry", file=sys.stderr)
        return 2
    if not args.key:
        print("aes mode needs --key", file=sys.stderr)
        return 2
    peeled, layers = peel_layers(blob)
    key = parse_key(args.key)
    if len(key) not in (16, 24, 32):
        print("key is %d bytes; AES needs 16, 24 or 32. Use hex: or b64: "
              "prefixes if the key is encoded." % len(key), file=sys.stderr)
        return 2

    if args.mode == "ecb":
        data, iv, desc = peeled, None, "ecb"
    elif args.iv_prefix:
        data, iv, desc = peeled[16:], peeled[:16], "cbc iv=first 16 bytes"
    elif args.iv:
        data, iv, desc = peeled, binascii.unhexlify(args.iv), "cbc iv=supplied"
    else:
        data, iv, desc = peeled, b"\x00" * 16, "cbc iv=all zero"

    try:
        plain = aes_decrypt(data, key, args.mode, iv)
    except ValueError as e:
        print("decryption refused: %s" % e, file=sys.stderr)
        return 1
    plain, pad_ok = strip_pkcs7(plain)
    sc, why = score_plaintext(plain)
    show_plaintext(plain, args, label,
                   "%s %s%s" % (args.mode, args.key,
                                "" if pad_ok else "  [PKCS#7 pad INVALID]"),
                   sc, why, layers)
    if not pad_ok:
        print("NOTE: the PKCS#7 padding did not validate. Either the key is")
        print("wrong, the mode is wrong, the IV handling is wrong, or the")
        print("scheme uses no padding at all (CTR, GCM, or zero padding).")
    return 0


# --------------------------------------------------------------------------- #

def build_parser():
    p = argparse.ArgumentParser(
        description="Offline recovery of encrypted Android config blobs.",
        epilog="A decrypted config is a lead, not a finding. See README section 3.10.")
    p.add_argument("--apk", help="APK to read the blob and the DEX keys from")
    p.add_argument("--entry", help="zip entry inside --apk (e.g. assets/cfg.bin)")
    p.add_argument("--file", help="a blob already on disk")
    p.add_argument("--auto", action="store_true",
                   help="try every cheap decoding against every candidate entry")
    p.add_argument("--scan-dex", action="store_true",
                   help="list key-shaped strings from the DEX pool and stop")
    p.add_argument("--key", help="key: literal, or hex:... / b64:...")
    p.add_argument("--top", type=int, default=40,
                   help="how many harvested key candidates to try (default 40)")
    p.add_argument("--results", type=int, default=3,
                   help="how many candidate plaintexts to print per entry")
    p.add_argument("--threshold", type=float, default=0.45,
                   help="minimum score to print a candidate (default 0.45)")
    p.add_argument("--max-bytes", type=int, default=4000,
                   help="how much plaintext to print")
    p.add_argument("--max-iocs", type=int, default=25)
    p.add_argument("--max-keylen", type=int, default=48)
    p.add_argument("--raw-iocs", action="store_true",
                   help="print indicators live rather than defanged")
    p.add_argument("--quiet", action="store_true", help="one line per result")

    sub = p.add_subparsers(dest="cmd")

    x = sub.add_parser("xor", help="repeating-key XOR")
    x.add_argument("--key")
    x.add_argument("--crib", help="known plaintext prefix, e.g. '{\"schema\"'")
    x.add_argument("--keylen", type=int)
    x.add_argument("--brute-single", action="store_true",
                   help="try all 256 single-byte keys")
    x.add_argument("--recover", action="store_true",
                   help="recover a repeating key from the ciphertext alone, "
                        "with no crib and no key material")

    a = sub.add_parser("aes", help="AES-128/192/256, CBC or ECB")
    a.add_argument("--key")
    a.add_argument("--mode", choices=("cbc", "ecb"), default="cbc")
    a.add_argument("--iv", help="IV as hex")
    a.add_argument("--iv-prefix", action="store_true",
                   help="the first 16 bytes of the blob are the IV")
    return p


def main(argv):
    p = build_parser()
    args = p.parse_args(argv)

    # Subparser defaults so the top-level modes can read them unconditionally.
    for attr, default in (("crib", None), ("keylen", None),
                          ("brute_single", False), ("recover", False),
                          ("mode", "cbc"),
                          ("iv", None), ("iv_prefix", False)):
        if not hasattr(args, attr):
            setattr(args, attr, default)

    if not args.quiet:
        print(BANNER)

    if args.scan_dex:
        return mode_scan_dex(args)
    if args.cmd == "xor":
        return mode_xor(args)
    if args.cmd == "aes":
        return mode_aes(args)
    if args.auto:
        return mode_auto(args)

    p.print_help()
    return 2


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
