Null-DRM-Official/apps/pkg/proxy/proxy.go
404errordeveloper f9c28be3f1
All checks were successful
release / build-and-upload (push) Successful in 6m8s
modules-release / build-and-upload (push) Successful in 4m47s
v0.1.1: external modules, publish YAML, proxy reset, binary-first README
- Host discovers/builds modules under modules/ (bbc, rte, tg4)
- module-publish.yaml tracked; local module.yaml gitignored
- drm --modules-dir / DRM_MODULES_DIR
- drm proxy reset; Magisk reinject reliability
- modules-v* Forgejo release workflow + build scripts
- BBC full Explore channel map including S4C
- README quickstart based on release binaries
2026-10-08 23:16:14 +02:00

906 lines
31 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package proxy
import (
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/binary"
"encoding/pem"
"fmt"
"math/big"
"net"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"drmdecryption/adb"
"drmdecryption/repo"
)
const (
// Universal on-device paths (still kill legacy rteproxy process names).
RemoteBin = "/data/local/tmp/appproxy"
RemoteCap = "/data/local/tmp/appproxy_cap.json"
RemoteLog = "/data/local/tmp/appproxy.log"
RemoteTraffic = "/data/local/tmp/appproxy_traffic.jsonl"
RemoteCACrt = "/data/local/tmp/rteproxy-ca.crt"
RemoteCAKey = "/data/local/tmp/rteproxy-ca.key"
DefaultCAHash = "6c3578b4"
)
var reWLANIPv4 = regexp.MustCompile(`(?m)^\s*inet\s+(\d{1,3}(?:\.\d{1,3}){3})/`)
// DeviceWLANIPv4 returns the phone's current wlan0 IPv4 address.
func DeviceWLANIPv4(c *adb.Client) (string, error) {
out := c.Out("shell", "ip", "-f", "inet", "addr", "show", "wlan0")
if m := reWLANIPv4.FindStringSubmatch(out); len(m) == 2 {
return m[1], nil
}
// Fallbacks used on some OEM builds.
for _, prop := range []string{"dhcp.wlan0.ipaddress", "dhcp.eth0.ipaddress"} {
if v := c.Out("shell", "getprop", prop); net.ParseIP(v) != nil && v != "0.0.0.0" {
return v, nil
}
}
return "", fmt.Errorf("no wlan0 IPv4 (is Wi‑Fi connected?)")
}
// DeviceHTTPProxyAddr returns "<wlan-ip>:port" for the on-device MITM.
// Loopback (127.0.0.1) must not be used: after MITM, some clients rewrite the
// upstream Host to the proxy address, and appproxy then dials 127.0.0.1:443.
func DeviceHTTPProxyAddr(c *adb.Client, port string) (string, error) {
if strings.TrimSpace(port) == "" {
port = "8080"
}
ip, err := DeviceWLANIPv4(c)
if err != nil {
return "", err
}
return net.JoinHostPort(ip, port), nil
}
func looksLikeLoopbackProxy(want string) bool {
host, _, err := net.SplitHostPort(strings.TrimSpace(want))
if err != nil {
host = strings.TrimSpace(want)
}
host = strings.Trim(host, "[]")
return host == "127.0.0.1" || host == "localhost" || host == "::1" || host == "0.0.0.0" || host == ""
}
// EnsureHTTPProxy points the device at the on-device mitm.
// Empty or loopback want is rewritten to the phone's WLAN IP:8080 so upstream
// MITM dials keep the real destination host (BBC/RTE/etc.).
func EnsureHTTPProxy(c *adb.Client, want string) error {
if looksLikeLoopbackProxy(want) {
port := "8080"
if hostport := strings.TrimSpace(want); hostport != "" {
if _, p, err := net.SplitHostPort(hostport); err == nil && p != "" {
port = p
}
}
addr, err := DeviceHTTPProxyAddr(c, port)
if err != nil {
return err
}
want = addr
}
cur := c.Out("shell", "settings", "get", "global", "http_proxy")
if cur == want {
fmt.Println("[+] HTTP proxy already", want)
return nil
}
fmt.Printf("[*] Setting HTTP proxy -> %s (was %q)\n", want, cur)
_, err := c.Shell("settings", "put", "global", "http_proxy", want)
got := c.Out("shell", "settings", "get", "global", "http_proxy")
if got != want {
return fmt.Errorf("failed to set http_proxy (got %q)", got)
}
return err
}
// ClearHTTPProxy disables the global HTTP proxy and stops any leftover mitm.
// Always call this after a capture/agent job so the phone can play apps normally.
func ClearHTTPProxy(c *adb.Client) {
_, _ = c.Shell("settings", "put", "global", "http_proxy", ":0")
_, _ = c.Shell("settings", "delete", "global", "http_proxy")
_, _ = c.Shell("settings", "delete", "global", "global_http_proxy_host")
_, _ = c.Shell("settings", "delete", "global", "global_http_proxy_port")
_, _ = c.Shell("settings", "delete", "global", "global_http_proxy_exclusion_list")
stopProxy(c)
fmt.Println("[*] HTTP proxy cleared")
}
func stopProxy(c *adb.Client) {
script := `
for name in appproxy rteproxy; do
pid=$(pidof $name 2>/dev/null || true)
if [ -n "$pid" ]; then kill $pid >/dev/null 2>&1 || true; fi
done
sleep 0.5
for name in appproxy rteproxy; do
pid=$(pidof $name 2>/dev/null || true)
if [ -n "$pid" ]; then kill -9 $pid >/dev/null 2>&1 || true; fi
done
# Root fallback — some builds ignore non-root kill.
if command -v su >/dev/null 2>&1; then
su -c 'killall appproxy rteproxy 2>/dev/null; killall -9 appproxy rteproxy 2>/dev/null; true' 2>/dev/null || true
fi
sleep 0.3
(pidof appproxy || pidof rteproxy) >/dev/null 2>&1 && echo STILL || echo STOPPED`
out, _ := c.Shell("sh", "-c", script)
if strings.Contains(out, "STILL") {
fmt.Println("[!] old appproxy still running after stop — port 8080 may stay busy")
}
}
// extraFlags renders extra device flags, quoting each value.
func extraFlags(args []string) string {
if len(args) == 0 {
return ""
}
var b strings.Builder
for _, a := range args {
b.WriteString(" ")
if strings.HasPrefix(a, "-") {
b.WriteString(a)
continue
}
b.WriteString("'" + strings.ReplaceAll(a, "'", "") + "'")
}
return b.String()
}
// PushAndStart installs and launches the on-device mitm binary. extraArgs are
// appended to its command line — app modules pass their manifest-scoring hosts
// that way, since the device binary cannot read a module's values file.
func PushAndStart(c *adb.Client, localBin string, extraArgs ...string) error {
if st, err := os.Stat(localBin); err != nil || st.IsDir() {
return fmt.Errorf("missing proxy binary %s — build apps/proxy first (proxyctl build)", localBin)
}
fmt.Println("[*] Stopping any old appproxy/rteproxy...")
stopProxy(c)
fmt.Println("[*] Pushing appproxy...")
if err := c.Push(localBin, RemoteBin); err != nil {
return err
}
_, _ = c.Shell("chmod", "755", RemoteBin)
_, _ = c.Shell("rm", "-f", RemoteCap, "/data/local/tmp/rte_cap.json", "/sdcard/Download/rte_cap.json", "/storage/emulated/0/Download/rte_cap.json", RemoteLog, "/data/local/tmp/rteproxy.log")
starter := "#!/system/bin/sh\n" +
"exec " + RemoteBin +
" -listen :8080" +
" -out " + RemoteCap +
" -ca-dir /data/local/tmp" +
" -dns 1.1.1.1,1.0.0.1,8.8.8.8,192.168.1.1" +
" >>" + RemoteLog + " 2>&1\n"
tmp := filepath.Join(os.TempDir(), "start_appproxy.sh")
if err := os.WriteFile(tmp, []byte(starter), 0o755); err != nil {
return err
}
defer os.Remove(tmp)
if err := c.Push(tmp, "/data/local/tmp/start_appproxy.sh"); err != nil {
return err
}
_, _ = c.Shell("chmod", "755", "/data/local/tmp/start_appproxy.sh")
// Keep backgrounded after adb exits.
_, _, _ = c.Run("shell", "setsid /data/local/tmp/start_appproxy.sh </dev/null >/dev/null 2>&1 &")
var pid, logHead string
for i := 0; i < 10; i++ {
time.Sleep(400 * time.Millisecond)
pid = c.Out("shell", "pidof", "appproxy")
if pid == "" {
pid = c.Out("shell", "pidof", "rteproxy")
}
logHead = c.Out("shell", "head", "-12", RemoteLog)
if pid != "" && strings.Contains(logHead, "listening") {
break
}
}
if logHead != "" {
fmt.Println(logHead)
}
errLog := c.Out("shell", "cat", RemoteLog)
if strings.Contains(errLog, "address already in use") ||
(strings.Contains(errLog, "listen ") && strings.Contains(errLog, "bind:")) {
fmt.Fprintln(os.Stderr, errLog)
return fmt.Errorf("appproxy failed to bind :8080 (old process still holding the port?)")
}
if pid == "" || !strings.Contains(logHead, "listening") {
if errLog != "" {
fmt.Fprintln(os.Stderr, errLog)
}
return fmt.Errorf("appproxy failed to start")
}
fmt.Printf("[+] appproxy pid=%s; capture -> %s\n", pid, RemoteCap)
return nil
}
// FindLocalBin returns the on-device MITM binary.
// Search order: next to this drm.exe (release zip layout), then under the repo.
func FindLocalBin(root string) string {
if root == "" {
root = repo.Root()
}
candidates := []string{}
if exe, err := os.Executable(); err == nil {
dir := filepath.Dir(exe)
candidates = append(candidates,
filepath.Join(dir, "proxy-android-arm64"),
filepath.Join(dir, "bin", "proxy-android-arm64"),
)
}
candidates = append(candidates,
filepath.Join(root, "bin", "proxy-android-arm64"),
filepath.Join(root, "apps", "proxy", "proxy-android-arm64"),
filepath.Join(root, "apps", "proxy", "rteproxy-android-arm64"),
filepath.Join(root, "bin", "rteproxy-android-arm64"),
filepath.Join(root, "proxy-android-arm64"),
)
for _, p := range candidates {
if st, err := os.Stat(p); err == nil && !st.IsDir() {
return p
}
}
return ""
}
// FindLocalCA returns the MITM CA cert for this install.
// Prefers a per-user pair under data/ (gitignored); falls back to a bundled
// apps/proxy/*.crt only when its matching .key is also present.
func FindLocalCA(root string) string {
if root == "" {
root = repo.Root()
}
user := filepath.Join(root, "data", "proxy-ca.crt")
if caPairExists(user) {
return user
}
for _, p := range []string{
filepath.Join(root, "apps", "proxy", "rteproxy-ca.crt"),
filepath.Join(root, "apps", "proxy", "appproxy-ca.crt"),
} {
if caPairExists(p) {
return p
}
}
return ""
}
func caPairExists(certPath string) bool {
if st, err := os.Stat(certPath); err != nil || st.IsDir() {
return false
}
keyPath := strings.TrimSuffix(certPath, filepath.Ext(certPath)) + ".key"
st, err := os.Stat(keyPath)
return err == nil && !st.IsDir()
}
// EnsureLocalCA returns the path to this install's MITM CA cert, creating a
// unique cert+key under data/ on first use so each user gets their own CA.
func EnsureLocalCA(root string) (certPath string, err error) {
if root == "" {
root = repo.Root()
}
if p := FindLocalCA(root); p != "" {
return p, nil
}
dir := filepath.Join(root, "data")
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
certPath = filepath.Join(dir, "proxy-ca.crt")
keyPath := filepath.Join(dir, "proxy-ca.key")
fmt.Println("[*] No local MITM CA yet — generating a unique cert+key for this install…")
if err := generateMITMCA(certPath, keyPath); err != nil {
return "", err
}
hash, err := AndroidCAHashFile(certPath)
if err != nil {
return certPath, nil
}
fmt.Printf("[+] Wrote %s and %s (hash %s)\n", certPath, keyPath, hash)
fmt.Println(" Keep data/ private; each machine should generate its own CA.")
return certPath, nil
}
func generateMITMCA(certPath, keyPath string) error {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return err
}
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
if err != nil {
return err
}
// Unique CN so Android subject_hash_old differs per install (filename HASH.0).
cn := fmt.Sprintf("Null DRM Capture CA %x", serial.Bytes()[:8])
tmpl := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{
Organization: []string{"Null DRM MITM CA"},
CommonName: cn,
},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(10 * 365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
IsCA: true,
MaxPathLen: 1,
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
return err
}
certOut, err := os.OpenFile(certPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644)
if err != nil {
return err
}
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil {
certOut.Close()
return err
}
certOut.Close()
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
return err
}
if err := pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}); err != nil {
keyOut.Close()
return err
}
return keyOut.Close()
}
// AndroidCAHashFile is AndroidCAHash for a PEM file on disk.
func AndroidCAHashFile(certPath string) (string, error) {
pemBytes, err := os.ReadFile(certPath)
if err != nil {
return "", err
}
return AndroidCAHash(pemBytes)
}
// AndroidCAHash returns the OpenSSL subject_hash_old used for system CA files.
func AndroidCAHash(certPEM []byte) (string, error) {
block, _ := pem.Decode(certPEM)
if block == nil {
return "", fmt.Errorf("no PEM certificate found")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return "", err
}
sum := md5.Sum(cert.RawSubject)
n := binary.LittleEndian.Uint32(sum[0:4])
return fmt.Sprintf("%08x", n), nil
}
// InstallCA pushes the MITM CA onto the device as HASH.0 and optionally Magisk-reinjects it.
// When reinject is true, runs the full Magisk conscrypt bind (needs root / Magisk busybox).
// If this install has no CA yet, EnsureLocalCA creates a unique pair under data/.
func InstallCA(c *adb.Client, localCA string, reinject bool) (hash string, err error) {
if localCA == "" {
localCA, err = EnsureLocalCA("")
if err != nil {
return "", err
}
}
pemBytes, err := os.ReadFile(localCA)
if err != nil {
return "", err
}
hash, err = AndroidCAHash(pemBytes)
if err != nil {
return "", err
}
fmt.Printf("[*] Installing CA %s (hash %s)\n", localCA, hash)
if err := c.Push(localCA, RemoteCACrt); err != nil {
return hash, err
}
// Also drop a copy named after the process for clarity.
_ = c.Push(localCA, "/data/local/tmp/appproxy-ca.crt")
// Private key must match the cert. Without it, transparent appproxy exits
// immediately with "tls: private key does not match public key".
if err := pushMatchingCAKey(c, localCA); err != nil {
return hash, err
}
tmpHash := filepath.Join(os.TempDir(), hash+".0")
if err := os.WriteFile(tmpHash, pemBytes, 0o644); err != nil {
return hash, err
}
defer os.Remove(tmpHash)
remoteHash := "/data/local/tmp/" + hash + ".0"
if err := c.Push(tmpHash, remoteHash); err != nil {
return hash, err
}
_, _ = c.Shell("chmod", "644", remoteHash, RemoteCACrt)
fmt.Printf("[+] Pushed %s and %s\n", RemoteCACrt, remoteHash)
if reinject {
ReinjectCA(c, hash)
} else {
fmt.Println("[*] Skipped Magisk reinject (pass -reinject / install-ca --reinject)")
fmt.Println(" User-CA path: Settings → Security → Install a certificate → CA certificate")
}
return hash, nil
}
// pushMatchingCAKey pushes the PEM key that belongs with localCA cert.
func pushMatchingCAKey(c *adb.Client, localCA string) error {
candidates := []string{
strings.TrimSuffix(localCA, filepath.Ext(localCA)) + ".key",
filepath.Join(repo.Root(), "data", "proxy-ca.key"),
filepath.Join(filepath.Dir(localCA), "rteproxy-ca.key"),
filepath.Join(filepath.Dir(localCA), "appproxy-ca.key"),
}
var localKey string
for _, p := range candidates {
if st, err := os.Stat(p); err == nil && !st.IsDir() {
localKey = p
break
}
}
if localKey == "" {
return fmt.Errorf("no CA private key for %s — run: drm proxy install-ca --reinject (generates data/proxy-ca.key)", localCA)
}
if err := c.Push(localKey, RemoteCAKey); err != nil {
return fmt.Errorf("push CA key: %w", err)
}
_ = c.Push(localKey, "/data/local/tmp/appproxy-ca.key")
_, _ = c.Shell("chmod", "600", RemoteCAKey, "/data/local/tmp/appproxy-ca.key")
fmt.Printf("[+] Pushed matching CA key (%s)\n", filepath.Base(localKey))
return nil
}
// Stop stops the on-device mitm process.
func Stop(c *adb.Client) {
stopProxy(c)
}
const (
RemoteTProxyScript = "/data/local/tmp/tproxy_iptables.sh"
RemoteCaptureRoot = "/data/local/tmp/capture"
)
// StartTransparent pushes appproxy in -transparent mode (no Wi‑Fi http_proxy),
// installs iptables UID REDIRECT for pkg, and writes captures under remoteDir.
func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool) error {
if port == "" {
port = "8080"
}
if remoteDir == "" {
remoteDir = RemoteCaptureRoot + "/" + pkg
}
stopProxy(c)
_ = stopTransparentRules(c)
// Ensure no global HTTP proxy — transparent mode must not use one.
ClearHTTPProxy(c)
localCA, err := EnsureLocalCA("")
if err != nil {
return fmt.Errorf("local CA: %w", err)
}
caHash, err := AndroidCAHashFile(localCA)
if err != nil {
return fmt.Errorf("CA hash: %w", err)
}
if reinject {
ReinjectCAForPackage(c, caHash, pkg)
}
if st, err := os.Stat(localBin); err != nil || st.IsDir() {
return fmt.Errorf("missing proxy binary %s", localBin)
}
fmt.Println("[*] Pushing appproxy (transparent)...")
if err := c.Push(localBin, RemoteBin); err != nil {
return err
}
_, _ = c.Shell("chmod", "755", RemoteBin)
if err := ensureTProxyScript(c); err != nil {
return fmt.Errorf("tproxy script: %w", err)
}
_, _ = c.Shell("mkdir", "-p", remoteDir)
_, _ = c.Shell("rm", "-f", remoteDir+"/cap.json", remoteDir+"/traffic.jsonl", remoteDir+"/appproxy.log")
starter := "#!/system/bin/sh\n" +
"mkdir -p '" + remoteDir + "'\n" +
"exec " + RemoteBin +
" -transparent" +
" -listen :" + port +
" -mitm-internal 127.0.0.1:18080" +
" -out-dir '" + remoteDir + "'" +
" -ca-dir /data/local/tmp" +
" -dns 1.1.1.1,1.0.0.1,8.8.8.8" +
" -log-all" +
" -v" +
"\n"
tmp := filepath.Join(os.TempDir(), "start_appproxy_tproxy.sh")
if err := os.WriteFile(tmp, []byte(starter), 0o755); err != nil {
return err
}
defer os.Remove(tmp)
if err := c.Push(tmp, "/data/local/tmp/start_appproxy_tproxy.sh"); err != nil {
return err
}
_, _ = c.Shell("chmod", "755", "/data/local/tmp/start_appproxy_tproxy.sh")
// Push this install's cert+key (never a mismatched leftover on the phone).
if err := c.Push(localCA, RemoteCACrt); err != nil {
return err
}
_ = c.Push(localCA, "/data/local/tmp/appproxy-ca.crt")
if err := pushMatchingCAKey(c, localCA); err != nil {
return fmt.Errorf("CA key: %w", err)
}
// Also drop HASH.0 for Magisk reinject / trust checks.
pemBytes, _ := os.ReadFile(localCA)
tmpHash := filepath.Join(os.TempDir(), caHash+".0")
_ = os.WriteFile(tmpHash, pemBytes, 0o644)
_ = c.Push(tmpHash, "/data/local/tmp/"+caHash+".0")
_ = os.Remove(tmpHash)
_, _ = c.Shell("chmod", "644", "/data/local/tmp/"+caHash+".0", RemoteCACrt)
_, _, _ = c.Run("shell", "setsid /data/local/tmp/start_appproxy_tproxy.sh </dev/null >/dev/null 2>&1 &")
var pid string
for i := 0; i < 15; i++ {
time.Sleep(400 * time.Millisecond)
pid = c.Out("shell", "pidof", "appproxy")
if pid != "" {
break
}
}
if pid == "" {
logTail := c.Out("shell", "tail", "-n", "20", remoteDir+"/appproxy.log")
if strings.TrimSpace(logTail) == "" {
logTail = c.Out("shell", "cat", "/data/local/tmp/appproxy-start.out")
}
if strings.Contains(logTail, "private key does not match") {
return fmt.Errorf("appproxy failed to start (transparent): CA cert/key mismatch on device — run: drm proxy install-ca --reinject\n%s", strings.TrimSpace(logTail))
}
if strings.TrimSpace(logTail) != "" {
return fmt.Errorf("appproxy failed to start (transparent):\n%s", strings.TrimSpace(logTail))
}
return fmt.Errorf("appproxy failed to start (transparent)")
}
fmt.Printf("[+] appproxy pid=%s; capture → %s\n", pid, remoteDir)
out, errOut, err := c.Run("shell", "su", "-c", "sh "+RemoteTProxyScript+" start "+pkg+" "+port)
fmt.Print(out)
if err != nil {
return fmt.Errorf("iptables: %v (%s)", err, strings.TrimSpace(errOut+out))
}
fmt.Println("[+] iptables REDIRECT installed (UK VPN can stay ON; do not set Wi‑Fi proxy)")
return nil
}
// StopTransparent removes iptables rules and stops appproxy (does not require Wi‑Fi proxy clear beyond safety).
func StopTransparent(c *adb.Client) {
_ = stopTransparentRules(c)
stopProxy(c)
ClearHTTPProxy(c)
fmt.Println("[*] transparent capture stopped")
}
// ResetOptions controls drm proxy reset.
type ResetOptions struct {
KeepCaptures bool // leave /data/local/tmp/capture/
}
// ResetDevice returns the phone to a clean MITM-free state: stop proxy/iptables,
// delete pushed CA/binaries/scripts/overlays. Does not delete host data/proxy-ca.*.
func ResetDevice(c *adb.Client, opt ResetOptions) error {
fmt.Println("[*] Resetting device MITM state…")
StopTransparent(c)
script := `
BB=/data/adb/magisk/busybox
# Best-effort undo conscrypt bind (ignore failures).
if [ -x "$BB" ]; then
$BB umount /apex/com.android.conscrypt/cacerts 2>/dev/null || true
$BB umount /system/etc/security/cacerts 2>/dev/null || true
fi
rm -f /data/local/tmp/appproxy \
/data/local/tmp/rteproxy \
/data/local/tmp/rteproxy-ca.crt /data/local/tmp/rteproxy-ca.key \
/data/local/tmp/appproxy-ca.crt /data/local/tmp/appproxy-ca.key \
/data/local/tmp/appproxy_cap.json /data/local/tmp/appproxy_traffic.jsonl \
/data/local/tmp/appproxy.log /data/local/tmp/rteproxy.log \
/data/local/tmp/appproxy-start.out \
/data/local/tmp/start_appproxy.sh /data/local/tmp/start_appproxy_tproxy.sh \
/data/local/tmp/tproxy_iptables.sh \
/data/local/tmp/reinject_ca.sh /data/local/tmp/reinject_ca.status \
/data/local/tmp/reinject_target_uid \
/data/local/tmp/rte_cap.json
# HASH.0 CA copies we pushed (8 hex chars).
rm -f /data/local/tmp/[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].0 2>/dev/null || true
rm -rf /data/local/tmp/cacerts-overlay
echo RESET_CORE_OK
`
if !opt.KeepCaptures {
script += "rm -rf /data/local/tmp/capture\necho RESET_CAPTURES_OK\n"
} else {
script += "echo RESET_CAPTURES_KEPT\n"
}
tmp := filepath.Join(os.TempDir(), "drm_proxy_reset.sh")
_ = os.WriteFile(tmp, []byte("#!/system/bin/sh\n"+script), 0o755)
defer os.Remove(tmp)
_ = c.Push(tmp, "/data/local/tmp/drm_proxy_reset.sh")
_, _ = c.Shell("chmod", "755", "/data/local/tmp/drm_proxy_reset.sh")
out, errOut, err := c.Run("shell", "su", "-c", "sh /data/local/tmp/drm_proxy_reset.sh")
_, _ = c.Shell("su", "-c", "rm -f /data/local/tmp/drm_proxy_reset.sh")
combined := out + errOut
if strings.TrimSpace(out) != "" {
for _, line := range strings.Split(strings.TrimSpace(out), "\n") {
fmt.Println(" ", line)
}
}
if err != nil && !strings.Contains(combined, "RESET_CORE_OK") {
return fmt.Errorf("proxy reset: %v %s", err, strings.TrimSpace(errOut))
}
fmt.Println("[+] Device MITM artifacts cleared — next transparent/capture starts fresh")
return nil
}
func stopTransparentRules(c *adb.Client) error {
out, errOut, err := c.Run("shell", "su", "-c", "sh "+RemoteTProxyScript+" stop")
if strings.TrimSpace(out) != "" {
fmt.Print(out)
}
if err != nil && !strings.Contains(errOut+out, "STOPPED") {
return fmt.Errorf("iptables stop: %v %s", err, errOut)
}
return nil
}
// PullDir pulls regular files under remoteDir into destDir.
// Avoids `adb shell sh -c "ls …"` — on Windows that often lists `/` instead of the path.
func PullDir(c *adb.Client, remoteDir, destDir string) error {
if err := os.MkdirAll(destDir, 0o755); err != nil {
return err
}
remoteDir = strings.TrimRight(strings.TrimSpace(remoteDir), "/")
// Prefer known capture artifacts; fall back to find -type f.
// Do not use `adb shell sh -c "ls …"` — on Windows that often lists `/`.
var names []string
for _, n := range []string{"cap.json", "traffic.jsonl", "appproxy.log"} {
if fileExistsOnDevice(c, remoteDir+"/"+n) {
names = append(names, n)
}
}
if len(names) == 0 {
list := c.Out("shell", "find", remoteDir, "-maxdepth", "1", "-type", "f")
for _, line := range strings.Split(list, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
names = append(names, filepath.Base(filepath.Clean(line)))
}
}
if len(names) == 0 {
return fmt.Errorf("no files in %s", remoteDir)
}
seen := map[string]bool{}
pulled := 0
for _, name := range names {
name = strings.TrimSpace(name)
if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\`) || seen[name] {
continue
}
seen[name] = true
remote := remoteDir + "/" + name
local := filepath.Join(destDir, name)
if err := c.Pull(remote, local); err != nil {
fmt.Printf("[!] pull %s: %v\n", remote, err)
continue
}
fmt.Printf("[+] %s\n", local)
pulled++
}
if pulled == 0 {
return fmt.Errorf("failed to pull any files from %s", remoteDir)
}
return nil
}
func fileExistsOnDevice(c *adb.Client, remote string) bool {
_, _, err := c.Run("shell", "ls", remote)
return err == nil
}
// PullCaptures pulls traffic/cap/log into destDir (created if missing).
func PullCaptures(c *adb.Client, destDir string) error {
if err := os.MkdirAll(destDir, 0o755); err != nil {
return err
}
for _, remote := range []string{RemoteTraffic, RemoteCap, RemoteLog} {
base := filepath.Base(remote)
local := filepath.Join(destDir, base)
if err := c.Pull(remote, local); err != nil {
fmt.Printf("[!] pull %s: %v\n", remote, err)
continue
}
fmt.Printf("[+] %s\n", local)
}
return nil
}
// DiscoverOutDir returns outputs/discover/<stamp> under the repo root.
func DiscoverOutDir(root, stamp string) string {
if root == "" {
root = repo.Root()
}
if stamp == "" {
stamp = time.Now().Format("20060102-150405")
}
return filepath.Join(root, "outputs", "discover", stamp)
}
const (
remoteReinjectScript = "/data/local/tmp/reinject_ca.sh"
remoteReinjectStatus = "/data/local/tmp/reinject_ca.status"
remoteReinjectUID = "/data/local/tmp/reinject_target_uid"
)
// ReinjectCA Magisk-binds the MITM CA into conscrypt (zygote + system).
func ReinjectCA(c *adb.Client, caHash string) {
ReinjectCAForPackage(c, caHash, "")
}
// ReinjectCAForPackage Magisk-binds the MITM CA, optionally also into one app's
// mount namespace (after writing its UID). A stale reinject_target_uid from an
// older run is cleared when pkg is empty — that leftover caused 20s host timeouts.
func ReinjectCAForPackage(c *adb.Client, caHash, pkg string) {
if caHash == "" {
caHash = DefaultCAHash
}
if pkg != "" {
uid := strings.TrimSpace(c.Out("shell", "su", "-c", "stat -c %u /data/data/"+pkg+" 2>/dev/null || dumpsys package "+pkg+" | grep userId= | head -1"))
// dumpsys form: userId=10382
if i := strings.Index(uid, "userId="); i >= 0 {
uid = strings.TrimSpace(uid[i+len("userId="):])
if j := strings.IndexAny(uid, " \t\r\n"); j >= 0 {
uid = uid[:j]
}
}
if uid != "" && uid != "0" {
tmp := filepath.Join(os.TempDir(), "reinject_target_uid")
_ = os.WriteFile(tmp, []byte(uid+"\n"), 0o644)
_ = c.Push(tmp, remoteReinjectUID)
_ = os.Remove(tmp)
fmt.Printf("[*] Magisk reinject target uid %s (%s)\n", uid, pkg)
}
} else {
// Stale UID files make the per-PID nsenter loop hang su -mm.
_, _ = c.Shell("su", "-c", "rm -f "+remoteReinjectUID)
}
script := fmt.Sprintf(`
BB=/data/adb/magisk/busybox
HASH=%s
STATUS=%s
echo RUNNING > "$STATUS"
[ -f /data/local/tmp/$HASH.0 ] || { echo CA_SKIP > "$STATUS"; exit 0; }
[ -x "$BB" ] || { echo CA_SKIP_NO_BB > "$STATUS"; exit 0; }
rm -rf /data/local/tmp/cacerts-overlay
mkdir -p /data/local/tmp/cacerts-overlay
# Copy from the real apex store. If a previous broken bind is mounted, prefer
# the Magisk mirror / stock path so we do not copy an empty/unreadable overlay.
if [ -r /apex/com.android.conscrypt/cacerts/0054e830.0 ] || ls /apex/com.android.conscrypt/cacerts/*.0 >/dev/null 2>&1; then
cp /apex/com.android.conscrypt/cacerts/* /data/local/tmp/cacerts-overlay/ 2>/dev/null || true
fi
cp /data/local/tmp/$HASH.0 /data/local/tmp/cacerts-overlay/$HASH.0
# tmpfs defaults to 0755 root:root; apps need +x on the dir and 0644 on PEMs.
# Wrong modes/contexts caused DirectoryCertificateSrc EACCES and broke iPlayer TLS.
chmod 755 /data/local/tmp/cacerts-overlay
chmod 644 /data/local/tmp/cacerts-overlay/*
chown root:root /data/local/tmp/cacerts-overlay /data/local/tmp/cacerts-overlay/* 2>/dev/null || true
$BB mount -t tmpfs -o mode=755,uid=0,gid=0 tmpfs /system/etc/security/cacerts 2>/dev/null || true
cp /data/local/tmp/cacerts-overlay/* /system/etc/security/cacerts/ 2>/dev/null || true
chmod 755 /system/etc/security/cacerts
chmod 644 /system/etc/security/cacerts/*
chown root:root /system/etc/security/cacerts /system/etc/security/cacerts/* 2>/dev/null || true
# Match AOSP cacerts file context (system_file is too loose on some Magisk builds).
chcon u:object_r:system_security_cacerts_file:s0 /system/etc/security/cacerts 2>/dev/null || \
chcon u:object_r:system_file:s0 /system/etc/security/cacerts 2>/dev/null || true
chcon u:object_r:system_security_cacerts_file:s0 /system/etc/security/cacerts/* 2>/dev/null || \
chcon u:object_r:system_file:s0 /system/etc/security/cacerts/* 2>/dev/null || true
$BB mount --bind /system/etc/security/cacerts /apex/com.android.conscrypt/cacerts 2>/dev/null || true
for Z in $(pidof zygote64 2>/dev/null); do
nsenter --mount=/proc/$Z/ns/mnt -- $BB mount --bind /system/etc/security/cacerts /apex/com.android.conscrypt/cacerts 2>/dev/null || true
done
PKG_UID_FILE=%s
if [ -f "$PKG_UID_FILE" ]; then
TUID=$(cat "$PKG_UID_FILE")
# Cap the sweep — a long-lived app with many threads must not hang forever.
N=0
for PID in $(ps -A -o PID=,UID= 2>/dev/null | awk -v u="$TUID" '$2==u {print $1}'); do
nsenter --mount=/proc/$PID/ns/mnt -- $BB mount --bind /system/etc/security/cacerts /apex/com.android.conscrypt/cacerts 2>/dev/null || true
N=$((N+1))
[ "$N" -ge 8 ] && break
done
fi
if ls /apex/com.android.conscrypt/cacerts/$HASH.0 >/dev/null 2>&1; then
echo CA_OK > "$STATUS"
else
echo CA_SKIP > "$STATUS"
fi
`, caHash, remoteReinjectStatus, remoteReinjectUID)
fmt.Println("[*] Re-injecting system CA (Magisk)...")
_, _ = c.Shell("su", "-c", "rm -f "+remoteReinjectStatus)
tmp := filepath.Join(os.TempDir(), "reinject_ca.sh")
_ = os.WriteFile(tmp, []byte("#!/system/bin/sh\n"+script), 0o755)
defer os.Remove(tmp)
_ = c.Push(tmp, remoteReinjectScript)
_, _ = c.Shell("chmod", "755", remoteReinjectScript)
// Run in background on device so a hung su -mm cannot block the host forever.
// Status is polled from reinject_ca.status.
go func() {
_, _, _ = c.Run("shell", "su", "-mm", "-c", "sh "+remoteReinjectScript)
}()
deadline := time.Now().Add(18 * time.Second)
var status string
for time.Now().Before(deadline) {
status = reinjectStatus(c)
if status == "CA_OK" || strings.HasPrefix(status, "CA_SKIP") {
break
}
time.Sleep(400 * time.Millisecond)
}
if status == "" || status == "RUNNING" {
_, _ = c.Shell("su", "-c", "killall reinject_ca.sh 2>/dev/null; true")
time.Sleep(300 * time.Millisecond)
status = reinjectStatus(c)
}
switch {
case status == "CA_OK" || caPresentOnDevice(c, caHash):
fmt.Println("[+] System CA present in conscrypt")
case strings.HasPrefix(status, "CA_SKIP"):
fmt.Printf("[!] CA inject skipped (%s) — re-run: drm proxy install-ca --reinject\n", status)
default:
if caPresentOnDevice(c, caHash) {
fmt.Println("[+] System CA present in conscrypt (status race, mount OK)")
} else {
fmt.Println("[!] CA reinject timed out — re-run: drm proxy install-ca --reinject")
}
}
}
func reinjectStatus(c *adb.Client) string {
return strings.TrimSpace(c.Out("shell", "su", "-c", "cat "+remoteReinjectStatus+" 2>/dev/null"))
}
func caPresentOnDevice(c *adb.Client, caHash string) bool {
if caHash == "" {
caHash = DefaultCAHash
}
path := "/apex/com.android.conscrypt/cacerts/" + caHash + ".0"
out := c.Out("shell", "su", "-c", "ls "+path+" 2>/dev/null")
if strings.Contains(out, caHash+".0") {
return true
}
// Overlay copy is a weaker signal but useful when apex ls races the bind.
out = c.Out("shell", "su", "-c", "ls /data/local/tmp/cacerts-overlay/"+caHash+".0 2>/dev/null")
return strings.Contains(out, caHash+".0")
}