v0.1.1: external modules, publish YAML, proxy reset, binary-first README
All checks were successful
release / build-and-upload (push) Successful in 6m8s
modules-release / build-and-upload (push) Successful in 4m47s

- 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
This commit is contained in:
404errordeveloper 2026-10-08 23:16:14 +02:00
parent 1d36961a7c
commit f9c28be3f1
52 changed files with 2915 additions and 636 deletions

View file

@ -132,6 +132,12 @@ func sameFile(a, b string) bool {
// EnsureAndLog runs Ensure and prints what was created (if anything).
func EnsureAndLog() error {
return EnsureAndLogFor("")
}
// EnsureAndLogFor is EnsureAndLog with an optional subcommand hint so proxy-only
// runs do not warn about missing modules/.
func EnsureAndLogFor(cmd string) error {
root, err := InstallRoot()
if err != nil {
return err
@ -150,10 +156,13 @@ func EnsureAndLog() error {
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")
// Providers live under modules/; only warn when the command needs them.
needsModules := cmd == "" || cmd == "modules" || cmd == "capture" || cmd == "catalog" || cmd == "agent" || cmd == "serve"
if needsModules {
modBBC := filepath.Join(root, "modules", "bbc", "module.yaml")
if _, err := os.Stat(modBBC); err != nil {
fmt.Fprintf(os.Stderr, "[!] no modules/*/ yet — add e.g. modules/bbc/ (Go source + module.yaml); see modules/README.md\n")
}
}
return nil
}

View file

@ -1,154 +1,22 @@
# DRM-Decryption
# Null DRM
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
---
Host binary **`drm`** + providers under **`modules/`**.
## 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:
1. Download `drm` (`v*` release) and module zips (`modules-v*` release).
2. Unzip providers into `modules/<name>/` and edit `module.yaml` (secrets only).
3. `drm proxy install-ca --reinject`
4. `drm capture --app bbc --channel bbcone --wait 120`
5. `drm proxy reset` when finished.
```text
apps/modules/tg4/module.yaml
apps/modules/rte/module.yaml
drm modules
drm capture --app NAME [--channel ID] [--wvd PATH]
drm catalog --app NAME --channel ID [--keys] [--json]
drm proxy install-ca --reinject | reset | transparent --package PKG
```
Where each value comes from:
`--modules-dir DIR` or `$DRM_MODULES_DIR` selects another modules folder.
- **[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/<app>/<timestamp>/`, 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/<app>/<stamp>/` |
| `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.
Full docs: https://git.nulldrm.com/nulldrm/Null-DRM-Official

View file

@ -0,0 +1,20 @@
# External modules
Each subdirectory is a provider the `drm` host discovers, builds, and runs.
```
modules/
bbc/
module.yaml # your values (required for channels)
go.mod + *.go # provider CLI (or ship prebuilt under .bin/)
.bin/bbc.exe # built on demand
```
The host binary does **not** embed providers. Add a folder here, then:
```
drm modules
drm capture --app bbc --channel bbcone
```
Requires Go on PATH to build from source. Release zips may ship `.bin/` prebuilt.

View file

@ -1,10 +1,12 @@
// Package modcfg loads an app module's values from its local, untracked
// apps/modules/<name>/module.yaml, with environment-variable overrides.
// Package modcfg loads an app module's values from modules/<name>/,
// with environment-variable overrides.
//
// Compiled-in module code is tracked in git and must contain no account ids,
// policy keys, video ids, license URLs or origin hostnames. Those live here, in
// a file git ignores, and can also be supplied by flag or environment so a run
// needs no file at all.
// Load order:
// 1. module-publish.yaml (tracked universal template) if present
// 2. module.yaml (local / release copy; may add secrets) overlays on top
//
// Local module.yaml is gitignored and never published. Release zips ship
// module-publish.yaml renamed to module.yaml.
package modcfg
import (
@ -13,42 +15,75 @@ import (
"path/filepath"
"strings"
"drmdecryption/modhost"
"drmdecryption/repo"
"gopkg.in/yaml.v3"
)
// Dir returns the directory holding a module's local values.
// Dir returns the directory holding a module's values.
// Prefers the active modules dir (see modhost / --modules-dir); falls back to
// apps/modules/<name>/ for older checkouts.
func Dir(name string) string {
return filepath.Join(repo.Root(), "apps", "modules", name)
preferred := filepath.Join(modhost.ModulesDir(""), name)
if st, err := os.Stat(preferred); err == nil && st.IsDir() {
return preferred
}
if modhost.ModulesDirOverride() != "" {
return preferred
}
root := repo.Root()
if _, err := os.Stat(filepath.Join(root, "modules")); err == nil {
return filepath.Join(root, "modules", name)
}
return filepath.Join(root, "apps", "modules", name)
}
// Path returns the module's values file path.
// Path returns the preferred values file path (module.yaml).
func Path(name string) string {
return filepath.Join(Dir(name), "module.yaml")
}
// PublishPath is the tracked universal template.
func PublishPath(name string) string {
return filepath.Join(Dir(name), "module-publish.yaml")
}
// Result reports where a module's values came from, for `drm modules`.
type Result struct {
Path string
Loaded bool
}
// Load reads apps/modules/<name>/module.yaml into dst. A missing file is not an
// error — the module runs on its Go defaults plus flags/env.
// Load reads module-publish.yaml then overlays module.yaml into dst.
// Missing files are not an error — the module runs on Go defaults plus flags/env.
func Load(name string, dst any) (Result, error) {
path := Path(name)
res := Result{Path: path}
b, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
return res, nil
dir := Dir(name)
publish := filepath.Join(dir, "module-publish.yaml")
local := filepath.Join(dir, "module.yaml")
res := Result{Path: local}
loadedAny := false
if b, err := os.ReadFile(publish); err == nil {
if err := yaml.Unmarshal(b, dst); err != nil {
return res, fmt.Errorf("%s: %w", publish, err)
}
loadedAny = true
res.Path = publish
} else if !os.IsNotExist(err) {
return res, err
}
if err := yaml.Unmarshal(b, dst); err != nil {
return res, fmt.Errorf("%s: %w", path, err)
if b, err := os.ReadFile(local); err == nil {
if err := yaml.Unmarshal(b, dst); err != nil {
return res, fmt.Errorf("%s: %w", local, err)
}
loadedAny = true
res.Path = local
} else if !os.IsNotExist(err) {
return res, err
}
res.Loaded = true
res.Loaded = loadedAny
return res, nil
}
@ -70,7 +105,6 @@ func Env(module, field string) string {
}
// Override picks the first non-empty of: flag value, environment, current value.
// Use it in a module's config resolution so precedence is uniform.
func Override(module, field, flagVal, current string) string {
if strings.TrimSpace(flagVal) != "" {
return flagVal

107
apps/pkg/modhost/build.go Normal file
View file

@ -0,0 +1,107 @@
package modhost
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
)
// EnsureBuilt returns the path to the module binary, building from Go source
// when needed. Prebuilt .bin/ is used as-is when source is absent.
func EnsureBuilt(m Module) (string, error) {
bin := m.BinPath()
hasSrc := hasGoSource(m.Dir)
binOK := fileExists(bin)
if !hasSrc && !binOK {
return "", fmt.Errorf("module %s: no Go source in %s and no binary at %s", m.Name, m.Dir, bin)
}
if binOK && (!hasSrc || !sourceNewerThan(m.Dir, bin)) {
return bin, nil
}
goBin, err := findGo()
if err != nil {
if binOK {
fmt.Fprintf(os.Stderr, "[!] go not found; using existing %s\n", bin)
return bin, nil
}
return "", fmt.Errorf("module %s needs building but go is not on PATH: %w", m.Name, err)
}
if err := os.MkdirAll(filepath.Dir(bin), 0o755); err != nil {
return "", err
}
fmt.Printf("[*] Building module %s → %s\n", m.Name, bin)
cmd := exec.Command(goBin, "build", "-trimpath", "-ldflags=-s -w", "-o", bin, ".")
cmd.Dir = m.Dir
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return "", fmt.Errorf("go build module %s: %w", m.Name, err)
}
return bin, nil
}
func hasGoSource(dir string) bool {
if fileExists(filepath.Join(dir, "go.mod")) {
return true
}
ents, err := os.ReadDir(dir)
if err != nil {
return false
}
for _, e := range ents {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".go") {
return true
}
}
return false
}
func sourceNewerThan(dir, bin string) bool {
bst, err := os.Stat(bin)
if err != nil {
return true
}
binTime := bst.ModTime()
newer := false
_ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil || info.IsDir() {
if info != nil && info.IsDir() && (info.Name() == ".bin" || info.Name() == "vendor") {
return filepath.SkipDir
}
return nil
}
name := info.Name()
if strings.HasSuffix(name, ".go") || name == "go.mod" || name == "go.sum" {
if info.ModTime().After(binTime) {
newer = true
}
}
return nil
})
return newer
}
func findGo() (string, error) {
if p, err := exec.LookPath("go"); err == nil {
return p, nil
}
home, _ := os.UserHomeDir()
candidates := []string{
filepath.Join(home, "go-sdk", "go", "bin", "go"),
filepath.Join(home, "go-sdk", "go", "bin", "go.exe"),
filepath.Join(home, "sdk", "go", "bin", "go"),
`C:\Program Files\Go\bin\go.exe`,
"/usr/local/go/bin/go",
}
for _, c := range candidates {
if st, err := os.Stat(c); err == nil && !st.IsDir() {
return c, nil
}
}
return "", fmt.Errorf("go binary not found (install Go or add it to PATH)")
}

View file

@ -0,0 +1,140 @@
package modhost
import (
"os"
"path/filepath"
"runtime"
"strings"
)
// Module is one on-disk provider under modules/<name>/.
type Module struct {
Name string // directory base name, e.g. "bbc"
Dir string // absolute path to modules/<name>
}
// ModulesDir returns the modules directory (honours --modules-dir / DRM_MODULES_DIR).
func ModulesDir(root string) string {
return EffectiveModulesDir(root)
}
// Discover lists modules/<name>/ directories that look like providers
// (have module.yaml / module-publish.yaml and/or Go source and/or a prebuilt binary).
func Discover(root string) ([]Module, error) {
dir := ModulesDir(root)
ents, err := os.ReadDir(dir)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
var out []Module
for _, e := range ents {
if !e.IsDir() {
continue
}
name := e.Name()
if strings.HasPrefix(name, ".") {
continue
}
modDir := filepath.Join(dir, name)
if !looksLikeModule(modDir, name) {
continue
}
out = append(out, Module{Name: name, Dir: modDir})
}
return out, nil
}
func looksLikeModule(dir, name string) bool {
if fileExists(filepath.Join(dir, "module.yaml")) {
return true
}
if fileExists(filepath.Join(dir, "module-publish.yaml")) {
return true
}
if fileExists(filepath.Join(dir, "go.mod")) {
return true
}
if fileExists(BinPath(dir, name)) {
return true
}
// Any .go file in the root of the module dir.
ents, err := os.ReadDir(dir)
if err != nil {
return false
}
for _, e := range ents {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".go") {
return true
}
}
return false
}
// Find returns the module named name, or an error listing what exists.
func Find(root, name string) (Module, error) {
mods, err := Discover(root)
if err != nil {
return Module{}, err
}
for _, m := range mods {
if m.Name == name {
return m, nil
}
}
names := make([]string, 0, len(mods))
for _, m := range mods {
names = append(names, m.Name)
}
if len(names) == 0 {
return Module{}, errNoModules(root)
}
return Module{}, &NotFoundError{Name: name, Available: names}
}
// BinPath is modules/<name>/.bin/<name>[.exe].
func BinPath(modDir, name string) string {
bin := filepath.Join(modDir, ".bin", name)
if runtime.GOOS == "windows" {
bin += ".exe"
}
return bin
}
func (m Module) BinPath() string {
return BinPath(m.Dir, m.Name)
}
func fileExists(p string) bool {
st, err := os.Stat(p)
return err == nil && !st.IsDir()
}
func errNoModules(root string) error {
return &NotFoundError{
Name: "",
Available: nil,
Hint: "create modules/<name>/ with Go source + module.yaml (see docs/modules.md)",
Root: ModulesDir(root),
}
}
// NotFoundError is returned when --app does not match a modules/ directory.
type NotFoundError struct {
Name string
Available []string
Hint string
Root string
}
func (e *NotFoundError) Error() string {
if e.Name == "" {
return "no modules found under " + e.Root + " — " + e.Hint
}
if len(e.Available) == 0 {
return "unknown module " + e.Name + " (modules dir empty) — " + e.Hint
}
return "unknown module " + e.Name + " — available: " + strings.Join(e.Available, ", ")
}

78
apps/pkg/modhost/exec.go Normal file
View file

@ -0,0 +1,78 @@
package modhost
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"strings"
)
// Run executes the module binary with args, inheriting stdout/stderr.
func Run(bin string, args ...string) error {
cmd := exec.Command(bin, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
return fmt.Errorf("%s %s: %w", bin, strings.Join(args, " "), err)
}
return nil
}
// RunOutput executes the module binary and returns combined stdout.
func RunOutput(bin string, args ...string) (string, error) {
cmd := exec.Command(bin, args...)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return stdout.String(), fmt.Errorf("%s %s: %w\n%s", bin, strings.Join(args, " "), err, stderr.String())
}
return stdout.String(), nil
}
// RunDescribe runs `bin describe` and parses JSON.
func RunDescribe(bin string) (Describe, error) {
out, err := RunOutput(bin, "describe")
if err != nil {
return Describe{}, err
}
// Allow log lines before JSON: find first '{'.
out = strings.TrimSpace(out)
if i := strings.IndexByte(out, '{'); i > 0 {
out = out[i:]
}
var d Describe
if err := json.Unmarshal([]byte(out), &d); err != nil {
return Describe{}, fmt.Errorf("describe JSON: %w\noutput: %s", err, out)
}
if d.Protocol != 0 && d.Protocol != ProtocolVersion {
return d, fmt.Errorf("module protocol %d unsupported (host wants %d)", d.Protocol, ProtocolVersion)
}
if d.Protocol == 0 {
d.Protocol = ProtocolVersion
}
return d, nil
}
// Load builds (if needed) and describes a module by name.
func Load(root, name string) (Module, string, Describe, error) {
m, err := Find(root, name)
if err != nil {
return Module{}, "", Describe{}, err
}
bin, err := EnsureBuilt(m)
if err != nil {
return m, "", Describe{}, err
}
d, err := RunDescribe(bin)
if err != nil {
return m, bin, Describe{}, err
}
if d.Name == "" {
d.Name = m.Name
}
return m, bin, d, nil
}

View file

@ -0,0 +1,33 @@
// Package modhost discovers, builds, and runs external provider modules that
// live under modules/<name>/ (Go source + module.yaml), outside drm.exe.
package modhost
import "drmdecryption/capture"
// ProtocolVersion is bumped when describe/launch/autoplay CLI contract changes.
const ProtocolVersion = 1
// Channel is one live target advertised by a module.
type Channel struct {
ID string `json:"id"`
Label string `json:"label"`
}
// Describe is the JSON printed by `module-bin describe`.
type Describe struct {
Protocol int `json:"protocol"`
Name string `json:"name"`
Package string `json:"package"`
LicenseURL string `json:"license_url,omitempty"`
KeyMode string `json:"key_mode"`
ProxyBin string `json:"proxy_bin,omitempty"`
CAHash string `json:"ca_hash,omitempty"`
TransparentMITM bool `json:"transparent_mitm"`
Rewriter string `json:"rewriter,omitempty"`
Channels []Channel `json:"channels"`
Require []string `json:"require,omitempty"`
Score capture.ScoreCfg `json:"score,omitempty"`
HasCatalog bool `json:"has_catalog"`
ValuesPath string `json:"values_path,omitempty"`
ValuesLoaded bool `json:"values_loaded"`
}

View file

@ -0,0 +1,224 @@
package modhost
import (
"encoding/json"
"fmt"
"path/filepath"
"strings"
"drmdecryption/adb"
"drmdecryption/app"
"drmdecryption/capture"
"drmdecryption/mpd"
"drmdecryption/session"
)
// RemoteApp implements app.App by calling an external module binary.
type RemoteApp struct {
Mod Module
Bin string
Desc Describe
}
// Open builds and describes modules/<name>, returning a RemoteApp.
func Open(root, name string) (*RemoteApp, error) {
m, bin, d, err := Load(root, name)
if err != nil {
return nil, err
}
return &RemoteApp{Mod: m, Bin: bin, Desc: d}, nil
}
func (r *RemoteApp) Name() string { return r.Desc.Name }
func (r *RemoteApp) Package() string { return r.Desc.Package }
func (r *RemoteApp) LicenseURL() string { return r.Desc.LicenseURL }
func (r *RemoteApp) ProxyBin() string { return r.Desc.ProxyBin }
func (r *RemoteApp) CAHash() string { return r.Desc.CAHash }
func (r *RemoteApp) KeyMode() string {
if r.Desc.KeyMode == "" {
return "none"
}
return r.Desc.KeyMode
}
func (r *RemoteApp) Channels() []app.Channel {
out := make([]app.Channel, 0, len(r.Desc.Channels))
for _, ch := range r.Desc.Channels {
out = append(out, app.Channel{ID: ch.ID, Label: ch.Label})
}
return out
}
func (r *RemoteApp) HasChannel(id string) bool {
for _, ch := range r.Desc.Channels {
if ch.ID == id {
return true
}
}
return false
}
func (r *RemoteApp) CaptureHints() capture.Hints {
req := r.Desc.Require
if len(req) == 0 {
req = []string{"mpd"}
}
h := capture.DefaultHints()
h.Require = req
h.Score = capture.DefaultScoreCfg().Merge(r.Desc.Score)
return h
}
func (r *RemoteApp) MPDRewriter() mpd.Rewriter {
name := r.Desc.Rewriter
if name == "" || name == "none" {
return mpd.Passthrough{}
}
if rw, ok := mpd.Lookup(name); ok {
return rw
}
return mpd.Passthrough{}
}
func (r *RemoteApp) UseTransparentMITM() bool { return r.Desc.TransparentMITM }
func (r *RemoteApp) RewriterName() string {
if r.Desc.Rewriter == "" {
return "none"
}
return r.Desc.Rewriter
}
func (r *RemoteApp) Launch(c *adb.Client) error {
args := []string{"launch"}
if c != nil && c.Serial != "" {
args = append(args, "--serial", c.Serial)
}
return Run(r.Bin, args...)
}
func (r *RemoteApp) AutoPlay(c *adb.Client, channel string) error {
args := []string{"autoplay", "--channel", channel}
if c != nil && c.Serial != "" {
args = append(args, "--serial", c.Serial)
}
return Run(r.Bin, args...)
}
// ValuesPath is where module.yaml should live for this module.
func (r *RemoteApp) ValuesPath() string {
if r.Desc.ValuesPath != "" {
return r.Desc.ValuesPath
}
return filepath.Join(r.Mod.Dir, "module.yaml")
}
// Ensure RemoteApp satisfies the interfaces capture / catalog use.
var (
_ app.App = (*RemoteApp)(nil)
_ app.TransparentMITM = (*RemoteApp)(nil)
_ app.StreamDefaults = (*RemoteApp)(nil)
_ app.Catalog = (*RemoteApp)(nil)
)
func (r *RemoteApp) VideoSelect() string { return "" }
func (r *RemoteApp) AudioSelect() string { return "" }
func (r *RemoteApp) LiveWaitSeconds() int { return 0 }
func (r *RemoteApp) TSReadyBytes() int64 { return 0 }
// Resolve runs `module catalog --channel ID --json`.
func (r *RemoteApp) Resolve(channel string) (session.Stream, error) {
if !r.Desc.HasCatalog {
return session.Stream{}, fmt.Errorf("module %s has no catalog", r.Desc.Name)
}
out, err := RunOutput(r.Bin, "catalog", "--channel", channel, "--json")
if err != nil {
return session.Stream{}, err
}
out = strings.TrimSpace(out)
if i := strings.IndexByte(out, '{'); i > 0 {
out = out[i:]
}
var info session.Stream
if err := json.Unmarshal([]byte(out), &info); err != nil {
return session.Stream{}, fmt.Errorf("catalog JSON: %w\noutput: %s", err, out)
}
return info, nil
}
// EnrichWithKeys is not yet implemented for external modules.
func (r *RemoteApp) EnrichWithKeys(info *session.Stream, python, wvd string) error {
return fmt.Errorf("module %s: --keys via external module is not supported yet", r.Desc.Name)
}
// Listed is one discovered module with its describe payload.
type Listed struct {
Mod Module
Bin string
Desc Describe
}
// ListAll discovers, builds, and describes every modules/<name>/.
func ListAll(root string) ([]Listed, error) {
mods, err := Discover(root)
if err != nil {
return nil, err
}
out := make([]Listed, 0, len(mods))
for _, m := range mods {
bin, err := EnsureBuilt(m)
if err != nil {
return out, fmt.Errorf("module %s: %w", m.Name, err)
}
d, err := RunDescribe(bin)
if err != nil {
return out, fmt.Errorf("module %s describe: %w", m.Name, err)
}
if d.Name == "" {
d.Name = m.Name
}
out = append(out, Listed{Mod: m, Bin: bin, Desc: d})
}
return out, nil
}
// Names lists discovered module directory names (no build).
func Names(root string) ([]string, error) {
mods, err := Discover(root)
if err != nil {
return nil, err
}
names := make([]string, 0, len(mods))
for _, m := range mods {
names = append(names, m.Name)
}
return names, nil
}
// FindChannelInModules scans described modules for a channel id.
func FindChannelInModules(root, channelID string) (appName string, ok bool) {
listed, err := ListAll(root)
if err != nil {
return "", false
}
for _, L := range listed {
for _, ch := range L.Desc.Channels {
if ch.ID == channelID {
return L.Mod.Name, true
}
}
}
return "", false
}
// FormatUnknown helps capturecmd error messages when --app is unknown.
func FormatUnknown(root, name string) error {
_, err := Find(root, name)
if err != nil {
if owner, ok := FindChannelInModules(root, name); ok {
return fmt.Errorf("%q is a channel of --app %s, not an app name — use: capture --app %s --channel %s", name, owner, owner, name)
}
return err
}
return fmt.Errorf("unknown module %q", name)
}

62
apps/pkg/modhost/root.go Normal file
View file

@ -0,0 +1,62 @@
package modhost
import (
"os"
"path/filepath"
"sync"
"drmdecryption/repo"
)
var (
rootMu sync.RWMutex
modulesDirOV string // absolute path override for the modules directory
)
// SetModulesDir overrides where providers are discovered (drm --modules-dir).
// Empty clears the override. Relative paths are resolved against the process cwd.
func SetModulesDir(dir string) error {
rootMu.Lock()
defer rootMu.Unlock()
if dir == "" {
modulesDirOV = ""
return nil
}
abs, err := filepath.Abs(dir)
if err != nil {
return err
}
modulesDirOV = abs
return nil
}
// ModulesDirOverride returns the --modules-dir override, or "".
func ModulesDirOverride() string {
rootMu.RLock()
defer rootMu.RUnlock()
return modulesDirOV
}
// EffectiveModulesDir is the directory that Discover/Open scan.
// Prefer --modules-dir / DRM_MODULES_DIR; else <root>/modules.
func EffectiveModulesDir(root string) string {
if ov := ModulesDirOverride(); ov != "" {
return ov
}
if root == "" {
root = repo.Root()
}
return filepath.Join(root, "modules")
}
// ApplyEnvModulesDir sets the override from DRM_MODULES_DIR when no flag was set.
func ApplyEnvModulesDir() error {
if ModulesDirOverride() != "" {
return nil
}
v := os.Getenv("DRM_MODULES_DIR")
if v == "" {
return nil
}
return SetModulesDir(v)
}

View file

@ -500,7 +500,7 @@ func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, rein
return fmt.Errorf("CA hash: %w", err)
}
if reinject {
ReinjectCA(c, caHash)
ReinjectCAForPackage(c, caHash, pkg)
}
if st, err := os.Stat(localBin); err != nil || st.IsDir() {
@ -597,6 +597,67 @@ func StopTransparent(c *adb.Client) {
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) != "" {
@ -692,80 +753,154 @@ func DiscoverOutDir(root, stamp string) string {
return filepath.Join(root, "outputs", "discover", stamp)
}
// ReinjectCA best-effort Magisk bind of the mitm CA into conscrypt.
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
}
// Bound the per-app nsenter loop — wait on hundreds of PIDs can hang forever.
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
[ -f /data/local/tmp/$HASH.0 ] || { echo CA_SKIP; exit 0; }
[ -x "$BB" ] || { echo CA_SKIP; exit 0; }
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
cp /apex/com.android.conscrypt/cacerts/* /data/local/tmp/cacerts-overlay/ 2>/dev/null || true
# 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/*
$BB mount -t tmpfs tmpfs /system/etc/security/cacerts 2>/dev/null || true
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 644 /system/etc/security/cacerts/* 2>/dev/null || true
chcon u:object_r:system_file:s0 /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
# Only rebind the target app if set; otherwise skip the full zygote-child sweep (hangs).
PKG_UID_FILE=/data/local/tmp/reinject_target_uid
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
ls /apex/com.android.conscrypt/cacerts/$HASH.0 2>/dev/null && echo CA_OK || echo CA_SKIP
`, caHash)
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, "/data/local/tmp/reinject_ca.sh")
_, _ = c.Shell("chmod", "755", "/data/local/tmp/reinject_ca.sh")
// Host-side timeout: su -mm + nsenter has hung on some Magisk builds.
type runResult struct {
out string
}
ch := make(chan runResult, 1)
_ = 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() {
out, _, _ := c.Run("shell", "su", "-mm", "-c", "sh /data/local/tmp/reinject_ca.sh")
ch <- runResult{out: out}
_, _, _ = c.Run("shell", "su", "-mm", "-c", "sh "+remoteReinjectScript)
}()
var out string
select {
case r := <-ch:
out = r.out
case <-time.After(20 * time.Second):
_, _ = 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")
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
}
return
time.Sleep(400 * time.Millisecond)
}
if strings.Contains(out, "CA_OK") || caPresentOnDevice(c, caHash) {
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")
} else {
fmt.Println("[!] CA inject skipped/failed — re-run: drm proxy install-ca --reinject")
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
}
out := c.Out("shell", "su", "-c", "ls /apex/com.android.conscrypt/cacerts/"+caHash+".0")
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")
}