Compare commits

..

3 Commits

Author SHA1 Message Date
8aa3e7d962 Add change explanation: tether-hotspot-block
Some checks are pending
Pre-commit checks / pre-commit (push) Waiting to run
Interactive /explain-diff walkthrough of the phone_focus_mode hotspot/tethering
enforcer (commit range HEAD~2..HEAD): background on netfilter OUTPUT vs FORWARD,
the second-phone bypass and fix, a steppable FORWARD-chain simulator, and a
debiased 5-question quiz. Refresh the explanations gallery index.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q6i3cdhKBoUrKxy4rmx6hH
2026-07-13 10:59:07 +02:00
dae6be2883 phone_focus_mode: prettier-format the README tethering section
Apply repo prettier formatting (table alignment, emphasis markers) to the
README updated in the previous commit, so the pre-push prettier hook passes.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q6i3cdhKBoUrKxy4rmx6hH
2026-07-13 10:50:48 +02:00
ef892eb162 phone_focus_mode: block hotspot/tethering to close the second-phone bypass
The focus system only ever filtered this phone's own traffic: /system/etc/hosts
via the system resolver, dns_enforcer and the curfew net layer via OUTPUT. A
tethered second phone's packets are FORWARDed + NAT'd through us on a path none
of that covers, so a second phone on the hotspot browses freely on our mobile
data and defeats focus mode.

Add tether_enforcer.sh: an always-on daemon that acts while focus mode is ON
(at home) or a force-test file is present, converging three levers each tick:
  1. disable Android tether offload (settings global tether_offload_disabled=1,
     snapshot/restore) so forwarded traffic goes through netfilter;
  2. blanket REJECT of the FORWARD chain (iptables + ip6tables, FOCUS_TETHER_BLOCK
     pinned at position 1), rebuilt only when tampered via a chain_intact gate so
     it does not fork an `iptables -L` every second (that overheated the phone
     during curfew-net tuning). Covers WiFi, USB and BT tethering;
  3. best-effort `cmd wifi stop-softap` (Android 11+) so the hotspot visibly
     flips off.
Reverts offload + tears down FORWARD on transition away from home / on SIGTERM.

Wiring: config.sh flags, focus_ctl.sh (tether-status/start/stop/log/test-on/off),
magisk_service.sh boot autostart, deploy.sh push/cp/restart. README section and
a working subprocess regression test (lib/tests/test_tether_enforcer.sh, 17/17).

Verified on-device (BL9000, Android 13): our REJECT jump sits ABOVE Android's
tetherctrl_FORWARD chain, tether_offload_disabled=1 took effect, and
`cmd wifi stop-softap` reports "Soft AP stopped successfully".

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q6i3cdhKBoUrKxy4rmx6hH
2026-07-13 10:48:59 +02:00
11 changed files with 1148 additions and 17 deletions

View File

@ -0,0 +1,453 @@
<title>Explaining: the hotspot / tethering block</title>
<style>
:root {
--bg: #ffffff; --fg: #1a1c20; --muted: #5b6270; --card: #f6f7f9;
--border: #e2e5ea; --accent: #2f6fed; --ok: #1a7f4b; --bad: #c0362c;
--ok-bg: #e7f5ee; --bad-bg: #fbeae8; --code: #f0f2f5; --chain: #eef1f6;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14161a; --fg: #e6e8ec; --muted: #9aa2b1; --card: #1c1f25;
--border: #2b2f38; --accent: #6ea0ff; --ok: #52c98a; --bad: #ff7a6e;
--ok-bg: #14301f; --bad-bg: #3a1815; --code: #1a1d23; --chain: #1a1e26;
}
}
:root[data-theme="light"] {
--bg: #ffffff; --fg: #1a1c20; --muted: #5b6270; --card: #f6f7f9;
--border: #e2e5ea; --accent: #2f6fed; --ok: #1a7f4b; --bad: #c0362c;
--ok-bg: #e7f5ee; --bad-bg: #fbeae8; --code: #f0f2f5; --chain: #eef1f6;
}
:root[data-theme="dark"] {
--bg: #14161a; --fg: #e6e8ec; --muted: #9aa2b1; --card: #1c1f25;
--border: #2b2f38; --accent: #6ea0ff; --ok: #52c98a; --bad: #ff7a6e;
--ok-bg: #14301f; --bad-bg: #3a1815; --code: #1a1d23; --chain: #1a1e26;
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--fg);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
line-height: 1.65; font-size: 17px;
}
.wrap { max-width: min(48rem, 92vw); margin: 0 auto; padding: 2rem 0 5rem; }
h1 { font-size: 1.9rem; line-height: 1.2; margin: 0 0 .3rem; }
h2 { font-size: 1.4rem; margin: 2.6rem 0 .8rem; padding-top: .6rem; border-top: 1px solid var(--border); }
h3 { font-size: 1.08rem; margin: 1.6rem 0 .5rem; }
p, li { color: var(--fg); }
.sub { color: var(--muted); margin: 0 0 1.6rem; }
a { color: var(--accent); }
code { background: var(--code); padding: .12em .4em; border-radius: 4px; font-size: .88em;
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; }
pre { background: var(--code); border: 1px solid var(--border); border-radius: 8px;
padding: .9rem 1rem; overflow-x: auto; white-space: pre-wrap; word-break: break-word;
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: .82rem; line-height: 1.5; }
.toc { background: var(--card); border: 1px solid var(--border); border-radius: 10px;
padding: .8rem 1.1rem; margin: 1.4rem 0 0; }
.toc ol { margin: .3rem 0; padding-left: 1.3rem; }
.toc a { text-decoration: none; }
.card { background: var(--card); border: 1px solid var(--border); border-radius: 10px;
padding: 1rem 1.2rem; margin: 1.2rem 0; }
.muted { color: var(--muted); }
.tag { display: inline-block; font-size: .72rem; font-weight: 600; letter-spacing: .03em;
text-transform: uppercase; padding: .12em .5em; border-radius: 5px; border: 1px solid var(--border);
color: var(--muted); }
/* diagram */
.flow { display: flex; flex-wrap: wrap; gap: .6rem; align-items: stretch; margin: 1rem 0; }
.node { flex: 1 1 150px; background: var(--card); border: 1px solid var(--border);
border-radius: 9px; padding: .7rem .8rem; min-width: 140px; }
.node .h { font-weight: 700; font-size: .92rem; margin-bottom: .2rem; }
.node .d { font-size: .8rem; color: var(--muted); }
.node.ok { border-color: var(--ok); }
.node.bad { border-color: var(--bad); }
.arrow { align-self: center; color: var(--muted); font-size: 1.3rem; padding: 0 .1rem; }
/* chain sim */
.sim { border: 1px solid var(--border); border-radius: 12px; padding: 1.1rem 1.2rem; margin: 1.4rem 0;
background: var(--card); }
.sim .controls { display: flex; flex-wrap: wrap; gap: .5rem; margin-bottom: .9rem; align-items: center; }
.btn { font: inherit; font-size: .9rem; cursor: pointer; border: 1px solid var(--border);
background: var(--bg); color: var(--fg); padding: .45rem .8rem; border-radius: 8px; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
.btn:active { transform: translateY(1px); }
.toggle { display: inline-flex; align-items: center; gap: .4rem; font-size: .9rem; margin-left: auto; }
.chain { display: flex; flex-direction: column; gap: .35rem; margin: .6rem 0; }
.rule { display: flex; align-items: center; gap: .6rem; border: 1px solid var(--border);
border-radius: 8px; padding: .45rem .7rem; background: var(--chain); font-size: .85rem;
font-family: ui-monospace, Menlo, monospace; transition: background .15s, border-color .15s; }
.rule .verdict { margin-left: auto; font-size: .74rem; font-family: -apple-system, sans-serif;
color: var(--muted); }
.rule.active { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 12%, var(--chain)); }
.rule.hit-ok { border-color: var(--ok); background: var(--ok-bg); }
.rule.hit-bad { border-color: var(--bad); background: var(--bad-bg); }
.rule.skipped { opacity: .45; }
.packet { font-size: .9rem; margin: .3rem 0 .2rem; }
.result { font-weight: 700; margin-top: .5rem; font-size: .95rem; }
.result.ok { color: var(--ok); }
.result.bad { color: var(--bad); }
/* quiz */
.q { border: 1px solid var(--border); border-radius: 10px; padding: 1rem 1.2rem; margin: 1rem 0; }
.q .stem { font-weight: 600; margin-bottom: .6rem; }
.opt { display: block; width: 100%; text-align: left; font: inherit; font-size: .92rem;
border: 1px solid var(--border); background: var(--bg); color: var(--fg);
padding: .55rem .75rem; border-radius: 8px; margin: .4rem 0; cursor: pointer; }
.opt:hover { border-color: var(--accent); }
.opt.correct { border-color: var(--ok); background: var(--ok-bg); }
.opt.wrong { border-color: var(--bad); background: var(--bad-bg); }
.opt:disabled { cursor: default; }
.rationale { font-size: .85rem; color: var(--muted); margin-top: .5rem; display: none; }
.rationale.show { display: block; }
.score { position: sticky; top: 0; background: var(--bg); padding: .5rem 0; z-index: 5;
border-bottom: 1px solid var(--border); font-size: .9rem; }
.themebtn { float: right; font-size: .8rem; }
kbd { background: var(--code); border: 1px solid var(--border); border-bottom-width: 2px;
border-radius: 4px; padding: 0 .35em; font-size: .82em; }
</style>
<div class="wrap">
<button class="btn themebtn" id="themebtn" title="Toggle theme">◐ theme</button>
<span class="tag">phone_focus_mode · shell / netfilter</span>
<h1>Closing the hotspot bypass</h1>
<p class="sub">How a new <code>tether_enforcer.sh</code> stops a second phone on the hotspot from walking straight around focus mode — and why it lives in the <code>FORWARD</code> chain, not <code>OUTPUT</code>.</p>
<nav class="toc">
<strong>Contents</strong>
<ol>
<li><a href="#background">Background — what focus mode already blocked</a></li>
<li><a href="#intuition">Intuition — the blind spot, and the fix</a></li>
<li><a href="#sim">Play — walk a packet through <code>FORWARD</code></a></li>
<li><a href="#code">Code — the gate, the three levers, the wiring</a></li>
<li><a href="#quiz">Quiz</a></li>
</ol>
</nav>
<h2 id="background">1 · Background</h2>
<p><strong>phone_focus_mode</strong> is a location-gated app blocker for a rooted Android phone (Magisk). When the phone is within ~150&nbsp;m of home it enters <em>focus mode</em>: a daemon <code>pm disable-user</code>s every app that isn't whitelisted, and several always-on "enforcer" daemons harden the phone further. The change lives entirely in this subsystem.</p>
<p>Three of those enforcers are about the <em>network</em>, and all three share a hidden assumption. To see it you need one idea from the Linux firewall (<code>netfilter</code>): every IP packet the kernel handles passes through one of a few <strong>chains</strong>, depending on where it's going.</p>
<div class="flow">
<div class="node"><div class="h">OUTPUT</div><div class="d">Packets this phone <em>originates</em> — its own apps talking to the internet.</div></div>
<div class="node"><div class="h">INPUT</div><div class="d">Packets addressed <em>to</em> this phone.</div></div>
<div class="node ok"><div class="h">FORWARD</div><div class="d">Packets merely <em>routed through</em> this phone — the tethering / NAT path.</div></div>
</div>
<p>Here is what each existing layer actually inspects, straight from the scripts:</p>
<ul>
<li><code>hosts_enforcer.sh</code> locks <code>/system/etc/hosts</code> — but that file is only consulted by <em>this phone's</em> system resolver.</li>
<li><code>dns_enforcer.sh</code> blocks DoH/DoT by adding rules to the <code>OUTPUT</code> chain.</li>
<li>the curfew net layer in <code>curfew_enforcer.sh</code> is a per-UID allow-list, also on <code>OUTPUT</code>.</li>
</ul>
<p>Every one of them filters traffic the phone <em>sends on its own behalf</em>. None of them touches <code>FORWARD</code>. That is the seam the bug slips through.</p>
<h2 id="intuition">2 · Intuition</h2>
<p>Turn the phone into a Wi-Fi hotspot and connect a second phone to it. Now the second phone's packets don't <em>originate</em> on your phone — they arrive over Wi-Fi, get NAT'd, and leave over mobile data. They are <strong>forwarded</strong>, so they travel the <code>FORWARD</code> chain, which nobody was guarding. The second phone browses YouTube freely on your data while your own phone sits there dutifully blocked.</p>
<div class="card">
<span class="tag">before</span>
<div class="flow" style="margin-top:.7rem">
<div class="node bad"><div class="h">📱 2nd phone</div><div class="d">wants youtube.com</div></div>
<div class="arrow">→</div>
<div class="node"><div class="h">🔁 FORWARD</div><div class="d">no rules here — packet sails through</div></div>
<div class="arrow">→</div>
<div class="node bad"><div class="h">🌐 internet</div><div class="d">reached. bypass complete.</div></div>
</div>
</div>
<p>The fix is a fourth enforcer, <code>tether_enforcer.sh</code>. While focus mode is on (i.e. you're home), it does three things every few seconds, and it's careful to be reversible the moment you leave:</p>
<div class="flow">
<div class="node ok"><div class="h">1 · offload off</div><div class="d">Disable Android's tether hardware offload so forwarded packets actually reach netfilter.</div></div>
<div class="node ok"><div class="h">2 · FORWARD reject</div><div class="d">Insert a blanket <code>REJECT</code> at the <em>top</em> of <code>FORWARD</code>.</div></div>
<div class="node ok"><div class="h">3 · stop softAP</div><div class="d">Best-effort tear the hotspot down so it visibly flips off.</div></div>
</div>
<div class="card">
<span class="tag">after</span>
<div class="flow" style="margin-top:.7rem">
<div class="node"><div class="h">📱 2nd phone</div><div class="d">wants youtube.com</div></div>
<div class="arrow">→</div>
<div class="node ok"><div class="h">🔁 FORWARD</div><div class="d"><code>FOCUS_TETHER_BLOCK</code> is rule&nbsp;#1 → REJECT</div></div>
<div class="arrow">→</div>
<div class="node ok"><div class="h">🚫 dropped</div><div class="d">no internet. bypass closed.</div></div>
</div>
</div>
<p>Two subtleties make or break this, and both are addressed in the code:</p>
<ul>
<li><strong>Ordering.</strong> Android's own tethering machinery adds an <em>accept</em> rule to <code>FORWARD</code> (<code>tetherctrl_FORWARD</code>). Our reject only wins if it's evaluated first — so it's inserted at position&nbsp;1, above Android's rules. Verified on-device: our jump sits on line 2 of <code>FORWARD</code>, Android's on line 6.</li>
<li><strong>Offload.</strong> Modern phones can shove forwarded traffic through a hardware/BPF fast path that <em>skips netfilter entirely</em>. If we only added the reject rule, it might never fire. Setting <code>tether_offload_disabled=1</code> forces the slow path so the rule bites.</li>
</ul>
<h2 id="sim">3 · Play: walk a packet through <code>FORWARD</code></h2>
<p>Pick who is sending, toggle focus mode, and step the packet down the chain. Notice that the <em>phone's own</em> traffic never enters <code>FORWARD</code> at all — which is exactly why a blanket reject here is safe.</p>
<div class="sim" id="sim">
<div class="controls">
<button class="btn" id="src-own">📱 phone's own packet</button>
<button class="btn primary" id="src-teth">📶 tethered phone's packet</button>
<label class="toggle"><input type="checkbox" id="focus" checked> focus mode ON (home)</label>
</div>
<div class="packet" id="packet"></div>
<div class="chain" id="chain"></div>
<div class="result" id="result"></div>
<div style="margin-top:.7rem; display:flex; gap:.5rem;">
<button class="btn primary" id="step">Step ▸</button>
<button class="btn" id="reset">Reset</button>
</div>
<p class="muted" style="font-size:.8rem; margin:.7rem 0 0">The <code>FOCUS_TETHER_BLOCK</code> rule only exists while focus mode is on — that's the <code>should_act</code> gate. Turn focus off and the chain reverts to Android's defaults.</p>
</div>
<h2 id="code">4 · Code</h2>
<p>~690 lines across 9 files, but it groups into four concerns. The heart is the new <code>tether_enforcer.sh</code>; everything else wires it into the existing machinery.</p>
<h3>a · The gate — when to act</h3>
<p>Like the curfew enforcer, this daemon runs forever but only <em>acts</em> under specific conditions. The gate mirrors <code>curfew_enforcer.sh::should_act</code>, but keyed on focus mode instead of the clock:</p>
<pre>should_act() {
[ "${TETHER_ENFORCER_ENABLED:-0}" = "1" ] || return 1
[ -e "$TETHER_OVERRIDE_FILE" ] && return 1 # escape hatch: suspend
[ -e "$TETHER_FORCE_FILE" ] && return 0 # daytime test hook
at_home # MODE_FILE == "focus"
}</pre>
<p>An <code>override</code> file lets you suspend it without killing the daemon (tethering a laptop at home); a <code>force</code> file lets you validate the whole stack in daylight without waiting to be home.</p>
<h3>b · The three levers</h3>
<p><strong>Offload</strong> is snapshotted before we touch it, so leaving home restores whatever value you had (mirrors the curfew enforcer's grayscale snapshot/restore):</p>
<pre>apply_offload_off() {
cur="$(settings get global "$TETHER_OFFLOAD_KEY" 2>/dev/null)"
[ "$cur" != "1" ] && settings put global "$TETHER_OFFLOAD_KEY" 1 ...
}</pre>
<p><strong>The FORWARD block</strong> pins one jump at the top of <code>FORWARD</code> and fills a single-rule reject chain. Crucially, it only <em>rebuilds</em> when something has tampered with it — a lesson paid for in the curfew net layer, where flushing every tick pegged <code>netd</code> and overheated the phone:</p>
<pre>chain_intact() { # cheap check: jump present + exactly 1 rule
iptw "$ipt" -C FORWARD -j "$TETHER_IPT_CHAIN" >/dev/null 2>&1 || return 1
actual="$(iptw "$ipt" -S "$TETHER_IPT_CHAIN" | grep -c '^-A')"
[ "$actual" = "1" ]
}
apply_forward_block() {
if chain_intact iptables; then :; # already good — do nothing, no fork
elif ensure_chain iptables && fill_chain iptables icmp-port-unreachable; then
log "iptables (v4) FORWARD block rebuilt (was missing/tampered)"
fi
# ... same for ip6tables
}</pre>
<p><strong>Stopping the softAP</strong> is best-effort and version-gated — <code>cmd wifi stop-softap</code> only exists on Android 11+:</p>
<pre>stop_softap() {
major="$(_android_major "$(getprop ro.build.version.release)")"
[ "$major" -ge 11 ] && cmd wifi stop-softap >/dev/null 2>&1 || true
}</pre>
<h3>c · Orchestration — reversible by construction</h3>
<p>A state marker file means the "engage" work logs once, not every tick, and the "revert" only runs on a real transition. On <code>SIGTERM</code> the cleanup path reverts too, so <code>tether-stop</code> is a clean escape hatch:</p>
<pre>enter_block() { # apply all three levers; snapshot offload on first entry
[ -e "$TETHER_ENFORCER_STATE" ] || snapshot_offload
apply_offload_off; apply_forward_block; stop_softap
}
exit_block() { # restore offload, tear down the chain — only if we had applied
[ -e "$TETHER_ENFORCER_STATE" ] || return 0
restore_offload; teardown_forward_block
}
main() { while true; do
if should_act; then enter_block; else exit_block; fi
sleep "$TETHER_CHECK_INTERVAL"
done }</pre>
<h3>d · Wiring &amp; proof</h3>
<p>The rest slots the daemon into the existing lifecycle, following each file's own pattern: <code>config.sh</code> flags; <code>focus_ctl.sh</code> gains <code>tether-status/start/stop/log/test-on/off</code>; <code>magisk_service.sh</code> launches it at boot; <code>deploy.sh</code> pushes, installs and restarts it. Finally <code>lib/tests/test_tether_enforcer.sh</code> runs the real daemon against <em>stubbed</em> Android tools and drives it through all five gate states — 17 assertions, and it's the working sibling of the repo's older, now-stale enforcer tests.</p>
<h2 id="quiz">5 · Quiz</h2>
<div class="score" id="score">Score: 0 / 0</div>
<div id="quiz"></div>
<p class="muted" style="margin-top:2.5rem; font-size:.82rem">Generated as an <code>/explain-diff</code> walkthrough of commit range <code>HEAD~2..HEAD</code> in <code>testsAndMisc</code>. 2026-07-13.</p>
</div>
<script>
(function () {
// ---------- theme toggle ----------
var root = document.documentElement;
document.getElementById('themebtn').addEventListener('click', function () {
var cur = root.getAttribute('data-theme');
var next = cur === 'dark' ? 'light'
: cur === 'light' ? 'dark'
: (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'light' : 'dark');
root.setAttribute('data-theme', next);
});
// ---------- FORWARD chain simulator ----------
var src = 'teth'; // 'own' | 'teth'
var focusOn = true;
var step = -1;
function rules() {
// The chain as it exists for this scenario. Phone's own traffic never
// enters FORWARD, so there is no chain to walk in that case.
var r = [];
if (focusOn) r.push({ t: '-A FORWARD -j FOCUS_TETHER_BLOCK', kind: 'ours' });
r.push({ t: '-A FORWARD -j oem_fwd', kind: 'sys' });
r.push({ t: '-A FORWARD -j tetherctrl_FORWARD', kind: 'accept' });
return r;
}
var packetEl = document.getElementById('packet');
var chainEl = document.getElementById('chain');
var resultEl = document.getElementById('result');
function render() {
if (src === 'own') {
packetEl.innerHTML = '<strong>📱 phone’s own app</strong> → dns.google. This packet is <em>originated</em> here, so the kernel sends it via <strong>OUTPUT</strong> — it never enters FORWARD.';
chainEl.innerHTML = '<div class="rule ' + (step >= 0 ? 'hit-ok' : '') + '">OUTPUT chain (dns_enforcer / curfew handle this)<span class="verdict">not a FORWARD packet</span></div>';
resultEl.className = 'result' + (step >= 0 ? ' ok' : '');
resultEl.textContent = step >= 0 ? '✓ Unaffected by the tether block — the phone’s own traffic is a different chain.' : '';
return;
}
packetEl.innerHTML = '<strong>📶 tethered phone</strong> → youtube.com. NAT’d and <em>forwarded</em>, so it walks the <strong>FORWARD</strong> chain top to bottom:';
var rs = rules();
var reachedReject = false;
chainEl.innerHTML = rs.map(function (rule, i) {
var cls = 'rule';
if (i === step) cls += ' active';
var verdict = '';
if (i <= step) {
if (rule.kind === 'ours') {
cls = i === step ? 'rule hit-bad' : 'rule hit-bad';
verdict = 'REJECT → stop';
reachedReject = true;
} else if (rule.kind === 'accept') {
cls = 'rule hit-ok'; verdict = 'ACCEPT → forwarded';
} else {
cls = 'rule'; verdict = 'no match, continue';
}
}
// grey out rules below a reject we already hit
if (reachedReject && i > rs.findIndex(function (x) { return x.kind === 'ours'; })) cls += ' skipped';
return '<div class="' + cls + '">' + rule.t + '<span class="verdict">' + verdict + '</span></div>';
}).join('');
var rejectIdx = rs.findIndex(function (x) { return x.kind === 'ours'; });
var acceptIdx = rs.findIndex(function (x) { return x.kind === 'accept'; });
if (focusOn && step >= rejectIdx) {
resultEl.className = 'result bad';
resultEl.textContent = '✕ REJECTed at rule #1 — the second phone gets no internet. Bypass closed.';
} else if (!focusOn && step >= acceptIdx) {
resultEl.className = 'result ok';
resultEl.textContent = '✓ ACCEPTed — no FOCUS_TETHER_BLOCK rule exists (focus off), so the old bypass is back.';
} else {
resultEl.className = 'result';
resultEl.textContent = '';
}
}
function setSrc(s) {
src = s; step = -1;
document.getElementById('src-own').classList.toggle('primary', s === 'own');
document.getElementById('src-teth').classList.toggle('primary', s === 'teth');
render();
}
document.getElementById('src-own').addEventListener('click', function () { setSrc('own'); });
document.getElementById('src-teth').addEventListener('click', function () { setSrc('teth'); });
document.getElementById('focus').addEventListener('change', function (e) {
focusOn = e.target.checked; step = -1; render();
});
document.getElementById('step').addEventListener('click', function () {
var max = src === 'own' ? 0 : rules().length - 1;
if (step < max) step++;
render();
});
document.getElementById('reset').addEventListener('click', function () { step = -1; render(); });
render();
// ---------- quiz ----------
var QUIZ = [
{
stem: 'Before this change, why could a second phone on the hotspot reach sites the phone itself blocks?',
options: [
'Android turns off the hosts file automatically whenever a hotspot is active on the device',
'The existing filters watch OUTPUT and the resolver, but tethered traffic crosses FORWARD',
'The curfew network layer only runs between 23:00 and 05:00, leaving daytime unguarded',
'The second phone relied on DNS-over-HTTPS to slip past the dns_enforcer block rules'
],
correct: 1,
why: 'Every prior net layer inspected the phone’s own traffic (OUTPUT / resolver). Forwarded packets travel FORWARD, which nothing guarded.'
},
{
stem: 'What does inserting the jump at position 1 of the FORWARD chain accomplish?',
options: [
'It rewrites the NAT table so tethered clients receive a private, unroutable IP address',
'It prevents the phone’s own apps from opening any brand-new outbound network sockets',
'Our REJECT is evaluated before Android’s tetherctrl_FORWARD accept rules run',
'It causes the hotspot password to rotate on every tick of the enforcer loop'
],
correct: 2,
why: 'Android’s tethering adds an ACCEPT to FORWARD. Chains are top-to-bottom, so our REJECT must sit above it to win — hence position 1.'
},
{
stem: 'Why does the enforcer also disable Android’s tether offload?',
options: [
'Offload can shunt forwarded packets around netfilter, so the FORWARD rule might never fire',
'Offload keeps the CPU awake through the night and drains the phone’s battery too quickly',
'Switching offload off is the actual mechanism that stops the Wi-Fi hotspot from starting',
'It frees the xtables lock so that netd stops rewriting the whole filter table so frequently'
],
correct: 0,
why: 'A hardware/BPF fast path can bypass netfilter entirely. Disabling offload forces the slow path so the REJECT rule actually applies.'
},
{
stem: 'Why rebuild the FORWARD chain only when chain_intact reports it was tampered with?',
options: [
'Because ip6tables and iptables are not allowed to hold the same chain name at once',
'Flushing and refilling on every tick pegs netd and overheats the phone over time',
'The chain must be completely torn down first before the offload snapshot is restored',
'Rebuilding would wipe the heartbeat counter that the status command reads each run'
],
correct: 1,
why: 'The curfew net layer proved that flushing every tick pins netd’s CPU and overheats the device. The intact-check skips redundant rebuilds.'
},
{
stem: 'When the phone leaves home and current_mode is no longer "focus", the enforcer:',
options: [
'keeps the FORWARD block pinned in place until the next full device reboot clears it',
'leaves all of its rules applied but writes a warning line telling you that you are away',
'disables focus mode itself and re-enables every app the daemon had previously blocked',
'restores the snapshotted offload value and tears the FORWARD chain down'
],
correct: 3,
why: 'should_act returns false, so exit_block runs: it restores the offload snapshot and removes the chain, leaving tethering usable again.'
}
];
var quizEl = document.getElementById('quiz');
var scoreEl = document.getElementById('score');
var answered = 0, correct = 0;
QUIZ.forEach(function (q, qi) {
var box = document.createElement('div');
box.className = 'q';
var stem = document.createElement('div');
stem.className = 'stem';
stem.textContent = (qi + 1) + '. ' + q.stem;
box.appendChild(stem);
var done = false;
q.options.forEach(function (opt, oi) {
var b = document.createElement('button');
b.className = 'opt';
b.textContent = opt;
b.addEventListener('click', function () {
if (done) return;
done = true; answered++;
var buttons = box.querySelectorAll('.opt');
buttons.forEach(function (bb, bi) {
bb.disabled = true;
if (bi === q.correct) bb.classList.add('correct');
else if (bi === oi) bb.classList.add('wrong');
});
if (oi === q.correct) correct++;
var rat = box.querySelector('.rationale');
rat.classList.add('show');
rat.textContent = (oi === q.correct ? '✓ Correct. ' : '✕ Not quite. ') + q.why;
scoreEl.textContent = 'Score: ' + correct + ' / ' + answered;
});
box.appendChild(b);
});
var rat = document.createElement('div');
rat.className = 'rationale';
box.appendChild(rat);
quizEl.appendChild(box);
});
})();
</script>

View File

@ -30,8 +30,12 @@
<div class="wrap">
<div class="kicker">explanations</div>
<h1>Change explanations</h1>
<p class="lead">2 explanations · interactive walkthroughs of notable changes, newest first.</p>
<p class="lead">3 explanations · interactive walkthroughs of notable changes, newest first.</p>
<div class="grid">
<a class="card" href="2026-07-13-explanation-tether-hotspot-block.html">
<span class="date">2026-07-13</span>
<span class="title">Explaining: the hotspot / tethering block</span>
</a>
<a class="card" href="2026-07-12-explanation-dufs-cloud.html">
<span class="date">2026-07-12</span>
<span class="title">Self-hosted dufs cloud + KeePass WebDAV sync — explained</span>

View File

@ -0,0 +1,18 @@
{
"title": "Block hotspot/tethering to close the phone-focus second-phone bypass",
"objective": "Add a tether_enforcer to phone_focus_mode that stops a tethered second phone from bypassing focus mode. Nothing filtered forwarded/NAT'd traffic before; the enforcer cuts it off while focus mode is ON at home. Success = a second phone on bl-9000's hotspot cannot reach the internet while at home, and the phone's own connectivity is unaffected.",
"acceptance_criteria": [
"tether_enforcer.sh self-gates on focus mode (MODE_FILE == focus) or a force-test file, and no-ops away from home.",
"While active it disables tether offload, pins a blanket REJECT on the FORWARD chain (iptables + ip6tables) above Android's tetherctrl_FORWARD, and best-effort stops the softAP.",
"The FORWARD chain is rebuilt only when tampered (chain_intact gate) so it does not fork iptables every tick.",
"On transition away from home / SIGTERM it restores the offload snapshot and tears down the FORWARD chain.",
"Wired into config.sh, focus_ctl.sh (tether-* commands), magisk_service.sh autostart, and deploy.sh push/cp/restart."
],
"out_of_scope": [
"Filtering the tethered device's DNS/hosts (full cutoff is used instead).",
"A companion-app (focus_status_app) button.",
"Persistent pm disable of any package (BL9000 MTK bootloop risk).",
"Fixing the pre-existing stale lib/tests/test_dns_enforcer.sh / test_magisk_service.sh mismatch."
],
"verifier": "bash phone_focus_mode/lib/tests/test_tether_enforcer.sh (17 assertions) + pre-commit + on-device: focus_ctl.sh tether-status / iptables -S FORWARD on BL9000"
}

View File

@ -0,0 +1,34 @@
{
"intent": "Close the focus-mode bypass where enabling bl-9000's WiFi hotspot lets a second phone browse freely on the phone's mobile data, since no existing layer filters forwarded/tethered traffic.",
"scope": [
"phone_focus_mode/tether_enforcer.sh (new always-on enforcer)",
"phone_focus_mode/config.sh, focus_ctl.sh, magisk_service.sh, deploy.sh, README.md (wiring)",
"Non-goal: filtering the tethered device's DNS (full cutoff instead); no companion-app button; no persistent package-disable (BL9000 MTK bootloop risk)"
],
"changes": [
"tether_enforcer.sh: self-gates on focus mode (MODE_FILE == focus) or a force-test file; converges three levers each tick: disable Android tether offload (settings global tether_offload_disabled=1, snapshot/restore), blanket REJECT of the FORWARD chain on iptables+ip6tables (chain FOCUS_TETHER_BLOCK, rebuilt only when tampered via chain_intact gate to avoid netd fork-storm), and best-effort 'cmd wifi stop-softap' (Android 11+). Reverts offload + tears down FORWARD on transition away from home / on SIGTERM.",
"config.sh: TETHER_ENFORCER_ENABLED/CHECK_INTERVAL/LOG/STATE/OFFLOAD_KEY/OFFLOAD_SNAP/IPT_CHAIN/STOP_SOFTAP_ENABLED/OVERRIDE_FILE/FORCE_FILE.",
"focus_ctl.sh: tether-status/start/stop/log/test-on/test-off commands + tether_enforcer_pid helper + case/usage entries.",
"magisk_service.sh: chmod + setsid autostart at boot. deploy.sh: push/cp/chmod/log-touch/kill/restart wiring."
],
"verification": [
{
"command": "local run harness with stubbed settings/iptables/ip6tables/cmd/getprop, driving the daemon through away/force-on/revert/focus/override",
"result": "pass",
"evidence": "18/18 assertions pass: gate correct in all 5 scenarios; offload snapshot(null)->set(1)->restore(delete); FORWARD jump pinned+torn down on v4+v6; exactly 1 REJECT rule (no rebuild loop); stop-softap invoked."
},
{
"command": "on-device (BL9000, Android 13, USB adb+Magisk su): install + focus_ctl.sh tether-start + tether-status + iptables -S FORWARD",
"result": "pass",
"evidence": "Enforcer RUNNING; block ACTIVE at home. 'iptables -S FORWARD' shows '-A FORWARD -j FOCUS_TETHER_BLOCK' ABOVE '-A FORWARD -j tetherctrl_FORWARD' (our REJECT precedes Android's tether-accept). tether_offload_disabled=1. FOCUS_TETHER_BLOCK REJECT present on v4+v6. 'cmd wifi stop-softap' -> 'Soft AP stopped successfully'."
}
],
"risks": [
"Hardware/BPF tether offload could bypass the FORWARD rule on some ROMs; mitigated by disabling offload (key confirmed present on this ROM) and by actively stopping the softAP (confirmed working). Definitive second-phone end-to-end check is the on-device validation step.",
"Blocks legitimate at-home tethering (e.g. a work laptop) by design (user chose 'block whenever at home'); escape hatch is focus_ctl.sh tether-stop over ADB or a tether_override file."
],
"rollback": [
"focus_ctl.sh tether-stop tears down the FORWARD chain and restores offload; set TETHER_ENFORCER_ENABLED=0 in config.sh and redeploy to disable permanently.",
"After rollback validate: iptables -S FORWARD shows no FOCUS_TETHER_BLOCK jump; a tethered device reaches the internet again."
]
}

View File

@ -109,15 +109,15 @@ script doesn't need this flag because `post-fs-data` already runs there.
## File layout
| File | Purpose |
| ------------------- | ------------------------------------------------------ |
| `config.sh` | Coordinates, radius, whitelist, constants |
| `focus_daemon.sh` | Main daemon — runs on device, loops every 60s |
| `focus_ctl.sh` | Control utility — runs on device |
| `curfew_enforcer.sh`| Night-curfew enforcer — grayscale + DND + optional net |
| `hosts_enforcer.sh` | Bind-mounts `hosts.canonical` over `/system/etc/hosts` |
| `magisk_service.sh` | Magisk boot hook → auto-starts both daemons |
| `deploy.sh` | PC-side ADB deployment and control script |
| File | Purpose |
| -------------------- | ------------------------------------------------------ |
| `config.sh` | Coordinates, radius, whitelist, constants |
| `focus_daemon.sh` | Main daemon — runs on device, loops every 60s |
| `focus_ctl.sh` | Control utility — runs on device |
| `curfew_enforcer.sh` | Night-curfew enforcer — grayscale + DND + optional net |
| `hosts_enforcer.sh` | Bind-mounts `hosts.canonical` over `/system/etc/hosts` |
| `magisk_service.sh` | Magisk boot hook → auto-starts both daemons |
| `deploy.sh` | PC-side ADB deployment and control script |
## Hosts hardening
@ -159,8 +159,8 @@ scrolling. It activates only when focus mode is already ON (i.e. you are at
home) **and** the local clock is inside the curfew window (default 23:00–05:00).
Out of that window, or away from home, nothing changes.
While the curfew is active it applies three allow-list layers — *block
everything except a short essential list*:
While the curfew is active it applies three allow-list layers — _block
everything except a short essential list_:
1. **Apps.** The daemon swaps the permissive `WHITELIST` for the strict
`NIGHT_WHITELIST` (banking, maps, calendar, clock, authenticators, gov ID,
@ -191,7 +191,7 @@ Edit `NIGHT_WHITELIST` (right below `WHITELIST`) to choose what stays usable at
night. Allow-list by design: when in doubt, leave it out. The active keyboard
and the core dialer/SMS/home apps are always protected automatically (a 1am
reboot can never strand you without a keyboard), and the default browser is
intentionally *not* protected at night so it can be disabled.
intentionally _not_ protected at night so it can be disabled.
### Control
@ -227,6 +227,79 @@ focus_ctl.sh curfew-test-off # blocked apps come BACK (the reconcile path)
The clock parser fails **open** (treated as daytime) on a malformed time, so a
broken `date` can never trap you behind the strict list.
## Hotspot / tethering block (closes the "second phone" bypass)
Every other network layer only filters **this** phone's own traffic:
`/system/etc/hosts` is consulted by the phone's system resolver, and both
`dns_enforcer` and the curfew net layer only touch the **OUTPUT** chain. When
the phone shares its mobile data as a WiFi hotspot, a tethered second phone's
packets are **FORWARDed + NAT'd** through this phone on a path none of that
covers — so the second phone browses freely and defeats focus mode.
`tether_enforcer.sh` closes that hole. It is always-on but **only acts while
focus mode is ON** (i.e. you are at home, `current_mode.txt == focus`), and
converges three levers every `TETHER_CHECK_INTERVAL` seconds:
1. **Disable tether offload** — sets `settings global tether_offload_disabled 1`
so forwarded traffic is actually seen by netfilter instead of being shunted
around it by the hardware/BPF fast path. Snapshotted on entry, restored on
exit.
2. **FORWARD blanket REJECT** — an `iptables`/`ip6tables` chain
(`FOCUS_TETHER_BLOCK`) pinned at position 1 of `FORWARD`, rejecting all
forwarded packets. This is the version-independent catch-all and covers
**WiFi, USB and Bluetooth** tethering. The phone's own traffic uses
OUTPUT/INPUT, never FORWARD, so normal connectivity is untouched. Rebuilt
only when tampered (chain-intact gate), so it does not fork an `iptables -L`
every second (that pegged netd and overheated the phone during curfew-net
tuning).
3. **Stop the softAP** (best-effort, WiFi only, Android 11+) — `cmd wifi
stop-softap` each tick so the hotspot toggle visibly flips back off.
On the transition away from home it restores the offload snapshot and tears the
FORWARD chain down, leaving tethering usable.
### Configuration (`config.sh`)
```sh
TETHER_ENFORCER_ENABLED=1 # master switch
TETHER_CHECK_INTERVAL=5 # re-assert cadence (seconds)
TETHER_STOP_SOFTAP_ENABLED=1 # also actively kill a running softAP
```
### Control
```bash
focus_ctl.sh tether-status # enforcer state, offload flag, FORWARD chain
focus_ctl.sh tether-test-on # FORCE the block now (daytime validation)
focus_ctl.sh tether-test-off # clear the force
focus_ctl.sh tether-stop # escape hatch: stop it, restore tethering
focus_ctl.sh tether-start # (re)start the enforcer
focus_ctl.sh tether-log # enforcer log
```
The escape hatch is `tether-stop` over ADB (or a fresh `deploy.sh`), consistent
with `dns_enforcer`/`launcher_enforcer` — there is no companion-app button.
`tether_override` (created manually) suspends the block without stopping the
daemon.
### Validating before you trust it
Because Android's tether offload can silently skip the FORWARD rule on some
ROMs, validate on-device with a **real second phone** — do not trust rule
counts:
```bash
focus_ctl.sh tether-test-on # hotspot on + second phone browsing → it loses
# internet within one interval; this phone stays
# online. Watch: focus_ctl.sh tether-log
focus_ctl.sh tether-test-off # forwarding restored, second phone browses again
```
If the second phone keeps browsing with the block applied, offload is being
bypassed: confirm the exact global key with
`adb shell su -c 'settings list global | grep -i offload'` and update
`TETHER_OFFLOAD_KEY` in `config.sh`.
## Updating
After editing `config.sh` (e.g. changing whitelist):

View File

@ -111,6 +111,42 @@ export CURFEW_NET_UID_CACHE="$STATE_DIR/curfew_net_uids.txt"
# the day. `curfew-test-off` removes it.
export CURFEW_FORCE_FILE="$STATE_DIR/curfew_force_on"
# ============================================================
# HOTSPOT / TETHERING BLOCK (closes the "second phone" bypass)
# ============================================================
# The hosts file, dns_enforcer and the curfew net layer all only touch this
# phone's OWN traffic (system resolver + OUTPUT chain). A tethered second
# device's packets are FORWARDed + NAT'd through us on an unfiltered path, so
# it browses freely on our mobile data. tether_enforcer.sh closes that hole.
# Always-on like dns_enforcer, but only ACTS while focus mode is ON (i.e. you
# are at home: $MODE_FILE == "focus") OR the force-test file is present. Covers
# WiFi, USB and Bluetooth tethering, since all of it traverses FORWARD.
export TETHER_ENFORCER_ENABLED=1
export TETHER_CHECK_INTERVAL=5
export TETHER_LOG="$STATE_DIR/tether_enforcer.log"
export TETHER_ENFORCER_STATE="$STATE_DIR/tether_applied"
# Lever 1: disable Android's hardware/BPF tether offload so forwarded traffic
# is actually seen by netfilter (otherwise the FORWARD rule can be silently
# skipped). AOSP global key Settings.Global.TETHER_OFFLOAD_DISABLED; 1=disabled.
# Snapshotted on entry and restored on exit so we never clobber a user value.
export TETHER_OFFLOAD_KEY="tether_offload_disabled"
export TETHER_OFFLOAD_SNAP="$STATE_DIR/tether_offload.snap"
# Lever 2: blanket REJECT of the FORWARD chain (both iptables + ip6tables).
# Re-pinned only when tampered (chain_intact gate, like dns_enforcer) so we do
# not fork an `iptables -L` every second — that pegged netd + overheated the
# phone during curfew-net tuning (see CURFEW_NET_REASSERT_INTERVAL note above).
export TETHER_IPT_CHAIN="FOCUS_TETHER_BLOCK"
# Lever 3 (best-effort, WiFi only): actively stop a running softAP each tick so
# the hotspot toggle visibly flips off. Version-gated (cmd wifi stop-softap is
# Android 11+). The FORWARD block remains the version-independent catch-all.
export TETHER_STOP_SOFTAP_ENABLED=1
# Escape hatches (mirrors the curfew override/force pair):
# tether_override -> suspend the block without stopping the daemon.
# tether_force_on -> force the block ACTIVE regardless of location (daytime
# on-device validation via `focus_ctl.sh tether-test-on`).
export TETHER_OVERRIDE_FILE="$STATE_DIR/tether_override"
export TETHER_FORCE_FILE="$STATE_DIR/tether_force_on"
# --- Boot-time autostart safety gate ---
# Critical safety default: do NOT auto-start focus daemons at boot unless
# explicitly enabled. This avoids device instability during early boot on

View File

@ -374,6 +374,7 @@ do_deploy() {
adb_cmd push "$SCRIPT_DIR/dns_enforcer.sh" "/data/local/tmp/focus_stage/dns_enforcer.sh"
adb_cmd push "$SCRIPT_DIR/launcher_enforcer.sh" "/data/local/tmp/focus_stage/launcher_enforcer.sh"
adb_cmd push "$SCRIPT_DIR/curfew_enforcer.sh" "/data/local/tmp/focus_stage/curfew_enforcer.sh"
adb_cmd push "$SCRIPT_DIR/tether_enforcer.sh" "/data/local/tmp/focus_stage/tether_enforcer.sh"
adb_cmd push "$SCRIPT_DIR/workout_detector.sh" "/data/local/tmp/focus_stage/workout_detector.sh"
adb_cmd push "$SCRIPT_DIR/magisk_service.sh" "/data/local/tmp/focus_stage/99-focus-mode.sh"
@ -486,6 +487,7 @@ do_deploy() {
adb_root "cp /data/local/tmp/focus_stage/dns_enforcer.sh $REMOTE_DIR/dns_enforcer.sh"
adb_root "cp /data/local/tmp/focus_stage/launcher_enforcer.sh $REMOTE_DIR/launcher_enforcer.sh"
adb_root "cp /data/local/tmp/focus_stage/curfew_enforcer.sh $REMOTE_DIR/curfew_enforcer.sh"
adb_root "cp /data/local/tmp/focus_stage/tether_enforcer.sh $REMOTE_DIR/tether_enforcer.sh"
adb_root "cp /data/local/tmp/focus_stage/workout_detector.sh $REMOTE_DIR/workout_detector.sh"
if adb_cmd shell "test -f /data/local/tmp/focus_stage/sqlite3" 2>/dev/null; then
adb_root "cp /data/local/tmp/focus_stage/sqlite3 $REMOTE_DIR/sqlite3"
@ -572,13 +574,13 @@ do_deploy() {
done; true"
echo "[5/7] Setting permissions..."
adb_root "chmod 755 $REMOTE_DIR/config.sh $REMOTE_DIR/focus_daemon.sh $REMOTE_DIR/focus_ctl.sh $REMOTE_DIR/hosts_enforcer.sh $REMOTE_DIR/dns_enforcer.sh $REMOTE_DIR/launcher_enforcer.sh $REMOTE_DIR/curfew_enforcer.sh $REMOTE_DIR/workout_detector.sh" || true
adb_root "chmod 755 $REMOTE_DIR/config.sh $REMOTE_DIR/focus_daemon.sh $REMOTE_DIR/focus_ctl.sh $REMOTE_DIR/hosts_enforcer.sh $REMOTE_DIR/dns_enforcer.sh $REMOTE_DIR/launcher_enforcer.sh $REMOTE_DIR/curfew_enforcer.sh $REMOTE_DIR/tether_enforcer.sh $REMOTE_DIR/workout_detector.sh" || true
if grep -q '^export FOCUS_BOOT_AUTOSTART=1' "$SCRIPT_DIR/config.sh"; then
adb_root "chmod 755 /data/adb/service.d/99-focus-mode.sh"
fi
adb_root "touch $REMOTE_DIR/disabled_by_focus.txt $REMOTE_DIR/focus_mode.log $REMOTE_DIR/hosts_enforcer.log $REMOTE_DIR/dns_enforcer.log $REMOTE_DIR/launcher_enforcer.log $REMOTE_DIR/workout_detector.log"
adb_root "touch $REMOTE_DIR/disabled_by_focus.txt $REMOTE_DIR/focus_mode.log $REMOTE_DIR/hosts_enforcer.log $REMOTE_DIR/dns_enforcer.log $REMOTE_DIR/launcher_enforcer.log $REMOTE_DIR/tether_enforcer.log $REMOTE_DIR/workout_detector.log"
# State files need 666 so the daemons can write regardless of SELinux context drift
adb_root "chmod 666 $REMOTE_DIR/disabled_by_focus.txt $REMOTE_DIR/focus_mode.log $REMOTE_DIR/hosts_enforcer.log $REMOTE_DIR/dns_enforcer.log $REMOTE_DIR/launcher_enforcer.log $REMOTE_DIR/workout_detector.log" || true
adb_root "chmod 666 $REMOTE_DIR/disabled_by_focus.txt $REMOTE_DIR/focus_mode.log $REMOTE_DIR/hosts_enforcer.log $REMOTE_DIR/dns_enforcer.log $REMOTE_DIR/launcher_enforcer.log $REMOTE_DIR/tether_enforcer.log $REMOTE_DIR/workout_detector.log" || true
echo "[6/7] Starting daemons..."
# Stop existing daemons, then start fresh
@ -587,11 +589,13 @@ do_deploy() {
adb_root "for p in \$(pgrep -f '/data/local/tmp/focus_mode/dns_enforcer.sh' 2>/dev/null); do kill \"\$p\" 2>/dev/null || true; done"
adb_root "for p in \$(pgrep -f '/data/local/tmp/focus_mode/launcher_enforcer.sh' 2>/dev/null); do kill \"\$p\" 2>/dev/null || true; done"
adb_root "for p in \$(pgrep -f '/data/local/tmp/focus_mode/curfew_enforcer.sh' 2>/dev/null); do kill \"\$p\" 2>/dev/null || true; done"
adb_root "for p in \$(pgrep -f '/data/local/tmp/focus_mode/tether_enforcer.sh' 2>/dev/null); do kill \"\$p\" 2>/dev/null || true; done"
adb_root "for p in \$(pgrep -f '/data/local/tmp/focus_mode/workout_detector.sh' 2>/dev/null); do kill \"\$p\" 2>/dev/null || true; done"
adb_root "kill \$(cat $REMOTE_DIR/daemon.pid 2>/dev/null) 2>/dev/null; true"
adb_root "kill \$(cat $REMOTE_DIR/hosts_enforcer.pid 2>/dev/null) 2>/dev/null; true"
adb_root "kill \$(cat $REMOTE_DIR/dns_enforcer.pid 2>/dev/null) 2>/dev/null; true"
adb_root "kill \$(cat $REMOTE_DIR/launcher_enforcer.pid 2>/dev/null) 2>/dev/null; true"
adb_root "kill \$(cat $REMOTE_DIR/tether_enforcer.pid 2>/dev/null) 2>/dev/null; true"
adb_root "kill \$(cat $REMOTE_DIR/workout_detector.pid 2>/dev/null) 2>/dev/null; true"
sleep 1
adb_root "for p in \$(pgrep -f '/data/local/tmp/focus_mode/focus_daemon.sh' 2>/dev/null); do kill -9 \"\$p\" 2>/dev/null || true; done"
@ -599,9 +603,10 @@ do_deploy() {
adb_root "for p in \$(pgrep -f '/data/local/tmp/focus_mode/dns_enforcer.sh' 2>/dev/null); do kill -9 \"\$p\" 2>/dev/null || true; done"
adb_root "for p in \$(pgrep -f '/data/local/tmp/focus_mode/launcher_enforcer.sh' 2>/dev/null); do kill -9 \"\$p\" 2>/dev/null || true; done"
adb_root "for p in \$(pgrep -f '/data/local/tmp/focus_mode/curfew_enforcer.sh' 2>/dev/null); do kill -9 \"\$p\" 2>/dev/null || true; done"
adb_root "for p in \$(pgrep -f '/data/local/tmp/focus_mode/tether_enforcer.sh' 2>/dev/null); do kill -9 \"\$p\" 2>/dev/null || true; done"
adb_root "for p in \$(pgrep -f '/data/local/tmp/focus_mode/workout_detector.sh' 2>/dev/null); do kill -9 \"\$p\" 2>/dev/null || true; done"
sleep 1
adb_root "rm -f $REMOTE_DIR/daemon.pid $REMOTE_DIR/hosts_enforcer.pid $REMOTE_DIR/dns_enforcer.pid $REMOTE_DIR/launcher_enforcer.pid $REMOTE_DIR/workout_detector.pid"
adb_root "rm -f $REMOTE_DIR/daemon.pid $REMOTE_DIR/hosts_enforcer.pid $REMOTE_DIR/dns_enforcer.pid $REMOTE_DIR/launcher_enforcer.pid $REMOTE_DIR/tether_enforcer.pid $REMOTE_DIR/workout_detector.pid"
# Start hosts enforcer first so hosts are locked before user can react.
# Use --mount-master so bind mounts propagate to the global namespace
# (where app processes live). Without this, only our isolated `su` session
@ -628,6 +633,10 @@ do_deploy() {
# Start night-curfew enforcer (grayscale + DND + optional net allow-list).
# Always on; self-gates on the clock + focus mode, no-op during the day.
adb_cmd shell su --mount-master -c 'setsid sh /data/local/tmp/focus_mode/curfew_enforcer.sh </dev/null >/dev/null 2>/dev/null &'
# Start hotspot/tethering enforcer (blocks forwarded/tethered traffic so a
# second phone on our hotspot can't bypass focus mode). Always on; self-gates
# on focus mode, no-op while away from home.
adb_cmd shell su --mount-master -c 'setsid sh /data/local/tmp/focus_mode/tether_enforcer.sh </dev/null >/dev/null 2>/dev/null &'
adb_cmd shell su --mount-master -c 'setsid sh /data/local/tmp/focus_mode/focus_daemon.sh </dev/null >/dev/null 2>/dev/null &'
# Wait for hosts_enforcer to apply the bind mount and restart netd.

View File

@ -89,6 +89,12 @@ usage() {
echo " curfew-demo-off - Stop the demo"
echo " curfew-off - Escape hatch: suspend curfew now (2am opt-out)"
echo " curfew-on - Re-arm curfew (clear the override)"
echo " tether-status - Show hotspot/tethering-block state"
echo " tether-start - Start the tether enforcer (FORWARD block + offload off)"
echo " tether-stop - Stop it and restore tethering (teardown FORWARD chain)"
echo " tether-log - Show tether enforcer log"
echo " tether-test-on - Force the tether block ACTIVE now (daytime validation)"
echo " tether-test-off - Clear the tether force"
echo " notif-status - Show companion status-notification details"
echo ""
}
@ -917,6 +923,102 @@ cmd_curfew_on() {
echo "Curfew re-armed (override cleared)."
}
# ============================================================
# Hotspot / tethering block control (see tether_enforcer.sh)
# ============================================================
TETHER_PIDFILE="$STATE_DIR/tether_enforcer.pid"
tether_enforcer_pid() {
if [ -f "$TETHER_PIDFILE" ]; then
local pid
pid="$(cat "$TETHER_PIDFILE")"
if kill -0 "$pid" 2>/dev/null; then
echo "$pid"
fi
fi
}
cmd_tether_status() {
local pid
pid="$(tether_enforcer_pid)"
echo "=== Hotspot / Tethering Block Status ==="
echo "Enabled: ${TETHER_ENFORCER_ENABLED}"
if [ -n "$pid" ]; then
echo "Enforcer: RUNNING (PID $pid)"
else
echo "Enforcer: STOPPED"
fi
if [ -f "$MODE_FILE" ]; then
echo "Focus mode: $(cat "$MODE_FILE" 2>/dev/null)"
fi
[ -e "$TETHER_FORCE_FILE" ] && echo "Forced ON: YES (test active)"
[ -e "$TETHER_OVERRIDE_FILE" ] && echo "Override: YES (block SUSPENDED)"
[ -e "$TETHER_ENFORCER_STATE" ] && echo "Applied now: YES (offload off + FORWARD reject)" \
|| echo "Applied now: no"
local off
off="$(settings get global "$TETHER_OFFLOAD_KEY" 2>/dev/null)"
echo "tether_offload_disabled: ${off:-<unset>}"
if iptables -C FORWARD -j "$TETHER_IPT_CHAIN" >/dev/null 2>&1; then
echo "iptables $TETHER_IPT_CHAIN: pinned to FORWARD ($(iptables -S "$TETHER_IPT_CHAIN" 2>/dev/null | grep -c '^-A') rule)"
else
echo "iptables $TETHER_IPT_CHAIN: absent (block not applied)"
fi
}
cmd_tether_start() {
local pid
pid="$(tether_enforcer_pid)"
if [ -n "$pid" ]; then
echo "Tether enforcer already running (PID $pid)"
return
fi
setsid sh "$SCRIPT_DIR/tether_enforcer.sh" </dev/null >/dev/null 2>&1 &
sleep 2
pid="$(tether_enforcer_pid)"
if [ -n "$pid" ]; then
echo "Tether enforcer started (PID $pid)"
else
echo "ERROR: tether enforcer failed to start. Check log: $TETHER_LOG"
fi
}
cmd_tether_stop() {
local pid
pid="$(tether_enforcer_pid)"
if [ -z "$pid" ]; then
echo "Tether enforcer not running"
rm -f "$TETHER_PIDFILE"
else
kill -TERM "$pid"
echo "Tether enforcer stopped (sent SIGTERM to PID $pid)"
fi
# Explicit teardown so maintenance can tether even if the daemon was already
# dead (its own TERM handler reverts too; this is the belt-and-suspenders).
iptables -D FORWARD -j "$TETHER_IPT_CHAIN" 2>/dev/null || true
iptables -F "$TETHER_IPT_CHAIN" 2>/dev/null || true
iptables -X "$TETHER_IPT_CHAIN" 2>/dev/null || true
ip6tables -D FORWARD -j "$TETHER_IPT_CHAIN" 2>/dev/null || true
ip6tables -F "$TETHER_IPT_CHAIN" 2>/dev/null || true
ip6tables -X "$TETHER_IPT_CHAIN" 2>/dev/null || true
echo "FORWARD chain $TETHER_IPT_CHAIN removed (tethering restored)"
}
cmd_tether_log() { tail -n "${1:-50}" "$TETHER_LOG" 2>/dev/null || echo "No tether log yet."; }
# Test hook: force the block ACTIVE regardless of location so the full stack can
# be validated during the day with a real second phone on the hotspot.
cmd_tether_test_on() {
touch "$TETHER_FORCE_FILE"; chmod 666 "$TETHER_FORCE_FILE" 2>/dev/null || true
rm -f "$TETHER_OVERRIDE_FILE"
echo "Tether block FORCED ON. Enforcer engages within ${TETHER_CHECK_INTERVAL}s."
echo "Validate: second phone on the hotspot loses internet; this phone stays online."
}
cmd_tether_test_off() {
rm -f "$TETHER_FORCE_FILE"
echo "Tether force cleared. Back to focus-mode-gated behaviour."
}
case "$1" in
start) cmd_start ;;
stop) cmd_stop ;;
@ -956,5 +1058,11 @@ case "$1" in
curfew-demo-off) cmd_curfew_demo_off ;;
curfew-off) cmd_curfew_off ;;
curfew-on) cmd_curfew_on ;;
tether-status) cmd_tether_status ;;
tether-start) cmd_tether_start ;;
tether-stop) cmd_tether_stop ;;
tether-log) cmd_tether_log "${2:-50}" ;;
tether-test-on) cmd_tether_test_on ;;
tether-test-off) cmd_tether_test_off ;;
*) usage ;;
esac

View File

@ -0,0 +1,123 @@
#!/usr/bin/env bash
# Regression test for tether_enforcer.sh.
#
# The enforcer ends in `main "$@"` (an infinite loop), so — like a real deploy —
# we run it as a subprocess with the Android tools it calls (settings, iptables,
# ip6tables, cmd, getprop) replaced by stubs on PATH, and drive it through the
# full gate + apply/revert state machine, asserting observable state each step.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SRC="$SCRIPT_DIR/../../tether_enforcer.sh"
RUN="$(mktemp -d)"
cleanup() {
if [ -n "${PID:-}" ]; then
kill "$PID" 2>/dev/null || true
wait "$PID" 2>/dev/null || true # let its TERM handler finish before rm
fi
rm -rf "$RUN"
}
trap cleanup EXIT
mkdir -p "$RUN/bin" "$RUN/state" "$RUN/ipt" "$RUN/settings" "$RUN/calls" "$RUN/app"
STATE="$RUN/state"
# --- fake config.sh in the daemon's own dir (it sources "$SCRIPT_DIR/config.sh") ---
cp "$SRC" "$RUN/app/tether_enforcer.sh"
cat > "$RUN/app/config.sh" <<EOF
export STATE_DIR="$STATE"
export MODE_FILE="$STATE/current_mode.txt"
export TETHER_ENFORCER_ENABLED=1
export TETHER_CHECK_INTERVAL=1
export TETHER_LOG="$STATE/tether_enforcer.log"
export TETHER_ENFORCER_STATE="$STATE/tether_applied"
export TETHER_OFFLOAD_KEY="tether_offload_disabled"
export TETHER_OFFLOAD_SNAP="$STATE/tether_offload.snap"
export TETHER_IPT_CHAIN="FOCUS_TETHER_BLOCK"
export TETHER_STOP_SOFTAP_ENABLED=1
export TETHER_OVERRIDE_FILE="$STATE/tether_override"
export TETHER_FORCE_FILE="$STATE/tether_force_on"
EOF
# --- stubs ---
cat > "$RUN/bin/settings" <<EOF
#!/usr/bin/env bash
db="$RUN/settings/tether_offload_disabled"
echo "settings \$*" >> "$RUN/calls/settings.log"
case "\$1 \$2" in
"get global") [ -f "\$db" ] && cat "\$db" || echo "null" ;;
"put global") printf '%s' "\$4" > "\$db" ;;
"delete global") rm -f "\$db" ;;
esac
exit 0
EOF
# iptables/ip6tables: minimal chain-state model so chain_intact converges.
cat > "$RUN/bin/iptables" <<EOF
#!/usr/bin/env bash
bin="\$(basename "\$0")"; s="$RUN/ipt/\$bin"; mkdir -p "\$s"
[ "\$1" = "-w" ] && shift 2
case "\$1" in
-L) [ -f "\$s/exists" ] ;;
-N) touch "\$s/exists"; : > "\$s/rules" ;;
-C) [ -f "\$s/jump" ] ;;
-D) if [ -f "\$s/jump" ]; then rm -f "\$s/jump"; exit 0; else exit 1; fi ;;
-I) touch "\$s/jump" ;;
-A) echo "-A rule" >> "\$s/rules" ;;
-F) : > "\$s/rules" ;;
-S) cat "\$s/rules" 2>/dev/null ;;
-X) rm -f "\$s/exists" "\$s/rules" "\$s/jump" ;;
esac
exit \$?
EOF
cp "$RUN/bin/iptables" "$RUN/bin/ip6tables"
printf '#!/usr/bin/env bash\necho "cmd $*" >> "%s/calls/cmd.log"\nexit 0\n' "$RUN" > "$RUN/bin/cmd"
printf '#!/usr/bin/env bash\necho 13\n' > "$RUN/bin/getprop"
chmod +x "$RUN/bin/"*
export PATH="$RUN/bin:$PATH"
PASS=0; FAIL=0
ok() { PASS=$((PASS + 1)); printf ' OK: %s\n' "$1"; }
no() { FAIL=$((FAIL + 1)); printf ' FAIL: %s\n' "$1"; }
applied() { [ -f "$STATE/tether_applied" ]; }
offload() { cat "$RUN/settings/tether_offload_disabled" 2>/dev/null || echo "<unset>"; }
v4jump() { [ -f "$RUN/ipt/iptables/jump" ]; }
v6jump() { [ -f "$RUN/ipt/ip6tables/jump" ]; }
v4rules() { grep -c '^-A' "$RUN/ipt/iptables/rules" 2>/dev/null || echo 0; }
softap() { grep -c 'stop-softap' "$RUN/calls/cmd.log" 2>/dev/null || echo 0; }
sh "$RUN/app/tether_enforcer.sh" & PID=$!
sleep 2
# [A] Away from home -> block OFF
applied && no "A: applied while away" || ok "A: not applied while away"
[ "$(offload)" = "<unset>" ] && ok "A: offload untouched away" || no "A: offload changed away"
v4jump && no "A: v4 jump while away" || ok "A: no v4 jump while away"
# [B] force-on -> block ENGAGES (all three levers)
touch "$STATE/tether_force_on"; sleep 3
applied && ok "B: applied on force" || no "B: not applied on force"
[ "$(offload)" = "1" ] && ok "B: offload disabled" || no "B: offload=$(offload)"
v4jump && ok "B: v4 FORWARD jump pinned" || no "B: no v4 jump"
v6jump && ok "B: v6 FORWARD jump pinned" || no "B: no v6 jump"
[ "$(v4rules)" = "1" ] && ok "B: single REJECT rule (no rebuild loop)" || no "B: v4 rules=$(v4rules)"
[ "$(softap)" -ge 1 ] && ok "B: stop-softap invoked" || no "B: softap not stopped"
[ "$(cat "$STATE/tether_offload.snap" 2>/dev/null)" = "null" ] && ok "B: offload snapshot captured" || no "B: bad snapshot"
# [C] clear force -> block REVERTS
rm -f "$STATE/tether_force_on"; sleep 3
applied && no "C: still applied" || ok "C: reverted on force-clear"
[ "$(offload)" = "<unset>" ] && ok "C: offload restored" || no "C: offload=$(offload)"
v4jump && no "C: v4 jump remains" || ok "C: v4 chain torn down"
# [D] current_mode=focus -> ENGAGES via home gate
echo focus > "$STATE/current_mode.txt"; sleep 3
applied && ok "D: applied at home (focus)" || no "D: not applied at home"
v4jump && ok "D: v4 jump pinned at home" || no "D: no v4 jump at home"
# [E] override -> SUSPENDS even at home
touch "$STATE/tether_override"; sleep 3
applied && no "E: applied despite override" || ok "E: suspended by override"
v4jump && no "E: v4 jump despite override" || ok "E: torn down by override"
printf '\n%d passed, %d failed\n' "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]

View File

@ -18,6 +18,7 @@ chmod +x "$SCRIPT_DIR/hosts_enforcer.sh"
chmod +x "$SCRIPT_DIR/dns_enforcer.sh"
chmod +x "$SCRIPT_DIR/launcher_enforcer.sh"
chmod +x "$SCRIPT_DIR/curfew_enforcer.sh" 2>/dev/null
chmod +x "$SCRIPT_DIR/tether_enforcer.sh" 2>/dev/null
chmod +x "$SCRIPT_DIR/workout_detector.sh" 2>/dev/null
chmod +x "$SCRIPT_DIR/sqlite3" 2>/dev/null
@ -47,6 +48,11 @@ setsid sh "$SCRIPT_DIR/launcher_enforcer.sh" </dev/null >/dev/null 2>&1 &
# self-gates on the clock + focus mode and is a no-op during the day.
setsid sh "$SCRIPT_DIR/curfew_enforcer.sh" </dev/null >/dev/null 2>&1 &
# Start hotspot/tethering enforcer - blocks forwarded (tethered) traffic so a
# second phone on our hotspot can't bypass focus mode. Always on; it self-gates
# on focus mode and is a no-op while away from home.
setsid sh "$SCRIPT_DIR/tether_enforcer.sh" </dev/null >/dev/null 2>&1 &
# Start focus daemon in a new session (detached from any controlling terminal)
setsid sh "$SCRIPT_DIR/focus_daemon.sh" </dev/null >/dev/null 2>&1 &

View File

@ -0,0 +1,267 @@
#!/system/bin/sh
# shellcheck shell=ash
# ============================================================
# Hotspot / tethering enforcer for rooted Android.
#
# Why this exists:
# Every other network layer here only filters THIS phone's own traffic:
# /system/etc/hosts is consulted by the phone's system resolver, and both
# dns_enforcer and the curfew net layer only touch the OUTPUT chain. When the
# phone shares its mobile data as a WiFi/USB/BT hotspot, the tethered device's
# packets are FORWARDed + NAT'd through us on a path none of that covers - so
# a second phone browses freely and defeats focus mode entirely.
#
# Strategy (belt-and-suspenders; all best-effort, converged every tick):
# 1. Disable tether offload (settings global) so forwarded traffic is not
# shunted around netfilter by the hardware/BPF fast path.
# 2. Blanket REJECT of the FORWARD chain (iptables + ip6tables). This is the
# version-independent catch-all and covers WiFi, USB and BT tethering.
# The phone's own traffic uses OUTPUT/INPUT, never FORWARD, so normal
# connectivity is untouched.
# 3. Best-effort actively stop a running softAP (WiFi only; Android 11+) so
# the hotspot toggle visibly flips back off.
#
# Acts ONLY while focus mode is ON ($MODE_FILE == "focus", i.e. at home) or the
# force-test file is present. On the transition away from home it restores the
# offload snapshot and tears the FORWARD chain down, leaving tethering usable.
#
# "Locked" = snap-back: re-toggling the hotspot on is reverted within one tick.
# ============================================================
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
# shellcheck source=config.sh
. "$SCRIPT_DIR/config.sh"
PIDFILE="$STATE_DIR/tether_enforcer.pid"
mkdir -p "$STATE_DIR"
touch "$TETHER_LOG"
chmod 666 "$TETHER_LOG" 2>/dev/null || true
log() {
local ts
ts="$(date '+%Y-%m-%d %H:%M:%S')"
echo "[$ts] $1" >> "$TETHER_LOG"
}
rotate_log() {
local lines
lines="$(wc -l < "$TETHER_LOG" 2>/dev/null || echo 0)"
if [ "$lines" -gt 500 ]; then
local tmp="$TETHER_LOG.tmp"
tail -n 500 "$TETHER_LOG" > "$tmp"
mv "$tmp" "$TETHER_LOG"
fi
}
acquire_lock() {
if [ -f "$PIDFILE" ]; then
local old_pid
old_pid="$(cat "$PIDFILE")"
if kill -0 "$old_pid" 2>/dev/null; then
local cmdline
cmdline="$(tr '\0' ' ' < "/proc/$old_pid/cmdline" 2>/dev/null)"
if echo "$cmdline" | grep -q "tether_enforcer"; then
echo "tether_enforcer already running (PID $old_pid)"
exit 0
fi
fi
rm -f "$PIDFILE"
fi
echo $$ > "$PIDFILE"
}
# ---- Activation gate (mirrors curfew_enforcer.sh::should_act) ----
at_home() {
[ -f "$MODE_FILE" ] && [ "$(cat "$MODE_FILE" 2>/dev/null)" = "focus" ]
}
should_act() {
[ "${TETHER_ENFORCER_ENABLED:-0}" = "1" ] || return 1
[ -e "$TETHER_OVERRIDE_FILE" ] && return 1
# Force hook bypasses the home gate so the full stack can be validated
# during the day from anywhere (`focus_ctl.sh tether-test-on`).
[ -e "$TETHER_FORCE_FILE" ] && return 0
at_home
}
# ---- Lever 1: tether offload ----
apply_offload_off() {
local cur
cur="$(settings get global "$TETHER_OFFLOAD_KEY" 2>/dev/null)"
if [ "$cur" != "1" ]; then
settings put global "$TETHER_OFFLOAD_KEY" 1 2>/dev/null \
&& log "tether offload was '$cur' - forced disabled (=1)"
fi
}
snapshot_offload() {
local cur
cur="$(settings get global "$TETHER_OFFLOAD_KEY" 2>/dev/null)"
printf '%s\n' "${cur:-null}" > "$TETHER_OFFLOAD_SNAP" 2>/dev/null || true
}
restore_offload() {
local snap
[ -f "$TETHER_OFFLOAD_SNAP" ] && snap="$(cat "$TETHER_OFFLOAD_SNAP" 2>/dev/null)"
case "$snap" in
''|null)
# No pre-existing value: clear ours so the OS default returns.
settings delete global "$TETHER_OFFLOAD_KEY" 2>/dev/null || true
;;
*)
settings put global "$TETHER_OFFLOAD_KEY" "$snap" 2>/dev/null || true
;;
esac
}
# ---- Lever 2: FORWARD chain blanket REJECT ----
# Run iptables/ip6tables with a 2s xtables lock-wait so our calls queue for the
# lock instead of silently failing the instant netd holds it (proven necessary
# on-device for the curfew net layer). $1 = binary.
iptw() {
local bin="$1"
shift
"$bin" -w 2 "$@"
}
ensure_chain() {
local ipt="$1"
if ! iptw "$ipt" -L "$TETHER_IPT_CHAIN" >/dev/null 2>&1; then
iptw "$ipt" -N "$TETHER_IPT_CHAIN" 2>/dev/null || {
log "ERROR: could not create $ipt chain $TETHER_IPT_CHAIN"
return 1
}
fi
# De-dupe: remove every existing FORWARD jump, then pin exactly one at #1
# (netd inserts its own tethering rules into FORWARD, so we must be first).
while iptw "$ipt" -D FORWARD -j "$TETHER_IPT_CHAIN" 2>/dev/null; do :; done
iptw "$ipt" -I FORWARD 1 -j "$TETHER_IPT_CHAIN" 2>/dev/null || {
log "ERROR: could not insert FORWARD -> $TETHER_IPT_CHAIN for $ipt"
return 1
}
}
fill_chain() {
local ipt="$1" reject="$2"
iptw "$ipt" -F "$TETHER_IPT_CHAIN" 2>/dev/null || return 1
# Single rule: reject everything that would be forwarded through us.
iptw "$ipt" -A "$TETHER_IPT_CHAIN" -j REJECT --reject-with "$reject" 2>/dev/null || true
}
# Only rebuild when actually tampered (chain missing, unlinked from FORWARD, or
# wrong size). Avoids forking a flush+refill every tick, which pegs netd.
chain_intact() {
local ipt="$1" actual
iptw "$ipt" -C FORWARD -j "$TETHER_IPT_CHAIN" >/dev/null 2>&1 || return 1
actual="$(iptw "$ipt" -S "$TETHER_IPT_CHAIN" 2>/dev/null | grep -c '^-A')"
[ "$actual" = "1" ]
}
apply_forward_block() {
if command -v iptables >/dev/null 2>&1; then
if chain_intact iptables; then :; \
elif ensure_chain iptables && fill_chain iptables icmp-port-unreachable; then
log "iptables (v4) FORWARD block rebuilt (was missing/tampered)"
fi
fi
if command -v ip6tables >/dev/null 2>&1; then
if chain_intact ip6tables; then :; \
elif ensure_chain ip6tables && fill_chain ip6tables icmp6-port-unreachable; then
log "ip6tables (v6) FORWARD block rebuilt (was missing/tampered)"
fi
fi
}
teardown_forward_block() {
local ipt
for ipt in iptables ip6tables; do
command -v "$ipt" >/dev/null 2>&1 || continue
while iptw "$ipt" -D FORWARD -j "$TETHER_IPT_CHAIN" 2>/dev/null; do :; done
iptw "$ipt" -F "$TETHER_IPT_CHAIN" 2>/dev/null || true
iptw "$ipt" -X "$TETHER_IPT_CHAIN" 2>/dev/null || true
done
}
# ---- Lever 3: actively stop the softAP (best-effort, WiFi only) ----
_android_major() {
local ver="${1%%.*}"
case "$ver" in
''|*[!0-9]*) echo 0 ;;
*) echo "$ver" ;;
esac
}
stop_softap() {
[ "${TETHER_STOP_SOFTAP_ENABLED:-0}" = "1" ] || return 0
command -v cmd >/dev/null 2>&1 || return 0
local major
major="$(_android_major "$(getprop ro.build.version.release 2>/dev/null)")"
# `cmd wifi stop-softap` landed in Android 11. Best-effort, idempotent: it
# no-ops (non-zero) when no softAP is running, which we intentionally ignore.
if [ "$major" -ge 11 ]; then
cmd wifi stop-softap >/dev/null 2>&1 || true
else
cmd wifi set-wifi-ap-enabled false >/dev/null 2>&1 || true
fi
}
# ---- Apply / revert orchestration ----
enter_block() {
if [ ! -e "$TETHER_ENFORCER_STATE" ]; then
snapshot_offload
: > "$TETHER_ENFORCER_STATE"
log "Tether block ON (focus mode) - offload off + FORWARD reject${TETHER_STOP_SOFTAP_ENABLED:+ + stop-softap}"
fi
apply_offload_off
apply_forward_block
stop_softap
}
exit_block() {
[ -e "$TETHER_ENFORCER_STATE" ] || return 0
restore_offload
teardown_forward_block
rm -f "$TETHER_ENFORCER_STATE"
log "Tether block OFF - restored offload, tore down FORWARD chain"
}
cleanup() {
# Clean stop leaves tethering usable again (the intuitive escape hatch:
# `focus_ctl.sh tether-stop`).
log "tether_enforcer shutting down - reverting"
exit_block
rm -f "$PIDFILE"
exit 0
}
trap cleanup INT TERM
main() {
acquire_lock
log "tether_enforcer started (PID=$$, enabled=${TETHER_ENFORCER_ENABLED})"
local tick=0 act fwd
while true; do
if should_act; then act=1; enter_block; else act=0; exit_block; fi
# Heartbeat every ~6 ticks (~30s) so "alive but idle" is distinguishable
# from "dead" in the log.
tick=$((tick + 1))
if [ "$((tick % 6))" -eq 0 ]; then
if iptw iptables -C FORWARD -j "$TETHER_IPT_CHAIN" >/dev/null 2>&1; then
fwd=up
else
fwd=down
fi
log "heartbeat tick=$tick act=$act forward=$fwd"
fi
rotate_log
sleep "$TETHER_CHECK_INTERVAL"
done
}
main "$@"