#!/usr/bin/env bash
#
# surface-enum.sh -- read-only attack-surface inventory of a connected Android
#                    device, for stage 1 of the research method.
#
# Chapter 70 -- Vulnerability Research, scripts/
#
# PURPOSE
#   Stage 1 of the method (chapter 70 section 3.2) is a written list of every
#   place untrusted data enters the system, and stage 2 is choosing a target
#   from it. This script collects the raw material for both, so that the part
#   you do by hand is the judgement rather than the typing.
#
#   It produces, into --out:
#       posture.txt        build fingerprint, patch level, ABI, SELinux mode,
#                          MTE and page-size state -- the facts every severity
#                          claim later depends on
#       packages.txt       every installed package with its APK path
#       exported.txt       packages that export at least one component
#       services.txt       the Binder services registered with servicemanager
#       services-desc.txt  the same list with the interface descriptors
#       native-libs.txt    the native library inventory, vendor first
#       processes.txt      what is actually running, with its user
#       seinfo.txt         SELinux enforcing state and the domains in use
#       SUMMARY.md         a filled-in surface table you then edit
#
# USAGE
#   ./surface-enum.sh --out /tmp/surface-$(date +%F)
#   ./surface-enum.sh --out DIR --serial 84f7a024      # pick a device
#   ./surface-enum.sh --out DIR --compare OTHERDIR     # diff two devices
#
# REQUIREMENTS
#   bash, adb on PATH, one authorised device. No root required and none used.
#
# WHAT THIS SCRIPT DOES TO THE DEVICE
#   Nothing. It runs `getprop`, `pm`, `dumpsys`, `service list`, `ls` and `ps`.
#   It installs nothing, writes nothing to the device, starts no component and
#   sends no Intent or broadcast. Read the commands below before you run it
#   against a device you care about -- that is a reasonable thing to insist on
#   and this script is short enough to make it easy.
#
# WHAT THIS WILL NOT TELL YOU
#   * Which of these is worth fuzzing. That is the five-factor yield model in
#     section 3.3, and it is a judgement you make with the output in front of
#     you. A list is not a plan.
#   * The full broadcast surface. Chapter 29 measured that 299 of 431 distinct
#     actions registered by third-party processes had NO manifest-declared
#     receiver anywhere on the device -- 69% invisible to any APK-based tool,
#     including this one. Enumerate from the running system as well.
#   * Whether an exported component is actually reachable. `exported=true` is
#     necessary, not sufficient: a permission may guard it, and the permission
#     may or may not be one an app can hold.
#   * Anything about vendor code you cannot see. The highest-yield targets are
#     usually the ones whose source you will never have.

set -eu

OUT=""
SERIAL=""
COMPARE=""

die() { printf 'error: %s\n' "$*" >&2; exit 1; }

while [ $# -gt 0 ]; do
    case "$1" in
        --out)     OUT="$2"; shift 2 ;;
        --serial)  SERIAL="$2"; shift 2 ;;
        --compare) COMPARE="$2"; shift 2 ;;
        -h|--help) sed -n '2,60p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
        *) die "unknown option: $1" ;;
    esac
done

[ -n "$OUT" ] || die "--out is required"
command -v adb >/dev/null 2>&1 || die "adb not on PATH"

ADB="adb"
[ -n "$SERIAL" ] && ADB="adb -s $SERIAL"

# Refuse to guess which device when several are attached. Picking the wrong one
# silently is how a measurement ends up attributed to the wrong Android version
# -- which this repository has already had to correct once.
NDEV=$($ADB devices | grep -cw "device" || true)
if [ "$NDEV" -eq 0 ]; then
    die "no authorised device. Check 'adb devices'."
fi
if [ -z "$SERIAL" ] && [ "$NDEV" -gt 1 ]; then
    $ADB devices -l
    die "more than one device attached; pass --serial"
fi

mkdir -p "$OUT"

sh_() { $ADB shell "$1" 2>/dev/null | tr -d '\r'; }

# ---------------------------------------------------------------------------
# 0. Posture. Everything else is meaningless without it.
# ---------------------------------------------------------------------------

printf '[*] posture\n'
{
    printf '# Device posture -- captured %s\n\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
    for p in ro.product.model ro.product.manufacturer ro.product.device \
             ro.build.version.release ro.build.version.sdk \
             ro.build.version.security_patch ro.build.fingerprint \
             ro.build.type ro.build.tags \
             ro.product.cpu.abi ro.product.cpu.abilist \
             ro.arm64.memtag.bootctl ro.config.low_ram; do
        printf '%-34s = %s\n' "$p" "$(sh_ "getprop $p")"
    done
    printf '\n%-34s = %s\n' "selinux" "$(sh_ 'getenforce')"
    printf '%-34s = %s\n' "PAGE_SIZE" "$(sh_ 'getconf PAGE_SIZE')"
    printf '%-34s = %s\n' "mte in cpuinfo" \
        "$(sh_ 'grep -o mte /proc/cpuinfo | head -1')"
    printf '\n# The security patch level is a CLAIM, not a measurement. A device\n'
    printf '# claiming a patch level has not necessarily received every fix in\n'
    printf '# it, especially for vendor components -- and where that is wrong,\n'
    printf '# the discrepancy is itself a finding. Chapter 70 section 6.3.\n'
} > "$OUT/posture.txt"

# ---------------------------------------------------------------------------
# 1. Packages
# ---------------------------------------------------------------------------

printf '[*] packages\n'
sh_ 'pm list packages -f' | sed 's/^package://' > "$OUT/packages.txt"
PKGCOUNT=$(wc -l < "$OUT/packages.txt" | tr -d ' ')

printf '[*] exported components (this is the slow one -- one dumpsys per package)\n'
: > "$OUT/exported.txt"
n=0
while IFS= read -r line; do
    pkg="${line##*=}"
    [ -n "$pkg" ] || continue
    n=$((n+1))
    if [ $((n % 25)) -eq 0 ]; then printf '    ... %d/%s\n' "$n" "$PKGCOUNT"; fi
    d=$(sh_ "dumpsys package $pkg")
    cnt=$(printf '%s' "$d" | grep -c 'exported=true' || true)
    if [ "${cnt:-0}" -gt 0 ]; then
        printf '%-60s exported=%s\n' "$pkg" "$cnt" >> "$OUT/exported.txt"
    fi
done < "$OUT/packages.txt"
sort -k2 -t= -rn "$OUT/exported.txt" 2>/dev/null > "$OUT/exported.sorted.txt" || \
    cp "$OUT/exported.txt" "$OUT/exported.sorted.txt"

# ---------------------------------------------------------------------------
# 2. Binder services -- the highest-value list in this script
# ---------------------------------------------------------------------------

printf '[*] binder services\n'
sh_ 'service list' > "$OUT/services-desc.txt"
# `[0-9][0-9]*` and not `[0-9]*`: the latter matches ZERO digits, so the
# header line "Found 217 services:" is captured as a service named
# "Found 217 services" and every count is one too high. Measured on a real
# device -- 218 reported against 217 actually present. An off-by-one in an
# inventory is exactly the kind of error that survives, because 218 looks
# just as plausible as 217.
sed -n 's/^[0-9][0-9]*[[:space:]]*\([^:]*\):.*/\1/p' "$OUT/services-desc.txt" \
    | sed 's/[[:space:]]*$//' | sort > "$OUT/services.txt"

# ---------------------------------------------------------------------------
# 3. Native libraries. Vendor first, deliberately: vendor code is written by
#    fewer people, reviewed by fewer, and fuzzed by nobody.
# ---------------------------------------------------------------------------

printf '[*] native libraries\n'
{
    for d in /vendor/lib64 /vendor/lib /odm/lib64 /system/lib64 /system/lib \
             /apex/com.android.runtime/lib64; do
        printf '\n### %s\n' "$d"
        sh_ "ls $d 2>/dev/null" | sed 's/^/    /'
    done
} > "$OUT/native-libs.txt"

# ---------------------------------------------------------------------------
# 4. Processes and SELinux domains
# ---------------------------------------------------------------------------

printf '[*] processes and domains\n'
sh_ 'ps -A -o USER,PID,NAME' > "$OUT/processes.txt"
{
    printf 'getenforce: %s\n\n' "$(sh_ 'getenforce')"
    printf '# Domains in use (from ps -Z), with a count. A domain you have not\n'
    printf '# seen before on a reference device is vendor policy, and chapter\n'
    printf '# 22 section 8.6 owns diffing it.\n\n'
    sh_ 'ps -A -Z' | awk '{print $1}' | sed 's/.*:\([^:]*\):.*/\1/' \
        | sort | uniq -c | sort -rn
} > "$OUT/seinfo.txt"

# ---------------------------------------------------------------------------
# 5. Optional comparison against another capture
# ---------------------------------------------------------------------------

DIFFNOTE="(no --compare given)"
if [ -n "$COMPARE" ] && [ -f "$COMPARE/services.txt" ]; then
    printf '[*] diffing against %s\n' "$COMPARE"
    comm -23 "$OUT/services.txt" "$COMPARE/services.txt" > "$OUT/services-only-here.txt"
    comm -13 "$OUT/services.txt" "$COMPARE/services.txt" > "$OUT/services-only-there.txt"
    ONLY=$(wc -l < "$OUT/services-only-here.txt" | tr -d ' ')
    DIFFNOTE="$ONLY services exist here and not in $COMPARE -- see services-only-here.txt"
fi

# ---------------------------------------------------------------------------
# 6. The summary you then edit by hand
# ---------------------------------------------------------------------------

MODEL=$(sh_ 'getprop ro.product.model')
SDK=$(sh_ 'getprop ro.build.version.sdk')
SVCCOUNT=$(wc -l < "$OUT/services.txt" | tr -d ' ')
EXPCOUNT=$(wc -l < "$OUT/exported.txt" | tr -d ' ')

cat > "$OUT/SUMMARY.md" <<SUM
# Attack surface — $MODEL (API $SDK)

Captured $(date -u '+%Y-%m-%d %H:%M UTC') by \`surface-enum.sh\`. Read-only; nothing
was installed, started or modified on the device.

| | |
|---|---|
| Packages | $PKGCOUNT |
| Packages with at least one exported component | $EXPCOUNT |
| Binder services registered | $SVCCOUNT |
| Service diff | $DIFFNOTE |

## What to do with this

**This is a list, not a plan.** The next three steps are yours:

1. **Find the vendor delta.** Re-run this against a reference device of the
   same Android version and pass \`--compare\`. The services present here and
   absent there are vendor code — the single highest-yield starting point for
   an independent researcher, per chapter 20 §5.8 and chapter 21 §5.12.
2. **Score the candidates** against the five-factor yield model (§3.3): eyes on
   it, language, age, input complexity, reachability. Fill in the table below.
3. **Write a paragraph** defending your choice. A researcher who cannot defend
   a target selection is choosing at random, and target selection dominates
   every other decision in the method.

## Surface table — fill this in

| Entry point | Format / protocol | Who can reach it | User interaction? | Harnessable? | Yield score |
|---|---|---|---|---|---|
| | | | | | |
| | | | | | |
| | | | | | |

## Reminders

- \`exported=true\` is necessary, not sufficient. Check the guarding permission
  and whether an ordinary app can hold it.
- 69% of the broadcast surface is invisible to package-based enumeration
  (chapter 29's measurement). Enumerate from the running system too.
- Establish authorisation before you build a harness, not after the crash
  (§1.6).
SUM

printf '\n[+] written to %s\n' "$OUT"
printf '    posture.txt services.txt exported.txt native-libs.txt SUMMARY.md\n'
printf '\n[!] SUMMARY.md is a template. The value of this script is what you\n'
printf '    write into it, not what it printed.\n'
