testsAndMisc/python_pkg/focus_policy/__main__.py
Krzysztof kuhy Rudnicki e3d5e1dd18 Serve the blocklist over DoT and hand the policy to the app as an asset
Two gaps stopped the unrooted path working end to end. The phone had no way to
read the focus policy, and the blocklist was only reachable as a hosts file or
over plain UDP/53 on the LAN -- while the rooted enforcer actively rejected
every DoT connection, so a self-hosted resolver could not have worked even if
one existed.

focus_owner now loads a generated policy.json instead of hardcoding anything,
so config.sh stays the single source of truth across Python, shell and Kotlin.
The committed asset is rendered with --redact-home and a test fails if home
coordinates ever appear in it. An unknown schema_version is rejected outright:
silently accepting a newer schema means enforcing a policy the app has misread,
and a misread allowlist is one that blocks the dialer.

dns_enforcer.sh rejected ALL port 853 traffic and pinned Private DNS off, every
20 seconds. That is right when DoT is a bypass channel and exactly wrong when
DoT is the enforcement channel, which is what an unrooted phone needs -- it has
no hosts file to fall back to. With DNS_TRUSTED_DOT_HOST set it now ACCEPTs the
trusted resolver before the blanket REJECT, and pins Private DNS to that
hostname so the user cannot pick an unfiltered one. Rule order is load-bearing:
iptables takes the first match, so an ACCEPT appended after the REJECT would
never be reached. expected_rule_count() counts the new rules, because a
mismatch there makes chain_intact() rebuild the chain every 20s -- a silent
fork storm that also drops the connection each time. With the variable empty
the behaviour is byte-identical, so the rooted phone is untouched until this is
deployed.

setup_dot_resolver.sh terminates DoT with stunnel rather than Caddy: DoT is a
raw TLS stream and stock caddy:2.8 has no layer4 module, so using Caddy would
have meant an xcaddy rebuild of a container serving five live sites. It reuses
the certificate Caddy already renews, so nothing competes for port 80. It binds
to the WireGuard address, not 0.0.0.0 -- a public DoT endpoint is an open
resolver, and over the existing tunnel it needs no port-forward, no firewall
rule and no rate limiting. Verified: example.com resolves, pornhub.com returns
0.0.0.0, TLS 1.3 against the LE cert, and both the LAN and public addresses
refuse.

The Device Owner checklist is planning only. Checking the device rather than
the config settled the one open risk: Google Wallet is not installed and no NFC
payment default is set, so the unconfirmable tap-to-pay question does not apply
here. The same check found that Aegis, MS Authenticator, Oracle IDM and PKO IKO
are absent -- they are in config.sh's whitelist, which describes the rooted
phone, not this one.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AwepyL5Lxs5QKbKkMpxxxL
2026-08-05 09:36:11 +02:00

81 lines
2.5 KiB
Python

r"""Render the focus policy as JSON for a non-Python enforcement backend.
The Device Owner app is Kotlin and cannot read ``config.sh`` or import this
package, so the policy is handed over as a generated asset:
python3 -m python_pkg.focus_policy \\
--config phone_focus_mode/config.sh \\
--output focus_owner/assets/policy.json
``--redact-home`` blanks the coordinates, for a policy that will be committed
or attached to a report.
"""
from __future__ import annotations
import argparse
from pathlib import Path
import sys
from python_pkg.focus_policy.export import policy_to_json
from python_pkg.focus_policy.loader import load_policy
from python_pkg.focus_policy.model import PolicyError
def build_parser() -> argparse.ArgumentParser:
"""Return the argument parser for the policy exporter."""
parser = argparse.ArgumentParser(
prog="python3 -m python_pkg.focus_policy",
description="Render phone_focus_mode's policy as backend-neutral JSON.",
)
parser.add_argument(
"--config",
type=Path,
required=True,
help="path to phone_focus_mode/config.sh",
)
parser.add_argument(
"--secrets",
type=Path,
default=None,
help="path to config_secrets.sh (defaults to alongside --config)",
)
parser.add_argument(
"--output",
type=Path,
default=None,
help="file to write (defaults to stdout)",
)
parser.add_argument(
"--redact-home",
action="store_true",
help="blank the home coordinates, keeping radius and hysteresis",
)
return parser
def main(argv: list[str] | None = None) -> int:
"""Render the policy, returning a process exit code."""
args = build_parser().parse_args(argv)
try:
policy = load_policy(args.config, args.secrets)
except (PolicyError, OSError) as error:
# Written to stderr rather than raised: the caller is a shell script or
# a build step, and a bare traceback buries the one line that says the
# coordinates were never filled in.
sys.stderr.write(f"error: {error}\n")
return 1
rendered = policy_to_json(policy, redact_home=args.redact_home) + "\n"
if args.output is None:
sys.stdout.write(rendered)
else:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(rendered, encoding="utf-8")
sys.stderr.write(f"wrote {args.output}\n")
return 0
if __name__ == "__main__":
raise SystemExit(main())