From 1d36961a7cfb1fd8044ac84649149d8d22456aad Mon Sep 17 00:00:00 2001 From: 404errordeveloper Date: Thu, 8 Oct 2026 20:44:10 +0200 Subject: [PATCH] Bugs fixed --- apps/cli/main.go | 19 ++- apps/modules/provider/provider.go | 16 +- apps/pkg/bootstrap/bootstrap.go | 159 ++++++++++++++++++ apps/pkg/bootstrap/embedded/README.md | 154 +++++++++++++++++ .../pkg/bootstrap/embedded/apps/pkg/pkg.gomod | 5 + .../apps/proxy/device/tproxy_iptables.sh | 81 +++++++++ apps/pkg/bootstrap/embedded/configs/.gitkeep | 2 + apps/pkg/bootstrap/embedded/root-go-mod.txt | 5 + apps/pkg/phonecap/phonecap.go | 20 +-- apps/pkg/proxy/embed.go | 58 +++++++ apps/pkg/proxy/embedded/tproxy_iptables.sh | 81 +++++++++ apps/pkg/proxy/proxy.go | 26 +-- apps/pkg/repo/root.go | 50 +++++- apps/proxy/proxyctlcmd/proxyctlcmd.go | 7 + docs/release.md | 24 ++- scripts/build-release.ps1 | 75 +++++++-- 16 files changed, 734 insertions(+), 48 deletions(-) create mode 100644 apps/pkg/bootstrap/bootstrap.go create mode 100644 apps/pkg/bootstrap/embedded/README.md create mode 100644 apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod create mode 100644 apps/pkg/bootstrap/embedded/apps/proxy/device/tproxy_iptables.sh create mode 100644 apps/pkg/bootstrap/embedded/configs/.gitkeep create mode 100644 apps/pkg/bootstrap/embedded/root-go-mod.txt create mode 100644 apps/pkg/proxy/embed.go create mode 100644 apps/pkg/proxy/embedded/tproxy_iptables.sh diff --git a/apps/cli/main.go b/apps/cli/main.go index c72d009..edc4bf3 100644 --- a/apps/cli/main.go +++ b/apps/cli/main.go @@ -13,6 +13,7 @@ import ( "drmdecryption/apps/cli/modulescmd" "drmdecryption/apps/proxy/proxyctlcmd" "drmdecryption/apps/streamd/servecmd" + "drmdecryption/bootstrap" // Links every app module into this binary. _ "drmdecryption/modules/all" @@ -24,6 +25,16 @@ func main() { os.Exit(2) } cmd, args := os.Args[1], os.Args[2:] + + // Materialise apps/, bin/, outputs/, … next to this exe when missing + // so a lone downloaded drm.exe becomes a GitHub-like install tree. + if cmd != "help" && cmd != "-h" && cmd != "--help" { + if err := bootstrap.EnsureAndLog(); err != nil { + fmt.Fprintln(os.Stderr, "[!] bootstrap:", err) + os.Exit(1) + } + } + var err error switch cmd { case "capture": @@ -67,9 +78,11 @@ Usage: drm proxy build|push|install-ca|start|stop|discover|pull|clear-proxy on-device HTTPS MITM -App modules are compiled in; their local values live in -apps/modules//module.yaml (gitignored) and can be overridden per run with ---. flags or _ environment variables. +App module *code* is compiled in; module *values* are never inside the exe. +Put configs at apps/modules//module.yaml yourself (see the GitHub repo). +On first run, drm only creates the scaffold (apps/pkg, bin/proxy, outputs, …). + +Overrides: --. flags or _ environment variables. Run any subcommand with --help for its own flags. `) diff --git a/apps/modules/provider/provider.go b/apps/modules/provider/provider.go index 8936d48..ab76703 100644 --- a/apps/modules/provider/provider.go +++ b/apps/modules/provider/provider.go @@ -53,7 +53,8 @@ func (b *Base) CacheDir() string { return b.cacheDir } func (b *Base) ConfigPath() string { return b.cfg.Path } func (b *Base) ConfigLoaded() bool { return b.cfg.Loaded } -// ProxyBin resolves the on-device MITM binary, relative paths against repo root. +// ProxyBin resolves the on-device MITM binary. Empty means “auto” (caller uses +// proxy.FindLocalBin — next to drm.exe, then repo bin/). func (b *Base) ProxyBin() string { if b.common.ProxyBin != "" { return modcfg.Resolve(b.common.ProxyBin) @@ -67,7 +68,18 @@ func (b *Base) ProxyBin() string { return p } } - return filepath.Join(root, "bin", "proxy-android-arm64") + if exe, err := os.Executable(); err == nil { + dir := filepath.Dir(exe) + for _, p := range []string{ + filepath.Join(dir, "proxy-android-arm64"), + filepath.Join(dir, "bin", "proxy-android-arm64"), + } { + if st, err := os.Stat(p); err == nil && !st.IsDir() { + return p + } + } + } + return "" } func (b *Base) CAHash() string { diff --git a/apps/pkg/bootstrap/bootstrap.go b/apps/pkg/bootstrap/bootstrap.go new file mode 100644 index 0000000..e357520 --- /dev/null +++ b/apps/pkg/bootstrap/bootstrap.go @@ -0,0 +1,159 @@ +// Package bootstrap materialises a GitHub-like install tree next to drm.exe +// so a single downloaded binary can create apps/, bin/, outputs/, etc. on first run. +package bootstrap + +import ( + "embed" + "fmt" + "io/fs" + "os" + "path/filepath" + "strings" +) + +//go:embed all:embedded +var embedded embed.FS + +const minProxyBytes = 100_000 // stub ELF is tiny; real proxy-android-arm64 is ~9MB + +// InstallRoot is the directory that should contain apps/, bin/, outputs/. +// If drm.exe lives in …/bin/, the parent is the root; otherwise the exe directory. +func InstallRoot() (string, error) { + exe, err := os.Executable() + if err != nil { + return "", err + } + exe, err = filepath.EvalSymlinks(exe) + if err != nil { + exe, _ = os.Executable() + } + dir := filepath.Dir(exe) + if strings.EqualFold(filepath.Base(dir), "bin") { + return filepath.Dir(dir), nil + } + return dir, nil +} + +// Ensure writes any missing layout files from the embedded tree into root. +// Existing files are left untouched (user edits to module.yaml are kept). +func Ensure(root string) (created []string, err error) { + if root == "" { + root, err = InstallRoot() + if err != nil { + return nil, err + } + } + err = fs.WalkDir(embedded, "embedded", func(path string, d fs.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + // embed.FS paths always use forward slashes — do not use filepath.Rel (Windows). + slashRel := strings.TrimPrefix(path, "embedded/") + if slashRel == path || slashRel == "embedded" || slashRel == "." { + return nil + } + // go:embed rejects files named go.mod. We ship root-go-mod.txt (and + // optionally apps/pkg/pkg.gomod) and materialise apps/pkg/go.mod. + outSlash := slashRel + switch slashRel { + case "root-go-mod.txt", "apps/pkg/pkg.gomod": + outSlash = "apps/pkg/go.mod" + } + dest := filepath.Join(root, filepath.FromSlash(outSlash)) + if d.IsDir() { + return os.MkdirAll(dest, 0o755) + } + if st, err := os.Stat(dest); err == nil && !st.IsDir() { + return nil // keep existing + } + data, err := embedded.ReadFile(path) + if err != nil { + return err + } + // Do not write the tiny release stub as a real MITM binary. + if slashRel == "bin/proxy-android-arm64" && len(data) < minProxyBytes { + return nil + } + if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { + return err + } + mode := os.FileMode(0o644) + if strings.HasSuffix(outSlash, "proxy-android-arm64") || strings.HasSuffix(outSlash, ".sh") { + mode = 0o755 + } + if err := os.WriteFile(dest, data, mode); err != nil { + return err + } + created = append(created, outSlash) + return nil + }) + if err != nil { + return created, err + } + + // If drm is not already under bin/, copy/link a drm.exe there for 1:1 layout. + if err := ensureBinDrm(root); err != nil { + return created, err + } + return created, nil +} + +func ensureBinDrm(root string) error { + exe, err := os.Executable() + if err != nil { + return nil + } + exe, _ = filepath.EvalSymlinks(exe) + dest := filepath.Join(root, "bin", "drm.exe") + if sameFile(exe, dest) { + return nil + } + if st, err := os.Stat(dest); err == nil && !st.IsDir() { + return nil + } + data, err := os.ReadFile(exe) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { + return err + } + return os.WriteFile(dest, data, 0o755) +} + +func sameFile(a, b string) bool { + absA, err1 := filepath.Abs(a) + absB, err2 := filepath.Abs(b) + if err1 != nil || err2 != nil { + return false + } + return strings.EqualFold(absA, absB) +} + +// EnsureAndLog runs Ensure and prints what was created (if anything). +func EnsureAndLog() error { + root, err := InstallRoot() + if err != nil { + return err + } + created, err := Ensure(root) + if err != nil { + return err + } + if len(created) > 0 { + fmt.Printf("[*] Bootstrapped install layout under %s (%d new files)\n", root, len(created)) + for _, c := range created { + fmt.Printf(" + %s\n", filepath.ToSlash(c)) + } + } + proxy := filepath.Join(root, "bin", "proxy-android-arm64") + if st, err := os.Stat(proxy); err != nil || st.Size() < minProxyBytes { + fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to drm or use a release build that embeds it\n") + } + // Module configs are never shipped inside drm.exe — operator must add them. + modBBC := filepath.Join(root, "apps", "modules", "bbc", "module.yaml") + if _, err := os.Stat(modBBC); err != nil { + fmt.Fprintf(os.Stderr, "[!] no apps/modules/*/module.yaml yet — create e.g. apps/modules/bbc/module.yaml (not bundled in the exe)\n") + } + return nil +} diff --git a/apps/pkg/bootstrap/embedded/README.md b/apps/pkg/bootstrap/embedded/README.md new file mode 100644 index 0000000..a2f3c9c --- /dev/null +++ b/apps/pkg/bootstrap/embedded/README.md @@ -0,0 +1,154 @@ +# DRM-Decryption + +Capture Widevine live sessions from Android streaming apps and restream them. + +Everything is one Go binary — `drm` — with every app module compiled in. Each +streaming app (RTE, TG4, …) is a Go package under `apps/modules/`; its secrets and +IDs live in a local, gitignored values file that you fill in yourself. + +- **[docs/](docs/)** — architecture, module authoring, per-provider setup +- **[docs/quickstart.md](docs/quickstart.md)** — the longer version of what follows + +--- + +## Quick start + +### 1. Prerequisites + +| Need | Why | +|---|---| +| **Go 1.25+** | builds everything | +| **Python 3.10+** | `apps/wvkey/wvkey.py` talks to the Widevine CDM | +| **adb** (platform-tools) on `PATH` | only for phone capture | +| A `.wvd` Widevine device file | only for fetching keys | + +Phone capture additionally needs a rooted Android device (Magisk) so the MITM CA +can be injected into the system trust store. Catalog lookups need no phone. + +### 2. Clone and build + +```bash +git clone https://git.nulldrm.com/nulldrm/Null-DRM-Official.git +cd Null-DRM-Official + +# Linux / macOS +go -C apps/cli build -o ../../bin/drm . + +# Windows +go -C apps/cli build -o ../../bin/drm.exe . +``` + +Check it: + +```bash +./bin/drm help +./bin/drm modules # which app modules this build contains +``` + +`drm modules` works immediately, but channel lists stay empty until you add +values — that is the next step. + +### 3. Python CDM helper + +```bash +python -m venv .venv +.venv/bin/pip install -r apps/wvkey/requirements.txt # Windows: .venv\Scripts\pip +``` + +Put your Widevine device file in `data/` (gitignored), e.g. `data/device.wvd`. + +### 4. Fill in a module's values + +Compiled-in module code carries **no** account IDs, policy keys, video IDs, +license URLs or key IDs. Those go in a gitignored file per module, which you create: + +```text +apps/modules/tg4/module.yaml +apps/modules/rte/module.yaml +``` + +Where each value comes from: + +- **[docs/providers/tg4.md](docs/providers/tg4.md)** — Brightcove account ID, policy key, video IDs +- **[docs/providers/rte.md](docs/providers/rte.md)** — license URL, origin hosts, channel KIDs +- **[docs/capture.md](docs/capture.md)** — how to discover all of it for a *new* app + +Any value can be passed per-run instead of stored: + +```bash +./bin/drm catalog --app tg4 --channel ioi --tg4.policy-key 'BCpkAD...' +TG4_POLICY_KEY='BCpkAD...' ./bin/drm catalog --app tg4 --channel ioi +``` + +### 5. Run something + +```bash +# keys from a public catalog — no phone needed +./bin/drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd + +# phone capture: launch the app, drive it to a channel, grab license + keys +./bin/drm proxy build # once: cross-compile the on-device MITM +./bin/drm capture --app rte --channel rteone --auto-play --wvd data/device.wvd + +# control plane + dashboard on http://127.0.0.1:8083 +./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd --token SECRET + +# always-on refresher: watches streamd, re-captures dead channels +STREAMD_TOKEN=SECRET ./bin/drm agent run --config apps/agent/agent.yaml +``` + +Results land in `outputs///`, with `latest/` kept as a copy. + +--- + +## Subcommands + +| Command | What it does | +|---|---| +| `drm modules` | list compiled-in app modules, their channels and config source | +| `drm capture` | one-shot phone MITM capture → `outputs///` | +| `drm catalog` | resolve a channel from its public catalog, no phone | +| `drm serve` | streamd: REST API + dashboard + media supervisor | +| `drm agent` | `run` / `status` / `devices` / `enqueue` / `cancel` | +| `drm proxy` | `build` / `push` / `install-ca` / `start` / `stop` / `discover` / `pull` | + +Run any of them with `--help`. + +## Layout + +```text +apps/cli/ the binary -> bin/drm +apps/modules/ app modules: Go (tracked) + module.yaml (gitignored) +apps/pkg/ shared, provider-neutral libraries +apps/capture/ phone capture command +apps/agent/ always-on key refresher +apps/streamd/ control plane: API, SQLite, dashboard, supervisor +apps/proxy/ MITM host CLI + on-device proxy source +apps/wvkey/ wvkey.py — CDM only +docs/ architecture, authoring, provider setup +data/ secrets: .wvd, CA (gitignored) +outputs/ capture sessions (gitignored) +bin/ built binaries (gitignored) +www/ static site +``` + +## Tests + +```bash +go -C apps/pkg test ./... +go -C apps/modules test ./... +go -C apps/streamd test ./... +``` + +Tests that hit a live origin are behind a build tag, so they stay out of the +normal run: + +```bash +go -C apps/modules test -tags live ./rte/ -v +``` + +## Scope + +For use only on services you are authorised to access, with content you have the +right to decrypt. [docs/architecture.md](docs/architecture.md) describes what the +system does and where it stops. diff --git a/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod b/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod new file mode 100644 index 0000000..c23f9f3 --- /dev/null +++ b/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod @@ -0,0 +1,5 @@ +module drmdecryption + +go 1.25.0 + +require gopkg.in/yaml.v3 v3.0.1 diff --git a/apps/pkg/bootstrap/embedded/apps/proxy/device/tproxy_iptables.sh b/apps/pkg/bootstrap/embedded/apps/proxy/device/tproxy_iptables.sh new file mode 100644 index 0000000..52a61d6 --- /dev/null +++ b/apps/pkg/bootstrap/embedded/apps/proxy/device/tproxy_iptables.sh @@ -0,0 +1,81 @@ +#!/system/bin/sh +# Transparent redirect: package UID TCP/443 → local appproxy (no Wi‑Fi http_proxy). +# Usage: +# tproxy_iptables.sh start [port] +# tproxy_iptables.sh stop +# tproxy_iptables.sh status + +set -eu +CHAIN=APPROXY_TPROXY +ACTION="${1:-}" + +uid_for_package() { + pkg="$1" + # dumpsys package | grep userId= OR stat on data dir + uid=$(dumpsys package "$pkg" 2>/dev/null | grep -m1 -oE 'userId=[0-9]+' | head -1 | cut -d= -f2 || true) + if [ -z "$uid" ]; then + uid=$(stat -c %u "/data/user/0/$pkg" 2>/dev/null || true) + fi + echo "$uid" +} + +stop_rules() { + iptables -t nat -D OUTPUT -j "$CHAIN" 2>/dev/null || true + iptables -t nat -F "$CHAIN" 2>/dev/null || true + iptables -t nat -X "$CHAIN" 2>/dev/null || true + echo "STOPPED" +} + +start_rules() { + pkg="$1" + port="$2" + uid=$(uid_for_package "$pkg") + if [ -z "$uid" ] || [ "$uid" = "0" ]; then + echo "ERR: cannot resolve uid for package $pkg" >&2 + exit 1 + fi + proxy_uid=$(stat -c %u /data/local/tmp/appproxy 2>/dev/null || echo "") + # Prefer the running process uid if available + if pidof appproxy >/dev/null 2>&1; then + proxy_uid=$(stat -c %u /proc/$(pidof appproxy | awk '{print $1}') 2>/dev/null || echo "$proxy_uid") + fi + + stop_rules >/dev/null + iptables -t nat -N "$CHAIN" + # Never redirect the mitm itself (loop). + if [ -n "$proxy_uid" ]; then + iptables -t nat -A "$CHAIN" -m owner --uid-owner "$proxy_uid" -j RETURN + fi + # Skip localhost / link-local. + iptables -t nat -A "$CHAIN" -d 127.0.0.0/8 -j RETURN + iptables -t nat -A "$CHAIN" -d 10.0.0.0/8 -j RETURN 2>/dev/null || true + # Redirect only the target app's HTTPS. + iptables -t nat -A "$CHAIN" -p tcp -m owner --uid-owner "$uid" --dport 443 -j REDIRECT --to-ports "$port" + iptables -t nat -A OUTPUT -j "$CHAIN" + echo "STARTED pkg=$pkg uid=$uid port=$port proxy_uid=${proxy_uid:-unknown}" +} + +status_rules() { + echo "=== $CHAIN ===" + iptables -t nat -L "$CHAIN" -n -v 2>/dev/null || echo "(no chain)" + echo "=== OUTPUT head ===" + iptables -t nat -L OUTPUT -n -v 2>/dev/null | head -20 +} + +case "$ACTION" in + start) + pkg="${2:?package required}" + port="${3:-8080}" + start_rules "$pkg" "$port" + ;; + stop) + stop_rules + ;; + status) + status_rules + ;; + *) + echo "usage: $0 start [port] | stop | status" >&2 + exit 2 + ;; +esac diff --git a/apps/pkg/bootstrap/embedded/configs/.gitkeep b/apps/pkg/bootstrap/embedded/configs/.gitkeep new file mode 100644 index 0000000..2aa133a --- /dev/null +++ b/apps/pkg/bootstrap/embedded/configs/.gitkeep @@ -0,0 +1,2 @@ +# Optional local configs + diff --git a/apps/pkg/bootstrap/embedded/root-go-mod.txt b/apps/pkg/bootstrap/embedded/root-go-mod.txt new file mode 100644 index 0000000..c23f9f3 --- /dev/null +++ b/apps/pkg/bootstrap/embedded/root-go-mod.txt @@ -0,0 +1,5 @@ +module drmdecryption + +go 1.25.0 + +require gopkg.in/yaml.v3 v3.0.1 diff --git a/apps/pkg/phonecap/phonecap.go b/apps/pkg/phonecap/phonecap.go index 84d5b3b..bcd9af9 100644 --- a/apps/pkg/phonecap/phonecap.go +++ b/apps/pkg/phonecap/phonecap.go @@ -349,26 +349,22 @@ func ClearProxyLater(c *adb.Client) { } func resolveProxy(a app.App, root string) (bin, caHash string) { - bin = filepath.Join(root, "bin", "proxy-android-arm64") caHash = DefaultCAHash if a != nil { if p := a.ProxyBin(); p != "" { - bin = p + if st, err := os.Stat(p); err == nil && !st.IsDir() { + bin = p + } } if h := a.CAHash(); h != "" { caHash = h } } - if _, err := os.Stat(bin); err != nil { - for _, p := range []string{ - filepath.Join(root, "bin", "proxy-android-arm64"), - filepath.Join(root, "apps", "proxy", "proxy-android-arm64"), - } { - if st, e := os.Stat(p); e == nil && !st.IsDir() { - bin = p - break - } - } + if bin == "" { + bin = proxy.FindLocalBin(root) + } + if bin == "" { + bin = filepath.Join(root, "bin", "proxy-android-arm64") } return bin, caHash } diff --git a/apps/pkg/proxy/embed.go b/apps/pkg/proxy/embed.go new file mode 100644 index 0000000..1c985c4 --- /dev/null +++ b/apps/pkg/proxy/embed.go @@ -0,0 +1,58 @@ +package proxy + +import ( + _ "embed" + "fmt" + "os" + "path/filepath" + + "drmdecryption/adb" + "drmdecryption/repo" +) + +//go:embed embedded/tproxy_iptables.sh +var embeddedTProxyScript []byte + +// ensureTProxyScript pushes the iptables helper to the phone. +// Prefers the source-tree copy; falls back to the copy embedded in drm.exe +// so a portable release zip does not need apps/proxy/device/. +func ensureTProxyScript(c *adb.Client) error { + candidates := []string{ + filepath.Join(repo.Root(), "apps", "proxy", "device", "tproxy_iptables.sh"), + } + if exe, err := os.Executable(); err == nil { + dir := filepath.Dir(exe) + candidates = append(candidates, + filepath.Join(dir, "tproxy_iptables.sh"), + filepath.Join(dir, "apps", "proxy", "device", "tproxy_iptables.sh"), + ) + } + var local string + for _, p := range candidates { + if st, err := os.Stat(p); err == nil && !st.IsDir() { + local = p + break + } + } + tmp := filepath.Join(os.TempDir(), "tproxy_iptables.sh") + if local != "" { + data, err := os.ReadFile(local) + if err != nil { + return err + } + if err := os.WriteFile(tmp, data, 0o755); err != nil { + return err + } + } else { + if err := os.WriteFile(tmp, embeddedTProxyScript, 0o755); err != nil { + return err + } + fmt.Println("[*] Using embedded tproxy_iptables.sh") + } + defer os.Remove(tmp) + if err := c.Push(tmp, RemoteTProxyScript); err != nil { + return err + } + _, _ = c.Shell("chmod", "755", RemoteTProxyScript) + return nil +} diff --git a/apps/pkg/proxy/embedded/tproxy_iptables.sh b/apps/pkg/proxy/embedded/tproxy_iptables.sh new file mode 100644 index 0000000..52a61d6 --- /dev/null +++ b/apps/pkg/proxy/embedded/tproxy_iptables.sh @@ -0,0 +1,81 @@ +#!/system/bin/sh +# Transparent redirect: package UID TCP/443 → local appproxy (no Wi‑Fi http_proxy). +# Usage: +# tproxy_iptables.sh start [port] +# tproxy_iptables.sh stop +# tproxy_iptables.sh status + +set -eu +CHAIN=APPROXY_TPROXY +ACTION="${1:-}" + +uid_for_package() { + pkg="$1" + # dumpsys package | grep userId= OR stat on data dir + uid=$(dumpsys package "$pkg" 2>/dev/null | grep -m1 -oE 'userId=[0-9]+' | head -1 | cut -d= -f2 || true) + if [ -z "$uid" ]; then + uid=$(stat -c %u "/data/user/0/$pkg" 2>/dev/null || true) + fi + echo "$uid" +} + +stop_rules() { + iptables -t nat -D OUTPUT -j "$CHAIN" 2>/dev/null || true + iptables -t nat -F "$CHAIN" 2>/dev/null || true + iptables -t nat -X "$CHAIN" 2>/dev/null || true + echo "STOPPED" +} + +start_rules() { + pkg="$1" + port="$2" + uid=$(uid_for_package "$pkg") + if [ -z "$uid" ] || [ "$uid" = "0" ]; then + echo "ERR: cannot resolve uid for package $pkg" >&2 + exit 1 + fi + proxy_uid=$(stat -c %u /data/local/tmp/appproxy 2>/dev/null || echo "") + # Prefer the running process uid if available + if pidof appproxy >/dev/null 2>&1; then + proxy_uid=$(stat -c %u /proc/$(pidof appproxy | awk '{print $1}') 2>/dev/null || echo "$proxy_uid") + fi + + stop_rules >/dev/null + iptables -t nat -N "$CHAIN" + # Never redirect the mitm itself (loop). + if [ -n "$proxy_uid" ]; then + iptables -t nat -A "$CHAIN" -m owner --uid-owner "$proxy_uid" -j RETURN + fi + # Skip localhost / link-local. + iptables -t nat -A "$CHAIN" -d 127.0.0.0/8 -j RETURN + iptables -t nat -A "$CHAIN" -d 10.0.0.0/8 -j RETURN 2>/dev/null || true + # Redirect only the target app's HTTPS. + iptables -t nat -A "$CHAIN" -p tcp -m owner --uid-owner "$uid" --dport 443 -j REDIRECT --to-ports "$port" + iptables -t nat -A OUTPUT -j "$CHAIN" + echo "STARTED pkg=$pkg uid=$uid port=$port proxy_uid=${proxy_uid:-unknown}" +} + +status_rules() { + echo "=== $CHAIN ===" + iptables -t nat -L "$CHAIN" -n -v 2>/dev/null || echo "(no chain)" + echo "=== OUTPUT head ===" + iptables -t nat -L OUTPUT -n -v 2>/dev/null | head -20 +} + +case "$ACTION" in + start) + pkg="${2:?package required}" + port="${3:-8080}" + start_rules "$pkg" "$port" + ;; + stop) + stop_rules + ;; + status) + status_rules + ;; + *) + echo "usage: $0 start [port] | stop | status" >&2 + exit 2 + ;; +esac diff --git a/apps/pkg/proxy/proxy.go b/apps/pkg/proxy/proxy.go index f7f03ca..54cb931 100644 --- a/apps/pkg/proxy/proxy.go +++ b/apps/pkg/proxy/proxy.go @@ -224,17 +224,28 @@ func PushAndStart(c *adb.Client, localBin string, extraArgs ...string) error { return nil } -// FindLocalBin returns the first existing proxy binary under the repo. +// 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() } - for _, p := range []string{ + 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 } @@ -501,14 +512,9 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein } _, _ = c.Shell("chmod", "755", RemoteBin) - scriptLocal := filepath.Join(repo.Root(), "apps", "proxy", "device", "tproxy_iptables.sh") - if _, err := os.Stat(scriptLocal); err != nil { - return fmt.Errorf("missing %s", scriptLocal) + if err := ensureTProxyScript(c); err != nil { + return fmt.Errorf("tproxy script: %w", err) } - if err := c.Push(scriptLocal, RemoteTProxyScript); err != nil { - return err - } - _, _ = c.Shell("chmod", "755", RemoteTProxyScript) _, _ = c.Shell("mkdir", "-p", remoteDir) _, _ = c.Shell("rm", "-f", remoteDir+"/cap.json", remoteDir+"/traffic.jsonl", remoteDir+"/appproxy.log") diff --git a/apps/pkg/repo/root.go b/apps/pkg/repo/root.go index 6dae3ca..a03ac8a 100644 --- a/apps/pkg/repo/root.go +++ b/apps/pkg/repo/root.go @@ -3,20 +3,54 @@ package repo import ( "os" "path/filepath" + "strings" ) -// Root finds the repository root (directory that contains apps/pkg/go.mod -// and is not itself under apps/ — i.e. the real checkout root). +// Root finds the install / repository root (directory that contains +// apps/pkg/go.mod plus a sibling marker such as README.md or outputs/). +// +// Search order: +// 1. Walk up from the current working directory +// 2. Walk up from drm.exe (if the exe lives in bin/, start at the parent) func Root() string { + if root := findRoot(wd()); root != "" { + return root + } + if root := findRoot(exeInstallDir()); root != "" { + return root + } + return wd() +} + +func wd() string { wd, err := os.Getwd() if err != nil { - wd = "." + return "." } - cur := wd + return wd +} + +func exeInstallDir() string { + exe, err := os.Executable() + if err != nil { + return "" + } + if resolved, err := filepath.EvalSymlinks(exe); err == nil { + exe = resolved + } + dir := filepath.Dir(exe) + if strings.EqualFold(filepath.Base(dir), "bin") { + return filepath.Dir(dir) + } + return dir +} + +func findRoot(start string) string { + if start == "" { + return "" + } + cur := start for i := 0; i < 16; i++ { - // Require apps/pkg/go.mod AND a sibling marker so that walking from - // inside apps/pkg does not treat apps/ as the root (apps/pkg/go.mod - // would match the old top-level pkg/ layout check). pkgMod := filepath.Join(cur, "apps", "pkg", "go.mod") if _, err := os.Stat(pkgMod); err == nil { if markerOK(cur) { @@ -29,7 +63,7 @@ func Root() string { } cur = parent } - return wd + return "" } func markerOK(root string) bool { diff --git a/apps/proxy/proxyctlcmd/proxyctlcmd.go b/apps/proxy/proxyctlcmd/proxyctlcmd.go index 64eb0d4..a2006ca 100644 --- a/apps/proxy/proxyctlcmd/proxyctlcmd.go +++ b/apps/proxy/proxyctlcmd/proxyctlcmd.go @@ -106,6 +106,13 @@ func buildCmd(args []string) { outLocal := filepath.Join(root, "apps", "proxy", "proxy-android-arm64") outBin := filepath.Join(root, "bin", "proxy-android-arm64") + if _, err := os.Stat(deviceDir); err != nil { + fmt.Fprintf(os.Stderr, "proxy build needs the full source tree (apps/proxy/device).\n") + fmt.Fprintf(os.Stderr, "For a release zip, put proxy-android-arm64 next to drm.exe instead — no Go build required.\n") + fmt.Fprintf(os.Stderr, "Missing: %s\n", deviceDir) + os.Exit(1) + } + fmt.Println("[*] Building linux/arm64 appproxy...") cmd := exec.Command("go", "build", "-ldflags=-s -w", "-o", outLocal, ".") cmd.Dir = deviceDir diff --git a/docs/release.md b/docs/release.md index 62cafba..bbf46c1 100644 --- a/docs/release.md +++ b/docs/release.md @@ -33,9 +33,27 @@ Releases **do not** ship a MITM private key. On each machine, the first (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 -do this for the current OS) and keep `proxy-android-arm64` next to it under -`bin/`. +**Single-exe bootstrap:** drop `drm-windows-amd64.exe` anywhere and run it. On +first command it creates scaffold folders next to itself (`apps/pkg`, `bin/`, +`outputs/`, …) and extracts `proxy-android-arm64`. It does **not** ship +`apps/modules/*/module.yaml` — those stay out of the exe. + +```text +./ + drm.exe + README.md + apps/pkg/go.mod + apps/proxy/device/tproxy_iptables.sh + apps/modules//module.yaml ← YOU add these (copy from GitHub / write your own) + bin/drm.exe + bin/proxy-android-arm64 + configs/ + outputs/ + data/ ← after first install-ca (private CA) +``` + +Existing files are never overwritten. `drm proxy build` is for full source +checkouts only. ## Forgejo (git.nulldrm.com) diff --git a/scripts/build-release.ps1 b/scripts/build-release.ps1 index 723e3d5..5ad8a7c 100644 --- a/scripts/build-release.ps1 +++ b/scripts/build-release.ps1 @@ -58,15 +58,7 @@ function Build-Host([string]$Goos, [string]$Goarch, [string]$Ext = "") { } } -Write-Host "==> building host drm ($Version) into $Out" -Build-Host windows amd64 ".exe" -Build-Host windows arm64 ".exe" -Build-Host linux amd64 -Build-Host linux arm64 -Build-Host darwin amd64 -Build-Host darwin arm64 - -Write-Host "==> building on-device MITM (linux/arm64)" +Write-Host "==> building on-device MITM (linux/arm64) first (embedded into drm.exe)" $env:GOOS = "linux" $env:GOARCH = "arm64" $env:CGO_ENABLED = "0" @@ -81,10 +73,31 @@ try { Remove-Item Env:CGO_ENABLED -ErrorAction SilentlyContinue } +# Stage into bootstrap embed so a lone drm.exe can extract bin/proxy-android-arm64. +$embedProxy = Join-Path $Root "apps\pkg\bootstrap\embedded\bin\proxy-android-arm64" +New-Item -ItemType Directory -Force -Path (Split-Path $embedProxy) | Out-Null +Copy-Item (Join-Path $Out "proxy-android-arm64") $embedProxy -Force +Write-Host " staged embed: $embedProxy" + +Write-Host "==> building host drm ($Version) into $Out" +Build-Host windows amd64 ".exe" +Build-Host windows arm64 ".exe" +Build-Host linux amd64 +Build-Host linux arm64 +Build-Host darwin amd64 +Build-Host darwin arm64 + New-Item -ItemType Directory -Force -Path (Join-Path $Root "bin"), (Join-Path $Root "apps\proxy") | Out-Null Copy-Item (Join-Path $Out "proxy-android-arm64") (Join-Path $Root "bin\proxy-android-arm64") -Force Copy-Item (Join-Path $Out "proxy-android-arm64") (Join-Path $Root "apps\proxy\proxy-android-arm64") -Force -Copy-Item (Join-Path $Out "drm-windows-amd64.exe") (Join-Path $Root "bin\drm.exe") -Force +try { + Copy-Item (Join-Path $Out "drm-windows-amd64.exe") (Join-Path $Root "bin\drm.exe") -Force +} catch { + Write-Host "WARN: could not refresh bin\drm.exe (file in use): $($_.Exception.Message)" +} +# Restore tiny embed stub so the 9MB MITM binary is not left in the source tree. +$stub = Join-Path $Root "apps\pkg\bootstrap\embedded\bin\proxy-android-arm64" +[System.IO.File]::WriteAllBytes($stub, [byte[]](0x7F, 0x45, 0x4C, 0x46)) Write-Host "==> checksums" $sumsPath = Join-Path $Out "SHA256SUMS.txt" @@ -96,5 +109,47 @@ $lines = Get-ChildItem $Out -File | [System.IO.File]::WriteAllLines($tmpSums, @($lines)) Move-Item -Force $tmpSums $sumsPath +# Portable Windows folder: binaries + minimal config (no Go / no full source). +$win = Join-Path $Out "windows-amd64" +New-Item -ItemType Directory -Force -Path @( + $win, + (Join-Path $win "bin"), + (Join-Path $win "apps\pkg"), + (Join-Path $win "apps\proxy\device"), + (Join-Path $win "outputs") +) | Out-Null +Copy-Item (Join-Path $Out "drm-windows-amd64.exe") (Join-Path $win "bin\drm.exe") -Force +Copy-Item (Join-Path $Out "proxy-android-arm64") (Join-Path $win "bin\proxy-android-arm64") -Force +# Also beside bin\ for users who cd into bin +Copy-Item (Join-Path $Out "drm-windows-amd64.exe") (Join-Path $win "drm.exe") -Force +Copy-Item (Join-Path $Out "proxy-android-arm64") (Join-Path $win "proxy-android-arm64") -Force +Copy-Item (Join-Path $Root "apps\proxy\device\tproxy_iptables.sh") (Join-Path $win "apps\proxy\device\") -Force +Copy-Item (Join-Path $Root "apps\pkg\go.mod") (Join-Path $win "apps\pkg\") -Force +Copy-Item (Join-Path $Root "README.md") (Join-Path $win "README.md") -Force -ErrorAction SilentlyContinue +# Module YAMLs are NOT shipped in the exe and not required in this zip — +# operators add apps/modules//module.yaml from the GitHub tree. +@" +Null DRM — Windows portable + +Scaffold (drm.exe also creates this on first run if you only download the exe): + bin\drm.exe + bin\proxy-android-arm64 + apps\proxy\device\tproxy_iptables.sh + +Modules are NOT inside the exe. Add your own: + apps\modules\bbc\module.yaml + (copy from the GitHub repo apps/modules/bbc/module.yaml) + +You do NOT need ``drm proxy build``. + + bin\drm.exe proxy install-ca --reinject + adb shell am force-stop bbc.iplayer.android + bin\drm.exe capture --app bbc --channel bbcone --wait 120 + +NordVPN UK on the phone. First install-ca creates data\proxy-ca.* (private CA). +"@ | Set-Content -Encoding utf8 (Join-Path $win "README.txt") + Write-Host "==> done ($Version)" Get-ChildItem $Out | Format-Table Name, Length +Write-Host "==> portable Windows folder: $win" +Get-ChildItem $win | Format-Table Name, Length