Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Added:
- **Internet schedule** (new page). Turn the internet off at set times of the week for chosen people (all their devices) or single devices: bedtime on school nights, study time, meal times. One click starts from a ready plan ("School nights", "Every night", "Study time", "Meal times"); a schedule can have several times, a time can run past midnight, and dates can be marked as days off (holidays, Eid). **Bonus time** gives a few extra minutes without changing the schedule. **Always allowed** sites (a school platform, a study site) keep working during every schedule. While a schedule is on, the device's card shows when the internet comes back, the home network (printer, shared drives, the dashboard) keeps working, and the cut is done by the gateway itself, so it works on any phone, tablet, TV or console with no app. Each device gets its end time in the system kernel, so it comes back online on time even if the gateway service restarts or stops. Sites on the "always allowed" list only open on devices that look names up through the gateway; a phone with Private DNS (or a browser with secure DNS) turned on keeps them blocked during a schedule. Contributed by @amr-elgharip2006. Closes #32.

Fixed:
- A short hiccup while the gateway updated its list of cut-off devices could switch off counting and blocking for everyone until a restart, or let a cut-off device through for a moment. The list is now changed in one step: if that step fails, the old list stays in force and the gateway simply tries again 15 seconds later. Contributed by @compnew2006.
- A guest who typed a valid code could get an error even though the code was accepted, and then be told the code was already used. The approval now always comes back, and a guest who retries gets the same approval again. Contributed by @compnew2006.
- The security filter on the dashboard (for access from outside the home) now checks a request's size as it arrives and keeps its memory bounded, so a flood of large or never-ending requests can no longer slow the gateway down. Access from inside the home is unchanged. Contributed by @compnew2006.
- README: a one-line, safe way to back up the gateway's data while it runs, plus a restore guide. Contributed by @compnew2006.
Expand Down
2 changes: 2 additions & 0 deletions api/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,8 @@ async def _dashboard_payload() -> dict[str, Any]:
"blocked_programmed": getattr(live, "gateway_blocked", None),
"engine_available": bool(
getattr(live, "engine_available", True)),
"engine_sync_error": str(
getattr(live, "engine_sync_error", "") or ""),
},
"wan": live.wan_status,
# The VPN-share switch + live kernel state ride the WS snapshot so
Expand Down
2 changes: 2 additions & 0 deletions quota/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ class EngineSnapshot:
#: blocked in that state, so the dashboard must say so instead of implying
#: enforcement is live.
engine_available: bool = True
#: transient error from atomically syncing enforcement sets, if any
engine_sync_error: str = ""
#: IPs of guest devices currently awaiting admin approval (for captive portal)
pending_guests: set[str] = field(default_factory=set)
ts: float = field(default_factory=time.time)
Expand Down
207 changes: 113 additions & 94 deletions quota/nftables.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
import json
import logging
import re
import tempfile
import time
from ipaddress import ip_address, ip_network
from typing import Any, Callable
Expand Down Expand Up @@ -213,6 +214,35 @@ def _which_network(networks: list[str], host: str) -> str | None:
_MAC_RE = re.compile(r"^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$")


def _valid_addresses(values: list[str], version: int) -> list[str]:
"""Return sorted canonical IP literals of the requested address family."""
valid: set[str] = set()
for value in values:
try:
address = ip_address(value)
except ValueError:
continue
if address.version == version and not getattr(address, "scope_id", None):
valid.add(str(address))
return sorted(valid)


def _valid_ip_to_mac(ip_to_mac: dict[str, str]) -> dict[str, str]:
"""Reject invalid and zone-scoped IPs before they enter nft rule syntax."""
valid: dict[str, str] = {}
for ip, mac in ip_to_mac.items():
try:
address = ip_address(ip)
except ValueError:
log.warning("ignoring invalid address in nft device map")
continue
if getattr(address, "scope_id", None):
log.warning("ignoring zone-scoped address in nft device map")
continue
valid[ip] = mac
return valid


class NftablesEngine:
"""Linux (nftables) accounting + hard-block engine.

Expand Down Expand Up @@ -267,14 +297,18 @@ def __init__(

self.available = True
self._warned = False
#: Last enforcement-set reconciliation error. A failed transaction is
#: observable without declaring the packet engine itself unavailable.
self.sync_error = ""
self.last_error = ""
self._ip_to_mac: dict[str, str] = {}
self._blocked: dict[str, bool] = {}
#: IPs most recently programmed into the kernel `blocked` set.
self._last_blocked_ips: list[str] = []
self._last_blocked_ips: list[str] | None = None
ipv6_pfx = (getattr(dhcp_cfg, "ipv6_prefix", "fd00:da7a:2::/64") or "fd00:da7a:2::/64").strip()
self._ipv6_prefix = ipv6_pfx
self._local_networks6 = sorted({"fe80::/10", "fd00::/8", "ff00::/8", ipv6_pfx})
self._last_blocked6_ips: list[str] = []
self._last_blocked6_ips: list[str] | None = None
#: Is the ISP's IPv6 reachable (probe verdict)? None = never programmed.
#: While False the ``v6gate`` chain answers every client IPv6 packet
#: bound for the internet with ICMPv6 "no route", so apps fall back to
Expand All @@ -283,7 +317,7 @@ def __init__(
#: MACs most recently programmed into the kernel `blocked_macs` set
#: (lease-less / static-IP devices are cut by ethernet address — see
#: :meth:`_sync_blocked_macs`).
self._last_blocked_macs: list[str] = []
self._last_blocked_macs: list[str] | None = None
#: IPs whose counter rules exist in the kernel.
self._installed: set[str] = set()
#: IPs whose LAN-monitoring counters exist; ``_last_lan`` is their
Expand Down Expand Up @@ -312,7 +346,7 @@ def __init__(
#: run.py sets the plain-HTTP side door here when the dashboard is HTTPS.
self.portal_port: int | None = None
#: IPs of pending guests programmed into the `pending_guests` captive portal set
self._last_pending_guests: list[str] = []
self._last_pending_guests: list[str] | None = None

# -- lifecycle ----------------------------------------------------------

Expand All @@ -329,9 +363,12 @@ def start(self) -> None:
self._lan_installed = set()
self._lan_carried = set()
self._last_lan = {}
self._last_blocked_ips = []
self._last_blocked6_ips = []
self._last_blocked_macs = []
# A table rebuild invalidates every set cache. Even a desired empty
# set must be flushed once so retained set objects cannot stay stale.
self._last_blocked_ips = None
self._last_blocked6_ips = None
self._last_blocked_macs = None
self._last_pending_guests = None
self._ipv6_wan_active = None
self._run(["add", "table", f"{FAMILY} {self.table}"])
self._run(["flush", "table", f"{FAMILY} {self.table}"])
Expand Down Expand Up @@ -443,6 +480,7 @@ def update_state(self, ip_to_mac: dict[str, str],
blocked: dict[str, bool],
pending_guests: list[str] | None = None) -> None:
"""Reconcile per-device counters + the blocked set with the service."""
ip_to_mac = _valid_ip_to_mac(ip_to_mac)
self._ip_to_mac = dict(ip_to_mac)
self._blocked = dict(blocked)
if not self.available:
Expand All @@ -461,64 +499,33 @@ def update_state(self, ip_to_mac: dict[str, str],
# lease is allowed even on ticks where the blocked set is unchanged.
self._sync_known_ips(ip_to_mac)

# Rebuild the blocked set from the current blocked MACs -> their IPs,
# but only when the desired membership actually changed AND is not
# empty. Re-flushing an identical set every ~15 s re-opens a small
# unblock window for every blocked device on every tick (the chain's
# policy is accept between the flush and the last re-add), and a
# mid-rebuild nft failure leaves the later devices missing from the set
# — both silent enforcement gaps. The empty case is cheap (one
# subprocess, no devices affected) so it always runs to keep the kernel
# authoritative.
# Reconcile all enforcement sets in one transaction. Unknown caches
# (startup/restart) force an authoritative first sync, including empty
# sets; thereafter identical memberships cost no nft invocation.
blocked_ips = sorted(
ip for ip, mac in ip_to_mac.items() if blocked.get(mac))
blocked_v4 = [ip for ip in blocked_ips if ":" not in ip]
blocked_v6 = [ip for ip in blocked_ips if ":" in ip]
self._sync_blocked_ips(blocked_v4)
self._sync_blocked6_ips(blocked_v6)
blocked_v4 = _valid_addresses(
[ip for ip in blocked_ips if ":" not in ip], 4)
blocked_v6 = _valid_addresses(
[ip for ip in blocked_ips if ":" in ip], 6)
# MAC-based drops are the SECOND enforcement channel, keyed by the
# device's ethernet address instead of its lease: they cut devices
# whose IP never entered ``ip_to_mac`` — a lease-less quota-blocked
# device (DHCP never assigned / lease pruned) or a static-IP device
# that routes through the box with no lease row. The IP set above
# cannot see those; the ether set can (its traffic still crosses the
# forward chain with its real saddr/daddr).
self._sync_blocked_macs(blocked)
blocked_macs = sorted(m for m, b in blocked.items()
if b and m != GATEWAY_MAC and _MAC_RE.fullmatch(m))
desired = {
"blocked": (blocked_v4, self._last_blocked_ips),
"blocked6": (blocked_v6, self._last_blocked6_ips),
"blocked_macs": (blocked_macs, self._last_blocked_macs),
}
if pending_guests is not None:
self._sync_pending_guests(pending_guests)

def _sync_pending_guests(self, pending_guests: list[str]) -> None:
"""Program the kernel ``pending_guests`` set for captive portal redirect."""
pg_sorted = sorted(pending_guests)
if pg_sorted == self._last_pending_guests:
return
self._last_pending_guests = None
if self._run(["flush", "set", f"{FAMILY} {self.table} pending_guests"]):
ok = True
for ip in pg_sorted:
if not self._run(["add", "element",
f"{FAMILY} {self.table} pending_guests",
f"{{ {ip} }}"]):
ok = False
break
if ok:
self._last_pending_guests = pg_sorted

def _sync_blocked_ips(self, blocked_ips: list[str]) -> None:
"""Program the kernel ``blocked`` set for leased, quota-blocked IPs."""
if blocked_ips and blocked_ips == self._last_blocked_ips:
return
self._last_blocked_ips = None # not yet committed; retry next tick if a step fails
if self._run(["flush", "set", f"{FAMILY} {self.table} blocked"]):
ok = True
for ip in blocked_ips:
if not self._run(["add", "element",
f"{FAMILY} {self.table} blocked",
f"{{ {ip} }}"]):
ok = False
break
if ok:
self._last_blocked_ips = blocked_ips
desired["pending_guests"] = (
_valid_addresses(pending_guests, 4), self._last_pending_guests)
self._sync_enforcement_sets(desired)

def set_ipv6_wan(self, active: bool) -> None:
"""Open (ISP IPv6 works) or close (it does not) the IPv6 WAN gate.
Expand Down Expand Up @@ -548,48 +555,58 @@ def ipv6_wan_active(self) -> bool | None:
"""Last IPv6-WAN verdict pushed to the kernel (None = never)."""
return self._ipv6_wan_active

def _sync_blocked6_ips(self, blocked6_ips: list[str]) -> None:
"""Program the kernel ``blocked6`` set for leased, quota-blocked IPv6s."""
if blocked6_ips and blocked6_ips == self._last_blocked6_ips:
return
self._last_blocked6_ips = None
if self._run(["flush", "set", f"{FAMILY} {self.table} blocked6"]):
ok = True
for ip in blocked6_ips:
if not self._run(["add", "element",
f"{FAMILY} {self.table} blocked6",
f"{{ {ip} }}"]):
ok = False
break
if ok:
self._last_blocked6_ips = blocked6_ips

def _sync_blocked_macs(self, blocked: dict[str, bool]) -> None:
"""Program the kernel ``blocked_macs`` set for every blocked device.
def _sync_enforcement_sets(
self, desired: dict[str, tuple[list[str], list[str] | None]],
) -> None:
"""Atomically replace only changed enforcement sets.

The set is ``ether_addr``-typed; the forward chain's drop rules match
``ether saddr/daddr @blocked_macs`` (both directions, LAN-excluded).
The box's own sentinel MAC is never programmed (its packets never
cross the forward chain). Cache-gated exactly like the IP set: a
same-set re-flush every tick would open a short unblock window.
nft applies a ``-f`` file as one transaction. If validation/programming
fails, every prior set remains live and each cache still describes the
last successful kernel state, so the next maintenance tick retries.
"""
# Only real MACs: one malformed entry makes `nft add element` fail with
# "Invalid LL address", which used to switch the whole engine off.
blocked_macs = sorted(m for m, b in blocked.items()
if b and m != GATEWAY_MAC and _MAC_RE.match(m))
if blocked_macs and blocked_macs == self._last_blocked_macs:
changed = {name: (members, previous)
for name, (members, previous) in desired.items()
if members != previous}
if not changed:
return
self._last_blocked_macs = None # not yet committed; retry next tick
if self._run(["flush", "set", f"{FAMILY} {self.table} blocked_macs"]):
ok = True
for mac in blocked_macs:
if not self._run(["add", "element",
f"{FAMILY} {self.table} blocked_macs",
f"{{ {mac} }}"]):
ok = False
break
if ok:
self._last_blocked_macs = blocked_macs
commands = []
for name, (members, _previous) in changed.items():
commands.append(f"flush set {FAMILY} {self.table} {name}")
if members:
commands.append(
f"add element {FAMILY} {self.table} {name} "
"{ " + ", ".join(members) + " }")
code, out = self._run_batch(commands)
if code == 0:
for name, (members, _previous) in changed.items():
setattr(self, {
"blocked": "_last_blocked_ips",
"blocked6": "_last_blocked6_ips",
"blocked_macs": "_last_blocked_macs",
"pending_guests": "_last_pending_guests",
}[name], members)
self.sync_error = ""
return

message = f"nft enforcement sync failed: {out.strip()}"
if code == 127 or any(term in out.lower() for term in (
"permission denied", "operation not permitted")):
self._fail(message, command=["-f", "<enforcement batch>"])
return
self.sync_error = message
log.error("%s; retaining last successful enforcement and retrying", message)

def _run_batch(self, commands: list[str]) -> tuple[int, str]:
"""Run an atomic nft batch from a temporary file using the injected runner."""
try:
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", prefix="quota-nft-",
suffix=".nft", delete=True) as batch:
batch.write("\n".join(commands) + "\n")
batch.flush()
return self._run_command(["nft", "-f", batch.name])
except OSError as exc:
return 1, str(exc)

def _sync_known_ips(self, ip_to_mac: dict[str, str]) -> None:
"""Keep the kernel ``known_ips`` set == the currently leased client IPs.
Expand Down Expand Up @@ -1100,6 +1117,8 @@ def _parse_counters(self, json_text: str) -> dict[str, int]:

def _fail(self, reason: str, command: list[str] | None = None) -> None:
self.available = False
self.sync_error = ""
self.last_error = reason
if not self._warned:
argv = f"nft {' '.join(command)}" if command else "nft <unknown>"
log.error("nftables engine unavailable: %s — no per-packet "
Expand Down
3 changes: 3 additions & 0 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -1700,6 +1700,7 @@ async def _maintenance_tick(self) -> None:
except Exception: # noqa: BLE001 — never let a share problem stop the tick
log.exception("disk shares: access sync failed")
engine_available = False
engine_sync_error = ""
gateway_blocked = None
if self.engine is not None:
# nft update_state + set_gateway_blocked shell out to `nft`
Expand All @@ -1724,6 +1725,7 @@ async def _maintenance_tick(self) -> None:
# getattr: some test fakes implement only the minimal engine
# surface; the real engine always carries both attributes.
engine_available = bool(getattr(self.engine, "available", True))
engine_sync_error = str(getattr(self.engine, "sync_error", "") or "")
# What the kernel actually holds for the box's cut (True/False), or
# None if it was never programmed — copied into the snapshot so the
# dashboard can show "Blocked in the UI but not cut at the kernel".
Expand Down Expand Up @@ -1753,6 +1755,7 @@ async def _maintenance_tick(self) -> None:
wan_status=wan_status,
gateway_blocked=gateway_blocked,
engine_available=engine_available,
engine_sync_error=engine_sync_error,
pending_guests=pending_guests,
interval_s=flush_interval,
flows_by_mac=flows_by_mac,
Expand Down
5 changes: 4 additions & 1 deletion tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -1748,7 +1748,8 @@ def test_gateway_payload_engine_programmed_but_ui_free(tmp_path):
# import asyncio
database = _db.Database(tmp_path / "gw.db")
holder = SnapshotHolder()
holder.swap(EngineSnapshot(gateway_blocked=True, engine_available=True))
holder.swap(EngineSnapshot(gateway_blocked=True, engine_available=True,
engine_sync_error="nft enforcement sync failed"))
service = QuotaService(database, timezone="Africa/Cairo")
_get_loop().run_until_complete(database.connect())
app = create_app(database, service, holder)
Expand All @@ -1759,6 +1760,8 @@ def test_gateway_payload_engine_programmed_but_ui_free(tmp_path):
assert dash["gateway"]["blocked_desired"] is False
assert dash["gateway"]["blocked_programmed"] is True
assert dash["gateway"]["engine_available"] is True
assert dash["gateway"]["engine_sync_error"] == \
"nft enforcement sync failed"
finally:
_get_loop().run_until_complete(database.close())

Expand Down
Loading
Loading