#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
make-config-assets.py — generate the inert sample's two encrypted config
                        blobs into a build directory.

PURPOSE
    The repository ships SOURCES, not binaries. So the two config blobs the
    inert sample carries are not committed; they are generated here, at build
    time, into the out-of-tree output directory that build.sh uses.

    That is not only artefact hygiene. It is also the point of the exercise:
    you can read exactly what the plaintext is, in this file, BEFORE you run
    the decryptor against the built APK. When ../../scripts/config-decrypt.py
    prints something, you can check it against the ground truth below rather
    than trusting the tool. A triage tool you have never seen produce a known
    answer is a tool you cannot rely on.

USAGE
    # host — normally invoked by build.sh
    python3 -B make-config-assets.py <output-assets-dir>

    # host — print the plaintexts and exit, writing nothing
    python3 -B make-config-assets.py --show

REQUIREMENTS
    Python 3.8+. Standard library only. The AES implementation is borrowed
    from ../../scripts/config-decrypt.py by executing that file into a
    namespace — deliberately NOT by importing it, because the filename
    contains a hyphen and because importlib writes __pycache__ even under
    PYTHONDONTWRITEBYTECODE, which this repository treats as a build
    artefact.

WHAT THIS WILL *NOT* DO
    * It will not produce a realistic packed sample. There is no obfuscation,
      no string table, no second stage. The blobs are two clean examples of
      the two commonest shapes, and nothing more.
    * It will not produce indicators that resolve. Every hostname is under
      `.invalid`, which RFC 2606 reserves permanently. No DNS server anywhere
      will answer for them, by design, forever.

SAFETY
    The plaintexts below are FICTION. They are written to look like a real
    config so that the shape is recognisable, and every value in them is
    inert: the campaign tag names this repository, the "targets" are
    `.invalid` package names that cannot exist on any store, and the kill
    switch is a sentence.
"""

import base64
import json
import os
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
DECRYPT = os.path.normpath(os.path.join(HERE, "..", "..", "scripts",
                                        "config-decrypt.py"))

# Execute the decryptor into a namespace to borrow its AES. No import, so no
# __pycache__ is created anywhere.
_NS = {"__name__": "config_decrypt_borrowed", "__file__": DECRYPT}
with open(DECRYPT, "r", encoding="utf-8") as _fh:
    exec(compile(_fh.read(), DECRYPT, "exec"), _NS)  # noqa: S102

aes_encrypt = _NS["aes_encrypt"]
xor_bytes = _NS["xor_bytes"]

# --------------------------------------------------------------------------- #
# GROUND TRUTH. Read this before you run the decryptor.
# --------------------------------------------------------------------------- #

# Shape A: repeating-key XOR, key as a plain string literal in ConfigVault.java.
XOR_KEY = b"ch69-inert-xor"

STAGE_ONE_CONFIG = {
    "schema": 1,
    "stage": "one",
    "campaign": "CH69-INERT-DEMO",
    "note": "INERT TEACHING SAMPLE. No payload exists. Nothing is fetched.",
    "next_stage_url": "https://stage2.c2-example.invalid/p/loader.bin",
    "next_stage_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
    "poll_seconds": 900,
    "min_battery_pct": 15,
    "require_sim": False,
    "kill_switch": "NO-OP: this build contains no execution path",
}

# Shape B: AES-128-CBC, IV prefixed, key a 16-character ASCII string literal
# in ConfigVault.java, used directly as 16 key bytes. This is the single most
# common real-world form.
AES_KEY = b"6b39ff0e2c7a41d5"
AES_IV = bytes(range(16))          # fixed, so the build is reproducible

STAGE_TWO_CONFIG = {
    "schema": 1,
    "stage": "two",
    "campaign": "CH69-INERT-DEMO",
    "gate": "https://gate.c2-example.invalid/v1/beacon",
    "fallback": [
        "https://alt1.c2-example.invalid/v1/beacon",
        "https://alt2.c2-example.invalid/v1/beacon",
    ],
    "pin_sha256": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
    "poll_seconds": 300,
    "targets": [
        "com.example.invalid.bank.alpha",
        "com.example.invalid.bank.beta",
        "com.example.invalid.wallet.gamma",
    ],
    "overlay_assets": {
        "com.example.invalid.bank.alpha": "ovl-alpha.html",
        "com.example.invalid.bank.beta": "ovl-beta.html",
    },
    "capabilities_requested": [
        "accessibility", "notification_listener", "overlay",
    ],
    "note": (
        "INERT TEACHING SAMPLE. This document describes capabilities the "
        "sample DOES NOT IMPLEMENT. No overlay asset exists in the APK, no "
        "network client exists, and no target package is ever queried."
    ),
}


def build_blobs():
    p1 = json.dumps(STAGE_ONE_CONFIG, indent=2, sort_keys=True).encode("utf-8")
    p2 = json.dumps(STAGE_TWO_CONFIG, indent=2, sort_keys=True).encode("utf-8")
    return {
        "cfg-xor.bin": xor_bytes(p1, XOR_KEY),
        "cfg-aes.bin": AES_IV + aes_encrypt(p2, AES_KEY, "cbc", AES_IV),
    }, {"cfg-xor.bin": p1, "cfg-aes.bin": p2}


def main(argv):
    if "--show" in argv:
        _, plains = build_blobs()
        for name, p in plains.items():
            print("=" * 70)
            print("%s  plaintext (%d bytes)" % (name, len(p)))
            print("=" * 70)
            print(p.decode("utf-8"))
            print()
        print("XOR key : %r" % XOR_KEY.decode())
        print("AES key : %r  (CBC, IV = first 16 bytes of the blob)"
              % AES_KEY.decode())
        return 0

    if len(argv) != 1:
        print(__doc__.strip().splitlines()[0], file=sys.stderr)
        print("usage: make-config-assets.py <output-assets-dir> | --show",
              file=sys.stderr)
        return 2

    outdir = argv[0]
    os.makedirs(outdir, exist_ok=True)
    blobs, plains = build_blobs()
    for name, data in blobs.items():
        path = os.path.join(outdir, name)
        with open(path, "wb") as fh:
            fh.write(data)
        print("wrote %s  %d bytes  (plaintext was %d bytes)"
              % (path, len(data), len(plains[name])))
    return 0


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