#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
apk-triage.py — one pass over a suspected-malicious APK that answers the six
                questions triage is actually for, and refuses to answer the
                one it cannot.

PURPOSE
    You have an APK and forty minutes. Before you open a decompiler you need,
    in this order:

      1. IDENTITY      what is this file? (hashes, package, versions, sizes)
      2. PROVENANCE    who signed it, and what is that worth?
      3. CAPABILITY    what could it do with what it has asked for?
      4. PERSISTENCE   how does it survive a reboot, a swipe, a kill?
      5. NATIVE        how much of it is not Java, and what runs earliest?
      6. LOADING       does the code you can see equal the code that runs?

    This script produces all six in a single pass over the file, with no
    unpacking step, no decompiler, no network and no device. It is
    deliberately dependency-free: standard library only, so it runs on the
    analysis machine you actually have rather than the one you would like.

    It reports SIGNALS and it reports them with the reasoning attached. It
    never prints a verdict, and there is no "malicious: yes/no" line, because
    a triage tool cannot know that and one that pretends to will be believed.

USAGE
    # host -- the whole report
    python3 -B apk-triage.py sample.apk

    # host -- several samples, one summary line each
    python3 -B apk-triage.py *.apk --quiet

    # host -- machine-readable, for a corpus
    python3 -B apk-triage.py sample.apk --json > sample.json

    # host -- only the sections you want
    python3 -B apk-triage.py sample.apk --only identity,provenance
    python3 -B apk-triage.py sample.apk --no-strings

REQUIREMENTS
    Python 3.8 or newer. Standard library only. Windows, macOS and Linux.
    No apktool, no jadx, no aapt2, no adb, no Java.

WHAT THIS WILL *NOT* TELL YOU  -- read this before you quote its output
    * WHETHER THE SAMPLE IS MALICIOUS. Every line it prints is a signal.
      A file-manager app legitimately holds QUERY_ALL_PACKAGES; a screen
      reader legitimately declares an accessibility service; a music player
      legitimately runs a foreground service that ignores task removal. The
      tool prints what is there and what it would mean; deciding is yours.
    * WHAT THE SAMPLE DOES AT RUNTIME. It reads a file. It never executes
      anything. Reflection, dynamically loaded DEX and native decryption are
      all invisible to it, by construction -- and the LOADING section exists
      to tell you when that blindness is likely to matter.
    * WHO WROTE IT. The signer identity it prints is a KEY, not a person and
      not a group. See the PROVENANCE section's own caveats, and README
      section 3.14.
    * WHETHER THE SIGNATURE VERIFIES. It parses the signing block and reads
      the certificates out of it. It does NOT verify a single digest. Run
      `apksigner verify -v --print-certs sample.apk` alongside it, always.
      A file can carry a perfectly readable certificate and a broken
      signature, and Janus-style attacks live in exactly that gap.
    * ANYTHING ABOUT SPLITS. Run it against every APK `pm path` reports, not
      only base.apk. A capability declared in a feature split is invisible
      here.
    * ANYTHING ABOUT THE MANIFEST AS THE PLATFORM PARSED IT. This reads the
      bytes. `adb shell dumpsys package <pkg>` reads the platform's
      conclusion, and the two can disagree -- that disagreement is an attack
      class in itself. See 10-APK-Internals section 18.
    * A DEEP MANIFEST AUDIT. Exported components, permission protection
      levels, deep links, provider grant posture and the targetSdk version
      matrix belong to ../../32-Manifest/scripts/manifest-audit.py, which is
      2,300 lines of exactly that and is not restaged here.
    * A CONTAINER AUDIT. Duplicate entries, LFH/CDFH divergence, trailing
      bytes and signing-block smuggling belong to
      ../../10-APK-Internals/scripts/apk-container-triage.py.
    * A FULL ELF READ. Sections, relocations, hardening flags and the real
      symbol tables belong to ../../15-Native-Code/scripts/elf-inspect.py
      and elf-harden-check.py. This prints the four native facts that change
      what you do next, and hands over.

RELATED
    ../README.md section 8          the static triage method this implements
    ../cheatsheet.md                the checklist and the capability table
    ../labs/lab-01-first-triage.md  this tool, driven end to end
    ./config-decrypt.py             the next step when an asset looks encrypted

SAFETY
    This script reads a file. It does not install, execute, connect, resolve
    or unpack to a path the operating system might index. Indicators found in
    strings are printed DEFANGED unless --raw-iocs is given.

AUTHORISED ANALYSIS ONLY. Handle real samples on a machine you can rebuild.
"""

import argparse
import binascii
import hashlib
import json
import math
import os
import re
import struct
import sys
import zipfile

# --------------------------------------------------------------------------- #
# Small helpers
# --------------------------------------------------------------------------- #

def human(n):
    for unit in ("B", "KiB", "MiB", "GiB"):
        if n < 1024 or unit == "GiB":
            return "%.1f %s" % (n, unit) if unit != "B" else "%d B" % n
        n /= 1024.0
    return "%d B" % n


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


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


# --------------------------------------------------------------------------- #
# Binary XML (AXML) parser
#
# The manifest inside an APK is not text. It is Android's binary XML: a string
# pool followed by a stream of element chunks. There are full parsers in this
# repository already -- 10-APK-Internals/examples/parse_axml.py is the
# teaching one -- and this is a compact operational copy, included so that
# triage needs no external tool.
#
# ONE TRAP IS WORTH STATING IN THE CODE. Each START_ELEMENT chunk declares
# attributeStart and attributeSize. Most files use 20 bytes per attribute, and
# a parser that hardcodes 20 works on almost everything -- and is exactly the
# parser that a widened-stride AXML confusion attack defeats, because the
# platform honours the declared size and the tool does not. 10-APK-Internals
# lab 04 builds that attack. So: honour attributeSize, always.
# --------------------------------------------------------------------------- #

RES_STRING_POOL_TYPE = 0x0001
RES_XML_TYPE = 0x0003
RES_XML_START_NAMESPACE = 0x0100
RES_XML_END_NAMESPACE = 0x0101
RES_XML_START_ELEMENT = 0x0102
RES_XML_END_ELEMENT = 0x0103
RES_XML_CDATA = 0x0104
RES_XML_RESOURCE_MAP = 0x0180

TYPE_REFERENCE = 0x01
TYPE_STRING = 0x03
TYPE_FLOAT = 0x04
TYPE_INT_DEC = 0x10
TYPE_INT_HEX = 0x11
TYPE_INT_BOOLEAN = 0x12


class AxmlError(Exception):
    pass


def _parse_string_pool(buf, off):
    typ, hdr_size, chunk_size = struct.unpack_from("<HHI", buf, off)
    if typ != RES_STRING_POOL_TYPE:
        raise AxmlError("expected string pool at 0x%x, got 0x%04x" % (off, typ))
    (count, style_count, flags, strings_start,
     styles_start) = struct.unpack_from("<IIIII", buf, off + 8)
    utf8 = bool(flags & (1 << 8))
    offsets = struct.unpack_from("<%dI" % count, buf, off + 28)
    base = off + strings_start
    out = []
    for o in offsets:
        pos = base + o
        try:
            if utf8:
                n, pos = _u8len(buf, pos)      # utf16 length, discarded
                blen, pos = _u8len(buf, pos)   # byte length
                out.append(buf[pos:pos + blen].decode("utf-8", "replace"))
            else:
                n, pos = _u16len(buf, pos)
                out.append(buf[pos:pos + 2 * n].decode("utf-16-le", "replace"))
        except (IndexError, struct.error):
            out.append("")
    return out, off + chunk_size


def _u8len(buf, pos):
    v = buf[pos]
    pos += 1
    if v & 0x80:
        v = ((v & 0x7F) << 8) | buf[pos]
        pos += 1
    return v, pos


def _u16len(buf, pos):
    (v,) = struct.unpack_from("<H", buf, pos)
    pos += 2
    if v & 0x8000:
        (v2,) = struct.unpack_from("<H", buf, pos)
        pos += 2
        v = ((v & 0x7FFF) << 16) | v2
    return v, pos


class AxmlElement(object):
    __slots__ = ("name", "attrs", "children", "parent")

    def __init__(self, name, parent=None):
        self.name = name
        self.attrs = {}
        self.children = []
        self.parent = parent

    def find_all(self, name):
        for c in self.children:
            if c.name == name:
                yield c
            for g in c.find_all(name):
                yield g

    def get(self, key, default=None):
        return self.attrs.get(key, default)


def parse_axml(buf):
    """Return the root AxmlElement of a binary AndroidManifest.xml."""
    if len(buf) < 8:
        raise AxmlError("too short")
    typ, hdr_size, total = struct.unpack_from("<HHI", buf, 0)
    if typ != RES_XML_TYPE:
        raise AxmlError("not binary XML (type 0x%04x)" % typ)
    off = hdr_size
    strings, off = _parse_string_pool(buf, off)

    def s(idx):
        if idx == 0xFFFFFFFF or idx >= len(strings):
            return None
        return strings[idx]

    root = None
    stack = []
    while off + 8 <= len(buf):
        ctype, chdr, csize = struct.unpack_from("<HHI", buf, off)
        if csize == 0:
            break
        if ctype == RES_XML_START_ELEMENT:
            base = off + chdr
            ns_i, name_i = struct.unpack_from("<II", buf, base)
            attr_start, attr_size, attr_count = struct.unpack_from("<HHH", buf, base + 8)
            el = AxmlElement(s(name_i) or "?", stack[-1] if stack else None)
            ap = base + attr_start
            for _ in range(attr_count):
                a_ns, a_name, a_raw = struct.unpack_from("<III", buf, ap)
                v_size, v_res0, v_type, v_data = struct.unpack_from("<HBBI", buf, ap + 12)
                key = s(a_name) or "?"
                if v_type == TYPE_STRING:
                    val = s(v_data)
                    if val is None:
                        val = s(a_raw)
                elif v_type == TYPE_INT_BOOLEAN:
                    val = "true" if v_data else "false"
                elif v_type == TYPE_INT_HEX:
                    val = "0x%x" % v_data
                elif v_type == TYPE_REFERENCE:
                    val = "@0x%08x" % v_data
                elif v_type == TYPE_FLOAT:
                    val = str(struct.unpack("<f", struct.pack("<I", v_data))[0])
                else:
                    val = str(struct.unpack("<i", struct.pack("<I", v_data))[0])
                el.attrs[key] = val
                # HONOUR THE DECLARED STRIDE. See the note above this parser.
                ap += attr_size if attr_size else 20
            if stack:
                stack[-1].children.append(el)
            else:
                root = el
            stack.append(el)
        elif ctype == RES_XML_END_ELEMENT:
            if stack:
                stack.pop()
        off += csize
    if root is None:
        raise AxmlError("no root element")
    return root


# --------------------------------------------------------------------------- #
# Minimal DER / X.509
#
# Enough to answer "which key signed this, and what does the certificate say
# about itself". Deliberately not a validating parser: it reads fields, it
# does not check them, and it never decides that a certificate is trustworthy,
# because in this context none of them are.
# --------------------------------------------------------------------------- #

def der_tlv(buf, off):
    """Return (tag, header_len, length, value_off, next_off)."""
    tag = buf[off]
    ln = buf[off + 1]
    p = off + 2
    if ln & 0x80:
        nbytes = ln & 0x7F
        ln = int.from_bytes(buf[p:p + nbytes], "big")
        p += nbytes
    return tag, p - off, ln, p, p + ln


def der_children(buf, off):
    tag, hl, ln, vo, no = der_tlv(buf, off)
    p = vo
    end = vo + ln
    while p < end:
        t, h, l, v, n = der_tlv(buf, p)
        yield (t, v, l, p)
        p = n


OID_CN = bytes([0x55, 0x04, 0x03])
OID_O = bytes([0x55, 0x04, 0x0A])
OID_C = bytes([0x55, 0x04, 0x06])


def der_name_to_str(buf, off):
    """Flatten an X.501 Name into 'CN=..., O=...'. Best effort."""
    parts = []
    try:
        for _t, rdn_v, rdn_l, _p in der_children(buf, off):
            # rdn is a SET OF AttributeTypeAndValue
            q = rdn_v
            end = rdn_v + rdn_l
            while q < end:
                t, h, l, v, n = der_tlv(buf, q)
                if t == 0x30:
                    oid_t, oid_h, oid_l, oid_v, oid_n = der_tlv(buf, v)
                    oid = buf[oid_v:oid_v + oid_l]
                    val_t, val_h, val_l, val_v, _ = der_tlv(buf, oid_n)
                    txt = buf[val_v:val_v + val_l].decode("utf-8", "replace")
                    label = {OID_CN: "CN", OID_O: "O", OID_C: "C"}.get(oid)
                    if label:
                        parts.append("%s=%s" % (label, txt))
                q = n
    except (IndexError, ValueError, struct.error):
        pass
    return ", ".join(parts) if parts else "(unreadable)"


def parse_certificate(der):
    """Pull subject, issuer, validity and serial out of an X.509 DER blob."""
    info = {
        "sha256": hashlib.sha256(der).hexdigest(),
        "sha1": hashlib.sha1(der).hexdigest(),
        "md5": hashlib.md5(der).hexdigest(),
        "size": len(der),
        "subject": "(unreadable)",
        "issuer": "(unreadable)",
        "not_before": "?",
        "not_after": "?",
        "serial": "?",
        "self_signed": None,
    }
    try:
        _t, _h, _l, cert_v, _n = der_tlv(der, 0)          # Certificate SEQ
        tbs_t, tbs_h, tbs_l, tbs_v, tbs_n = der_tlv(der, cert_v)  # tbsCertificate
        p = tbs_v
        # optional [0] EXPLICIT version
        t, h, l, v, n = der_tlv(der, p)
        if t == 0xA0:
            p = n
        # serialNumber INTEGER
        t, h, l, v, n = der_tlv(der, p)
        info["serial"] = binascii.hexlify(der[v:v + l]).decode()
        p = n
        # signature AlgorithmIdentifier
        _t, _h, _l, _v, n = der_tlv(der, p)
        p = n
        # issuer Name
        issuer_off = p
        info["issuer"] = der_name_to_str(der, p)
        _t, _h, _l, _v, n = der_tlv(der, p)
        p = n
        # validity SEQUENCE { notBefore, notAfter }
        t, h, l, v, n = der_tlv(der, p)
        nb_t, nb_h, nb_l, nb_v, nb_n = der_tlv(der, v)
        info["not_before"] = der[nb_v:nb_v + nb_l].decode("ascii", "replace")
        na_t, na_h, na_l, na_v, _ = der_tlv(der, nb_n)
        info["not_after"] = der[na_v:na_v + na_l].decode("ascii", "replace")
        p = n
        # subject Name
        info["subject"] = der_name_to_str(der, p)
        info["self_signed"] = (info["subject"] == info["issuer"])
    except (IndexError, ValueError, struct.error):
        pass
    return info


def find_certs_in_pkcs7(buf):
    """Heuristic scan for X.509 certificates inside a PKCS#7 blob.

    A full CMS parser is not warranted here. Every X.509 certificate begins
    with SEQUENCE { SEQUENCE { [0] { INTEGER 2 } ... } }, which on the wire
    is `30 82 xx xx 30 82 xx xx a0 03 02 01 02`. That 13-byte shape is
    specific enough to find every v3 certificate and nothing else.

    It is a HEURISTIC and the report says so. For an authoritative read use
    `apksigner verify --print-certs` or `openssl pkcs7 -inform DER -print_certs`.
    """
    out = []
    i = 0
    pat = b"\xa0\x03\x02\x01\x02"
    while True:
        j = buf.find(pat, i)
        if j < 0:
            break
        i = j + 1
        # walk backwards to the two nested SEQUENCE headers
        start = j - 8
        if start < 0:
            continue
        if buf[start] == 0x30 and buf[start + 1] == 0x82 and \
           buf[start + 4] == 0x30 and buf[start + 5] == 0x82:
            total = 4 + struct.unpack_from(">H", buf, start + 2)[0]
            if start + total <= len(buf):
                out.append(buf[start:start + total])
    return out


# --------------------------------------------------------------------------- #
# APK signing block
# --------------------------------------------------------------------------- #

APK_SIG_BLOCK_MAGIC = b"APK Sig Block 42"
ID_V2 = 0x7109871A
ID_V3 = 0xF05368C0
ID_V31 = 0x1B93AD61
ID_STAMP_V1 = 0x2B09189E
ID_STAMP_V2 = 0x6DFF800D
ID_PADDING = 0x42726577

KNOWN_BLOCK_IDS = {
    ID_V2: "APK Signature Scheme v2",
    ID_V3: "APK Signature Scheme v3",
    ID_V31: "APK Signature Scheme v3.1",
    ID_STAMP_V1: "Source stamp v1",
    ID_STAMP_V2: "Source stamp v2",
    ID_PADDING: "padding",
    0x504B4453: "dependency info (Play)",
}


def find_eocd(data):
    tail = data[-(min(len(data), 65557)):]
    idx = tail.rfind(b"PK\x05\x06")
    if idx < 0:
        return None
    return len(data) - len(tail) + idx


def read_signing_block(data):
    eocd = find_eocd(data)
    if eocd is None:
        return None, "no EOCD found -- is this a zip?"
    (cd_off,) = struct.unpack_from("<I", data, eocd + 16)
    if cd_off < 32:
        return None, "central directory too early for a signing block"
    if data[cd_off - 16:cd_off] != APK_SIG_BLOCK_MAGIC:
        return None, "no APK Signing Block (v1-only, or unsigned)"
    (size_footer,) = struct.unpack_from("<Q", data, cd_off - 24)
    block_start = cd_off - size_footer - 8
    if block_start < 0:
        return None, "signing block size is impossible"
    (size_header,) = struct.unpack_from("<Q", data, block_start)
    pairs = {}
    p = block_start + 8
    end = cd_off - 24
    while p + 12 <= end:
        (plen,) = struct.unpack_from("<Q", data, p)
        if plen < 4 or p + 8 + plen > end + 8:
            break
        (pid,) = struct.unpack_from("<I", data, p + 8)
        pairs[pid] = data[p + 12:p + 8 + plen]
        p += 8 + plen
    return {
        "start": block_start,
        "size_header": size_header,
        "size_footer": size_footer,
        "consistent": size_header == size_footer,
        "pairs": pairs,
    }, None


def _lp_seq(buf):
    """Iterate a sequence of uint32-length-prefixed items."""
    p = 0
    while p + 4 <= len(buf):
        (n,) = struct.unpack_from("<I", buf, p)
        p += 4
        if p + n > len(buf):
            break
        yield buf[p:p + n]
        p += n


def certs_from_v2v3(value):
    """Extract the certificate DER blobs from a v2 or v3 block value.

    Layout (both schemes, for the part we need):
        value    = length-prefixed sequence of signers
        signer   = signed_data || signatures || public_key   (each lp)
        signed_data = digests || certificates || ...          (each lp)
        certificates = length-prefixed sequence of X.509 DER
    """
    certs = []
    for signers in _lp_seq(value):
        for signer in _lp_seq(signers):
            parts = list(_lp_seq(signer))
            if not parts:
                continue
            signed_data = parts[0]
            sd = list(_lp_seq(signed_data))
            if len(sd) >= 2:
                for c in _lp_seq(sd[1]):
                    certs.append(c)
            break
        break
    return certs


# --------------------------------------------------------------------------- #
# DEX strings
# --------------------------------------------------------------------------- #

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):
    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


def dex_header_facts(buf):
    if len(buf) < 0x70 or buf[:8] not in DEX_MAGICS:
        return None
    ver = buf[4:7].decode("ascii", "replace")
    (checksum,) = struct.unpack_from("<I", buf, 8)
    file_size, header_size, endian = struct.unpack_from("<III", buf, 0x20)
    string_ids_size = struct.unpack_from("<I", buf, 0x38)[0]
    type_ids_size = struct.unpack_from("<I", buf, 0x40)[0]
    method_ids_size = struct.unpack_from("<I", buf, 0x58)[0]
    class_defs_size = struct.unpack_from("<I", buf, 0x60)[0]
    return {
        "version": ver,
        "checksum": "0x%08x" % checksum,
        "file_size": file_size,
        "header_size": header_size,
        "endian_ok": endian == 0x12345678,
        "strings": string_ids_size,
        "types": type_ids_size,
        "methods": method_ids_size,
        "classes": class_defs_size,
    }


# --------------------------------------------------------------------------- #
# ELF, the four facts that change what you do next
# --------------------------------------------------------------------------- #

EM_NAMES = {0x28: "arm (32-bit)", 0xB7: "aarch64", 0x03: "x86", 0x3E: "x86-64",
            0x08: "mips", 0xF3: "riscv"}

DT_NEEDED, DT_INIT, DT_SONAME, DT_INIT_ARRAY = 1, 12, 14, 25


def elf_facts(buf):
    if len(buf) < 64 or buf[:4] != b"\x7fELF":
        return None
    is64 = buf[4] == 2
    little = buf[5] == 1
    end = "<" if little else ">"
    machine = struct.unpack_from(end + "H", buf, 18)[0]
    facts = {
        "class": "ELF64" if is64 else "ELF32",
        "machine": EM_NAMES.get(machine, "0x%x" % machine),
        "size": len(buf),
        "has_init": False,
        "has_init_array": False,
        "needed_count": 0,
        "stripped": None,
    }
    try:
        if is64:
            e_phoff = struct.unpack_from(end + "Q", buf, 32)[0]
            e_phentsize = struct.unpack_from(end + "H", buf, 54)[0]
            e_phnum = struct.unpack_from(end + "H", buf, 56)[0]
        else:
            e_phoff = struct.unpack_from(end + "I", buf, 28)[0]
            e_phentsize = struct.unpack_from(end + "H", buf, 42)[0]
            e_phnum = struct.unpack_from(end + "H", buf, 44)[0]
        for i in range(e_phnum):
            ph = e_phoff + i * e_phentsize
            p_type = struct.unpack_from(end + "I", buf, ph)[0]
            if p_type != 2:                       # PT_DYNAMIC
                continue
            if is64:
                p_offset = struct.unpack_from(end + "Q", buf, ph + 8)[0]
                p_filesz = struct.unpack_from(end + "Q", buf, ph + 32)[0]
                step, fmt = 16, end + "qQ"
            else:
                p_offset = struct.unpack_from(end + "I", buf, ph + 4)[0]
                p_filesz = struct.unpack_from(end + "I", buf, ph + 16)[0]
                step, fmt = 8, end + "iI"
            q = p_offset
            while q + step <= p_offset + p_filesz and q + step <= len(buf):
                tag, val = struct.unpack_from(fmt, buf, q)
                if tag == 0:
                    break
                if tag == DT_NEEDED:
                    facts["needed_count"] += 1
                elif tag == DT_INIT:
                    facts["has_init"] = True
                elif tag == DT_INIT_ARRAY:
                    facts["has_init_array"] = True
                q += step
    except (struct.error, IndexError):
        pass
    facts["symtab"] = b".symtab" in buf
    facts["stripped"] = not facts["symtab"]
    return facts


# --------------------------------------------------------------------------- #
# THE CAPABILITY MODEL
#
# This is the heart of the tool and the heart of the chapter. Android malware
# overwhelmingly uses capability the user GRANTED rather than capability it
# stole. So a triage tool's job is not to look for exploits; it is to compute
# what this application could do if every request it makes were granted.
#
# Each row is: what was requested -> what it enables -> how strong a signal it
# is on its own. The third column is the one that stops a report being noise.
# --------------------------------------------------------------------------- #

# weight: 3 = rarely legitimate outside a narrow app class
#         2 = common in malware, common in legitimate apps too
#         1 = context only
CAPABILITY_PERMISSIONS = [
    # (permission suffix, capability, weight, note)
    ("BIND_ACCESSIBILITY_SERVICE", "accessibility (read+drive every app)", 3,
     "Held by the system; the app DECLARES it on a service. The single most "
     "powerful capability a user can grant."),
    ("BIND_NOTIFICATION_LISTENER_SERVICE", "notification access (read+cancel)", 3,
     "Reads every notification from every app, including OTP codes, and can "
     "cancel them so the user never sees them."),
    ("BIND_DEVICE_ADMIN", "device admin (uninstall resistance)", 2,
     "Declining in value: most legacy policies are deprecated from API 28-29, "
     "and an active admin still resists uninstall regardless of policy."),
    ("SYSTEM_ALERT_WINDOW", "overlay (draw over other apps)", 3,
     "TYPE_APPLICATION_OVERLAY. The classic credential-phishing primitive and "
     "the classic tapjacking primitive."),
    ("BIND_ACCESSIBILITY", "accessibility (variant spelling)", 3, ""),
    ("REQUEST_INSTALL_PACKAGES", "install other packages (dropper)", 3,
     "The defining permission of a dropper: stage one installs stage two."),
    ("REQUEST_DELETE_PACKAGES", "uninstall other packages", 2,
     "Used to remove stage one after stage two lands, and to prompt removal "
     "of security software."),
    ("QUERY_ALL_PACKAGES", "enumerate every installed app", 2,
     "Since API 30 this is required to see the package list at all. In a "
     "sideloaded app with no plausible need, it is target selection."),
    ("READ_SMS", "read SMS", 3, "Second-factor interception."),
    ("RECEIVE_SMS", "receive SMS in the background", 3, "Second-factor interception."),
    ("SEND_SMS", "send SMS", 3, "Premium-rate fraud and self-propagation."),
    ("READ_PHONE_STATE", "IMEI / SIM / call state", 1,
     "Very common legitimately. Interesting only alongside other signals."),
    ("READ_CONTACTS", "contact list", 2, "Propagation and social engineering."),
    ("READ_CALL_LOG", "call history", 2, ""),
    ("ANSWER_PHONE_CALLS", "answer calls", 3, "Vishing automation."),
    ("CALL_PHONE", "place calls", 2, ""),
    ("RECORD_AUDIO", "microphone", 3, ""),
    ("CAMERA", "camera", 2, ""),
    ("ACCESS_FINE_LOCATION", "precise location", 1, ""),
    ("ACCESS_BACKGROUND_LOCATION", "location while in background", 2, ""),
    ("RECEIVE_BOOT_COMPLETED", "start at boot", 2,
     "Persistence. Extremely common legitimately, so weight it low alone."),
    ("FOREGROUND_SERVICE", "long-running foreground service", 1,
     "Persistence enabler. Required since API 28 for any foreground service."),
    ("REQUEST_IGNORE_BATTERY_OPTIMIZATIONS", "battery exemption", 2,
     "Persistence. Play restricts it; a sideloaded app is unrestricted."),
    ("PACKAGE_USAGE_STATS", "app usage statistics", 2,
     "Special access. Used to detect which app is in the foreground, which is "
     "the trigger for an overlay."),
    ("GET_TASKS", "running task list (legacy)", 2,
     "Deprecated since API 21 and now returns only the caller's own tasks; a "
     "sample that still asks is old or copied."),
    ("WRITE_SETTINGS", "modify system settings", 2, ""),
    ("WRITE_SECURE_SETTINGS", "modify SECURE settings", 3,
     "Signature-level. An ordinary app cannot be granted it; if you see this "
     "requested, the app is either system-signed, targeting a rooted device, "
     "or the developer copied a manifest they did not understand."),
    ("MANAGE_EXTERNAL_STORAGE", "all-files access", 2, ""),
    ("DISABLE_KEYGUARD", "dismiss the lock screen", 2, ""),
    ("USE_FULL_SCREEN_INTENT", "full-screen notification", 2,
     "An overlay substitute that needs no special access on some releases."),
    ("POST_NOTIFICATIONS", "post notifications (API 33+)", 1, ""),
    ("INTERNET", "network", 1, "Necessary but meaningless alone."),
]

# DEX string markers, grouped. Each is a class of behaviour, not a signature.
DEX_MARKERS = {
    "capability": [
        ("android.accessibilityservice.AccessibilityService", "accessibility service"),
        ("performGlobalAction", "accessibility global actions"),
        ("dispatchGesture", "accessibility synthesised input"),
        ("AccessibilityNodeInfo", "accessibility node tree reads"),
        ("onNotificationPosted", "notification listener callback"),
        ("cancelNotification", "notification suppression"),
        ("TYPE_APPLICATION_OVERLAY", "overlay window type"),
        ("android.settings.action.MANAGE_OVERLAY_PERMISSION", "drives user to overlay toggle"),
        ("android.settings.ACCESSIBILITY_SETTINGS", "drives user to accessibility toggle"),
        ("ACTION_NOTIFICATION_LISTENER_SETTINGS", "drives user to notification toggle"),
        ("android.app.action.ADD_DEVICE_ADMIN", "requests device admin"),
        ("DevicePolicyManager", "device policy API"),
        ("wipeData", "device wipe"),
        ("lockNow", "device lock"),
    ],
    "persistence": [
        ("android.intent.action.BOOT_COMPLETED", "boot receiver"),
        ("android.intent.action.MY_PACKAGE_REPLACED", "self-update receiver"),
        ("QUICKBOOT_POWERON", "OEM quick-boot receiver"),
        ("startForegroundService", "foreground service start"),
        ("JobScheduler", "job scheduling"),
        ("androidx.work", "WorkManager"),
        ("AlarmManager", "alarms"),
        ("setComponentEnabledSetting", "component enable/disable (icon hiding)"),
        ("android.provider.Settings$ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS",
         "battery exemption prompt"),
        ("REQUEST_IGNORE_BATTERY_OPTIMIZATIONS", "battery exemption prompt"),
    ],
    "loading": [
        ("dalvik.system.DexClassLoader", "DEX loaded from a file"),
        ("dalvik.system.InMemoryDexClassLoader", "DEX loaded from memory (nothing on disk)"),
        ("dalvik.system.PathClassLoader", "class loader construction"),
        ("dalvik.system.BaseDexClassLoader", "class loader construction"),
        ("java.lang.reflect.Method", "reflection"),
        ("getDeclaredMethod", "reflection by name"),
        ("Class.forName", "class lookup by name"),
        ("setAccessible", "reflective access to non-public members"),
        ("android.content.pm.PackageInstaller", "session-based installer (dropper)"),
        ("ACTION_INSTALL_PACKAGE", "legacy install intent"),
    ],
    "crypto": [
        ("javax.crypto.Cipher", "JCA cipher"),
        ("SecretKeySpec", "raw key material"),
        ("AES/CBC/PKCS5Padding", "AES-CBC"),
        ("AES/ECB/PKCS5Padding", "AES-ECB (deterministic, a strong smell)"),
        ("PBEWith", "password-based derivation"),
        ("javax.crypto.spec.IvParameterSpec", "explicit IV"),
        ("MessageDigest", "hashing"),
    ],
    "evasion": [
        ("Build.FINGERPRINT", "build fingerprint check"),
        ("generic_x86", "emulator fingerprint string"),
        ("goldfish", "emulator device string"),
        ("ranchu", "emulator device string"),
        ("/system/bin/su", "root check path"),
        ("/system/xbin/su", "root check path"),
        ("de.robv.android.xposed", "Xposed detection"),
        ("frida", "Frida detection"),
        ("isDebuggerConnected", "debugger check"),
        ("ro.debuggable", "debuggable property check"),
        ("/proc/self/maps", "self-map inspection"),
        ("TracerPid", "ptrace-based debugger check"),
    ],
    "attribution": [
        ("getInstallerPackageName", "installer attribution check (weak)"),
        ("getInstallSourceInfo", "install source triple (strong)"),
        ("com.android.vending", "Play Store package name"),
        ("getPackageInfo", "self-inspection or signature check"),
        ("GET_SIGNING_CERTIFICATES", "signature self-check"),
        ("signingCertificateHistory", "rotation-aware signature check"),
    ],
    "native": [
        ("System.loadLibrary", "native library load"),
        ("System.load", "native library load by path"),
        ("registerNatives", "dynamic JNI registration (string form)"),
    ],
}

# Manifest-level persistence hooks
FOREGROUND_TYPES_SUSPICIOUS = {"dataSync", "specialUse", "shortService",
                               "systemExempted"}

# android:foregroundServiceType is stored as an int bitmask, so a triage tool
# that prints the raw value ("type=0x1") has told the reader nothing. Since
# API 34 the declared type is enforced -- the platform throws if a service
# starts with a type it did not declare -- which makes the declared type a
# CLAIM the sample is making about itself, and worth reading.
FGS_TYPES = [
    (0x00000001, "dataSync"),
    (0x00000002, "mediaPlayback"),
    (0x00000004, "phoneCall"),
    (0x00000008, "location"),
    (0x00000010, "connectedDevice"),
    (0x00000020, "mediaProjection"),
    (0x00000040, "camera"),
    (0x00000080, "microphone"),
    (0x00000100, "health"),
    (0x00000200, "remoteMessaging"),
    (0x00000400, "systemExempted"),
    (0x00000800, "shortService"),
    (0x00001000, "fileManagement"),
    (0x00002000, "mediaProcessing"),
    (0x40000000, "specialUse"),
]


def decode_fgs_type(v):
    """Turn an android:foregroundServiceType attribute into names."""
    if v is None:
        return None
    try:
        n = int(v, 16) if str(v).startswith("0x") else int(v)
    except (TypeError, ValueError):
        return str(v)
    names = [name for bit, name in FGS_TYPES if n & bit]
    left = n
    for bit, _ in FGS_TYPES:
        left &= ~bit
    if left:
        names.append("unknown:0x%x" % left)
    return "|".join(names) if names else "none"


# --------------------------------------------------------------------------- #
# The report
# --------------------------------------------------------------------------- #

class Report(object):
    def __init__(self, path):
        self.path = path
        self.sections = {}
        self.signals = []          # (weight, section, text)

    def add(self, name, data):
        self.sections[name] = data

    def signal(self, weight, section, text):
        self.signals.append({"weight": weight, "section": section, "text": text})


def sha(data, algo):
    h = hashlib.new(algo)
    h.update(data)
    return h.hexdigest()


def section_identity(rep, path, data, zf):
    ident = {
        "file": os.path.basename(path),
        "size": len(data),
        "size_h": human(len(data)),
        "md5": sha(data, "md5"),
        "sha1": sha(data, "sha1"),
        "sha256": sha(data, "sha256"),
        "entries": len(zf.namelist()),
    }
    dexes = []
    for name in zf.namelist():
        if name.endswith(".dex"):
            d = zf.read(name)
            facts = dex_header_facts(d) or {}
            facts.update({"name": name, "size": len(d),
                          "sha256": sha(d, "sha256")})
            dexes.append(facts)
    ident["dex"] = dexes
    ident["dex_total"] = sum(d["size"] for d in dexes)
    ident["code_fraction"] = (ident["dex_total"] / len(data)) if data else 0.0
    rep.add("identity", ident)

    # A tiny DEX inside a large APK is the classic packer shape (chapter 40
    # section 3.7: "a stub of 20-150 KB against a real app's megabytes").
    if dexes and ident["dex_total"] < 200 * 1024 and len(data) > 2 * 1024 * 1024:
        rep.signal(3, "identity",
                   "DEX is only %s of a %s file (%.1f%%). That is the shape of "
                   "a packer stub: the real code is somewhere else in the "
                   "container. See 40-Obfuscation section 3.7."
                   % (human(ident["dex_total"]), human(len(data)),
                      100 * ident["code_fraction"]))


def section_provenance(rep, path, data, zf):
    prov = {"schemes": [], "certs": [], "v1_files": [], "notes": []}
    block, err = read_signing_block(data)
    if err:
        prov["notes"].append(err)
    if block:
        if not block["consistent"]:
            prov["notes"].append(
                "signing block size fields disagree (%d vs %d) -- this is "
                "malformed and worth a container audit"
                % (block["size_header"], block["size_footer"]))
        for pid, value in block["pairs"].items():
            name = KNOWN_BLOCK_IDS.get(pid, "UNKNOWN id 0x%08x" % pid)
            prov["schemes"].append({"id": "0x%08x" % pid, "name": name,
                                    "size": len(value)})
            if pid not in KNOWN_BLOCK_IDS:
                rep.signal(2, "provenance",
                           "unknown signing-block id 0x%08x carrying %s. "
                           "Unknown ID-value pairs are ignored by the platform "
                           "and are a documented smuggling channel -- run "
                           "10-APK-Internals/scripts/apk-container-triage.py."
                           % (pid, human(len(value))))
        for pid in (ID_V3, ID_V31, ID_V2):
            if pid in block["pairs"]:
                for der in certs_from_v2v3(block["pairs"][pid]):
                    info = parse_certificate(der)
                    info["source"] = KNOWN_BLOCK_IDS.get(pid, "?")
                    prov["certs"].append(info)
                if prov["certs"]:
                    break

    for name in zf.namelist():
        if name.upper().startswith("META-INF/") and \
           name.upper().endswith((".RSA", ".DSA", ".EC")):
            prov["v1_files"].append(name)
            if not prov["certs"]:
                for der in find_certs_in_pkcs7(zf.read(name)):
                    info = parse_certificate(der)
                    info["source"] = "v1 (%s, heuristic scan)" % name
                    prov["certs"].append(info)

    if prov["v1_files"]:
        prov["schemes"].append({"id": "v1", "name": "JAR signing (v1)",
                                "size": len(prov["v1_files"])})

    # De-duplicate certificates by SHA-256.
    seen = set()
    uniq = []
    for c in prov["certs"]:
        if c["sha256"] in seen:
            continue
        seen.add(c["sha256"])
        uniq.append(c)
    prov["certs"] = uniq

    if not prov["certs"]:
        prov["notes"].append("no certificate could be read from this file")
    for c in prov["certs"]:
        if c.get("self_signed"):
            prov["notes"].append(
                "certificate %s... is self-signed -- which is NORMAL for "
                "Android and is not a finding" % c["sha256"][:16])
    rep.add("provenance", prov)


def section_manifest(rep, zf):
    man = {"ok": False}
    try:
        raw = zf.read("AndroidManifest.xml")
    except KeyError:
        man["error"] = "no AndroidManifest.xml in the archive"
        rep.add("manifest", man)
        return None
    try:
        root = parse_axml(raw)
    except (AxmlError, struct.error, IndexError) as e:
        man["error"] = "AXML parse failed: %s" % e
        rep.signal(3, "manifest",
                   "the manifest could not be parsed (%s). A manifest that "
                   "defeats a parser but not the platform is an attack class "
                   "in its own right -- see 10-APK-Internals section 18." % e)
        rep.add("manifest", man)
        return None

    A = "{http://schemas.android.com/apk/res/android}"

    def attr(el, key):
        # The AXML string pool stores attribute names without the namespace,
        # so a plain lookup is right here; the fallback covers decoded files.
        return el.get(key) or el.get(A + key)

    man["ok"] = True
    man["package"] = attr(root, "package") or root.get("package")
    man["versionCode"] = attr(root, "versionCode")
    man["versionName"] = attr(root, "versionName")
    for us in root.find_all("uses-sdk"):
        man["minSdkVersion"] = attr(us, "minSdkVersion")
        man["targetSdkVersion"] = attr(us, "targetSdkVersion")
    man.setdefault("minSdkVersion", None)
    man.setdefault("targetSdkVersion", None)

    perms = []
    for p in root.find_all("uses-permission"):
        n = attr(p, "name")
        if n:
            perms.append(n)
    for p in root.find_all("uses-permission-sdk-23"):
        n = attr(p, "name")
        if n:
            perms.append(n)
    man["permissions"] = sorted(set(perms))

    apps = [c for c in root.children if c.name == "application"]
    app = apps[0] if apps else None
    man["application"] = {}
    if app is not None:
        for k in ("name", "allowBackup", "debuggable", "extractNativeLibs",
                  "usesCleartextTraffic", "networkSecurityConfig",
                  "hasFragileUserData", "label"):
            v = attr(app, k)
            if v is not None:
                man["application"][k] = v

    def comp_list(kind):
        out = []
        if app is None:
            return out
        for el in app.children:
            if el.name != kind:
                continue
            actions = []
            for f in el.find_all("action"):
                a = attr(f, "name")
                if a:
                    actions.append(a)
            metas = {}
            for m in el.children:
                if m.name == "meta-data":
                    metas[attr(m, "name") or "?"] = (attr(m, "value")
                                                     or attr(m, "resource") or "")
            out.append({
                "name": attr(el, "name"),
                "exported": attr(el, "exported"),
                "enabled": attr(el, "enabled"),
                "permission": attr(el, "permission"),
                "process": attr(el, "process"),
                "authorities": attr(el, "authorities"),
                "initOrder": attr(el, "initOrder"),
                "foregroundServiceType": attr(el, "foregroundServiceType"),
                "stopWithTask": attr(el, "stopWithTask"),
                "directBootAware": attr(el, "directBootAware"),
                "excludeFromRecents": attr(el, "excludeFromRecents"),
                "actions": actions,
                "meta": metas,
            })
        return out

    man["activities"] = comp_list("activity")
    man["activity_aliases"] = comp_list("activity-alias")
    man["services"] = comp_list("service")
    man["receivers"] = comp_list("receiver")
    man["providers"] = comp_list("provider")
    rep.add("manifest", man)
    return man


def scan_capability_descriptors(rep, zf):
    """Parse every res/xml/*.xml and report the two that carry capability.

    A <meta-data> in the manifest points at a resource ID, not a filename, so
    a manifest-only reading prints `@0x7f010000` and stops. The descriptor is
    where the actual answer lives: an accessibility service is defined by
    canRetrieveWindowContent, canPerformGestures and the presence or absence
    of packageNames, not by the class it names.

    Resolving the resource ID properly means parsing resources.arsc. This
    does not. It parses every res/xml entry and reports the ones whose ROOT
    ELEMENT is a capability descriptor -- which finds them all, and which can
    over-report when an app ships several. Stated plainly rather than hidden:
    the mapping from meta-data to file is NOT proven here.
    """
    found = []
    for name in zf.namelist():
        if not (name.startswith("res/xml") and name.endswith(".xml")):
            continue
        try:
            root = parse_axml(zf.read(name))
        except (AxmlError, struct.error, IndexError, ValueError):
            continue
        if root.name not in ("accessibility-service", "device-admin"):
            continue
        entry = {"file": name, "kind": root.name, "attrs": dict(root.attrs),
                 "policies": []}
        if root.name == "device-admin":
            for up in root.find_all("uses-policies"):
                for child in up.children:
                    entry["policies"].append(child.name)
        found.append(entry)

        if root.name == "accessibility-service":
            a = root.attrs
            hot = []
            if a.get("canRetrieveWindowContent") == "true":
                hot.append("canRetrieveWindowContent")
            if a.get("canPerformGestures") == "true":
                hot.append("canPerformGestures")
            if "packageNames" not in a:
                hot.append("no packageNames filter (every app on the device)")
            ev = a.get("accessibilityEventTypes", "")
            if ev in ("0xffffffff", "-1") or "typeAllMask" in str(ev):
                hot.append("accessibilityEventTypes=typeAllMask")
            if len(hot) >= 3:
                rep.signal(3, "capability",
                           "%s asks for the whole device: %s. A purpose-built "
                           "accessibility tool names the packages it serves "
                           "and subscribes to the events it needs."
                           % (name, "; ".join(hot)))
            elif hot:
                rep.signal(2, "capability",
                           "%s: %s" % (name, "; ".join(hot)))
        else:
            if entry["policies"]:
                strong = [p for p in entry["policies"]
                          if p in ("wipe-data", "reset-password")]
                rep.signal(3 if strong else 1, "capability",
                           "%s requests device-admin policies: %s"
                           % (name, ", ".join(entry["policies"])))
            else:
                rep.signal(1, "capability",
                           "%s declares device admin with an EMPTY policy "
                           "list. Note that uninstall resistance comes from "
                           "being an ACTIVE admin at all, not from any "
                           "policy, so an empty list is not a weaker "
                           "declaration for that purpose." % name)
    return found


def section_capability(rep, man, zf):
    cap = {"granted_model": [], "declared": [], "absent_but_notable": [],
           "descriptors": scan_capability_descriptors(rep, zf)}
    if not man or not man.get("ok"):
        rep.add("capability", cap)
        return
    perms = man["permissions"]
    for suffix, capability, weight, note in CAPABILITY_PERMISSIONS:
        hit = [p for p in perms if p.endswith("." + suffix) or p == suffix]
        if hit:
            cap["granted_model"].append({
                "permission": hit[0], "capability": capability,
                "weight": weight, "note": note})
            if weight >= 3:
                rep.signal(weight, "capability",
                           "%s -> %s" % (hit[0].split(".")[-1], capability))

    # Component-level declarations. These are stronger than the permission,
    # because a permission can be requested and never used, while a declared
    # service with the right intent-filter is the app asking for the binding.
    for svc in man.get("services", []):
        perm = (svc.get("permission") or "")
        if perm.endswith("BIND_ACCESSIBILITY_SERVICE"):
            cap["declared"].append({
                "component": svc["name"], "kind": "accessibility service",
                "meta": svc.get("meta", {}), "weight": 3})
            rep.signal(3, "capability",
                       "accessibility service DECLARED: %s. Read its "
                       "meta-data XML: canRetrieveWindowContent, "
                       "canPerformGestures and the presence or absence of "
                       "packageNames are where the real answer is."
                       % svc["name"])
        if perm.endswith("BIND_NOTIFICATION_LISTENER_SERVICE"):
            cap["declared"].append({
                "component": svc["name"], "kind": "notification listener",
                "weight": 3})
            rep.signal(3, "capability",
                       "notification listener DECLARED: %s. Reads and can "
                       "cancel every notification on the device, which "
                       "includes one-time codes." % svc["name"])
    for rcv in man.get("receivers", []):
        if (rcv.get("permission") or "").endswith("BIND_DEVICE_ADMIN"):
            cap["declared"].append({
                "component": rcv["name"], "kind": "device admin",
                "meta": rcv.get("meta", {}), "weight": 2})
            rep.signal(2, "capability",
                       "device admin receiver DECLARED: %s. Read the policy "
                       "XML it points at -- an empty <uses-policies> still "
                       "gives uninstall resistance." % rcv["name"])
    rep.add("capability", cap)


def section_persistence(rep, man):
    per = {"hooks": [], "processes": set()}
    if not man or not man.get("ok"):
        per["processes"] = []
        rep.add("persistence", per)
        return

    for p in man.get("providers", []):
        per["hooks"].append({
            "kind": "ContentProvider",
            "component": p["name"],
            "detail": "authorities=%s initOrder=%s exported=%s"
                      % (p.get("authorities"), p.get("initOrder"),
                         p.get("exported")),
            "why": "ContentProvider.onCreate() runs inside "
                   "ActivityThread.installContentProviders(), BEFORE "
                   "Application.onCreate(). Measured in 09-Android-App-"
                   "Internals section 9.2: provider at 31.118, Application at "
                   "31.141, a 23 ms gap on that device.",
            "weight": 2 if (p.get("initOrder") or p.get("exported") == "true") else 1,
        })

    boot_actions = {"android.intent.action.BOOT_COMPLETED",
                    "android.intent.action.LOCKED_BOOT_COMPLETED",
                    "android.intent.action.MY_PACKAGE_REPLACED",
                    "android.intent.action.QUICKBOOT_POWERON",
                    "com.htc.intent.action.QUICKBOOT_POWERON"}
    for r in man.get("receivers", []):
        hits = sorted(set(r["actions"]) & boot_actions)
        if hits:
            shown = []
            for a in hits:
                short = a.split(".")[-1]
                if short not in shown:
                    shown.append(short)
            per["hooks"].append({
                "kind": "boot receiver",
                "component": r["name"],
                "detail": ", ".join(shown),
                "why": "Restarts the app after a reboot or after its own "
                       "update. Note that an app in the STOPPED state gets "
                       "nothing, so a launcher Activity is a prerequisite.",
                "weight": 2 if len(hits) > 1 else 1,
            })
            if "android.intent.action.MY_PACKAGE_REPLACED" in hits:
                rep.signal(2, "persistence",
                           "%s listens for MY_PACKAGE_REPLACED -- it re-arms "
                           "itself after its own update." % r["name"])

    for s in man.get("services", []):
        fst = decode_fgs_type(s.get("foregroundServiceType"))
        if fst:
            per["hooks"].append({
                "kind": "foreground service",
                "component": s["name"],
                "detail": "type=%s stopWithTask=%s" % (fst, s.get("stopWithTask")),
                "why": "A foreground service is exempt from the background "
                       "execution limits introduced at API 26 and tightened "
                       "at API 31. The declared TYPE is the claim being made; "
                       "compare it with what the code does.",
                "weight": 2 if fst in FOREGROUND_TYPES_SUSPICIOUS else 1,
            })
        if s.get("stopWithTask") == "false":
            rep.signal(1, "persistence",
                       "%s declares stopWithTask=false -- it survives the "
                       "user swiping the task away." % s["name"])

    for kind in ("activities", "services", "receivers", "providers"):
        for c in man.get(kind, []):
            if c.get("process"):
                per["processes"].add(c["process"])
    per["processes"] = sorted(per["processes"])
    if len(per["processes"]) >= 1:
        per["hooks"].append({
            "kind": "multi-process",
            "component": ", ".join(per["processes"]),
            "detail": "%d extra process name(s)" % len(per["processes"]),
            "why": "A second process is killed independently of the first, "
                   "which is what makes a watchdog pair possible. It buys NO "
                   "extra privilege: same uid, same SELinux label, same data "
                   "directory. Check whether each process's components "
                   "reference the other's.",
            "weight": 2 if len(per["processes"]) >= 1 else 1,
        })
        rep.signal(2, "persistence",
                   "components run in %d additional process(es): %s. Look for "
                   "a watchdog pair -- two components in two processes that "
                   "name each other and exchange no data."
                   % (len(per["processes"]), ", ".join(per["processes"])))

    for a in man.get("activity_aliases", []):
        per["hooks"].append({
            "kind": "activity-alias",
            "component": a["name"],
            "detail": "enabled=%s" % a.get("enabled"),
            "why": "An alias carrying the LAUNCHER filter can be disabled at "
                   "runtime with setComponentEnabledSetting(), which removes "
                   "the icon from the drawer while the app stays installed.",
            "weight": 2,
        })
        rep.signal(2, "persistence",
                   "activity-alias %s -- the standard icon-hiding construct. "
                   "Confirm on a device with `cmd package resolve-activity "
                   "--brief <pkg>`." % a["name"])

    rep.add("persistence", per)


def section_native(rep, zf):
    nat = {"libs": [], "abis": []}
    for name in zf.namelist():
        if not name.startswith("lib/") or not name.endswith(".so"):
            continue
        parts = name.split("/")
        abi = parts[1] if len(parts) > 2 else "?"
        data = zf.read(name)
        f = elf_facts(data) or {}
        f.update({"name": name, "abi": abi,
                  "sha256": sha(data, "sha256"),
                  "jni_onload": b"JNI_OnLoad" in data,
                  "java_exports": len(re.findall(rb"Java_[A-Za-z0-9_]{4,}", data)),
                  "registernatives": b"RegisterNatives" in data,
                  "entropy": entropy(data[:262144]),
                  })
        nat["libs"].append(f)
        if abi not in nat["abis"]:
            nat["abis"].append(abi)

    for f in nat["libs"]:
        if f.get("has_init_array"):
            rep.signal(2, "native",
                       "%s has DT_INIT_ARRAY. Those functions run when the "
                       "linker loads the library -- BEFORE dlopen returns and "
                       "therefore before JNI_OnLoad and before any Java code "
                       "can observe it. Chapter 15 section 3.12. To see them "
                       "you must spawn-gate, not attach." % f["name"])
        if f.get("registernatives") and f.get("java_exports", 0) == 0:
            rep.signal(3, "native",
                       "%s calls RegisterNatives and exports NO Java_* "
                       "symbols. The Java-to-native mapping is therefore "
                       "absent from the file entirely and cannot be recovered "
                       "statically. This is the blind spot 15, 51 and 52 all "
                       "name." % f["name"])
        if f.get("entropy", 0) > 7.5:
            rep.signal(2, "native",
                       "%s has entropy %.2f over its first 256 KiB, which is "
                       "packed-or-compressed territory. Entropy alone proves "
                       "nothing -- check for a stub-sized DEX alongside it."
                       % (f["name"], f["entropy"]))
    rep.add("native", nat)


def section_loading(rep, zf, man):
    """Does the code you can see equal the code that runs?"""
    load = {"assets": [], "high_entropy": [], "notes": []}
    for info in zf.infolist():
        n = info.filename
        if n.endswith("/") or info.file_size == 0:
            continue
        if not (n.startswith("assets/") or n.startswith("res/raw/")):
            continue
        data = zf.read(n)
        e = entropy(data[:262144])
        rec = {"name": n, "size": info.file_size, "entropy": round(e, 2),
               "magic": binascii.hexlify(data[:4]).decode(),
               "compress_ratio": round(info.compress_size / info.file_size, 3)
               if info.file_size else 0}
        # A DEX or ELF hiding behind a harmless extension.
        if data[:8] in DEX_MAGICS:
            rec["contains"] = "DEX"
            rep.signal(3, "loading",
                       "%s IS A DEX FILE regardless of its name. The code you "
                       "decompiled from classes.dex is not all the code."
                       % n)
        elif data[:4] == b"\x7fELF":
            rec["contains"] = "ELF"
            rep.signal(3, "loading",
                       "%s is an ELF binary outside lib/. Ask what loads it, "
                       "and how it is made executable given that app data "
                       "directories are noexec on modern releases." % n)
        elif data[:2] == b"PK":
            rec["contains"] = "zip/jar/apk"
        load["assets"].append(rec)
        if e > 7.5 and info.file_size > 1024:
            load["high_entropy"].append(rec)
            rep.signal(2, "loading",
                       "%s: %s at entropy %.2f, compressed ratio %.2f. "
                       "Chapter 40's rule is `check entropy, not extension`. "
                       "An incompressible blob is encrypted, already "
                       "compressed, or media. Try "
                       "config-decrypt.py --apk <apk> --auto."
                       % (n, human(info.file_size), e, rec["compress_ratio"]))
    rep.add("loading", load)


def section_strings(rep, zf, args):
    """DEX string-pool markers, grouped by what they would mean."""
    st = {"groups": {}, "total_strings": 0, "iocs": {}}
    allstr = []
    for name in zf.namelist():
        if name.endswith(".dex"):
            allstr.extend(dex_strings(zf.read(name)))
    st["total_strings"] = len(allstr)
    pool = set(allstr)
    joined = "\n".join(allstr)
    # A DEX string pool stores CLASS names as type descriptors --
    # `Landroid/accessibilityservice/AccessibilityService;` -- not as dotted
    # names. A marker list written in dotted form therefore matches NOTHING,
    # silently, and the tool reports a clean sample. This normalisation is
    # the fix, and the bug is worth recording: the first run of this script
    # against the chapter's own sample missed every accessibility marker for
    # exactly this reason, while correctly reporting the manifest
    # declaration. Two independent readings disagreeing is what caught it.
    joined_norm = joined.replace("/", ".")

    for group, markers in DEX_MARKERS.items():
        hits = []
        for needle, meaning in markers:
            n = joined.count(needle)
            if not n:
                n = joined_norm.count(needle)
            if not n and needle in pool:
                n = 1
            if n:
                hits.append({"marker": needle, "meaning": meaning, "count": n})
        if hits:
            st["groups"][group] = hits

    # Indicators. Deliberately conservative regexes; this is triage, not a
    # threat-intel feed.
    urls = set(re.findall(r"[a-z][a-z0-9+.-]{2,10}://[^\s\"'<>\\)]{4,180}", joined))
    urls = {u for u in urls
            if not u.startswith(("http://schemas.android.com",
                                 "http://www.w3.org",
                                 "http://xmlpull.org",
                                 "https://schemas.android.com"))}
    st["iocs"]["url"] = sorted(urls)[:args.max_iocs]
    st["iocs"]["url_total"] = len(urls)
    rep.add("strings", st)

    if "loading" in st["groups"]:
        for h in st["groups"]["loading"]:
            if "InMemoryDexClassLoader" in h["marker"]:
                rep.signal(3, "loading",
                           "InMemoryDexClassLoader appears in the DEX string "
                           "pool. DEX loaded from a ByteBuffer never touches "
                           "disk, so there is nothing to pull off the device. "
                           "Dump it from memory instead -- "
                           "40-Obfuscation/scripts/frida-classloader-dump.js.")
            if "DexClassLoader" == h["marker"].split(".")[-1]:
                rep.signal(2, "loading",
                           "DexClassLoader appears. Some code is loaded at "
                           "runtime; a static reading of classes.dex is "
                           "therefore incomplete by an unknown amount.")
    if "evasion" in st["groups"]:
        rep.signal(2, "evasion",
                   "%d anti-analysis markers in the string pool. Characterise "
                   "them before you defeat them -- which checks a sample "
                   "performs is a classification signal, and 37/38/39/67 own "
                   "the defeat." % len(st["groups"]["evasion"]))
    if "attribution" in st["groups"]:
        for h in st["groups"]["attribution"]:
            if h["marker"] == "getInstallerPackageName":
                rep.signal(1, "attribution",
                           "getInstallerPackageName is referenced. As a "
                           "control it is defeated by `adb install -i "
                           "com.android.vending`; as a signal it tells you "
                           "the author cared where the app came from.")


# --------------------------------------------------------------------------- #
# Printing
# --------------------------------------------------------------------------- #

RULE = "=" * 78
THIN = "-" * 78

BANNER = """\
%s
 apk-triage.py - static malware triage, one pass, no execution
 Every line below is a SIGNAL. There is no verdict line, deliberately.
 Nothing was executed, installed, resolved or unpacked.
%s""" % (RULE, RULE)


def w_mark(w):
    return {3: "[***]", 2: "[** ]", 1: "[*  ]"}.get(w, "[   ]")


def print_report(rep, args):
    sec = rep.sections
    only = set(args.only.split(",")) if args.only else None

    def want(name):
        return only is None or name in only

    print(BANNER)
    print()

    if want("identity"):
        i = sec.get("identity", {})
        print(RULE)
        print("1. IDENTITY -- what is this file")
        print(RULE)
        print("  file            %s" % i.get("file"))
        print("  size            %s (%d bytes)" % (i.get("size_h"), i.get("size", 0)))
        print("  md5             %s" % i.get("md5"))
        print("  sha1            %s" % i.get("sha1"))
        print("  sha256          %s" % i.get("sha256"))
        print("  zip entries     %d" % i.get("entries", 0))
        m = sec.get("manifest", {})
        if m.get("ok"):
            print("  package         %s" % m.get("package"))
            print("  version         code=%s name=%s"
                  % (m.get("versionCode"), m.get("versionName")))
            print("  sdk             min=%s target=%s"
                  % (m.get("minSdkVersion"), m.get("targetSdkVersion")))
            app = m.get("application", {})
            if app:
                print("  application     %s" % ", ".join(
                    "%s=%s" % (k, v) for k, v in sorted(app.items())))
        elif m.get("error"):
            print("  manifest        %s" % m["error"])
        for d in i.get("dex", []):
            print("  dex             %-16s %9s  v%s  %s classes, %s methods, "
                  "%s strings"
                  % (d.get("name"), human(d.get("size", 0)), d.get("version"),
                     d.get("classes"), d.get("methods"), d.get("strings")))
            print("                  sha256 %s" % d.get("sha256"))
        if i.get("dex"):
            print("  code fraction   %.1f%% of the file is DEX"
                  % (100 * i.get("code_fraction", 0)))
        print()
        print("  Hash first, always. The sha256 is how you ask whether anyone")
        print("  has seen this file before, and it is the only identifier in")
        print("  this report that is not forgeable.")
        print()

    if want("provenance"):
        p = sec.get("provenance", {})
        print(RULE)
        print("2. PROVENANCE -- who signed it, and what that is worth")
        print(RULE)
        if p.get("schemes"):
            for s in p["schemes"]:
                print("  scheme          %-28s %s" % (s["name"], s["id"]))
        else:
            print("  scheme          none detected")
        for c in p.get("certs", []):
            print(THIN)
            print("  certificate     %s" % c.get("source"))
            print("    subject       %s" % c.get("subject"))
            print("    issuer        %s" % c.get("issuer"))
            print("    validity      %s .. %s" % (c.get("not_before"), c.get("not_after")))
            print("    serial        %s" % c.get("serial"))
            print("    sha256        %s" % c.get("sha256"))
            print("    sha1          %s" % c.get("sha1"))
        for n in p.get("notes", []):
            print("  note            %s" % n)
        print()
        print("  WHAT THE SIGNER HASH IS WORTH, precisely:")
        print("    * It identifies a KEY. Two APKs with the same certificate")
        print("      SHA-256 were signed by whoever held that private key.")
        print("      That is a strong, cheap corpus link and it is the single")
        print("      most useful clustering key you have.")
        print("    * It does NOT identify a person, a group or a country.")
        print("    * Self-signed is NORMAL on Android. Every app is. A")
        print("      self-signed certificate is not a finding.")
        print("    * The subject fields are attacker-controlled free text.")
        print("      They are worth recording and worth nothing as evidence.")
        print("    * Certificates are copied between actors, sold, leaked and")
        print("      reused by build tools. A shared debug key (CN=Android")
        print("      Debug) links nothing at all -- thousands of unrelated")
        print("      apps share it.")
        print("    * This tool did NOT verify the signature. Run:")
        print("        apksigner verify -v --print-certs <apk>")
        print("    * The INSTALLER attribution is not in the file at all. It")
        print("      is recorded by the device at install time. Ask the")
        print("      device: adb shell dumpsys package <pkg> | grep -E")
        print("        'installer|Initiator|originating|packageSource'")
        print("      and prefer getInstallSourceInfo()'s initiating package,")
        print("      which the system records from the UID that opened the")
        print("      session, over installerPackageName, which `pm install -i`")
        print("      sets to anything you like. See 09 section 5.5.")
        print()

    if want("capability"):
        c = sec.get("capability", {})
        print(RULE)
        print("3. CAPABILITY -- what it could do if every request were granted")
        print(RULE)
        rows = sorted(c.get("granted_model", []), key=lambda r: -r["weight"])
        if rows:
            print("  %-6s %-38s %s" % ("weight", "permission", "capability"))
            for r in rows:
                print("  %-6s %-38s %s"
                      % (w_mark(r["weight"]), r["permission"].split(".")[-1],
                         r["capability"]))
        else:
            print("  no capability-relevant permissions requested")
        if c.get("declared"):
            print()
            print("  COMPONENT DECLARATIONS -- stronger than a permission,")
            print("  because this is the app asking the system to bind it:")
            for d in c["declared"]:
                print("   %s %-24s %s" % (w_mark(d["weight"]), d["kind"], d["component"]))
                for k, v in (d.get("meta") or {}).items():
                    print("        meta-data %s = %s" % (k, v))
                    if str(v).startswith("@0x"):
                        print("        (a resource ID. The descriptor it names "
                              "is below; resources.arsc")
                        print("         is not parsed, so the ID-to-file "
                              "mapping is NOT proven here.)")
        if c.get("descriptors"):
            print()
            print("  CAPABILITY DESCRIPTORS found in res/xml -- this is where")
            print("  the real answer lives, not in the class name:")
            for d in c["descriptors"]:
                print("    %-38s <%s>" % (d["file"], d["kind"]))
                for k, v in sorted(d["attrs"].items()):
                    print("        %-32s %s" % (k, v))
                if d["kind"] == "device-admin":
                    print("        %-32s %s" % ("uses-policies",
                                                ", ".join(d["policies"]) or "(empty)"))
                if d["kind"] == "accessibility-service" and \
                        "packageNames" not in d["attrs"]:
                    print("        %-32s %s" % ("packageNames",
                                                "ABSENT -- every package"))
        print()
        for r in rows:
            if r["note"]:
                print("  %s:" % r["permission"].split(".")[-1])
                for line in _wrap(r["note"], 72):
                    print("      " + line)
        print()

    if want("persistence"):
        p = sec.get("persistence", {})
        print(RULE)
        print("4. PERSISTENCE -- how it survives a reboot, a swipe, a kill")
        print(RULE)
        hooks = sorted(p.get("hooks", []), key=lambda h: -h["weight"])
        if not hooks:
            print("  no manifest-level persistence hook found.")
            print("  That does NOT mean there is none: JobScheduler,")
            print("  WorkManager and AlarmManager are code, not manifest.")
        for h in hooks:
            print(THIN)
            print("  %s %-18s %s" % (w_mark(h["weight"]), h["kind"], h["component"]))
            print("      %s" % h["detail"])
            for line in _wrap(h["why"], 70):
                print("      " + line)
        print()

    if want("native"):
        n = sec.get("native", {})
        print(RULE)
        print("5. NATIVE -- how much is not Java, and what runs earliest")
        print(RULE)
        if not n.get("libs"):
            print("  no native libraries in lib/.")
            print("  Note that this is not the same as `no native code`: a")
            print("  library can be unpacked from an asset at runtime, and")
            print("  System.load() takes an arbitrary path.")
        for f in n.get("libs", []):
            print(THIN)
            print("  %-40s %s" % (f["name"], human(f.get("size", 0))))
            print("      %s %s  entropy %.2f  %s"
                  % (f.get("class"), f.get("machine"), f.get("entropy", 0),
                     "stripped" if f.get("stripped") else "has .symtab"))
            print("      DT_INIT=%s DT_INIT_ARRAY=%s DT_NEEDED=%d"
                  % (f.get("has_init"), f.get("has_init_array"),
                     f.get("needed_count", 0)))
            print("      JNI_OnLoad=%s  Java_* symbols=%d  RegisterNatives=%s"
                  % (f.get("jni_onload"), f.get("java_exports", 0),
                     f.get("registernatives")))
            print("      sha256 %s" % f.get("sha256"))
        if n.get("libs"):
            print()
            print("  For the full ELF read -- sections, relocations, hardening")
            print("  flags, real symbol tables -- hand over to chapter 15:")
            print("    python3 ../../15-Native-Code/scripts/elf-inspect.py <so>")
            print("    ../../15-Native-Code/scripts/so-triage.sh --apk <apk>")
        print()

    if want("loading"):
        l = sec.get("loading", {})
        print(RULE)
        print("6. LOADING -- does the code you can see equal the code that runs")
        print(RULE)
        assets = sorted(l.get("assets", []), key=lambda a: -a["entropy"])
        if not assets:
            print("  no assets/ or res/raw/ entries.")
        for a in assets[:args.max_assets]:
            tag = a.get("contains", "")
            print("  %-46s %9s  H=%.2f  ratio=%.2f  %s"
                  % (a["name"][:46], human(a["size"]), a["entropy"],
                     a["compress_ratio"], tag))
        if len(assets) > args.max_assets:
            print("  ... and %d more" % (len(assets) - args.max_assets))
        print()
        print("  High entropy is NOT evidence of encryption -- a PNG, a JPEG")
        print("  and a zip are all incompressible. The signal is entropy PLUS")
        print("  context: a compression ratio near 1.0, a magic number that")
        print("  does not match the extension, and a size in the right range.")
        print()

    if want("strings") and not args.no_strings:
        s = sec.get("strings", {})
        print(RULE)
        print("7. STRING-POOL MARKERS -- %d strings across all DEX files"
              % s.get("total_strings", 0))
        print(RULE)
        for group in ("capability", "persistence", "loading", "crypto",
                      "evasion", "attribution", "native"):
            hits = s.get("groups", {}).get(group)
            if not hits:
                continue
            print("  %s" % group.upper())
            for h in sorted(hits, key=lambda x: -x["count"]):
                print("    %-52s %s" % (h["marker"][:52], h["meaning"]))
        urls = s.get("iocs", {}).get("url", [])
        if urls:
            print()
            print("  URLs in the string pool (%d total, showing %d%s):"
                  % (s["iocs"].get("url_total", 0), len(urls),
                     "" if args.raw_iocs else ", defanged"))
            for u in urls:
                print("    %s" % (u if args.raw_iocs else defang(u)))
        print()
        print("  A marker is a mention, not a call. The string pool records")
        print("  that a name appears somewhere in the file; it does not say")
        print("  the code path is reachable, or that it is the app's own code")
        print("  rather than a bundled SDK's. Chapter 52's arithmetic applies")
        print("  unchanged: a hit is not a lead and a lead is not a finding.")
        print()

    print(RULE)
    print("SIGNALS, ranked -- %d total" % len(rep.signals))
    print(RULE)
    if not rep.signals:
        print("  none above the reporting threshold.")
        print("  A quiet triage is not a clean sample. It means the cheap")
        print("  static checks found nothing, which is exactly what a packed")
        print("  sample looks like too. Check section 6 before concluding.")
    for s in sorted(rep.signals, key=lambda x: -x["weight"]):
        print("  %s %-12s %s" % (w_mark(s["weight"]), s["section"],
                                 _wrap(s["text"], 58)[0]))
        for line in _wrap(s["text"], 58)[1:]:
            print("  %s %-12s %s" % ("     ", "", line))
    print()
    print(RULE)
    print("WHAT THIS REPORT DOES NOT SAY")
    print(RULE)
    print("  It does not say this sample is malicious, or benign. It says")
    print("  what capability was requested, what persistence was declared,")
    print("  what native surface exists and what the code you can read")
    print("  mentions. Deciding is a human act and it needs at least:")
    print("    * the app's claimed purpose, and whether the capability fits it")
    print("    * where the file came from, from the DEVICE, not the file")
    print("    * a dynamic pass in isolation, if you can run it safely")
    print("    * public reporting on the signer hash and the sha256")
    print()
    print("  NEXT COMMANDS, in the order they are usually worth running:")
    print("    apksigner verify -v --print-certs <apk>")
    print("    python3 -B config-decrypt.py --apk <apk> --auto")
    print("    python3 ../../32-Manifest/scripts/manifest-audit.py <manifest>")
    print("    python3 ../../10-APK-Internals/scripts/apk-container-triage.py <apk>")
    print("    ../../15-Native-Code/scripts/so-triage.sh --apk <apk>")
    print("    jadx -d out <apk>   then   "
          "python3 ../../52-StaticAnalysis/scripts/static-sweep.py out")
    print()


def _wrap(text, width):
    words = text.split()
    lines, cur = [], ""
    for w in words:
        if len(cur) + len(w) + 1 > width:
            lines.append(cur)
            cur = w
        else:
            cur = (cur + " " + w).strip()
    if cur:
        lines.append(cur)
    return lines or [""]


def quiet_line(rep):
    i = rep.sections.get("identity", {})
    m = rep.sections.get("manifest", {})
    hi = sum(1 for s in rep.signals if s["weight"] == 3)
    md = sum(1 for s in rep.signals if s["weight"] == 2)
    certs = rep.sections.get("provenance", {}).get("certs", [])
    signer = certs[0]["sha256"][:16] if certs else "?" * 16
    return "%s  %-34s  signer=%s  signals=%d/%d" % (
        i.get("sha256", "?")[:16], (m.get("package") or "(unparsed)")[:34],
        signer, hi, md)


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

def triage(path, args):
    with open(path, "rb") as fh:
        data = fh.read()
    rep = Report(path)
    try:
        zf = zipfile.ZipFile(path)
    except zipfile.BadZipFile as e:
        print("%s: not a zip archive (%s)" % (path, e), file=sys.stderr)
        return None
    with zf:
        section_identity(rep, path, data, zf)
        man = section_manifest(rep, zf)
        section_provenance(rep, path, data, zf)
        section_capability(rep, man, zf)
        section_persistence(rep, man)
        section_native(rep, zf)
        section_loading(rep, zf, man)
        if not args.no_strings:
            section_strings(rep, zf, args)
    return rep


def main(argv):
    ap = argparse.ArgumentParser(
        description="Static malware triage for Android APKs. Signals, not verdicts.")
    ap.add_argument("apk", nargs="+")
    ap.add_argument("--json", action="store_true", help="machine-readable output")
    ap.add_argument("--quiet", action="store_true", help="one line per APK")
    ap.add_argument("--only", help="comma-separated sections: identity,"
                                   "provenance,capability,persistence,native,"
                                   "loading,strings")
    ap.add_argument("--no-strings", action="store_true",
                    help="skip the DEX string pass (much faster on big files)")
    ap.add_argument("--raw-iocs", action="store_true",
                    help="print indicators live rather than defanged")
    ap.add_argument("--max-iocs", type=int, default=30)
    ap.add_argument("--max-assets", type=int, default=25)
    args = ap.parse_args(argv)

    rc = 0
    for path in args.apk:
        if not os.path.isfile(path):
            print("%s: no such file" % path, file=sys.stderr)
            rc = 2
            continue
        rep = triage(path, args)
        if rep is None:
            rc = 2
            continue
        if args.json:
            out = dict(rep.sections)
            out["signals"] = rep.signals
            out["_file"] = path
            print(json.dumps(out, indent=2, sort_keys=True, default=str))
        elif args.quiet:
            print(quiet_line(rep))
        else:
            print_report(rep, args)
    return rc


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