Skip to content

Architecture

Naresh Mehta edited this page Nov 18, 2026 · 1 revision

Architecture

Gatekeeper is an OpenWrt network-access controller with Telegram and optional LuCI management interfaces. Shell scripts make admission decisions; nftables enforces them. Components coordinate through UCI configuration, nftables sets, and temporary files rather than an application database or central backend server.

This page describes source reviewed at commit ea918c8. Source links are pinned to that revision. This is a source-level architecture review, not a live-router validation or a test-run report.

System overview

flowchart TD
    Device[Device DHCP event] --> Dnsmasq[dnsmasq]
    subgraph Router[OpenWrt router]
        Dnsmasq --> Bridge[dnsmasq_trigger.sh]
        Bridge --> Event[ubus dnsmasq.event]
        Event --> Listener[gatekeeper_trigger.sh]
        Listener --> Handler[gatekeeper.sh admission policy]
        Handler --> State[Shared state: UCI, nftables, /tmp]
        Bot[tg_bot.sh commands, callbacks, scheduler] --> State
        RPC[Gatekeeper rpcd shell plugin] --> State
        Views[Six LuCI JavaScript views] --> RPC
        Packets[Forwarded packets] --> Firewall[nftables Gatekeeper chain]
        State -. live allowlists .-> Firewall
    end
    Handler --> Telegram[Telegram Bot API]
    Telegram <--> Bot
    Admin[Telegram administrator] <--> Telegram
    Browser[Authenticated LuCI browser] --> Views
Loading

DHCP event pipeline

  1. dnsmasq invokes dnsmasq_trigger.sh with the action, MAC, IP address, and hostname.
  2. dnsmasq_trigger.sh forwards those fields to ubus send dnsmasq.event without policy filtering.
  3. gatekeeper_trigger.sh monitors ubus, lowercases MACs, skips empty MACs and IP strings containing :, and rate-limits accepted events to once per MAC per 60 seconds. After an event passes those checks, it removes rate-limit records older than 300 seconds.
  4. The listener synchronously invokes gatekeeper.sh, which decides whether to suppress notification, auto-approve, deny, or request approval.
  5. tg_bot.sh receives administrator commands and inline-button callbacks through Telegram long polling and changes router state directly.

The listener always passes add as the handler's action. The original DHCP action is argument five, which the handler does not read. Thus accepted renewals and deletions enter the admission path too; there is no DHCP-delete revocation path. Because handler execution is synchronous, external API latency can delay subsequent event processing.

Sources: DHCP bridge, event listener.

Admission decisions

flowchart TD
    Start[Handler invocation] --> Credentials{Telegram credentials present?}
    Credentials -- No --> Exit[Exit without a new prompt]
    Credentials -- Yes --> Disabled{Gatekeeper disabled?}
    Disabled -- Yes --> Exit
    Disabled -- No --> Static[Read UCI static hosts and mark trusted MAC]
    Static --> Existing{Already denied or approved?}
    Existing -- Yes --> Exit
    Existing -- No --> Valid{Nonblank MAC?}
    Valid -- No --> Exit
    Valid -- Yes --> Trusted{Static device?}
    Trusted -- Yes --> NoPrompt[No approval request needed]
    Trusted -- No --> Random{Random-block enabled and locally administered MAC?}
    Random -- Yes --> DenyDay[Deny 24h and notify]
    Random -- No --> Blacklist{Blacklist mode ON and MAC not listed?}
    Blacklist -- Yes --> ApproveDay[Approve 24h and notify]
    Blacklist -- No --> Schedule{Active schedule with at least 60s left?}
    Schedule -- Yes --> Scheduled[Approve until window end]
    Schedule -- No --> Vendor[Best-effort cached vendor lookup]
    Vendor --> Prompt[Send Telegram Approve and Deny buttons]
    Prompt --> Approve[Approve: allow 30m]
    Prompt --> Deny[Deny: remove approval and deny 30m]
    Prompt --> Timer[After 5m, if still not approved: deny 30m]
Loading

This diagram describes the listener-driven add path. Static recognition sets a flag rather than returning immediately; later non-static policy branches are skipped. Static packet access depends on the separately synchronized static_macs set.

Pending devices are already blocked. The five-minute timer is not an access grace period. It changes the Telegram message and adds a 30-minute denial entry to suppress repeated prompts. Expiry of an approval or denial does not itself send a new prompt.

The randomized-MAC check detects the locally administered bit, not proof that an address was randomized. Existing approvals and static devices bypass that handler check. Blacklist membership means a device requires the remaining admission checks, not that it is unconditionally denied; an active schedule can still approve it.

Vendor enrichment is best-effort and uses the external maclookup.app API. On a cache miss for an eligible MAC, the lookup sends the full device MAC to that service; known vendor information is cached per OUI under /tmp/gatekeeper_oui. If the device supplies no hostname, the vendor can also be cached in /tmp/mac_names for later status displays. Lookup implementation.

Sources: configuration guard, policy checks, notification and timer, button callbacks.

Packet enforcement

Despite its extension, gatekeeper.nft is a shell script, registered as a firewall include and executed during fw4 reloads. It creates an inet fw4 forward-hook chain with priority -10 and policy accept.

flowchart TD
    Packet[Forwarded IPv4 or IPv6 packet] --> Disabled{Gatekeeper disabled?}
    Disabled -- Yes --> Continue[No Gatekeeper restriction; other firewall rules apply]
    Disabled -- No --> Static{Source MAC in static_macs?}
    Static -- Yes --> Continue
    Static -- No --> Approved{Source MAC in approved_macs?}
    Approved -- Yes --> Continue
    Approved -- No --> LAN{Ingress interface is br-lan?}
    LAN -- Yes --> Drop[DROP]
    LAN -- No --> Continue
Loading

The disabled decision represents rule construction: disabling flushes the chain, and subsequent reloads leave it empty. It is not a per-packet UCI lookup.

nftables set Role Typical entry lifetime
static_macs Packet allowlist mirrored from static DHCP configuration No timeout
approved_macs Packet allowlist for guests and scheduled devices 30m manually, 24h for blacklist-mode auto-approval, or schedule remainder
denied_macs Admission suppression and scheduler exclusion 30m normally; 24h for randomized-MAC blocking
blacklist_macs Devices requiring approval when blacklist mode is enabled No timeout

Only static_macs and approved_macs appear in packet-matching rules. Denial normally works by removing approval and relying on the default br-lan drop. A MAC present in both approved and denied sets still passes this chain's approval rule, although admission and scheduler checks treat it as denied.

Network scope

  • The default drop covers routed forwarding entering exactly br-lan, not just traffic destined for the WAN.
  • The inet family can cover forwarded IPv4 and IPv6 traffic. Ignoring IPv6 DHCP events does not make the firewall IPv4-only.
  • Router-local input/output and ordinary same-Layer-2 bridged traffic are not gated by this forward-chain policy.
  • Other ingress interfaces are not default-blocked by this chain.
  • Acceptance here does not override drops in other applicable firewall chains.
  • MAC addresses can be spoofed; this is MAC-based access control, not strong device authentication.

Source: firewall setup and rules.

State and lifecycle

State layer Contents Persistence
UCI: /etc/config/gatekeeper Settings, credentials, blacklist, schedule definitions Survives reboot
UCI: /etc/config/dhcp Static DHCP hosts and configured hostnames Survives reboot
nftables Static/blacklist mirrors and live approval/denial entries Kernel state; dynamic entries expire and are not backed by persistent sessions
/tmp/gatekeeper.log, /tmp/mac_names Activity log and device-name cache Cleared on reboot
/tmp/tg_offset Next Telegram update offset Cleared on reboot
/tmp/mac_map, /tmp/denied_mac_map Numeric IDs generated by STATUS and DSTATUS Rebuilt by the corresponding status command
/tmp/dns_locks/, /tmp/gatekeeper_timer_* Event throttles and per-MAC timer PIDs Temporary
/tmp/sched_active, /tmp/sched_lock Schedule snapshot and optional reconciliation lock Temporary
/tmp/restore_* Restore records, preview, plan, and pending confirmation Temporary; shared by management interfaces

Boot, reload, and bypass

  • gatekeeper_init synchronizes static and blacklist MACs at boot; it does not create the firewall sets itself.
  • gatekeeper_sync.sh supports static, blacklist, and all, flushing and rebuilding the selected mirrors.
  • gatekeeper.nft repopulates static and blacklist MACs from UCI on firewall reload. Dynamic guest sessions have no persistence/restore mechanism if the firewall table is recreated.
  • DISABLE persists disabled=1 and flushes the Gatekeeper chain. Reloads preserve the bypass by leaving that chain empty.
  • ENABLE clears the flag, reloads the firewall, and resynchronizes static and blacklist state.
  • procd supervises the event listener and Telegram bot with respawn enabled. The bot service starts later in the boot sequence and requires configured Telegram credentials.

Sources: boot synchronization, manual synchronization, bot service, enable/disable commands.

Scheduling

Schedules are UCI sections containing a MAC, days, start/stop times, and an enabled flag. Times use the router's local timezone. Overnight windows are anchored to their start day.

There are two enforcement paths:

  1. Reactive admission: gatekeeper.sh detects an active schedule during a DHCP event and chooses the latest matching window end.
  2. Proactive reconciliation: scheduler_tick() in tg_bot.sh updates approvals for active schedules, records them in /tmp/sched_active, and removes approvals for MACs no longer active.

The scheduler is not an independent daemon or cron job. Normal periodic reconciliation runs after valid Telegram polling responses. Missing credentials, a stopped bot, or API/network failures can prevent proactive activation. Existing kernel timeouts continue to expire without the bot.

Important implementation limits at the reviewed revision:

  • The periodic scheduler skips denied MACs but does not repeat the handler's randomized-MAC check.
  • Scheduled and manual grants share one approval entry. A tick can overwrite a manual extension, and window-end cleanup can remove it.
  • The periodic scheduler processes overlapping schedules sequentially, so the last processed window can determine the timeout rather than the latest end.
  • Both paths require at least 60 seconds remaining before granting schedule access.

Sources: reactive schedule lookup, scheduler and polling loop.

Management interfaces

Telegram

tg_bot.sh long-polls the Bot API, dispatches text commands and button callbacks, and writes UCI/nftables state directly. Commands cover device status and access, blacklist management, schedules, emergency bypass, synchronization, backup/restore, and system maintenance.

Text-command authorization uses the configured chat ID, not an individual sender ID. In a configured group, participants can issue those commands. STATUS and DSTATUS regenerate numeric device mappings, so IDs from an earlier listing should not be treated as durable identifiers.

LuCI

Six native LuCI JavaScript views call the gatekeeper ubus object through a POSIX-shell rpcd exec plugin:

Page Responsibility
Overview Counts, status information, log tail, optional refresh
Devices Active, denied, and static devices; per-device actions
Blacklist Mode toggle and MAC-list editing
Schedules Schedule CRUD and enable/disable controls
Backup / Restore Download/upload, merge preview, apply
Settings Configuration, bot diagnostic, maintenance actions

The backend advertises 31 methods through its list operation and receives JSON for call <method>. LuCI authentication and rpcd ACLs gate access. Management works without a running Telegram daemon, but proactive scheduling still depends on that daemon.

Sources: rpcd method catalog, ACL, views.

Backup and restore

Both interfaces source /usr/lib/gatekeeper/restore_helpers.sh for validation, parsing, hostname resolution, and merge planning.

flowchart LR
    Backup[Backup upload] --> Validate[Validate format and size]
    Validate --> Parse[Parse records]
    Parse --> Plan[Build merge plan and preview]
    Plan --> Confirm[Administrator confirms]
    Confirm --> Apply[Apply UCI changes and commit]
    Apply --> Sync[Resync blacklist]
Loading
  • Backups export Gatekeeper configuration plus static DHCP host blocks. By default they include credentials; use the NOSECRETS option to omit token/chat values.
  • Restore is a merge, not a complete snapshot rollback: it updates differing nonempty main settings except credentials, adds missing blacklist MACs, and adds schedules whose section names do not already exist.
  • DHCP host entries are exported but not restored: the parser stops at the DHCP section marker.
  • Telegram restore uses a reply-based preview and a 10-minute confirmation window. LuCI uses preview-then-apply RPC calls.

Sources: shared helpers, LuCI backup/restore methods.

Build, deployment, and tests

  • Router-side code targets POSIX /bin/sh on BusyBox/OpenWrt. deploy.sh is the deliberate Bash exception running on the development machine.
  • GitHub Actions assembles gatekeeper and luci-app-gatekeeper .ipk archives directly using tar and ar, without the OpenWrt SDK. Tagged builds publish release assets.
  • opkg/Makefile provides an alternative SDK package recipe.
  • deploy.sh copies runtime and optional LuCI files over SSH/SCP and can restart the relevant services. The dnsmasq hook and firewall include must be wired into the router configuration.
  • The runtime package preserves /etc/config/gatekeeper across package upgrades. A default script deployment can copy the configuration template; use the documented --no-config option when preserving an existing deployment's settings.
  • Development-only shell suites cover BusyBox compatibility, schedules, backup/restore, rpcd helpers/methods, system commands, randomized MACs, and vendor lookup. The reviewed packaging workflow does not run those suites.
  • Router integration with uci, nft, Telegram, and LuCI requires manual validation. Date-sensitive tests on macOS need GNU coreutils on PATH.

Sources: build workflow, deployment script, test instructions.

Review findings and hardening priorities

These observations apply to the reviewed commit and are not claims that a fix has been implemented or an exploit validated:

  1. Callback authorization: inline Telegram callbacks are handled before the configured-chat check used by text commands. Authorize and validate callbacks before any state changes. Source.
  2. Restore execution boundary: backup values are interpolated into generated shell commands and later evaluated. Replace shell-plan evaluation with validated, allowlisted structured UCI operations. Plan generation, application.
  3. Restore isolation: bot and browser restore workflows share global temporary plan files. Session-scoped plans, locking, expiry, and confirmation binding would prevent one preview from replacing another's pending plan. Shared paths.
  4. Timer lifecycle: the disabled guard prevents new handler timers, but existing timers only recheck approval and can still add denial entries after disabling. Source.

The principal architectural improvement would be to separate local schedule reconciliation from Telegram polling and define ownership of manual versus scheduled approvals.