fixed issues with CA now generates its own new cert
All checks were successful
release / build-and-upload (push) Successful in 16m53s

This commit is contained in:
404errordeveloper 2026-10-08 20:16:08 +02:00
parent a930a697fa
commit c1948a1439
11 changed files with 458 additions and 34 deletions

View file

@ -0,0 +1,30 @@
package capturecmd
import "testing"
func TestNormalizeArgsUnicodeDashes(t *testing.T) {
in := []string{"\u2014app", "bbc", "\u2013channel", "bbcone"}
out := normalizeArgs(in)
if out[0] != "--app" {
t.Fatalf("em-dash app: got %q want --app", out[0])
}
if out[1] != "bbc" {
t.Fatalf("app value: got %q", out[1])
}
if out[2] != "--channel" {
t.Fatalf("en-dash channel: got %q want --channel", out[2])
}
if out[3] != "bbcone" {
t.Fatalf("channel value: got %q", out[3])
}
}
func TestNormalizeArgsASCIIUnchanged(t *testing.T) {
in := []string{"--app", "bbc", "--channel", "bbcone"}
out := normalizeArgs(in)
for i := range in {
if out[i] != in[i] {
t.Fatalf("index %d: got %q want %q", i, out[i], in[i])
}
}
}

View file

@ -7,6 +7,7 @@ import (
"fmt" "fmt"
"strings" "strings"
"time" "time"
"unicode"
"drmdecryption/adb" "drmdecryption/adb"
"drmdecryption/app" "drmdecryption/app"
@ -17,7 +18,9 @@ import (
// Run performs one capture. App modules are compiled in, so there is no modules // Run performs one capture. App modules are compiled in, so there is no modules
// directory to scan: --app names a registered provider. // directory to scan: --app names a registered provider.
func Run(args []string) error { func Run(args []string) error {
fs := flag.NewFlagSet("capture", flag.ExitOnError) args = normalizeArgs(args)
fs := flag.NewFlagSet("capture", flag.ContinueOnError)
appName := fs.String("app", "", "app module. Empty = passive MITM, no launch/auto-play") appName := fs.String("app", "", "app module. Empty = passive MITM, no launch/auto-play")
channel := fs.String("channel", "", "channel id for --auto-play") channel := fs.String("channel", "", "channel id for --auto-play")
autoPlay := fs.Bool("auto-play", false, "auto-navigate to --channel (requires --app and --channel)") autoPlay := fs.Bool("auto-play", false, "auto-navigate to --channel (requires --app and --channel)")
@ -31,12 +34,16 @@ func Run(args []string) error {
// Each module contributes --<app>.<field> overrides for its local values. // Each module contributes --<app>.<field> overrides for its local values.
app.BindFlags(fs) app.BindFlags(fs)
fs.Usage = func() { fs.Usage = func() {
fmt.Fprintf(fs.Output(), "capture — one-shot phone MITM capture\n\nUsage:\n capture --app <%s> [--channel ID] [--auto-play] [--wvd PATH]\n capture (passive: play anything on the phone)\n\nFlags:\n", strings.Join(app.Names(), "|")) fmt.Fprintf(fs.Output(), "capture — one-shot phone MITM capture\n\nUsage:\n capture --app <%s> [--channel ID] [--auto-play] [--wvd PATH]\n capture (passive: play anything on the phone)\n\nExample (BBC + NordVPN UK):\n capture --app bbc --channel bbcone --wait 120\n\nFlags:\n", strings.Join(app.Names(), "|"))
fs.PrintDefaults() fs.PrintDefaults()
} }
if err := fs.Parse(args); err != nil { if err := fs.Parse(args); err != nil {
return err return err
} }
if rest := fs.Args(); len(rest) > 0 {
return fmt.Errorf("unexpected arguments %v — use flags only (example: capture --app bbc --channel bbcone)", rest)
}
c := adb.New() c := adb.New()
if *serial != "" { if *serial != "" {
@ -85,6 +92,34 @@ func Run(args []string) error {
return err return err
} }
// normalizeArgs rewrites Unicode dashes Word/Terminal often insert (— – −)
// into ASCII - so `--app` is not silently dropped as a positional token.
func normalizeArgs(args []string) []string {
out := make([]string, len(args))
for i, a := range args {
var b strings.Builder
b.Grow(len(a) + 4)
for _, r := range a {
switch r {
case '\u2014', '\u2013', '\u2212': // em, en, minus
// "—app" → "--app"; standalone dash stays single "-"
if b.Len() == 0 {
b.WriteString("--")
} else {
b.WriteByte('-')
}
default:
if unicode.Is(unicode.Cf, r) {
continue // strip zero-width / format chars
}
b.WriteRune(r)
}
}
out[i] = b.String()
}
return out
}
// knownChannels describes what the operator can pick, or where to declare it when // knownChannels describes what the operator can pick, or where to declare it when
// the module has no local values file yet. // the module has no local values file yet.
func knownChannels(a app.App) string { func knownChannels(a app.App) string {

View file

@ -0,0 +1,41 @@
package main
import (
"strings"
"testing"
"drmdecryption/apps/capture/capturecmd"
_ "drmdecryption/modules/all"
)
func TestCaptureRejectsChannelAsApp(t *testing.T) {
err := capturecmd.Run([]string{"--app", "bbcone"})
if err == nil {
t.Fatal("expected error for --app bbcone")
}
if !strings.Contains(err.Error(), "--app bbc") || !strings.Contains(err.Error(), "--channel bbcone") {
t.Fatalf("want suggestion for bbc/bbcone, got: %v", err)
}
}
func TestCaptureRejectsLeftoverArgs(t *testing.T) {
err := capturecmd.Run([]string{"--app", "bbc", "bbcone"})
if err == nil {
t.Fatal("expected error for leftover positional args")
}
if !strings.Contains(err.Error(), "unexpected arguments") {
t.Fatalf("got: %v", err)
}
}
func TestCaptureNormalizesEmDashThenSuggestsChannel(t *testing.T) {
// Word/Terminal often turns -- into an em dash: capture —app bbcone
err := capturecmd.Run([]string{"\u2014app", "bbcone"})
if err == nil {
t.Fatal("expected error")
}
if !strings.Contains(err.Error(), "--app bbc") {
t.Fatalf("got: %v", err)
}
}

View file

@ -101,11 +101,37 @@ func Get(name string) (App, error) {
ctor, ok := registry[name] ctor, ok := registry[name]
mu.RUnlock() mu.RUnlock()
if !ok { if !ok {
if owner, ch, ok := FindChannel(name); ok {
return nil, fmt.Errorf("%q is a channel of --app %s, not an app name — use: capture --app %s --channel %s", name, owner, owner, ch)
}
return nil, fmt.Errorf("unknown app %q — compiled-in apps: %v", name, Names()) return nil, fmt.Errorf("unknown app %q — compiled-in apps: %v", name, Names())
} }
return ctor() return ctor()
} }
// FindChannel reports which registered app owns a channel id (via HasChannel).
// Does not call Get's unknown-app path (constructs from the registry directly).
func FindChannel(id string) (appName, channelID string, ok bool) {
mu.RLock()
names := make([]string, 0, len(registry))
ctors := make([]func() (App, error), 0, len(registry))
for n, ctor := range registry {
names = append(names, n)
ctors = append(ctors, ctor)
}
mu.RUnlock()
for i, ctor := range ctors {
a, err := ctor()
if err != nil {
continue
}
if a.HasChannel(id) {
return names[i], id, true
}
}
return "", "", false
}
// Names lists registered app ids, sorted. // Names lists registered app ids, sorted.
func Names() []string { func Names() []string {
mu.RLock() mu.RLock()

View file

@ -76,6 +76,11 @@ func RunPassive(opt Options) (res Result, err error) {
} }
proxyBin, caHash := resolveProxy(nil, root) proxyBin, caHash := resolveProxy(nil, root)
if h, err := proxy.InstallCA(c, "", false); err != nil {
return res, fmt.Errorf("CA: %w", err)
} else if h != "" {
caHash = h
}
if err := proxy.PushAndStart(c, proxyBin); err != nil { if err := proxy.PushAndStart(c, proxyBin); err != nil {
return res, err return res, err
} }
@ -201,32 +206,37 @@ func Run(opt Options) (res Result, err error) {
if useTProxy { if useTProxy {
// Transparent REDIRECT — keeps phone VPN (BBC UK geo) working. // Transparent REDIRECT — keeps phone VPN (BBC UK geo) working.
// StartTransparent creates a per-install CA under data/ if needed and pushes cert+key.
proxy.ClearHTTPProxy(c) proxy.ClearHTTPProxy(c)
remoteDir := "/data/local/tmp/capture/" + a.Package() remoteDir := "/data/local/tmp/capture/" + a.Package()
if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false); err != nil { if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false); err != nil {
return res, err return res, fmt.Errorf("transparent MITM start: %w", err)
} }
defer proxy.StopTransparent(c) defer proxy.StopTransparent(c)
hints.RemoteCaps = []string{remoteDir + "/cap.json"} hints.RemoteCaps = []string{remoteDir + "/cap.json"}
hints.RemoteLog = remoteDir + "/appproxy.log" hints.RemoteLog = remoteDir + "/appproxy.log"
fmt.Println("[*] Transparent MITM (VPN OK) — package", a.Package()) fmt.Println("[*] Transparent MITM (VPN OK) — package", a.Package())
} else { } else {
if h, err := proxy.InstallCA(c, "", false); err != nil {
return res, fmt.Errorf("CA: %w", err)
} else if h != "" {
caHash = h
}
if err := proxy.PushAndStart(c, proxyBin, hints.Score.ProxyArgs()...); err != nil { if err := proxy.PushAndStart(c, proxyBin, hints.Score.ProxyArgs()...); err != nil {
return res, err return res, fmt.Errorf("proxy start: %w", err)
} }
if err := proxy.EnsureHTTPProxy(c, ""); err != nil { if err := proxy.EnsureHTTPProxy(c, ""); err != nil {
return res, err return res, fmt.Errorf("http_proxy: %w", err)
} }
proxy.ReinjectCA(c, caHash) proxy.ReinjectCA(c, caHash)
} }
if err := a.Launch(c); err != nil { if err := a.Launch(c); err != nil {
fmt.Fprintf(os.Stderr, "[!] launch: %v\n", err) return res, fmt.Errorf("launch: %w", err)
} }
if !opt.NoAutoPlay { if !opt.NoAutoPlay {
if err := a.AutoPlay(c, opt.Channel); err != nil { if err := a.AutoPlay(c, opt.Channel); err != nil {
fmt.Fprintf(os.Stderr, "[!] auto-play failed: %v\n", err) return res, fmt.Errorf("auto-play: %w", err)
fmt.Println("[*] Open the channel on the phone manually and start playback…")
} }
} else { } else {
fmt.Println("[*] Open the channel on the phone and wait for playback…") fmt.Println("[*] Open the channel on the phone and wait for playback…")

61
apps/pkg/proxy/ca_test.go Normal file
View file

@ -0,0 +1,61 @@
package proxy
import (
"os"
"path/filepath"
"testing"
)
func TestEnsureLocalCAGeneratesUniquePair(t *testing.T) {
root := t.TempDir()
cert1, err := EnsureLocalCA(root)
if err != nil {
t.Fatal(err)
}
want := filepath.Join(root, "data", "proxy-ca.crt")
if cert1 != want {
t.Fatalf("cert path: got %q want %q", cert1, want)
}
key1 := filepath.Join(root, "data", "proxy-ca.key")
if _, err := os.Stat(key1); err != nil {
t.Fatal("missing key", err)
}
hash1, err := AndroidCAHashFile(cert1)
if err != nil || hash1 == "" {
t.Fatalf("hash: %q %v", hash1, err)
}
// Second call reuses the same pair.
cert2, err := EnsureLocalCA(root)
if err != nil {
t.Fatal(err)
}
if cert2 != cert1 {
t.Fatalf("expected reuse, got %q vs %q", cert2, cert1)
}
// A different install root gets a different CA.
rootB := t.TempDir()
certB, err := EnsureLocalCA(rootB)
if err != nil {
t.Fatal(err)
}
hashB, _ := AndroidCAHashFile(certB)
if hashB == hash1 {
t.Fatal("expected different installs to get different CA hashes")
}
}
func TestFindLocalCAIgnoresCertWithoutKey(t *testing.T) {
root := t.TempDir()
dir := filepath.Join(root, "apps", "proxy")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "rteproxy-ca.crt"), []byte("not-a-real-cert"), 0o644); err != nil {
t.Fatal(err)
}
if p := FindLocalCA(root); p != "" {
t.Fatalf("expected empty without key, got %q", p)
}
}

View file

@ -2,10 +2,14 @@ package proxy
import ( import (
"crypto/md5" "crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/x509" "crypto/x509"
"crypto/x509/pkix"
"encoding/binary" "encoding/binary"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"math/big"
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
@ -24,6 +28,7 @@ const (
RemoteLog = "/data/local/tmp/appproxy.log" RemoteLog = "/data/local/tmp/appproxy.log"
RemoteTraffic = "/data/local/tmp/appproxy_traffic.jsonl" RemoteTraffic = "/data/local/tmp/appproxy_traffic.jsonl"
RemoteCACrt = "/data/local/tmp/rteproxy-ca.crt" RemoteCACrt = "/data/local/tmp/rteproxy-ca.crt"
RemoteCAKey = "/data/local/tmp/rteproxy-ca.key"
DefaultCAHash = "6c3578b4" DefaultCAHash = "6c3578b4"
) )
@ -237,22 +242,124 @@ func FindLocalBin(root string) string {
return "" return ""
} }
// FindLocalCA returns the first existing MITM CA cert under the repo. // 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 { func FindLocalCA(root string) string {
if root == "" { if root == "" {
root = repo.Root() root = repo.Root()
} }
user := filepath.Join(root, "data", "proxy-ca.crt")
if caPairExists(user) {
return user
}
for _, p := range []string{ for _, p := range []string{
filepath.Join(root, "apps", "proxy", "rteproxy-ca.crt"), filepath.Join(root, "apps", "proxy", "rteproxy-ca.crt"),
filepath.Join(root, "data", "proxy-ca.crt"), filepath.Join(root, "apps", "proxy", "appproxy-ca.crt"),
} { } {
if st, err := os.Stat(p); err == nil && !st.IsDir() { if caPairExists(p) {
return p return p
} }
} }
return "" 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. // AndroidCAHash returns the OpenSSL subject_hash_old used for system CA files.
func AndroidCAHash(certPEM []byte) (string, error) { func AndroidCAHash(certPEM []byte) (string, error) {
block, _ := pem.Decode(certPEM) block, _ := pem.Decode(certPEM)
@ -270,12 +377,13 @@ func AndroidCAHash(certPEM []byte) (string, error) {
// InstallCA pushes the MITM CA onto the device as HASH.0 and optionally Magisk-reinjects it. // 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). // 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) { func InstallCA(c *adb.Client, localCA string, reinject bool) (hash string, err error) {
if localCA == "" { if localCA == "" {
localCA = FindLocalCA("") localCA, err = EnsureLocalCA("")
} if err != nil {
if localCA == "" { return "", err
return "", fmt.Errorf("no local CA cert found (expected apps/proxy/rteproxy-ca.crt)") }
} }
pemBytes, err := os.ReadFile(localCA) pemBytes, err := os.ReadFile(localCA)
if err != nil { if err != nil {
@ -293,6 +401,12 @@ func InstallCA(c *adb.Client, localCA string, reinject bool) (hash string, err e
// Also drop a copy named after the process for clarity. // Also drop a copy named after the process for clarity.
_ = c.Push(localCA, "/data/local/tmp/appproxy-ca.crt") _ = 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") tmpHash := filepath.Join(os.TempDir(), hash+".0")
if err := os.WriteFile(tmpHash, pemBytes, 0o644); err != nil { if err := os.WriteFile(tmpHash, pemBytes, 0o644); err != nil {
return hash, err return hash, err
@ -314,6 +428,33 @@ func InstallCA(c *adb.Client, localCA string, reinject bool) (hash string, err e
return hash, nil 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. // Stop stops the on-device mitm process.
func Stop(c *adb.Client) { func Stop(c *adb.Client) {
stopProxy(c) stopProxy(c)
@ -339,8 +480,16 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
// Ensure no global HTTP proxy — transparent mode must not use one. // Ensure no global HTTP proxy — transparent mode must not use one.
ClearHTTPProxy(c) 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 { if reinject {
ReinjectCA(c, DefaultCAHash) ReinjectCA(c, caHash)
} }
if st, err := os.Stat(localBin); err != nil || st.IsDir() { if st, err := os.Stat(localBin); err != nil || st.IsDir() {
@ -384,6 +533,22 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
return err return err
} }
_, _ = c.Shell("chmod", "755", "/data/local/tmp/start_appproxy_tproxy.sh") _, _ = 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 &") _, _, _ = c.Run("shell", "setsid /data/local/tmp/start_appproxy_tproxy.sh </dev/null >/dev/null 2>&1 &")
var pid string var pid string
@ -395,6 +560,16 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
} }
} }
if pid == "" { 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)") return fmt.Errorf("appproxy failed to start (transparent)")
} }
fmt.Printf("[+] appproxy pid=%s; capture → %s\n", pid, remoteDir) fmt.Printf("[+] appproxy pid=%s; capture → %s\n", pid, remoteDir)
@ -565,13 +740,26 @@ ls /apex/com.android.conscrypt/cacerts/$HASH.0 2>/dev/null && echo CA_OK || echo
case r := <-ch: case r := <-ch:
out = r.out out = r.out
case <-time.After(20 * time.Second): case <-time.After(20 * time.Second):
fmt.Println("[!] CA reinject timed out after 20s — continuing (CA likely already mounted)")
_, _ = c.Shell("su", "-c", "killall reinject_ca.sh 2>/dev/null; true") _, _ = c.Shell("su", "-c", "killall reinject_ca.sh 2>/dev/null; true")
// Script may have finished mounting even if su -mm hung; verify on device.
if caPresentOnDevice(c, caHash) {
fmt.Println("[+] System CA present in conscrypt (reinject timed out, mount OK)")
} else {
fmt.Println("[!] CA reinject timed out after 20s — re-run: drm proxy install-ca --reinject")
}
return return
} }
if strings.Contains(out, "CA_OK") { if strings.Contains(out, "CA_OK") || caPresentOnDevice(c, caHash) {
fmt.Println("[+] System CA present in conscrypt") fmt.Println("[+] System CA present in conscrypt")
} else { } else {
fmt.Println("[!] CA inject skipped/failed — if TLS errors, re-run Magisk CA mount") fmt.Println("[!] CA inject skipped/failed — re-run: drm proxy install-ca --reinject")
} }
} }
func caPresentOnDevice(c *adb.Client, caHash string) bool {
if caHash == "" {
caHash = DefaultCAHash
}
out := c.Out("shell", "su", "-c", "ls /apex/com.android.conscrypt/cacerts/"+caHash+".0")
return strings.Contains(out, caHash+".0")
}

View file

@ -1240,15 +1240,19 @@ func loadOrCreateCA(certPath, keyPath string) (*tls.Certificate, error) {
if _, err := os.Stat(keyPath); err == nil { if _, err := os.Stat(keyPath); err == nil {
cert, err := tls.LoadX509KeyPair(certPath, keyPath) cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil { if err != nil {
return nil, err // Stale key left on device after install-ca replaced only the cert.
} log.Printf("CA pair unusable (%v) — removing %s and %s so a matching pair can be pushed/recreated", err, certPath, keyPath)
if len(cert.Certificate) > 0 { _ = os.Remove(certPath)
leaf, err := x509.ParseCertificate(cert.Certificate[0]) _ = os.Remove(keyPath)
if err == nil { } else {
cert.Leaf = leaf if len(cert.Certificate) > 0 {
leaf, err := x509.ParseCertificate(cert.Certificate[0])
if err == nil {
cert.Leaf = leaf
}
} }
return &cert, nil
} }
return &cert, nil
} }
} }

View file

@ -12,22 +12,26 @@ adb devices # phone listed and authorised
./bin/drm proxy install-ca --reinject ./bin/drm proxy install-ca --reinject
``` ```
The phone must be rooted (Magisk). `install-ca` pushes the MITM CA and bind-mounts The phone must be rooted (Magisk). On first `install-ca`, the host **generates a
it over the system trust store, including into already-running zygote namespaces — unique MITM CA** for this install under `data/proxy-ca.crt` + `data/proxy-ca.key`
a user-store CA is not enough, modern apps ignore it. (gitignored). That pair is what gets pushed to the phone — each user/machine gets
their own CA, not a shared key from the zip.
Verify the mount: `install-ca --reinject` Magisk-bind-mounts **your** CA into the system trust store
(including zygote). A user-store CA is not enough; modern apps ignore it.
Verify the mount (hash is printed by `install-ca`, not a fixed value):
```bash ```bash
adb shell 'ls /system/etc/security/cacerts/ | grep 6c3578b4' # hash from: [+] … (hash abcdef01)
adb shell 'su -c "ls /apex/com.android.conscrypt/cacerts/6c3578b4.0"' adb shell 'su -c "ls /apex/com.android.conscrypt/cacerts/<hash>.0"'
``` ```
If an app still reports `tls: unknown certificate`, re-run the reinject and If an app still reports `tls: unknown certificate`, re-run the reinject and
force-stop the app so it inherits the mount: force-stop the app so it inherits the mount:
```bash ```bash
./bin/drm proxy reinject-ca ./bin/drm proxy install-ca --reinject
adb shell am force-stop <package> adb shell am force-stop <package>
``` ```
@ -334,7 +338,7 @@ Also sanity-check that the KID you captured matches whatever you recorded in
|---|---| |---|---|
| `tls: unknown certificate` in the app | CA not mounted into conscrypt; reinject, then force-stop the app | | `tls: unknown certificate` in the app | CA not mounted into conscrypt; reinject, then force-stop the app |
| `timed out waiting for capture ([auth pid pssh mpd])` | playback never started, or `Hints` asks for a field this app does not send | | `timed out waiting for capture ([auth pid pssh mpd])` | playback never started, or `Hints` asks for a field this app does not send |
| `appproxy failed to start (transparent)` | see log; often CA key mismatch (`appproxy-ca.key` ≠ cert) — copy matching `rteproxy-ca.key` | | `appproxy failed to start (transparent)` | CA cert/key mismatch on phone — `install-ca` must push **both** `rteproxy-ca.crt` and `rteproxy-ca.key`, then `--reinject`. Check `adb shell cat …/appproxy.log` for `private key does not match` |
| App loads catalog but stream spins / fails after a capture | leftover `APPROXY_TPROXY` iptables REDIRECT — run cleanup above | | App loads catalog but stream spins / fails after a capture | leftover `APPROXY_TPROXY` iptables REDIRECT — run cleanup above |
| `launch: ui node not found within Ns` | launch marker does not match — dump the tree and pick a resource id | | `launch: ui node not found within Ns` | launch marker does not match — dump the tree and pick a resource id |
| `launch: exit status 1` | monkey raced a force-stop; usually transient, retry | | `launch: exit status 1` | monkey raced a force-stop; usually transient, retry |
@ -343,6 +347,11 @@ Also sanity-check that the KID you captured matches whatever you recorded in
| `CA inject skipped/failed` | transient after repeated runs; re-run `proxy reinject-ca` | | `CA inject skipped/failed` | transient after repeated runs; re-run `proxy reinject-ca` |
| Screen asleep mid-run | `adb shell svc power stayon true` | | Screen asleep mid-run | `adb shell svc power stayon true` |
| VPN on + classic `http_proxy` capture | use transparent mode instead (see above) | | VPN on + classic `http_proxy` capture | use transparent mode instead (see above) |
| Log shows `Setting HTTP proxy -> 192.168…` for BBC | wrong args / passive mode — use `--app bbc --channel bbcone` (ASCII `--`, not a Word em-dash `—`) |
| `"bbcone" is a channel of --app bbc` | you passed a channel as `--app`; fix the flags |
| `unexpected arguments […]` | only flags are accepted; no bare words after the command |
| `launch:` / `auto-play:` aborts the run | fail-fast — fix the phone UI / channel, or omit `--auto-play` and navigate by hand |
Clear the phone's proxy / transparent redirect if a run is interrupted: Clear the phone's proxy / transparent redirect if a run is interrupted:

View file

@ -86,6 +86,21 @@ same fields (`mpd` required; no `key` / `pssh` for clear streams).
adb shell "su -c 'sh /data/local/tmp/tproxy_iptables.sh stop; killall -9 appproxy 2>/dev/null; true'" adb shell "su -c 'sh /data/local/tmp/tproxy_iptables.sh stop; killall -9 appproxy 2>/dev/null; true'"
``` ```
### `appproxy failed to start (transparent)`
Usually a **CA cert/key mismatch** left on the phone from an older build. Current
builds keep a **per-install** CA under `data/proxy-ca.crt` + `data/proxy-ca.key`
and push both. Fix:
```powershell
drm proxy install-ca --reinject
adb shell am force-stop bbc.iplayer.android
drm capture --app bbc --channel bbcone --wait 120
```
You should see a unique hash on first run (`[+] Wrote data\proxy-ca.crt …`) and
`[+] Pushed matching CA key`. Do not share `data/proxy-ca.key` between users.
### Replay ### Replay
```powershell ```powershell

View file

@ -28,6 +28,11 @@ Writes `dist/release/`:
| `proxy-android-arm64` | Phone MITM (`drm proxy push` / transparent) | | `proxy-android-arm64` | Phone MITM (`drm proxy push` / transparent) |
| `SHA256SUMS.txt` | SHA-256 of the above | | `SHA256SUMS.txt` | SHA-256 of the above |
Releases **do not** ship a MITM private key. On each machine, the first
`drm proxy install-ca --reinject` creates `data/proxy-ca.crt` + `data/proxy-ca.key`
(unique per install). Users must not copy `data/` between PCs if they want
separate CAs.
Copy the matching host binary to `bin/drm` / `bin/drm.exe` (the scripts already Copy the matching host binary to `bin/drm` / `bin/drm.exe` (the scripts already
do this for the current OS) and keep `proxy-android-arm64` next to it under do this for the current OS) and keep `proxy-android-arm64` next to it under
`bin/`. `bin/`.