#!/usr/bin/env bash
# examples/inert-sample/build.sh
#
# PURPOSE
#   Build the chapter 69 INERT TEACHING SAMPLE from the sources in this
#   directory, using only the Android SDK build-tools and a JDK. No Gradle,
#   no Android Studio, no network.
#
#   The result is an APK that has the SHAPE of a persistent Android sample --
#   provider persistence, a boot receiver, a two-process watchdog pair, three
#   declared granted-capability components, two encrypted config blobs and an
#   optional native library -- and NONE of the function. Every code path logs
#   and returns. There is no payload, no C2 client, no exfiltration, no
#   evasion, and no privilege escalation anywhere in it.
#
#   It exists to be ANALYSED. It is the target for ../../scripts/apk-triage.py,
#   for ../../scripts/config-decrypt.py, and for labs 01 to 03.
#
# USAGE
#   # host -- build; the APK lands OUTSIDE the repository
#   ./build.sh
#
#   # host -- choose where
#   OUTDIR=/tmp/ch69 ./build.sh
#
#   # host -- build and immediately triage
#   ./build.sh --triage
#
#   # host -- print the config plaintexts without building anything
#   python3 -B make-config-assets.py --show
#
# REQUIREMENTS
#   * ANDROID_HOME or ANDROID_SDK_ROOT pointing at an Android SDK with
#     build-tools (aapt2, d8, zipalign, apksigner) and one platform
#     android.jar. The newest of each is used.
#   * A JDK with javac and keytool.
#   * python3, for the zip surgery and the config generator.
#   * OPTIONAL: an NDK, for the native library. Without one the build still
#     succeeds and the APK simply has no lib/ directory -- which is itself a
#     result worth seeing in the triage output.
#
# WHAT THIS WILL *NOT* DO
#   * It will NOT install anything. There is deliberately no --install flag.
#     Read the safety rules in ../../README.md section 7.1: a sample-shaped
#     APK goes on an emulator you can throw away, and putting one on a phone
#     you use is a habit worth never acquiring, even when the sample is one
#     you wrote yourself and know to be inert.
#   * It will NOT produce a realistic sample. It is not packed, not
#     obfuscated, not anti-analysis-hardened, and its config is encrypted
#     with the two easiest schemes there are. Chapter 40 owns the hard
#     versions.
#   * It will NOT write anything into the repository. Everything lands under
#     $OUTDIR. `.apk`, `.dex`, `.class` and `.so` are on the repository's
#     artefact blocklist.
#   * It will NOT give you a stable signer hash. The signing key is generated
#     on the spot, so the certificate SHA-256 that apk-triage.py reports
#     differs on every machine and on every fresh $OUTDIR. That is deliberate
#     and it is the subject of lab 03: a signer hash identifies a KEY, and
#     you have just made a new one.

set -u

HERE="$(cd "$(dirname "$0")" && pwd)"
OUTDIR="${OUTDIR:-${TMPDIR:-/tmp}/ch69-build}"
PKG="com.pentest.ch69.inert"
PKGPATH="com/pentest/ch69/inert"
APKNAME="inert-sample.apk"

# On Git Bash / MSYS the SDK tools are native Windows binaries and do not
# understand /c/Users/... paths. Without this, aapt2 reports "failed to load
# XML file" on a file that plainly exists.
p() {
    if command -v cygpath >/dev/null 2>&1; then cygpath -w "$1"; else printf '%s' "$1"; fi
}

# --------------------------------------------------------------------------- #
# Locate the SDK
# --------------------------------------------------------------------------- #
SDK="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}"
if [ -z "$SDK" ]; then
    for c in "$HOME/Android/Sdk" "$HOME/Library/Android/sdk" \
             "${LOCALAPPDATA:-}/Android/Sdk"; do
        [ -d "$c" ] && SDK="$c" && break
    done
fi
[ -d "${SDK:-}" ] || { echo "error: set ANDROID_HOME to your Android SDK"; exit 2; }

BT="$(ls -d "$SDK"/build-tools/* 2>/dev/null | sort -V | tail -1)"
AJ="$(ls -d "$SDK"/platforms/*/android.jar 2>/dev/null | sort -V | tail -1)"
[ -n "$BT" ] || { echo "error: no build-tools under $SDK"; exit 2; }
[ -n "$AJ" ] || { echo "error: no platform android.jar under $SDK"; exit 2; }

pick() { [ -x "$BT/$1" ] && echo "$BT/$1" || echo "$BT/$1.bat"; }
AAPT2="$(pick aapt2)"; D8="$(pick d8)"
ZIPALIGN="$(pick zipalign)"; APKSIGNER="$(pick apksigner)"
[ -x "$AAPT2" ]    || AAPT2="$BT/aapt2.exe"
[ -x "$ZIPALIGN" ] || ZIPALIGN="$BT/zipalign.exe"

echo "SDK         $SDK"
echo "build-tools $(basename "$BT")"
echo "android.jar $AJ"
echo "outdir      $OUTDIR"
echo

WORK="$OUTDIR/work"
rm -rf "$WORK"
mkdir -p "$WORK/src/$PKGPATH" "$WORK/classes" "$WORK/assets" "$WORK/res-compiled"

# --------------------------------------------------------------------------- #
# 1. Config assets. Generated, never committed -- see make-config-assets.py.
# --------------------------------------------------------------------------- #
echo "=== 1. generating config assets ==="
python3 -B "$HERE/make-config-assets.py" "$WORK/assets" || exit 1
echo

# --------------------------------------------------------------------------- #
# 2. Resources
# --------------------------------------------------------------------------- #
echo "=== 2. compiling resources ==="
"$AAPT2" compile --dir "$(p "$HERE/res")" -o "$(p "$WORK/res.zip")" || exit 1
echo

# --------------------------------------------------------------------------- #
# 3. Link: manifest + resources + assets -> a resource-only APK
# --------------------------------------------------------------------------- #
echo "=== 3. linking ==="
"$AAPT2" link -o "$(p "$WORK/base.apk")" -I "$(p "$AJ")" \
    --manifest "$(p "$HERE/AndroidManifest.xml")" \
    -R "$(p "$WORK/res.zip")" \
    -A "$(p "$WORK/assets")" \
    --min-sdk-version 21 --target-sdk-version 33 \
    --auto-add-overlay || exit 1
echo

# --------------------------------------------------------------------------- #
# 4. Java -> classes -> DEX
# --------------------------------------------------------------------------- #
echo "=== 4. compiling Java ==="
cp "$HERE"/*.java "$WORK/src/$PKGPATH/" || exit 1
javac --release 8 -nowarn -classpath "$(p "$AJ")" -d "$WORK/classes" \
    "$WORK/src/$PKGPATH"/*.java 2>&1 | grep -vE 'obsolete|Xlint|^[0-9]+ warning'

CLASSFILES=()
while IFS= read -r f; do CLASSFILES+=("$(p "$f")"); done \
    < <(find "$WORK/classes" -name '*.class')
[ "${#CLASSFILES[@]}" -gt 0 ] || { echo "error: javac produced no classes"; exit 1; }

"$D8" --lib "$(p "$AJ")" --min-api 21 --output "$(p "$WORK")" "${CLASSFILES[@]}" || exit 1
echo "dex: $(ls -l "$WORK/classes.dex" | awk '{print $5}') bytes"
echo

# --------------------------------------------------------------------------- #
# 5. Native library, if an NDK is available
# --------------------------------------------------------------------------- #
echo "=== 5. native library (optional) ==="
NDK="${ANDROID_NDK_HOME:-${ANDROID_NDK_ROOT:-}}"
if [ -z "$NDK" ]; then
    NDK="$(ls -d "$SDK"/ndk/* 2>/dev/null | sort -V | tail -1)"
fi
CC=""
if [ -n "${NDK:-}" ] && [ -d "$NDK" ]; then
    for host in windows-x86_64 linux-x86_64 darwin-x86_64; do
        cand="$NDK/toolchains/llvm/prebuilt/$host/bin/aarch64-linux-android21-clang"
        [ -x "$cand" ] && CC="$cand" && break
        [ -x "$cand.cmd" ] && CC="$cand.cmd" && break
    done
fi
if [ -n "$CC" ]; then
    mkdir -p "$WORK/lib/arm64-v8a"
    "$CC" -shared -fPIC -O2 -o "$WORK/lib/arm64-v8a/libinertstub.so" \
        "$HERE/jni/inert_stub.c" -llog -Wall -Wextra || exit 1
    echo "built lib/arm64-v8a/libinertstub.so with $(basename "$CC")"
else
    echo "no NDK found -- skipping the native library."
    echo "The APK will have no lib/ directory and apk-triage.py will report"
    echo "'no native libraries', which is a legitimate triage result."
fi
echo

# --------------------------------------------------------------------------- #
# 6. Assemble
# --------------------------------------------------------------------------- #
echo "=== 6. assembling ==="
( cd "$WORK" && python3 -B -c "
import os, shutil, zipfile
shutil.copy('base.apk', 'unaligned.apk')
z = zipfile.ZipFile('unaligned.apk', 'a', zipfile.ZIP_DEFLATED)
z.write('classes.dex', 'classes.dex')
for root, _, files in os.walk('lib'):
    for f in files:
        full = os.path.join(root, f)
        arc = full.replace(os.sep, '/')
        # Native libraries are stored, not deflated, when extractNativeLibs
        # is false. This sample sets it true, so deflate is correct here.
        z.write(full, arc)
z.close()
print('entries:', len(zipfile.ZipFile('unaligned.apk').namelist()))
" ) || exit 1

KS="$OUTDIR/throwaway.ks"
if [ ! -f "$KS" ]; then
    keytool -genkeypair -keystore "$KS" -storepass android -keypass android \
        -alias ch69 -dname "CN=CH69 Inert Sample,O=Android Security Handbook,C=XX" \
        -validity 3650 -keyalg RSA -keysize 2048 >/dev/null 2>&1 \
        || { echo "error: keytool failed -- is a JDK on PATH?"; exit 2; }
    echo "generated a THROWAWAY signing key at $KS"
    echo "  (the signer hash apk-triage.py prints is this key's, and it is new)"
fi

"$ZIPALIGN" -f -p 4 "$(p "$WORK/unaligned.apk")" "$(p "$WORK/aligned.apk")" || exit 1
"$APKSIGNER" sign --ks "$(p "$KS")" --ks-pass pass:android --key-pass pass:android \
    --out "$(p "$OUTDIR/$APKNAME")" "$(p "$WORK/aligned.apk")" 2>&1 | grep -v WARNING

echo
echo "built $OUTDIR/$APKNAME"
echo "      $(ls -l "$OUTDIR/$APKNAME" | awk '{print $5}') bytes"
echo
echo "Nothing was written into the repository."
echo
echo "NEXT:"
echo "  python3 -B ../../scripts/apk-triage.py \"$OUTDIR/$APKNAME\""
echo "  python3 -B ../../scripts/config-decrypt.py --apk \"$OUTDIR/$APKNAME\" --auto"
echo
echo "DO NOT INSTALL THIS ON A PHONE YOU USE. Emulator only."

if [ "${1:-}" = "--triage" ]; then
    echo
    python3 -B "$HERE/../../scripts/apk-triage.py" "$OUTDIR/$APKNAME"
fi
