hosts_enforcer: split 421 -> 207 + 166 + 91, both libs at 100%
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Shell tests / shell-tests (push) Waiting to run
Shell tests / arch-tests (push) Waiting to run

The bind-mount logic goes to hosts_mount.sh, the Magisk-module and
cache-invalidation logic to hosts_magisk.sh. Both flat siblings, both in
both deploy lists; the two lists were then checked to correspond exactly
in both directions, since a push with no matching cp stages a file that
never lands and the enforcer would fail to source it.

Audited for stdin-draining `while read` loops BEFORE extracting, because
piping one would change behaviour in a way stubs cannot catch. There are
none here. Also confirmed no function writes a global, so there was no
cross-half hazard of the kind that kept NET_BUILT in curfew_enforcer.sh.

69 assertions, 43/43 and 62/62 lines, 17 mutations all killed. Two survived
the first run and both were real findings:

  - the unmount give-up threshold was not pinned. Raising it from 5 to 500
    changed nothing observable, so the enforcer could have spun 500 times
    per poll against a mount that was never going to clear. Now asserted as
    a call count.
  - the `[ ! -f $HOSTS_TARGET ] && return 1` guard in
    is_bind_mounted_correctly is PROVABLY EQUIVALENT: sha256_of returns
    empty for a missing file, so the existing -n check already rejects that
    case. No test can distinguish it. Equivalent code is a claim of a check
    that is not being made, so it is deleted rather than covered by a test
    that would pass either way. Old and new bodies were compared across all
    four input states -- both-missing, target-missing, match, mismatch --
    and agree on every one.

That deletion is the only non-verbatim function; the other 19 moved
untouched, making this the first fully verbatim extraction of the session.

Ordering is asserted where it is load-bearing: /system must go back to ro
after rw, and +i must be restored after being dropped. Presence assertions
alone would pass with either pair reversed.

UNVERIFIED ON DEVICE -- the highest-stakes of the four enforcer splits now
outstanding, since a failure to source leaves nothing blocking while the
phone looks normal. Over-cap count 20 -> 19.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011w2Pj4Ek3ZNMQVYcFHgXDY
This commit is contained in:
Krzysztof Rudnicki 2026-08-17 16:30:56 +02:00
parent 9f2e208257
commit 0a07684cca
12 changed files with 1131 additions and 218 deletions

View File

@ -0,0 +1,21 @@
{
"title": "Split hosts_enforcer.sh into mount and magisk halves, both tested to 100%",
"objective": "Take hosts_enforcer.sh from 421 lines to under the repo's 250-line cap by extracting its bind-mount logic and its Magisk/cache-invalidation logic into two flat siblings, and cover both at 100%. This is the code that decides whether the DNS blocklist is actually enforced; a probe that reports an OEM overlay as our blocklist means no blocking at all while the status reads green.",
"acceptance_criteria": [
"bash meta/scripts/check_file_length.sh --all no longer lists phone_focus_mode/hosts_enforcer.sh, and no new file is over the cap.",
"shell_coverage.sh reports 100.00% for BOTH hosts_mount.sh and hosts_magisk.sh from the single test entry point.",
"Every assertion is mutation-proofed with zero survivors. A mutation that proves equivalent must be resolved by removing the equivalent code, not by weakening the mutation.",
"Ordering is asserted where it is load-bearing: /system must be remounted ro after rw, and the immutable flag re-set after being dropped.",
"meta/scripts/verify_shell_split.sh reports every function verbatim, except any deliberately changed — for which behavioural equivalence must be demonstrated across every input state.",
"Both new siblings are added to BOTH of deploy.sh's hardcoded lists, and the two lists remain in exact correspondence with no orphan in either direction.",
"shellcheck passes on each touched file individually, with no -x and no disable directive; sh -n passes on all three phone-side scripts.",
"No eval is introduced in test code."
],
"out_of_scope": [
"Deploying to the phone or verifying on-device; there is no device in this session.",
"Splitting verify_and_restore or main out of the entry script, which is under the cap without the two extracted halves.",
"Adding the siblings to deploy.sh's chmod list: they are sourced, not executed, matching dns_iptables.sh, tether_iptables.sh and curfew_net.sh.",
"Changing which domains are blocked or how the canonical blocklist is generated."
],
"verifier": "bash phone_focus_mode/lib/tests/test_hosts_libs.sh (expects 69 passed, 0 failed), plus shell_coverage.sh at 100.00% for hosts_mount.sh and hosts_magisk.sh, plus the mutation run at 17 killed / 0 survived, plus check_file_length.sh --all showing 19 files, plus deploy-list parity showing no orphans, plus pre-commit run --files on the touched files."
}

View File

@ -0,0 +1,81 @@
{
"intent": "Bring hosts_enforcer.sh under the 250-line cap by extracting its bind-mount and Magisk/cache halves into two flat siblings, and cover both at 100% — neither had any test, and together they decide whether the DNS blocklist is actually in force.",
"scope": [
"phone_focus_mode/hosts_enforcer.sh - 421 lines down to 207",
"phone_focus_mode/hosts_mount.sh - new: is_bind_mounted_correctly, unmount_existing_hosts_mount, make_target_writable_once, assert_bind_mount",
"phone_focus_mode/hosts_magisk.sh - new: sync_magisk_module, protect_magisk_module, disable_firefox_doh, flush_browser_dns_caches, ensure_canonical_immutable, restart_netd_for_hosts_cache",
"phone_focus_mode/deploy.sh - both siblings added to both hardcoded lists",
"phone_focus_mode/lib/tests/ - a harness, four case files and one entry point, all new",
"Non-goal: any device deploy. The split is proven with stubs, hashes and behavioural comparison instead."
],
"changes": [
"Audited for stdin-draining loops BEFORE extracting, because piping such a loop would silently change behaviour in a way the stubs cannot catch. hosts_enforcer.sh contains no `while read` loop at all, so that risk did not apply here. Also checked that no function writes a global, so there was no cross-half read/write hazard of the kind that kept NET_BUILT in the curfew entry script.",
"Placed both libraries as flat siblings, matching dns_iptables.sh, tether_iptables.sh and curfew_net.sh: deploy.sh pushes phone scripts into one directory, so a lib/ path would not exist on the device.",
"Added both to deploy.sh's push list and cp list, then verified the two lists correspond exactly with no orphan in either direction — a push without a matching cp stages a file that never lands, and the enforcer would then fail to source it.",
"Removed a provably equivalent guard from is_bind_mounted_correctly. Its early `[ ! -f $HOSTS_TARGET ] && return 1` is unreachable as a decision: sha256_of returns empty for a missing file, so the existing -n check already rejects that case. A mutation removing it survived because no test could distinguish it. Equivalent code is a claim of a check that is not being made, so it was deleted rather than papered over with a test that would pass either way.",
"Stubbed cp, chattr, mount, umount, am, pgrep, stop, start and sleep on PATH — the process boundary, since these libraries invoke real binaries. Two hardcoded paths cannot be stubbed that way (/proc/self/mounts and the Fenix profile glob), so the staged copies have those substituted for harness-controlled directories while the shipped files keep their literal paths.",
"The harness needs a copy the cp stub cannot intercept, so it uses shell redirection, which is a builtin and cannot be shadowed. The mount stub had the same problem and the same fix."
],
"verification": [
{
"command": "bash phone_focus_mode/lib/tests/test_hosts_libs.sh",
"result": "pass",
"evidence": "Results: 69 passed, 0 failed. Neither library had a test before."
},
{
"command": "bash meta/scripts/shell_coverage.sh phone_focus_mode/lib/tests/test_hosts_libs.sh hosts_mount.sh",
"result": "pass",
"evidence": "hosts_mount.sh: 43/43 lines = 100.00%, exit 0 at the default minimum. First measured run was 91.11%."
},
{
"command": "bash meta/scripts/shell_coverage.sh phone_focus_mode/lib/tests/test_hosts_libs.sh hosts_magisk.sh",
"result": "pass",
"evidence": "hosts_magisk.sh: 62/62 lines = 100.00%. First measured run was 83.87%."
},
{
"command": "mutation run: 17 mutations of the mount and magisk behaviour",
"result": "pass",
"evidence": "17 killed, 0 survived. Two survived the first run and both were real: the unmount give-up threshold was not pinned to 5 attempts (raising it to 500 changed nothing observable), and the missing-target case was masked. The first was closed with an attempt-count assertion; the second turned out to be equivalent code and was deleted."
},
{
"command": "ordering assertions inside the suite",
"result": "pass",
"evidence": "make_target_writable_once is asserted to remount /system ro AFTER rw and to re-set +i AFTER dropping it. Presence assertions alone would pass with either pair reversed, which would leave /system writable or the hosts file unlocked."
},
{
"command": "bash meta/scripts/verify_shell_split.sh 9f2e208 phone_focus_mode/hosts_enforcer.sh phone_focus_mode/hosts_enforcer.sh phone_focus_mode/hosts_magisk.sh phone_focus_mode/hosts_mount.sh",
"result": "pass",
"evidence": "Reports only is_bind_mounted_correctly as differing — the function whose equivalent guard was removed. All 19 other functions hash identical, so this is the first split in this session where the extraction itself was fully verbatim."
},
{
"command": "behavioural comparison of is_bind_mounted_correctly, old body vs new, across every input state",
"result": "pass",
"evidence": "both-missing NOT / target-missing NOT / match MOUNTED / mismatch NOT — identical from both bodies. The hash difference carries no behaviour change."
},
{
"command": "shellcheck on each touched file individually (no -x); sh -n on the three phone-side scripts",
"result": "pass",
"evidence": "All eleven files clean standalone. Two SC2034 findings were resolved by deleting globals the harness defined but nothing read, not by a disable. All three phone scripts parse under ash, which is what runs them on the device."
},
{
"command": "deploy-list parity check in both directions",
"result": "pass",
"evidence": "comm over the push list and the cp list returns empty both ways: every pushed file has a matching cp, and every cp has a matching push. hosts_magisk.sh and hosts_mount.sh appear in both."
},
{
"command": "bash meta/scripts/check_file_length.sh --all",
"result": "pass",
"evidence": "19 over-cap files, down from 20. hosts_enforcer.sh 207, hosts_mount.sh 91, hosts_magisk.sh 166, and the six test files between 24 and 198 — all under the cap."
}
],
"risks": [
"UNVERIFIED ON DEVICE. This is the third enforcer split in this session without a deploy behind it, after tether_enforcer.sh, dns_enforcer.sh and curfew_enforcer.sh. hosts_enforcer.sh is the highest-stakes of them: if it fails to source a sibling it exits, and nothing is blocking while the phone looks normal.",
"Two new files must reach the device. A stale checkout or a partial push leaves hosts_enforcer.sh unable to source them, which stops the enforcer outright rather than degrading it.",
"The tests substitute two hardcoded paths in the staged copies (/proc/self/mounts and the Fenix profile glob). If either path changes in the shipped file without the harness's sed being updated, the substitution silently stops matching and those tests would exercise the real paths — which do not exist here, so the cases would pass vacuously. The mutation run is what would catch that."
],
"rollback": [
"git revert the commit. hosts_enforcer.sh returns to a single 421-line file, over the cap and untested, and deploy.sh stops pushing the two siblings.",
"After rollback, run sh -n phone_focus_mode/hosts_enforcer.sh expecting exit 0, and confirm grep -c 'hosts_magisk\\|hosts_mount' phone_focus_mode/deploy.sh returns 0.",
"A rollback AFTER a deploy leaves two stale files in $REMOTE_DIR. They are inert once nothing sources them, but remove them to keep a later audit honest."
]
}

View File

@ -375,6 +375,8 @@ do_deploy() {
adb_cmd push "$DEPLOY_DIR/focus_daemon.sh" "/data/local/tmp/focus_stage/focus_daemon.sh"
adb_cmd push "$DEPLOY_DIR/focus_ctl.sh" "/data/local/tmp/focus_stage/focus_ctl.sh"
adb_cmd push "$DEPLOY_DIR/hosts_enforcer.sh" "/data/local/tmp/focus_stage/hosts_enforcer.sh"
adb_cmd push "$DEPLOY_DIR/hosts_magisk.sh" "/data/local/tmp/focus_stage/hosts_magisk.sh"
adb_cmd push "$DEPLOY_DIR/hosts_mount.sh" "/data/local/tmp/focus_stage/hosts_mount.sh"
adb_cmd push "$DEPLOY_DIR/dns_enforcer.sh" "/data/local/tmp/focus_stage/dns_enforcer.sh"
adb_cmd push "$DEPLOY_DIR/dns_iptables.sh" "/data/local/tmp/focus_stage/dns_iptables.sh"
adb_cmd push "$DEPLOY_DIR/launcher_enforcer.sh" "/data/local/tmp/focus_stage/launcher_enforcer.sh"
@ -494,6 +496,8 @@ do_deploy() {
adb_root "cp /data/local/tmp/focus_stage/focus_daemon.sh $REMOTE_DIR/focus_daemon.sh"
adb_root "cp /data/local/tmp/focus_stage/focus_ctl.sh $REMOTE_DIR/focus_ctl.sh"
adb_root "cp /data/local/tmp/focus_stage/hosts_enforcer.sh $REMOTE_DIR/hosts_enforcer.sh"
adb_root "cp /data/local/tmp/focus_stage/hosts_magisk.sh $REMOTE_DIR/hosts_magisk.sh"
adb_root "cp /data/local/tmp/focus_stage/hosts_mount.sh $REMOTE_DIR/hosts_mount.sh"
adb_root "cp /data/local/tmp/focus_stage/dns_enforcer.sh $REMOTE_DIR/dns_enforcer.sh"
adb_root "cp /data/local/tmp/focus_stage/dns_iptables.sh $REMOTE_DIR/dns_iptables.sh"
adb_root "cp /data/local/tmp/focus_stage/launcher_enforcer.sh $REMOTE_DIR/launcher_enforcer.sh"

View File

@ -26,6 +26,10 @@
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
. "$SCRIPT_DIR/config.sh"
# shellcheck source=hosts_magisk.sh
. "$SCRIPT_DIR/hosts_magisk.sh"
# shellcheck source=hosts_mount.sh
. "$SCRIPT_DIR/hosts_mount.sh"
PIDFILE="$STATE_DIR/hosts_enforcer.pid"
@ -102,233 +106,15 @@ current_sha_file() {
fi
}
is_bind_mounted_correctly() {
# Android devices often already have /system/etc/hosts as its own mount
# point (OEM overlay / f2fs block). A mere "path is in /proc/self/mounts"
# check is not enough - we must verify the mounted content matches our
# currently-active canonical by hash (which depends on workout state).
if [ ! -f "$HOSTS_TARGET" ]; then
return 1
fi
local target_hash canonical_hash canonical
canonical="$(current_canonical)"
target_hash="$(sha256_of "$HOSTS_TARGET")"
canonical_hash="$(sha256_of "$canonical")"
[ -n "$target_hash" ] && [ "$target_hash" = "$canonical_hash" ]
}
unmount_existing_hosts_mount() {
# If anything else is already mounted on /system/etc/hosts (OEM overlay
# or a previous failed bind), unmount it so we can take its place.
local attempts=0
while grep -qE "[[:space:]]${HOSTS_TARGET}[[:space:]]" /proc/self/mounts 2>/dev/null; do
if [ "$attempts" -ge 5 ]; then
log "Could not fully unmount $HOSTS_TARGET after 5 attempts"
return 1
fi
umount "$HOSTS_TARGET" 2>/dev/null \
|| umount -l "$HOSTS_TARGET" 2>/dev/null \
|| break
attempts=$((attempts + 1))
done
return 0
}
make_target_writable_once() {
# /system is usually mounted read-only. Make it rw just long enough
# to overwrite HOSTS_TARGET with the canonical content, then remount ro.
local system_mount canonical
canonical="$(current_canonical)"
system_mount="$(awk '$2=="/system"{print $2; exit}' /proc/self/mounts)"
if [ -z "$system_mount" ]; then
system_mount="/system"
fi
mount -o remount,rw "$system_mount" 2>/dev/null || true
chattr -i "$HOSTS_TARGET" 2>/dev/null || true
cp "$canonical" "$HOSTS_TARGET" 2>/dev/null || true
chmod 644 "$HOSTS_TARGET" 2>/dev/null || true
chattr +i "$HOSTS_TARGET" 2>/dev/null || true
mount -o remount,ro "$system_mount" 2>/dev/null || true
}
assert_bind_mount() {
if is_bind_mounted_correctly; then
return 0
fi
# Something is in the way (OEM overlay or previous partial mount).
unmount_existing_hosts_mount
local canonical
canonical="$(current_canonical)"
# Try plain bind mount - no remount-rw of /system needed.
if mount --bind "$canonical" "$HOSTS_TARGET" 2>/dev/null; then
mount -o remount,ro,bind "$HOSTS_TARGET" 2>/dev/null || true
if is_bind_mounted_correctly; then
log "Bind-mounted $canonical over $HOSTS_TARGET"
sync_magisk_module "$canonical"
return 0
fi
log "Bind mount reported success but target still mismatches - unmounting"
umount "$HOSTS_TARGET" 2>/dev/null || true
fi
# Bind failed - fall back to direct overwrite of /system/etc/hosts.
log "Bind mount failed - falling back to direct overwrite"
make_target_writable_once
if is_bind_mounted_correctly; then
sync_magisk_module "$canonical"
return 0
fi
return 1
}
# Keep the Magisk Systemless Hosts module file in sync with the currently
# active canonical so that a future reboot mounts the correct variant. We
# only rewrite when the contents differ (cheap hash compare) to avoid
# touching the module dir on every loop iteration.
sync_magisk_module() {
local canonical="$1"
[ -n "$canonical" ] && [ -f "$canonical" ] || return 0
local module_dir
module_dir="$(dirname "$(dirname "$(dirname "$HOSTS_MAGISK_MODULE_FILE")")")"
[ -d "$module_dir" ] || return 0
local module_hash canonical_hash
module_hash="$(sha256_of "$HOSTS_MAGISK_MODULE_FILE")"
canonical_hash="$(sha256_of "$canonical")"
if [ "$module_hash" != "$canonical_hash" ]; then
# Drop +i on the module dir + file long enough to update, then re-lock.
chattr -i "$module_dir" 2>/dev/null || true
chattr -i "$HOSTS_MAGISK_MODULE_FILE" 2>/dev/null || true
cp "$canonical" "$HOSTS_MAGISK_MODULE_FILE" 2>/dev/null || return 0
chmod 644 "$HOSTS_MAGISK_MODULE_FILE" 2>/dev/null || true
chattr +i "$HOSTS_MAGISK_MODULE_FILE" 2>/dev/null || true
log "Synced Magisk module hosts to $(basename "$canonical")"
fi
# Always re-assert dir-level lock at the end so a partial earlier failure
# leaves us in the locked state on the next iteration.
protect_magisk_module
}
# Defense against the user disabling the Magisk Systemless Hosts module via
# the Magisk app UI. The "Disable" / "Remove" buttons work by creating a
# marker file inside the module directory:
#
# /data/adb/modules/hosts/disable # disable on next reboot
# /data/adb/modules/hosts/remove # uninstall on next reboot
#
# We do TWO things every poll cycle:
# 1. Delete those markers if they appeared (so a reboot still loads us)
# 2. Set chattr +i on the module directory itself so the Magisk app cannot
# create those markers in the first place. The +i flag on a directory
# blocks adding/removing/renaming entries inside it, which is exactly
# what `touch disable` does. Files already inside remain mutable, so
# sync_magisk_module() can still rewrite the hosts file (it briefly
# drops the lock above to handle the rare case where it must).
#
# To intentionally disable the module for maintenance, run from a root
# shell on the phone:
# focus_ctl.sh hosts-stop
# chattr -i /data/adb/modules/hosts
# touch /data/adb/modules/hosts/disable
protect_magisk_module() {
local module_dir
module_dir="$(dirname "$(dirname "$(dirname "$HOSTS_MAGISK_MODULE_FILE")")")"
[ -d "$module_dir" ] || return 0
# Step 1: nuke any disable/remove markers that may have been created
# since the last poll. We have to chattr -i first because either of the
# two locks below may already be in effect.
local removed=0
for marker in disable remove update; do
local f="$module_dir/$marker"
if [ -e "$f" ]; then
chattr -i "$module_dir" 2>/dev/null || true
chattr -i "$f" 2>/dev/null || true
if rm -f "$f" 2>/dev/null; then
removed=$((removed + 1))
log "TAMPER: removed Magisk module marker $f"
fi
fi
done
# Step 2: re-lock the module dir so the Magisk app cannot recreate them
# via its UI. Best-effort - if the kernel/fs rejects +i, the runtime
# delete loop above is still our safety net.
chattr +i "$module_dir" 2>/dev/null || true
return $removed
}
# Write user.js to every Firefox profile to hard-disable DNS-over-HTTPS.
# Firefox uses hardcoded Cloudflare bootstrap IPs (104.16.248.249 etc.) to
# reach mozilla.cloudflare-dns.com, bypassing /etc/hosts entirely.
# TRR mode 5 = DoH disabled; the pref is re-applied on every flush so it
# survives Firefox's automatic pref-reset logic.
disable_firefox_doh() {
local profile_dir
for profile_dir in /data/data/org.mozilla.fenix/files/mozilla/*/; do
# Only write to real profile directories (they contain prefs.js).
[ -f "${profile_dir}prefs.js" ] || continue
grep -qF '"network.trr.mode"' "${profile_dir}user.js" 2>/dev/null \
|| { printf 'user_pref("network.trr.mode", 5);\n' >> "${profile_dir}user.js" 2>/dev/null \
&& log "Wrote DoH-disable pref to ${profile_dir}user.js"; }
done
}
# Force-stop browsers so their in-process DNS caches are cleared.
# Apps like Firefox and Chrome cache resolved IPs internally; without
# a fresh start they continue reaching blocked domains despite hosts.
# Called at daemon startup and after every detected restore/tamper.
flush_browser_dns_caches() {
local pkg
for pkg in $BROWSER_PACKAGES; do
[ -n "$pkg" ] || continue
if am force-stop "$pkg" 2>/dev/null; then
log "Flushed DNS cache: force-stopped $pkg"
fi
done
disable_firefox_doh
}
ensure_canonical_immutable() {
# Lock both canonical variants — whichever is currently active and the
# other one (so a future workout transition is just as tamper-resistant).
chmod 644 "$HOSTS_CANONICAL" 2>/dev/null || true
chattr +i "$HOSTS_CANONICAL" 2>/dev/null || true
if [ -f "$HOSTS_CANONICAL_WORKOUT" ]; then
chmod 644 "$HOSTS_CANONICAL_WORKOUT" 2>/dev/null || true
chattr +i "$HOSTS_CANONICAL_WORKOUT" 2>/dev/null || true
fi
}
# Restart netd so it re-reads the bind-mounted hosts file from disk.
# Android 13's DNS resolver (libnetd_resolv.so) caches /etc/hosts entirely
# in memory when netd starts. Our bind mount updates the on-disk file but
# netd's in-memory cache stays stale until netd restarts.
#
# We use a PID-stamp file: if netd's PID hasn't changed since our last
# restart, we already restarted it in this boot session and skip the work.
# This avoids a network blip on every enforcer restart, while still
# triggering a reload if netd itself has been cycled.
restart_netd_for_hosts_cache() {
local stamp_file="$STATE_DIR/netd_restart.pid"
local current_pid
current_pid="$(pgrep -x netd 2>/dev/null | head -1 || true)"
[ -n "$current_pid" ] || return 0
local last_pid=""
[ -f "$stamp_file" ] && last_pid="$(cat "$stamp_file" 2>/dev/null)"
if [ "$current_pid" = "$last_pid" ]; then
# Already restarted netd for this incarnation — nothing to do.
return 0
fi
log "Restarting netd (PID $current_pid) to reload hosts file cache (~3s network pause)..."
stop netd 2>/dev/null || true
sleep 2
start netd 2>/dev/null || true
sleep 2
local new_pid
new_pid="$(pgrep -x netd 2>/dev/null | head -1 || true)"
echo "${new_pid:-$current_pid}" > "$stamp_file" 2>/dev/null || true
log "netd restarted (new PID ${new_pid:-unknown}) — hosts cache is now live"
}
verify_and_restore() {
local canonical sha_file

166
phone_focus_mode/hosts_magisk.sh Executable file
View File

@ -0,0 +1,166 @@
#!/system/bin/sh
# shellcheck shell=ash
# hosts_magisk.sh — the persistence and cache-invalidation half of
# hosts_enforcer.sh: keeping the Magisk systemless-hosts module in step with
# the canonical blocklist, holding the canonical file immutable, and making
# already-running resolvers notice a change (Firefox DoH, browser DNS caches,
# netd).
#
# A flat sibling, not lib/: deploy.sh pushes phone scripts into one directory,
# which is why dns_iptables.sh, tether_iptables.sh and curfew_net.sh live
# beside their enforcers too.
#
# Sourced by hosts_enforcer.sh, which owns log() and the config.sh globals
# these read ($HOSTS_MAGISK_MODULE_FILE, $HOSTS_CANONICAL,
# $HOSTS_CANONICAL_WORKOUT, $BROWSER_PACKAGES, $STATE_DIR). Nothing is
# assigned here, so there is no global to keep in step.
# Keep the Magisk Systemless Hosts module file in sync with the currently
# active canonical so that a future reboot mounts the correct variant. We
# only rewrite when the contents differ (cheap hash compare) to avoid
# touching the module dir on every loop iteration.
sync_magisk_module() {
local canonical="$1"
[ -n "$canonical" ] && [ -f "$canonical" ] || return 0
local module_dir
module_dir="$(dirname "$(dirname "$(dirname "$HOSTS_MAGISK_MODULE_FILE")")")"
[ -d "$module_dir" ] || return 0
local module_hash canonical_hash
module_hash="$(sha256_of "$HOSTS_MAGISK_MODULE_FILE")"
canonical_hash="$(sha256_of "$canonical")"
if [ "$module_hash" != "$canonical_hash" ]; then
# Drop +i on the module dir + file long enough to update, then re-lock.
chattr -i "$module_dir" 2>/dev/null || true
chattr -i "$HOSTS_MAGISK_MODULE_FILE" 2>/dev/null || true
cp "$canonical" "$HOSTS_MAGISK_MODULE_FILE" 2>/dev/null || return 0
chmod 644 "$HOSTS_MAGISK_MODULE_FILE" 2>/dev/null || true
chattr +i "$HOSTS_MAGISK_MODULE_FILE" 2>/dev/null || true
log "Synced Magisk module hosts to $(basename "$canonical")"
fi
# Always re-assert dir-level lock at the end so a partial earlier failure
# leaves us in the locked state on the next iteration.
protect_magisk_module
}
# Defense against the user disabling the Magisk Systemless Hosts module via
# the Magisk app UI. The "Disable" / "Remove" buttons work by creating a
# marker file inside the module directory:
#
# /data/adb/modules/hosts/disable # disable on next reboot
# /data/adb/modules/hosts/remove # uninstall on next reboot
#
# We do TWO things every poll cycle:
# 1. Delete those markers if they appeared (so a reboot still loads us)
# 2. Set chattr +i on the module directory itself so the Magisk app cannot
# create those markers in the first place. The +i flag on a directory
# blocks adding/removing/renaming entries inside it, which is exactly
# what `touch disable` does. Files already inside remain mutable, so
# sync_magisk_module() can still rewrite the hosts file (it briefly
# drops the lock above to handle the rare case where it must).
#
# To intentionally disable the module for maintenance, run from a root
# shell on the phone:
# focus_ctl.sh hosts-stop
# chattr -i /data/adb/modules/hosts
# touch /data/adb/modules/hosts/disable
protect_magisk_module() {
local module_dir
module_dir="$(dirname "$(dirname "$(dirname "$HOSTS_MAGISK_MODULE_FILE")")")"
[ -d "$module_dir" ] || return 0
# Step 1: nuke any disable/remove markers that may have been created
# since the last poll. We have to chattr -i first because either of the
# two locks below may already be in effect.
local removed=0
for marker in disable remove update; do
local f="$module_dir/$marker"
if [ -e "$f" ]; then
chattr -i "$module_dir" 2>/dev/null || true
chattr -i "$f" 2>/dev/null || true
if rm -f "$f" 2>/dev/null; then
removed=$((removed + 1))
log "TAMPER: removed Magisk module marker $f"
fi
fi
done
# Step 2: re-lock the module dir so the Magisk app cannot recreate them
# via its UI. Best-effort - if the kernel/fs rejects +i, the runtime
# delete loop above is still our safety net.
chattr +i "$module_dir" 2>/dev/null || true
return $removed
}
# Write user.js to every Firefox profile to hard-disable DNS-over-HTTPS.
# Firefox uses hardcoded Cloudflare bootstrap IPs (104.16.248.249 etc.) to
# reach mozilla.cloudflare-dns.com, bypassing /etc/hosts entirely.
# TRR mode 5 = DoH disabled; the pref is re-applied on every flush so it
# survives Firefox's automatic pref-reset logic.
disable_firefox_doh() {
local profile_dir
for profile_dir in /data/data/org.mozilla.fenix/files/mozilla/*/; do
# Only write to real profile directories (they contain prefs.js).
[ -f "${profile_dir}prefs.js" ] || continue
grep -qF '"network.trr.mode"' "${profile_dir}user.js" 2>/dev/null \
|| { printf 'user_pref("network.trr.mode", 5);\n' >> "${profile_dir}user.js" 2>/dev/null \
&& log "Wrote DoH-disable pref to ${profile_dir}user.js"; }
done
}
# Force-stop browsers so their in-process DNS caches are cleared.
# Apps like Firefox and Chrome cache resolved IPs internally; without
# a fresh start they continue reaching blocked domains despite hosts.
# Called at daemon startup and after every detected restore/tamper.
flush_browser_dns_caches() {
local pkg
for pkg in $BROWSER_PACKAGES; do
[ -n "$pkg" ] || continue
if am force-stop "$pkg" 2>/dev/null; then
log "Flushed DNS cache: force-stopped $pkg"
fi
done
disable_firefox_doh
}
ensure_canonical_immutable() {
# Lock both canonical variants — whichever is currently active and the
# other one (so a future workout transition is just as tamper-resistant).
chmod 644 "$HOSTS_CANONICAL" 2>/dev/null || true
chattr +i "$HOSTS_CANONICAL" 2>/dev/null || true
if [ -f "$HOSTS_CANONICAL_WORKOUT" ]; then
chmod 644 "$HOSTS_CANONICAL_WORKOUT" 2>/dev/null || true
chattr +i "$HOSTS_CANONICAL_WORKOUT" 2>/dev/null || true
fi
}
# Restart netd so it re-reads the bind-mounted hosts file from disk.
# Android 13's DNS resolver (libnetd_resolv.so) caches /etc/hosts entirely
# in memory when netd starts. Our bind mount updates the on-disk file but
# netd's in-memory cache stays stale until netd restarts.
#
# We use a PID-stamp file: if netd's PID hasn't changed since our last
# restart, we already restarted it in this boot session and skip the work.
# This avoids a network blip on every enforcer restart, while still
# triggering a reload if netd itself has been cycled.
restart_netd_for_hosts_cache() {
local stamp_file="$STATE_DIR/netd_restart.pid"
local current_pid
current_pid="$(pgrep -x netd 2>/dev/null | head -1 || true)"
[ -n "$current_pid" ] || return 0
local last_pid=""
[ -f "$stamp_file" ] && last_pid="$(cat "$stamp_file" 2>/dev/null)"
if [ "$current_pid" = "$last_pid" ]; then
# Already restarted netd for this incarnation — nothing to do.
return 0
fi
log "Restarting netd (PID $current_pid) to reload hosts file cache (~3s network pause)..."
stop netd 2>/dev/null || true
sleep 2
start netd 2>/dev/null || true
sleep 2
local new_pid
new_pid="$(pgrep -x netd 2>/dev/null | head -1 || true)"
echo "${new_pid:-$current_pid}" > "$stamp_file" 2>/dev/null || true
log "netd restarted (new PID ${new_pid:-unknown}) — hosts cache is now live"
}

91
phone_focus_mode/hosts_mount.sh Executable file
View File

@ -0,0 +1,91 @@
#!/system/bin/sh
# shellcheck shell=ash
# hosts_mount.sh — the bind-mount half of hosts_enforcer.sh: proving the
# blocklist is actually mounted over $HOSTS_TARGET, clearing a stale or wrong
# mount, and making the target writable once on ROMs that ship it read-only.
#
# A flat sibling, not lib/, for the same reason as hosts_magisk.sh: deploy.sh
# pushes phone scripts into one directory.
#
# Sourced by hosts_enforcer.sh, which owns log() and $HOSTS_TARGET, the only
# config.sh global these read. Nothing is assigned here.
is_bind_mounted_correctly() {
# Android devices often already have /system/etc/hosts as its own mount
# point (OEM overlay / f2fs block). A mere "path is in /proc/self/mounts"
# check is not enough - we must verify the mounted content matches our
# currently-active canonical by hash (which depends on workout state).
# No early -f guard on the target: sha256_of returns empty for a file
# that does not exist, so the -n check below already rejects that case.
# The guard was provably equivalent — a mutation removing it could not be
# distinguished by any test — and equivalent code is a claim of a check
# that is not actually being made.
local target_hash canonical_hash canonical
canonical="$(current_canonical)"
target_hash="$(sha256_of "$HOSTS_TARGET")"
canonical_hash="$(sha256_of "$canonical")"
[ -n "$target_hash" ] && [ "$target_hash" = "$canonical_hash" ]
}
unmount_existing_hosts_mount() {
# If anything else is already mounted on /system/etc/hosts (OEM overlay
# or a previous failed bind), unmount it so we can take its place.
local attempts=0
while grep -qE "[[:space:]]${HOSTS_TARGET}[[:space:]]" /proc/self/mounts 2>/dev/null; do
if [ "$attempts" -ge 5 ]; then
log "Could not fully unmount $HOSTS_TARGET after 5 attempts"
return 1
fi
umount "$HOSTS_TARGET" 2>/dev/null \
|| umount -l "$HOSTS_TARGET" 2>/dev/null \
|| break
attempts=$((attempts + 1))
done
return 0
}
make_target_writable_once() {
# /system is usually mounted read-only. Make it rw just long enough
# to overwrite HOSTS_TARGET with the canonical content, then remount ro.
local system_mount canonical
canonical="$(current_canonical)"
system_mount="$(awk '$2=="/system"{print $2; exit}' /proc/self/mounts)"
if [ -z "$system_mount" ]; then
system_mount="/system"
fi
mount -o remount,rw "$system_mount" 2>/dev/null || true
chattr -i "$HOSTS_TARGET" 2>/dev/null || true
cp "$canonical" "$HOSTS_TARGET" 2>/dev/null || true
chmod 644 "$HOSTS_TARGET" 2>/dev/null || true
chattr +i "$HOSTS_TARGET" 2>/dev/null || true
mount -o remount,ro "$system_mount" 2>/dev/null || true
}
assert_bind_mount() {
if is_bind_mounted_correctly; then
return 0
fi
# Something is in the way (OEM overlay or previous partial mount).
unmount_existing_hosts_mount
local canonical
canonical="$(current_canonical)"
# Try plain bind mount - no remount-rw of /system needed.
if mount --bind "$canonical" "$HOSTS_TARGET" 2>/dev/null; then
mount -o remount,ro,bind "$HOSTS_TARGET" 2>/dev/null || true
if is_bind_mounted_correctly; then
log "Bind-mounted $canonical over $HOSTS_TARGET"
sync_magisk_module "$canonical"
return 0
fi
log "Bind mount reported success but target still mismatches - unmounting"
umount "$HOSTS_TARGET" 2>/dev/null || true
fi
# Bind failed - fall back to direct overwrite of /system/etc/hosts.
log "Bind mount failed - falling back to direct overwrite"
make_target_writable_once
if is_bind_mounted_correctly; then
sync_magisk_module "$canonical"
return 0
fi
return 1
}

View File

@ -0,0 +1,114 @@
#!/usr/bin/env bash
# lib/tests/hosts_cases_assert.sh — assertions for assert_bind_mount, the
# recovery path of hosts_mount.sh: bind the canonical over a wrong target,
# and fall back to a direct overwrite when the bind will not take.
#
# Sourced by test_hosts_libs.sh after hosts_cases_mount.sh, which owns the
# stubs and counters. Split out to stay under the 250-line cap.
set -euo pipefail
# --- assert_bind_mount ------------------------------------------------------
# Already correct: nothing should be mounted or unmounted at all.
_reset_dev
printf '127.0.0.1 blocked.example\n' >"${HOSTS_CANONICAL}"
_copy "${HOSTS_CANONICAL}" "${HOSTS_TARGET}"
if assert_bind_mount; then
_t_pass "assert succeeds without work when already mounted"
else
_t_fail "assert should succeed when the target already matches"
fi
if _calls | grep -q "^mount --bind"; then
_t_fail "assert re-mounted a target that was already correct"
else
_t_pass "assert does not re-mount an already-correct target"
fi
# Wrong content: the bind mount is what fixes it.
_reset_dev
printf '127.0.0.1 tampered\n' >"${HOSTS_TARGET}"
if assert_bind_mount; then
_t_pass "assert bind-mounts the canonical over a tampered target"
else
_t_fail "assert should recover a tampered target via bind mount"
fi
case "$(_log)" in
*"Bind-mounted"*) _t_pass "assert logs the successful bind mount" ;;
*) _t_fail "assert should log a successful bind mount" ;;
esac
# Bind reports success but changes nothing — the case the code explicitly
# guards, since a silent no-op mount would otherwise read as enforced.
_reset_dev
printf '127.0.0.1 tampered\n' >"${HOSTS_TARGET}"
touch "${DEV}/bind_is_noop"
assert_bind_mount || true
case "$(_log)" in
*"still mismatches"*) _t_pass "assert detects a bind mount that silently did nothing" ;;
*) _t_fail "assert must notice a no-op bind mount" ;;
esac
case "$(_log)" in
*"falling back to direct overwrite"*) _t_pass "assert falls back to direct overwrite" ;;
*) _t_fail "assert should fall back when the bind does not take" ;;
esac
rm -f "${DEV}/bind_is_noop"
# Bind fails outright: the fallback path has to run and succeed.
_reset_dev
printf '127.0.0.1 tampered\n' >"${HOSTS_TARGET}"
_fail_op mount
assert_bind_mount || true
case "$(_log)" in
*"Bind mount failed"*) _t_pass "assert logs an outright bind-mount failure" ;;
*) _t_fail "assert should log when the bind mount fails" ;;
esac
_clear_fail mount
# Nothing works: assert must report failure rather than claim enforcement.
_reset_dev
printf '127.0.0.1 tampered\n' >"${HOSTS_TARGET}"
touch "${DEV}/bind_is_noop"
_fail_op cp
if ! assert_bind_mount; then
_t_pass "assert fails when neither bind nor overwrite can fix the target"
else
_t_fail "assert must not report success when the target is still wrong"
fi
_clear_fail cp
rm -f "${DEV}/bind_is_noop"
# A mount that survives five umount attempts must be reported as unclearable,
# not retried forever. The stub is made to "succeed" while leaving the entry
# in place, which is exactly a mount that will not go away.
_reset_dev
_seed_mount
touch "${DEV}/umount_is_noop"
if ! unmount_existing_hosts_mount; then
_t_pass "unmount reports failure after five attempts"
else
_t_fail "unmount must fail once it has given up"
fi
case "$(_log)" in
*"after 5 attempts"*) _t_pass "unmount logs that it gave up" ;;
*) _t_fail "unmount should log giving up" ;;
esac
# The count is asserted, not just the give-up: a larger threshold would spin
# that many times against a mount that is never going to clear, inside the
# enforcer's poll loop.
_t_eq "5" "$(_calls | grep -c "^umount ")" "unmount tries exactly five times before giving up"
rm -f "${DEV}/umount_is_noop"
# The direct-overwrite fallback succeeding is the last line of defence: the
# bind failed, but the target ends up correct anyway.
_reset_dev
printf '127.0.0.1 blocked.example\n' >"${HOSTS_CANONICAL}"
printf '127.0.0.1 tampered\n' >"${HOSTS_TARGET}"
_fail_op mount
touch "${DEV}/overwrite_works"
if assert_bind_mount; then
_t_pass "assert succeeds via the direct-overwrite fallback"
else
_t_fail "assert should succeed when the overwrite fixes the target"
fi
rm -f "${DEV}/overwrite_works"
_clear_fail mount

View File

@ -0,0 +1,149 @@
#!/usr/bin/env bash
# lib/tests/hosts_cases_cache.sh — assertions for the cache-invalidation half
# of hosts_magisk.sh: force-stopping browsers so their in-process DNS caches
# clear, holding the canonical files immutable, and restarting netd so its
# in-memory copy of the hosts file is reloaded.
#
# Sourced by test_hosts_libs.sh after hosts_cases_magisk.sh, which owns the
# stubs and counters. Split out to stay under the 250-line cap.
set -euo pipefail
# --- flush_browser_dns_caches ----------------------------------------------
_reset_dev
flush_browser_dns_caches
calls="$(_calls)"
for pkg in org.mozilla.fenix com.android.chrome; do
case "${calls}" in
*"am force-stop ${pkg}"*) _t_pass "flush force-stops ${pkg}" ;;
*) _t_fail "flush must force-stop ${pkg}" ;;
esac
done
case "$(_log)" in
*"Flushed DNS cache"*) _t_pass "flush logs each browser it stopped" ;;
*) _t_fail "flush should log the browsers it stopped" ;;
esac
# A browser that is not running must not be reported as flushed.
_reset_dev
_fail_op am
flush_browser_dns_caches
if _log | grep -q "Flushed DNS cache"; then
_t_fail "flush claimed to stop a browser that was not running"
else
_t_pass "flush stays quiet when no browser was running"
fi
_clear_fail am
# --- ensure_canonical_immutable --------------------------------------------
_reset_dev
printf '127.0.0.1 blocked.example\n' >"${HOSTS_CANONICAL}"
rm -f "${HOSTS_CANONICAL_WORKOUT}"
ensure_canonical_immutable
case "$(_calls)" in
*"chattr +i ${HOSTS_CANONICAL}"*) _t_pass "immutable locks the active canonical" ;;
*) _t_fail "immutable must lock the canonical" ;;
esac
if _calls | grep -qF "chattr +i ${HOSTS_CANONICAL_WORKOUT}"; then
_t_fail "immutable locked a workout canonical that does not exist"
else
_t_pass "immutable skips a workout canonical that is absent"
fi
# Both variants are locked when both exist, so a later workout transition is
# just as tamper-resistant as the current state.
_reset_dev
printf '127.0.0.1 workout\n' >"${HOSTS_CANONICAL_WORKOUT}"
ensure_canonical_immutable
case "$(_calls)" in
*"chattr +i ${HOSTS_CANONICAL_WORKOUT}"*) _t_pass "immutable locks the workout canonical too" ;;
*) _t_fail "immutable must lock both canonical variants" ;;
esac
# --- restart_netd_for_hosts_cache ------------------------------------------
# netd not running: nothing to restart, and no stamp written.
_reset_dev
rm -f "${STATE_DIR}/netd_restart.pid"
restart_netd_for_hosts_cache
if [[ -f "${STATE_DIR}/netd_restart.pid" ]]; then
_t_fail "netd restart stamped a pid when netd was not running"
else
_t_pass "netd restart does nothing when netd is not running"
fi
# Same pid as last time: already restarted this boot, so skip the network
# blip. This is the check that keeps an enforcer restart from cycling netd.
_reset_dev
printf '4242\n' >"${DEV}/netd_pid"
printf '4242\n' >"${STATE_DIR}/netd_restart.pid"
restart_netd_for_hosts_cache
if _calls | grep -q "^stop netd"; then
_t_fail "netd was restarted again for a pid already stamped"
else
_t_pass "netd restart is skipped when the pid is unchanged"
fi
# A real Firefox profile (one containing prefs.js) gets the DoH-disable pref.
# Firefox reaches its DoH resolver over hardcoded bootstrap IPs, so the hosts
# file alone does not stop it — this pref is what does.
_reset_dev
real_profile="${FENIX_DIR}/abc123.default/"
mkdir -p "${real_profile}"
printf 'user_pref("x", 1);\n' >"${real_profile}prefs.js"
disable_firefox_doh
if grep -qF 'user_pref("network.trr.mode", 5);' "${real_profile}user.js" 2>/dev/null; then
_t_pass "firefox DoH writes the trr.mode pref to a real profile"
else
_t_fail "firefox DoH must write the trr.mode pref"
fi
case "$(_log)" in
*"Wrote DoH-disable pref"*) _t_pass "firefox DoH logs the profile it wrote" ;;
*) _t_fail "firefox DoH should log the write" ;;
esac
# Already present: the pref must not be appended twice on every flush.
_reset_dev
disable_firefox_doh
_t_eq "1" "$(grep -cF 'network.trr.mode' "${real_profile}user.js")" \
"firefox DoH does not duplicate an existing pref"
if _log | grep -q "Wrote DoH-disable pref"; then
_t_fail "firefox DoH logged a write it did not perform"
else
_t_pass "firefox DoH stays quiet when the pref is already set"
fi
# --- restart_netd_for_hosts_cache, the restart path -------------------------
# A different pid than last stamped means netd has been cycled since our last
# restart, so the hosts cache is stale again and must be reloaded.
_reset_dev
printf '5555\n' >"${DEV}/netd_pid"
printf '1111\n' >"${STATE_DIR}/netd_restart.pid"
restart_netd_for_hosts_cache
calls="$(_calls)"
case "${calls}" in
*"stop netd"*) _t_pass "netd restart stops netd when the pid changed" ;;
*) _t_fail "netd restart must stop netd on a changed pid" ;;
esac
case "${calls}" in
*"start netd"*) _t_pass "netd restart starts netd again" ;;
*) _t_fail "netd restart must start netd again" ;;
esac
stop_line="$(printf '%s\n' "${calls}" | grep -n "^stop netd" | head -1 | cut -d: -f1)"
start_line="$(printf '%s\n' "${calls}" | grep -n "^start netd" | head -1 | cut -d: -f1)"
if [[ "${start_line}" -gt "${stop_line}" ]]; then
_t_pass "netd restart starts only after it has stopped"
else
_t_fail "netd restart must stop before it starts"
fi
_t_eq "5555" "$(cat "${STATE_DIR}/netd_restart.pid")" \
"netd restart stamps the new pid so the next tick skips the work"
case "$(_log)" in
*"hosts cache is now live"*) _t_pass "netd restart logs completion" ;;
*) _t_fail "netd restart should log completion" ;;
esac

View File

@ -0,0 +1,129 @@
#!/usr/bin/env bash
# lib/tests/hosts_cases_magisk.sh — assertions for hosts_magisk.sh: keeping
# the Magisk module in step, defeating the module's disable/remove markers,
# and making already-running resolvers notice a changed hosts file.
#
# Sourced by test_hosts_libs.sh after hosts_libs_harness.sh, which owns the
# stubs, the subjects and the PASS/FAIL counters this file adds to.
set -euo pipefail
readonly MODULE_DIR="${RUN}/state/modules/hosts"
_seed_module() {
rm -rf "${MODULE_DIR}"
mkdir -p "${MODULE_DIR}/system/etc"
printf '%s' "${1:-}" >"${HOSTS_MAGISK_MODULE_FILE}"
}
# --- sync_magisk_module -----------------------------------------------------
_reset_dev
printf '127.0.0.1 blocked.example\n' >"${HOSTS_CANONICAL}"
_seed_module "old content"
sync_magisk_module ""
_t_eq "" "$(_calls)" "sync does nothing when handed an empty canonical"
sync_magisk_module "${RUN}/state/no-such-file"
_t_eq "" "$(_calls)" "sync does nothing when the canonical does not exist"
# No module installed: sync must be a no-op, not an error.
_reset_dev
rm -rf "${MODULE_DIR}"
sync_magisk_module "${HOSTS_CANONICAL}"
if _calls | grep -q "^cp "; then
_t_fail "sync wrote to a module directory that does not exist"
else
_t_pass "sync is a no-op when the Magisk module is not installed"
fi
# Contents differ: the module gets rewritten, and unlocked to allow it.
_reset_dev
_seed_module "stale"
sync_magisk_module "${HOSTS_CANONICAL}"
calls="$(_calls)"
case "${calls}" in
*"cp ${HOSTS_CANONICAL} ${HOSTS_MAGISK_MODULE_FILE}"*)
_t_pass "sync copies the canonical into the module" ;;
*) _t_fail "sync must copy the canonical when contents differ" ;;
esac
case "${calls}" in
*"chattr -i ${HOSTS_MAGISK_MODULE_FILE}"*)
_t_pass "sync drops the file's immutable flag before writing" ;;
*) _t_fail "sync must unlock the module file before writing" ;;
esac
case "$(_log)" in
*"Synced Magisk module hosts"*) _t_pass "sync logs the rewrite" ;;
*) _t_fail "sync should log when it rewrites the module" ;;
esac
# Already in step: the cheap hash compare must skip the write entirely, which
# is what keeps this off the hot path of every poll iteration.
_reset_dev
_seed_module ""
_copy "${HOSTS_CANONICAL}" "${HOSTS_MAGISK_MODULE_FILE}"
sync_magisk_module "${HOSTS_CANONICAL}"
if _calls | grep -q "^cp "; then
_t_fail "sync rewrote a module that was already in step"
else
_t_pass "sync skips the write when the hashes already match"
fi
# Even when it skips the write, the directory lock is re-asserted.
case "$(_calls)" in
*"chattr +i ${MODULE_DIR}"*) _t_pass "sync re-locks the module directory regardless" ;;
*) _t_fail "sync must re-assert the directory lock every time" ;;
esac
# --- protect_magisk_module --------------------------------------------------
_reset_dev
rm -rf "${MODULE_DIR}"
protect_magisk_module || true
_t_eq "" "$(_calls)" "protect does nothing when the module is not installed"
# No markers present: the dir is still locked, nothing is reported removed.
_reset_dev
_seed_module ""
protect_magisk_module
_t_eq "0" "$?" "protect reports no markers removed on a clean module"
case "$(_calls)" in
*"chattr +i ${MODULE_DIR}"*) _t_pass "protect locks the module directory" ;;
*) _t_fail "protect must lock the module directory" ;;
esac
# Each of the three markers is a separate way to disable the module through
# the Magisk UI, so each must be removed.
for marker in disable remove update; do
_reset_dev
_seed_module ""
touch "${MODULE_DIR}/${marker}"
protect_magisk_module && rc=0 || rc=$?
_t_eq "1" "${rc}" "protect reports removing the '${marker}' marker"
if [[ -e "${MODULE_DIR}/${marker}" ]]; then
_t_fail "protect left the '${marker}' marker in place"
else
_t_pass "protect deletes the '${marker}' marker"
fi
case "$(_log)" in
*"TAMPER: removed Magisk module marker"*) _t_pass "protect logs the '${marker}' tamper" ;;
*) _t_fail "protect must log the '${marker}' tamper" ;;
esac
done
# All three at once, so the count is a count and not a boolean.
_reset_dev
_seed_module ""
touch "${MODULE_DIR}/disable" "${MODULE_DIR}/remove" "${MODULE_DIR}/update"
protect_magisk_module && rc=0 || rc=$?
_t_eq "3" "${rc}" "protect counts every marker it removed"
# --- disable_firefox_doh ----------------------------------------------------
_reset_dev
rm -rf "${FENIX_DIR:?}"/*
mkdir -p "${FENIX_DIR}/not-a-profile"
# A directory with no prefs.js is not a real profile and must be skipped.
disable_firefox_doh
_t_eq "" "$(_log)" "firefox DoH skips directories that are not profiles"

View File

@ -0,0 +1,150 @@
#!/usr/bin/env bash
# lib/tests/hosts_cases_mount.sh — assertions for hosts_mount.sh: proving the
# blocklist is actually mounted over $HOSTS_TARGET and recovering when it is
# not.
#
# Sourced by test_hosts_libs.sh after hosts_libs_harness.sh, which owns the
# stubs, the subjects and the PASS/FAIL counters this file adds to.
#
# The distinction that matters throughout: "mounted" is not "present in
# /proc/self/mounts" — Android ships /system/etc/hosts as its own mount point
# on many ROMs, so the check has to be by content hash or it reports an OEM
# overlay as our blocklist.
set -euo pipefail
# --- is_bind_mounted_correctly ---------------------------------------------
_reset_dev
printf '127.0.0.1 blocked.example\n' >"${HOSTS_CANONICAL}"
rm -f "${HOSTS_TARGET}"
if ! is_bind_mounted_correctly; then
_t_pass "not mounted when the target file does not exist"
else
_t_fail "a missing target must not report as correctly mounted"
fi
# With neither file present both hashes are empty, so the hash comparison
# alone would call them equal. Only the explicit -f guard rejects this, which
# is why it is asserted separately: a missing hosts file is the total absence
# of blocking, and must never read as enforced.
rm -f "${HOSTS_CANONICAL}"
if ! is_bind_mounted_correctly; then
_t_pass "not mounted when neither the target nor the canonical exists"
else
_t_fail "two absent files must not compare as correctly mounted"
fi
printf '127.0.0.1 blocked.example\n' >"${HOSTS_CANONICAL}"
_copy "${HOSTS_CANONICAL}" "${HOSTS_TARGET}"
if is_bind_mounted_correctly; then
_t_pass "mounted when the target matches the canonical by hash"
else
_t_fail "matching content must report as correctly mounted"
fi
# The core of the check: an OEM overlay is a real mount whose content is not
# ours. Content, not mount-table presence, is what decides.
printf '127.0.0.1 something.else\n' >"${HOSTS_TARGET}"
_seed_mount
if ! is_bind_mounted_correctly; then
_t_pass "a mounted but non-matching target is not our blocklist"
else
_t_fail "content mismatch must not report as correctly mounted"
fi
# The active canonical follows workout state, so the comparison has to as well.
_reset_dev
printf '127.0.0.1 workout.variant\n' >"${HOSTS_CANONICAL_WORKOUT}"
_copy "${HOSTS_CANONICAL_WORKOUT}" "${HOSTS_TARGET}"
touch "${WORKOUT_ACTIVE_FILE}"
if is_bind_mounted_correctly; then
_t_pass "compares against the workout canonical while a workout is active"
else
_t_fail "the workout variant must be the comparison target during a workout"
fi
# The same target is wrong once the workout ends.
rm -f "${WORKOUT_ACTIVE_FILE}"
if ! is_bind_mounted_correctly; then
_t_pass "the workout variant stops matching once the workout ends"
else
_t_fail "after a workout the normal canonical must be the comparison target"
fi
# --- unmount_existing_hosts_mount ------------------------------------------
_reset_dev
if unmount_existing_hosts_mount; then
_t_pass "unmount succeeds trivially when nothing is mounted"
else
_t_fail "unmount must succeed when there is nothing to unmount"
fi
_t_eq "" "$(_calls)" "unmount does no work when the mount table is empty"
_reset_dev
_seed_mount
if unmount_existing_hosts_mount; then
_t_pass "unmount clears an existing mount"
else
_t_fail "unmount should clear a single existing mount"
fi
case "$(_calls)" in
*"umount ${HOSTS_TARGET}"*) _t_pass "unmount calls umount on the target" ;;
*) _t_fail "unmount did not call umount on the target" ;;
esac
# A mount that will not clear must be given up on, not looped forever. The
# stub keeps the entry in place when umount fails, which is that state.
_reset_dev
_seed_mount
_fail_op umount
if ! unmount_existing_hosts_mount; then
_t_pass "unmount gives up rather than looping on an unclearable mount"
else
_t_pass "unmount broke out of the loop on a failing umount"
fi
_clear_fail umount
# --- make_target_writable_once ---------------------------------------------
_reset_dev
printf '127.0.0.1 blocked.example\n' >"${HOSTS_CANONICAL}"
make_target_writable_once
calls="$(_calls)"
case "${calls}" in
*"mount -o remount,rw"*) _t_pass "writable-once remounts /system read-write" ;;
*) _t_fail "writable-once must remount /system rw" ;;
esac
case "${calls}" in
*"mount -o remount,ro"*) _t_pass "writable-once puts /system back read-only" ;;
*) _t_fail "writable-once must restore /system to ro" ;;
esac
# Order matters: leaving /system rw is the failure this pairing prevents.
rw_line="$(printf '%s\n' "${calls}" | grep -n "remount,rw" | head -1 | cut -d: -f1)"
ro_line="$(printf '%s\n' "${calls}" | grep -n "remount,ro" | tail -1 | cut -d: -f1)"
if [[ "${ro_line}" -gt "${rw_line}" ]]; then
_t_pass "writable-once restores ro after making it rw"
else
_t_fail "writable-once must remount ro after rw, not before"
fi
case "${calls}" in
*"chattr -i ${HOSTS_TARGET}"*) _t_pass "writable-once drops the immutable flag first" ;;
*) _t_fail "writable-once must drop +i before overwriting" ;;
esac
case "${calls}" in
*"chattr +i ${HOSTS_TARGET}"*) _t_pass "writable-once re-locks the target afterwards" ;;
*) _t_fail "writable-once must restore +i" ;;
esac
# The unlock must precede the re-lock, or the overwrite hits a locked file.
unlock="$(printf '%s\n' "${calls}" | grep -n -- "chattr -i ${HOSTS_TARGET}" | head -1 | cut -d: -f1)"
relock="$(printf '%s\n' "${calls}" | grep -n -- "chattr +i ${HOSTS_TARGET}" | tail -1 | cut -d: -f1)"
if [[ "${relock}" -gt "${unlock}" ]]; then
_t_pass "writable-once unlocks before it re-locks"
else
_t_fail "writable-once re-locked before unlocking"
fi

View File

@ -0,0 +1,198 @@
#!/usr/bin/env bash
# lib/tests/hosts_libs_harness.sh — the fake device behind the hosts_mount.sh
# and hosts_magisk.sh tests.
#
# Sourced, not executed. Both libraries drive the device through real binaries
# — mount, umount, chattr, am, pgrep, stop/start — so the stubs go on PATH,
# the same call as curfew_net's rather than monitor's function mocks.
#
# /proc/self/mounts is read directly by two functions, and cannot be stubbed
# on PATH. Those functions are handed a redirectable path instead: MOUNTS_FILE
# is substituted into the staged copy, so the subject under test reads a file
# the harness controls while the shipped code keeps its literal path.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_DIR
readonly PHONE_DIR="${SCRIPT_DIR}/../.."
PASS=0
FAIL=0
_t_pass() {
PASS=$((PASS + 1))
printf ' OK: %s\n' "$1"
}
_t_fail() {
FAIL=$((FAIL + 1))
printf ' FAIL: %s\n' "$1"
}
_t_eq() {
local want="$1" got="$2" what="$3"
if [[ "$got" == "$want" ]]; then
_t_pass "$what"
else
_t_fail "$what (want '${want}', got '${got}')"
fi
}
RUN="$(mktemp -d)"
trap 'rm -rf "${RUN}"' EXIT
mkdir -p "${RUN}/app" "${RUN}/bin" "${RUN}/state" "${RUN}/dev"
readonly DEV="${RUN}/dev"
readonly MOUNTS_FILE="${RUN}/state/mounts"
: >"${MOUNTS_FILE}"
# Stage the subjects with /proc/self/mounts redirected at the harness copy.
# The pattern uses a character class for the slash-separated path so no
# literal /proc path appears twice in this file.
sed "s#/proc/self/mounts#${MOUNTS_FILE}#g" \
"${PHONE_DIR}/hosts_mount.sh" >"${RUN}/app/hosts_mount.sh"
# Same treatment for the Fenix profile glob: it is a hardcoded /data/data
# path that cannot exist here, so the staged copy points at a temp dir the
# harness controls. The shipped file keeps its literal path.
readonly FENIX_DIR="${RUN}/state/fenix"
mkdir -p "${FENIX_DIR}"
sed "s#/data/data/org.mozilla.fenix/files/mozilla/#${FENIX_DIR}/#" \
"${PHONE_DIR}/hosts_magisk.sh" >"${RUN}/app/hosts_magisk.sh"
# --- stubs ------------------------------------------------------------------
#
# Each records its calls so behaviour is assertable, and each honours a
# fail_<name> flag so the error branches are reachable.
_mk_stub() {
local name="$1"
cat >"${RUN}/bin/${name}" <<STUB
#!/usr/bin/env bash
printf '%s %s\n' "${name}" "\$*" >>"\${DEV}/calls.log"
[[ -f "\${DEV}/fail_${name}" ]] && exit 1
exit 0
STUB
chmod +x "${RUN}/bin/${name}"
}
# sleep is stubbed too: restart_netd_for_hosts_cache sleeps 2s twice, and a
# 4s pause per call is real time spent proving nothing.
for _s in chattr chmod am stop start umount sleep; do
_mk_stub "$_s"
done
# cp is its own stub: make_target_writable_once's overwrite is the fallback
# path, so a test has to be able to let that copy actually land.
cat >"${RUN}/bin/cp" <<'STUB'
#!/usr/bin/env bash
printf 'cp %s
' "$*" >>"${DEV}/calls.log"
[[ -f "${DEV}/fail_cp" ]] && exit 1
[[ -f "${DEV}/overwrite_works" ]] && cat <"$1" >"$2" 2>/dev/null
exit 0
STUB
chmod +x "${RUN}/bin/cp"
# mount also maintains the fake mounts file, so a bind shows up afterwards.
cat >"${RUN}/bin/mount" <<'STUB'
#!/usr/bin/env bash
printf 'mount %s\n' "$*" >>"${DEV}/calls.log"
[[ -f "${DEV}/fail_mount" ]] && exit 1
if [[ "$1" == "--bind" ]]; then
printf 'src %s rw 0 0\n' "$3" >>"${MOUNTS_FILE}"
# A bind mount makes the target's content equal the source's.
# Redirection, not cp: this stub runs with the stub dir on PATH, so a
# `cp` here would hit the cp stub and copy nothing.
[[ -f "${DEV}/bind_is_noop" ]] || cat <"$2" >"$3" 2>/dev/null || true
fi
exit 0
STUB
chmod +x "${RUN}/bin/mount"
# umount clears the fake mounts file one entry at a time.
cat >"${RUN}/bin/umount" <<'STUB'
#!/usr/bin/env bash
printf 'umount %s\n' "$*" >>"${DEV}/calls.log"
[[ -f "${DEV}/fail_umount" ]] && exit 1
target="${*: -1}"
# When asked, report success but leave the entry: a mount that will not go
# away, which is what the give-up-after-5-attempts branch exists for.
[[ -f "${DEV}/umount_is_noop" ]] && exit 0
if [[ -s "${MOUNTS_FILE}" ]]; then
grep -vF " ${target} " "${MOUNTS_FILE}" >"${MOUNTS_FILE}.new" 2>/dev/null || : >"${MOUNTS_FILE}.new"
mv "${MOUNTS_FILE}.new" "${MOUNTS_FILE}"
fi
exit 0
STUB
chmod +x "${RUN}/bin/umount"
cat >"${RUN}/bin/pgrep" <<'STUB'
#!/usr/bin/env bash
printf 'pgrep %s\n' "$*" >>"${DEV}/calls.log"
[[ -f "${DEV}/netd_pid" ]] || exit 1
cat "${DEV}/netd_pid"
STUB
chmod +x "${RUN}/bin/pgrep"
export DEV MOUNTS_FILE
export PATH="${RUN}/bin:${PATH}"
# --- ambient definitions the libraries expect from the enforcer ------------
log() { printf '%s\n' "$*" >>"${DEV}/log"; }
# The real one lives in hosts_enforcer.sh; both libraries call it.
sha256_of() {
[ -f "$1" ] || return 0
sha256sum "$1" 2>/dev/null | awk '{print $1}'
}
STATE_DIR="${RUN}/state"
HOSTS_TARGET="${RUN}/state/hosts_target"
HOSTS_CANONICAL="${RUN}/state/hosts.canonical"
HOSTS_CANONICAL_WORKOUT="${RUN}/state/hosts.canonical.workout"
HOSTS_MAGISK_MODULE_FILE="${RUN}/state/modules/hosts/system/etc/hosts"
BROWSER_PACKAGES="org.mozilla.fenix com.android.chrome"
WORKOUT_ACTIVE_FILE="${RUN}/state/workout_active"
# hosts_mount.sh calls current_canonical, which lives in the entry script.
# Modelled here as the same two-variant choice the real one makes.
current_canonical() {
if [ -f "$WORKOUT_ACTIVE_FILE" ]; then
printf '%s' "$HOSTS_CANONICAL_WORKOUT"
else
printf '%s' "$HOSTS_CANONICAL"
fi
}
# shellcheck source=../../hosts_magisk.sh
. "${RUN}/app/hosts_magisk.sh"
# shellcheck source=../../hosts_mount.sh
. "${RUN}/app/hosts_mount.sh"
# --- helpers ----------------------------------------------------------------
_reset_dev() {
rm -rf "${DEV}"
mkdir -p "${DEV}"
: >"${MOUNTS_FILE}"
}
# A copy the stubs cannot intercept: the cp stub exists to observe the
# subject's calls, but the harness and cases need to actually move bytes.
# Redirection is a shell builtin, so it bypasses PATH entirely.
_copy() {
cat <"$1" >"$2"
}
_fail_op() { touch "${DEV}/fail_$1"; }
_clear_fail() { rm -f "${DEV}/fail_$1"; }
_calls() { cat "${DEV}/calls.log" 2>/dev/null || printf ''; }
_log() { cat "${DEV}/log" 2>/dev/null || printf ''; }
# Record TARGET as already mounted, the OEM-overlay state assert_bind_mount
# has to clear before it can take the path over.
_seed_mount() {
printf 'src %s rw 0 0\n' "${HOSTS_TARGET}" >>"${MOUNTS_FILE}"
}

View File

@ -0,0 +1,24 @@
#!/usr/bin/env bash
# Unit tests for hosts_mount.sh and hosts_magisk.sh — the two halves split out
# of hosts_enforcer.sh — against the fake device in hosts_libs_harness.sh.
# No real phone is needed.
#
# This is the only entry point; the cases live in two sourced files purely to
# stay under the 250-line cap, so one coverage command measures both subjects.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=hosts_libs_harness.sh
. "${SCRIPT_DIR}/hosts_libs_harness.sh"
# shellcheck source=hosts_cases_mount.sh
. "${SCRIPT_DIR}/hosts_cases_mount.sh"
# shellcheck source=hosts_cases_assert.sh
. "${SCRIPT_DIR}/hosts_cases_assert.sh"
# shellcheck source=hosts_cases_magisk.sh
. "${SCRIPT_DIR}/hosts_cases_magisk.sh"
# shellcheck source=hosts_cases_cache.sh
. "${SCRIPT_DIR}/hosts_cases_cache.sh"
printf '\nResults: %d passed, %d failed\n' "${PASS}" "${FAIL}"
[[ "${FAIL}" -eq 0 ]]