Tag: nftables

  • Patronus: a time limit on one device, and the browser tab that stayed stuck

    Patronus: a time limit on one device, and the browser tab that stayed stuck

    Full disclosure: I make Patronus, a router and firewall OS built on Gentoo. It’s young. Version 0.2.0 came out on October 30.

    Most of what I write about it comes out of CI logs, and a green netlab run tells you very little about what a feature is like to use. So on November 8 I took one 0.2.0 feature, per-device time limits, and used it the way a parent would. I set a policy, pushed traffic through the router from a pretend tablet, watched the tablet get cut off, and pressed the buttons.

    What this setup is

    It’s a lab, not my house. One container with four network namespaces: the router (the real patronus-web and patronus apply built from main, commit 9f5b2361), a LAN client I called kids-tablet, a fake ISP, and a fake internet that uses documentation addresses and *.example.test names. The browser on the “tablet” runs inside the client namespace, so every page it loads really crosses the router.

    The clock is the one fake part. I moved the router’s time with PATRONUS_FAKE_TIME_FILE, the knob the tests use, so an evening took half a minute. Bytes, conntrack counters, nft sets and the pages are real. The passing of time isn’t, so this covers one quota day and a few next-day checks, not a month of living with it. That’s also why the screenshots say 2026-11-09.

    The policy

    120 minutes a day, only between 16:00 and 20:00, a warning 5 minutes before the cut, the day resetting at 06:00, attached to a group called kids. kids-tablet is the only device in that group.

    Time limits page: kids-tablet has used 45 of 120 minutes, with buttons to add 30 minutes or pause the internet, above a policy of 120 minutes a day between 16:00 and 20:00 applied to the kids group
    The Time limits page under Segmentation. The policy table is at the bottom.

    A minute only counts if the device moved more than a byte threshold in it (20000 bytes by default, taken from conntrack counters). The docs say the point is that a tablet sitting idle doesn’t use up the day. Minutes spent blocked don’t count either: the tablet sat at 120 of 120 while I reloaded the blocked page over and over.

    Green usage bar at 46 of 120 minutes, state online ok
    46 of 120, after real traffic through the router.
    Amber usage bar at 115 of 120 minutes, state ending soon
    115 of 120. This is where the warning fires.

    At 115 the tablet’s next plain http page was replaced by a “5 minutes left” notice. That’s a one-shot redirect that lasts two minutes.

    Warning page on the tablet: 5 minutes left
    What the tablet shows.

    The clip

    This is the tablet’s browser on the left and the router’s admin page on the right, recorded in one take with no cuts and no speed changes. I added the labels and captions afterwards. The 118 minutes of usage before the clip came from real traffic, not from editing the database.

    The quota runs out and the tablet gets “Time’s up”. Then +30 minutes, pause, resume. 32 seconds, real time apart from the simulated clock.

    Quota runs out and the tablet gets “Time’s up”. I press +30 min today and access comes back. I press Pause internet now and it’s blocked again 97 ms after the click. Resume and it works again. After each restore I open a different site in the tablet instead of reloading the old tab, and there’s a reason for that further down.

    Time's up page on the tablet saying the internet is switched off and when it comes back
    The other way to get cut off: the 16:00 to 20:00 window closed.

    What it does in the kernel

    Enforcement is its own nft table, inet patronus_time, hooked at priority -11 so it runs ahead of the isolation table at -10. The docs say each change is one atomic nft -f, so other devices don’t see a blip when one device is toggled. A blocked tablet is three set elements: its IPv4 address in blocked_v4, its MAC in blocked_mac for IPv6, and the warning set for the two minutes after a warning.

    nft ruleset of the patronus_time table with the tablet address in the blocked set
    nft list table inet patronus_time while the tablet was blocked. The text is the real output. I added the colouring.

    The router keeps answering ICMP and DNS for a blocked device and serves the page on :8081. I checked that ping and name lookups work, that the admin port times out, and that outbound TCP gets a reset. I did not test DHCP or SSH while blocked. After a simulated reboot (fresh namespaces plus patronus apply, no web UI yet) the tablet was already blocked and its usage was unchanged.

    Timings from the lab: with a new TCP connection per probe, pause to first “Time’s up” response took 7 to 20 ms over 8 cycles, and resume to first real page 8 to 14 ms. Parent buttons act immediately. Window and quota changes are picked up by a ticker that runs every 5 seconds by default, so with the real default the page changed 4 to 5 seconds after a window edge.

    Tests: 15 firewall unit tests and 2 captive-portal tests cover this code and they pass. The web crate has no time-limit unit tests of its own. There’s also a netlab scenario, lane-s-time.sh, which I did not run this time. No commit has touched the time-limit code since October 30.

    What doesn’t work (yet)

    The one that annoyed me most is the stuck tab. A tab that was redirected to the time’s-up page keeps its connection to the router’s page server. After +30 min or Resume the old tab reloads, but it lands on the router’s own “You’re all set” page and stays there. In the runs where I kept reloading it, it took anywhere from 16 seconds to over two minutes to recover, and in one run it hadn’t recovered after 80 seconds. A new browser context or a different site works at once. Force-quitting the browser recovers faster than pressing reload. That’s why the clip opens a different site after each restore. I haven’t fixed it.

    https gets nothing useful. Only port 80 is redirected, so on an https site the browser shows its own connection error and apps just say there’s no internet. The “Time’s up” page only shows up for plain http.

    Identity is the device’s IPv4 address, plus its MAC for IPv6. With the tablet paused I gave the same client another address and the internet worked, because only the old address was in the blocked set. A device that isn’t enrolled isn’t limited at all. The docs admit a phone that rotates its MAC on every connection can’t be bound.

    IPv6 is cut but not counted. I got an IPv6 path working and the pause did stop it, but three simulated minutes of IPv6-only downloads left the usage at 4 minutes before and 4 after. The “Time’s up” redirect is IPv4 only too.

    Accounting is a byte threshold per whole minute, so it isn’t a screen-time meter. One 47 KB response costs a full minute. Fifteen tiny connections in a minute cost nothing, thirty cost one. If you give a group a policy you get one quota per device, not a shared family pool, and bonus minutes are per device as well.

    The enforcer lives in the web process. The ticker runs inside patronus-web. With it stopped and the clock moved 30 minutes past the end of the window, the tablet stayed online for the 10 seconds I watched. With it stopped and an already-blocked tablet, the tablet got connection refused instead of a page, since nothing was serving :8081. It catches up within a fraction of a second when the web process starts again.

    A transfer already running when I paused did not fail fast. A 10 second stream delivered about 16 KB before the pause and 20 KB shortly after, then stalled until the client’s own 14 second timeout.

    Minor things: in the policy form the seven day checkboxes stack in one tall column, the “who it applies to” form doesn’t preselect the current policy, and the usage table refreshes on a 15 second timer, so the admin page lags the tablet by a few seconds.

    Things I haven’t tried at all: a real DoH client or VPN app, the stricter mode that also cuts DNS, a per-device policy overriding a group one, captive-portal probes from a real Android or iPhone, DST or NTP steps, and anything over more than a day of real clock time. DNS stays open while blocked by default, and I didn’t look for anything that stops someone tunnelling through it.

    Where it stands

    It does the basic job in the lab: a device with a policy gets cut when its quota or window runs out, a parent can add time, pause or resume, and the block survives a reboot. It’s less finished than the changelog suggests. I’d fix the stuck tab first, since parents will think the button failed. I have no fixes for any of the items above yet.

    Next: a few days on a real clock with a real phone.

    Patronus lives at patronus.errant.solutions.

  • Egress filtering and DNS exfiltration: the outbound controls most networks skip

    Egress filtering and DNS exfiltration: the outbound controls most networks skip

    Most of the firewall rules I review are about what can get in. The rule sets are long, argued over, and audited every year. Outbound is usually one line: allow any to any. Then an incident happens, the attacker’s implant calls home over 443 or 53, and nobody is surprised except the people who owned the firewall.

    Egress control is the cheapest high-value change a mid-sized network can make, and most teams put it off because it breaks things in the first week. This post is about doing it anyway, and about the outbound protocol almost nobody can block outright: DNS.

    Why default allow outbound hurts

    Before and after diagram: with default allow outbound, command and control and a DNS tunnel both reach the attacker; with controlled egress the server reaches only an internal resolver and proxy, direct connections are dropped and logged, and resolver queries are filtered

    The diagram compares a network with default allow outbound against one with controlled egress, showing where direct connections are dropped and where DNS queries get filtered and logged.

    An intrusion has to talk to something. Initial access might come through a phished laptop or an exposed service, but after that the attacker needs command and control, tooling downloaded from somewhere, and a path to carry data out. Inbound filtering does nothing about any of those.

    Servers are the easy case. A database host has no business browsing the web. An application server needs a handful of destinations: its database, a package mirror, a payment API, maybe a metrics endpoint. If you can name those, you can write a default-deny outbound policy and the attacker’s reverse shell to a random VPS simply fails. Log4Shell (CVE-2021-44228) made this concrete for a lot of people. Exploitation needed the vulnerable server to make an outbound LDAP or RMI connection to the attacker. Hosts with tight egress were far harder to exploit in practice, even before patching.

    Workstations are harder because people browse. For those I’d settle for forcing all web traffic through a proxy or a filtering resolver and blocking direct outbound on everything else.

    A default-deny starting point

    Here is a minimal nftables ruleset for an application server. The addresses are examples, replace them with your own resolver and proxy.

    table inet egress {
      set resolvers { type ipv4_addr; elements = { 10.0.0.2, 10.0.0.3 } }
      set proxies   { type ipv4_addr; elements = { 10.0.1.10 } }
    
      chain output {
        type filter hook output priority 0; policy drop;
        oifname "lo" accept
        ct state established,related accept
        ip daddr @resolvers udp dport 53 accept
        ip daddr @resolvers tcp dport 53 accept
        ip daddr @proxies tcp dport 3128 accept
        limit rate 5/minute log prefix "egress-drop "
      }
    }

    The last rule earns its place. Every outbound packet that matches nothing above gets logged just before the policy drops it, rate limited so a noisy host doesn’t flood the journal. In the first week that log is your to-do list: each entry is either a legitimate dependency you forgot or something you should be worried about. I’ve found a forgotten telemetry agent and a cron job posting to a defunct webhook this way, both on hosts I thought I understood.

    Run it in log-only mode first (swap the policy to accept and keep the log rule) for a week or two. Then flip it.

    Why DNS is different

    Everything above leaves the resolver alone, because the host has to be able to resolve names. And a resolver is a program that forwards arbitrary questions to arbitrary servers on the internet. If an attacker controls the authoritative server for a domain they registered, every query for a name under that domain is delivered to them by your own infrastructure.

    That is DNS tunneling. The client encodes data into the query name, for example `mfrggzdfmztwq2lk.a1.t.example.net`, and the attacker’s authoritative server decodes it and replies with data in a TXT, CNAME or NULL record. Tools like iodine and dnscat2 do exactly this, and so does a fair amount of real malware.

    The protocol limits shape what it looks like. A label can be 63 octets and a full name 253 characters in text form (RFC 1035). Names are case-insensitive, so the encoding is usually base32 or hex, which gives about 5 or 4 bits per character rather than 6. In practice that means a few dozen bytes of payload per query, so a tunnel needs a lot of queries to move anything. That volume is your best detection signal.

    What tunnels look like in the logs

    A tunnel tends to show three things, and none of them is reliable alone.

    Many unique subdomains under one parent domain. A CDN may generate some, but a tunnel generates thousands that are never repeated, so caching does not help the attacker or hide the traffic.

    Long, high-entropy labels. Legitimate names are made of words. Base32 payloads are not.

    Unusual record types and response sizes. A host that suddenly asks for lots of TXT or NULL records, or gets large responses, deserves a look.

    With Zeek writing JSON dns.log, the first signal is a one-liner. It counts distinct names per parent domain. The “last two labels” shortcut breaks on suffixes like co.uk, so use a public suffix list if you turn this into a real detection.

    jq -r '.query' dns.log \
      | awk -F. 'NF>2 && !($0 in seen) {seen[$0]=1; n[$(NF-1)"."$NF]++}
                 END {for (d in n) print n[d], d}' \
      | sort -rn | head -20

    And a small entropy check you can bolt onto a pipeline:

    import math
    from collections import Counter
    
    def entropy(label: str) -> float:
        counts = Counter(label)
        total = len(label)
        return -sum(c / total * math.log2(c / total) for c in counts.values())
    
    def suspicious(name: str) -> bool:
        first = name.split(".")[0]
        return len(first) >= 20 and entropy(first) > 3.5

    Those thresholds are mine, picked from eyeballing my own traffic, not from a paper. Treat them as a starting point and tune them against a week of your real logs, because CDN and anti-virus lookups will trip a naive version. I’d alert on the combination: many unique names to one parent domain from one host, plus long high-entropy labels.

    Controls that work better than detection

    Detection is the backstop. Shrinking what DNS can reach is the better investment.

    Force every client to use your internal resolver and block outbound 53 from everything else. Hosts that hardcode 8.8.8.8 are either misconfigured or hiding something, and the drop log will tell you which.

    Run the resolver with response policy zones (RPZ) or a filtering service so newly registered and known-bad domains don’t resolve. Domain age is a surprisingly good signal because attackers register throwaway names.

    Close the side doors. DNS over TLS (RFC 7858) uses port 853 and DNS over HTTPS (RFC 8484) uses 443, so a client can bypass your resolver entirely. Block 853 outright. For DoH, you can disable it in browsers by policy and block the well-known public DoH endpoints, but I won’t pretend that is complete, since anything on 443 can be a DoH server. This is the argument for forcing web traffic through a proxy, too.

    Pin the resolver’s own upstream. If the resolver can forward to the whole internet, restrict it to the recursion it needs and log its queries centrally. Query logs from the resolver are far better than logs from a tap, because they show which internal client asked.

    Expect it to break things

    I haven’t seen a first egress rollout that went without surprises. Package managers, license servers, NTP, OCSP and CRL fetches, and cloud metadata endpoints all show up as drops. That is the point of the log-only period. Budget a couple of weeks, start with the servers that matter most, and keep the allow list in version control so changes get reviewed like any other firewall change.

    If you do one thing this month, turn on logging for outbound drops and for resolver queries. A week of that data will teach you more about your network than most audits.

  • Patronus: I switched on the guest network and tried to get out of it

    Patronus: I switched on the guest network and tried to get out of it

    Full disclosure: I make Patronus, a router and firewall OS built on Gentoo. The guest network page is the newest thing I’ve added to it. It went into main on November 17 and isn’t in a tagged release yet.

    Every router says guests can’t reach your LAN. I wanted to check that claim, so on November 22 I switched the guest network on in a lab and tried to reach the NAS, the router’s admin page, the modem and the other guest.

    The lab

    This was a lab, not my house. One container with a handful of network namespaces: the router (the real patronus-web plus the apply step, built from main at commit 02e0a2c7, 5 minutes 11 seconds cold in a capped container), one LAN device, two “visitor” devices on two spare router ports, a fake ISP and a fake internet. The NAS is a tiny web server on the LAN that answers “192.168.50.13 sees 192.168.50.10”. The ISP modem’s admin page is another one at 10.77.7.7, behind the WAN. Everything is curl and a DHCP client. I drove the admin page with a real browser, from the LAN device’s namespace.

    Some of it is fake or missing. There is no radio, so this is the wired half only: visitors are plugged into ports and the Wi-Fi switch stayed off. The visitors run busybox’s udhcpc, not a phone. The lab router has no resolver of its own, so I filled in the “Router DNS forwards to” box with the fake internet’s DNS server. The page still carries a “This router has not been set up yet” banner because I never ran the setup wizard in this lab.

    Turning it on

    The guest network is off until you switch it on, and everything lives on one page: /svc/guest. It’s one long form. I ticked the box, set the VLAN id to 0 (no VLAN, use ports only), listed the two spare ports, left the address at its default of 192.168.30.1/24, and set a per-guest download cap of 4000 kbit/s.

    The guest network settings form with the network switched on, extra ports gst-a and gst-b, address 192.168.30.1/24 and a per-guest download cap of 4000
    The settings form as I filled it in. The DNS forwarder box is only filled because my lab router has no resolver.

    Before the real save I tried to break it. I typed the LAN’s own subnet, 192.168.50.5/24, as the guest address. The page refused with “Invalid guest subnet 192.168.50.0/24 (overlaps 192.168.50.0/24 on rtr-lan; pick another address)”, and when I asked the API afterwards the address was still 192.168.30.1/24. The red box shows up at the top of the page though, above the part you’re looking at when you click Save, so on a laptop it looks like nothing happened until you scroll up.

    A red message reading Not applied: Configuration error: Invalid guest subnet 192.168.50.0/24 overlaps 192.168.50.0/24 on rtr-lan, above the settings card with the address field filled with 192.168.50.5/24
    The refusal. The stored address did not change.

    The real save took between 0.7 and 0.8 seconds in four runs, measured from the click to the status card saying the bridge is up. Then I plugged in the two visitors.

    The live status card showing bridge up yes, DHCP and DNS running yes, and two clients listed by address and MAC
    Status card with two guests. Clients are an address, a MAC and a star where a name would go.

    Being a visitor

    Both visitors got a lease from 192.168.30.1 with a 7200 second lease time (the default of 120 minutes), the router as gateway and DNS, and could fetch a page from the fake internet. The site saw the router’s WAN address, so the traffic is masqueraded. A ping to the router answers, which is a setting that defaults to on.

    Terminal output: a visitor runs udhcpc and gets 192.168.30.193 from 192.168.30.1, fetches www.example.test and sees the router's WAN address, and pings the router
    A visitor joins. Lab names and documentation addresses throughout.

    From the visitor I tried the NAS, the router’s admin page on its guest address, on its LAN address and on its WAN address, the modem’s page behind the WAN, and the other visitor. All six timed out. As a control, the LAN device fetched the NAS fine, and a LAN device trying to open a connection to a visitor also timed out, which is what the docs promise (nothing starts a connection into the guest network).

    Terminal output: the LAN device reaches the NAS, while the visitor's curl to the NAS, the router admin page on three addresses, the modem page and the other guest all end with exit 28, and a LAN device curling a guest also times out
    The LAN control fetch, then the six visitor probes. Exit 28 is curl giving up after 3 seconds.

    These are drops, so a visitor just waits for the timeout. I looked at the firewall to see why. The guest rules are their own nft table at priority -15, ahead of the main firewall, and its input chain ends with a drop commented “guests reach nothing else on the router”. The forward chain drops private ranges beyond the WAN, drops a source address that isn’t in the guest subnet, and the way back into the guest network only allows established flows.

    Output of nft list table inet patronus_guest: input chain allowing DHCP, DNS and ping then dropping, forward chains guest_out and to_guest, a per-guest download cap set, and a masquerade rule
    The kernel’s view of the guest network. I removed one line of live meter entries, nothing else.

    The speed cap

    I set 4000 kbit/s per guest, which is 500 kilobytes a second. Each visitor downloaded for 8 seconds from a bulk server and curl reported 576,369 and 580,724 bytes a second. Across four runs the figures stayed between 576,000 and 581,000, about 15 percent over the setting. The docs say per-guest caps are policed with nft meters, that packets over the rate are dropped and that TCP settles somewhere near it, and they estimate the error at “within about 20 percent”. The LAN device on the same server got about 8.3 gigabytes a second through the lab’s virtual links, so the cap is the only thing slowing the visitors. I only tested the per-guest download cap, not the network-wide caps or either upload cap.

    Terminal output: two visitors measured at about 576 and 581 kilobytes per second, and the LAN device at over 8 gigabytes per second
    Measured with curl over 8 seconds. The LAN device number is the lab’s virtual link, not a real speed.

    Closing it, and the clip

    The page has buttons: new Wi-Fi password, new voucher, open for a while, close now, and show the password with a QR code. I pressed close now. The visitor’s internet request timed out, and a DHCP renew still worked, so the device keeps its address. DNS and ping to the router were refused. The docs say that’s intended: while closed, DHCP still answers and nothing else does.

    Terminal output after pressing Close now: the visitor's curl times out, udhcpc renews a lease, ping to the router gets 100 percent loss, and a name lookup fails
    After Close now. The lease renews, nothing else works.

    The clip is a different run on the same lab, 37 seconds, real time. The router page is on top and a terminal is underneath: I switch it on from the form, a visitor joins, tries the NAS, the router page and the other visitor, I press close now, then open for a while, and the internet comes back. The two panes were recorded at the same time but separately, so don’t read anything into sub-second timing.

    Switch on, join, probe, close now, open for 120 minutes. Router page on top, terminal below. Lab clocks are real.

    The share card is the other button I used. It generates a 16 character password and shows it with the standard Wi-Fi join text and a QR code. It’s the demo password from my lab, and I didn’t scan the QR or join anything with it, because there is no radio in this lab.

    The Actions card with five buttons and, below them, the guest SSID, a WIFI join string with a password, and a QR code
    The share card. Password is from the throwaway lab.

    What the docs say about the design

    Several choices are written down in docs/GUEST-NETWORK.md. The guest network is one bridge. VLAN sub-interfaces, spare ports and the guest SSID all join it, the ports are isolated from each other, and the SSID runs client isolation. The doc says plainly that a guest VLAN that continues onto an unmanaged switch can’t be isolated by the router, because the trunk is one bridge port. Guests get their own dnsmasq bound to the guest address only. Schedules and timed windows are nft rules, written that way “so they close by themselves, with no daemon” and survive a reboot. Vouchers are WPA2-only because stock hostapd reads SAE passwords only at start. The intro says it follows the way pfSense and OPNsense guest VLANs, OpenWrt guest networks and UniFi and Firewalla guest networks work. I haven’t done a feature-by-feature comparison against any of them.

    The docs don’t say why the default is 192.168.30.0/24 on VLAN 30, or why leases are 120 minutes, or why it ships switched off. They also don’t say why guest IPv6 is dropped, only that it isn’t supported yet. I don’t know why.

    What doesn’t work (yet)

    Worst bug: the status card shows the wrong state for schedules. I set the access mode to a daily schedule of 03:00 to 04:00 and looked at the card at 18:25 and again at 18:37 on the lab clock. The card said “schedule 03:00-04:00” and “access now: open”. The visitor’s request timed out both times, because the firewall rules were doing their job. When I changed the window to 00:00 to 23:59 the visitor got through. The rules are right and the label is wrong. I read the status function in guest.rs and it never checks the clock for a schedule, it just reports open.

    The live status card showing ACCESS DETAIL schedule 03:00-04:00 and ACCESS NOW open
    The page says open. The visitor’s internet was closed when this was taken.

    Close now and Open for a while change the access mode to timed and leave it there. After “open for 120 minutes” the network closes by itself when the time runs out and stays shut until somebody opens it again, which the docs say. I didn’t wait it out. Switching back to always open is a separate step on the form.

    Smaller annoyances. The header says “Home / Svc-guest”; a commit this morning fixed names like DHCP and DNS in the breadcrumb and this page didn’t get the same treatment. The form has “Open until (epoch seconds)” as a raw number. The minutes for open-for-a-while and for a voucher come from the browser’s own popup boxes. The clients list is an address and a MAC with a star where a hostname would be, and there is no way to kick one, which the docs list under “not yet”. On a 390 pixel wide phone the Guest network checkbox floats awkwardly next to its label. The status card looks fine there, but I only skimmed the long settings form.

    The live status card on a 390 pixel wide phone, listing ACCESS DETAIL schedule 00:00-23:59, bridge up yes, two clients, DHCP and DNS running
    Status card on a phone. This was taken at the end of the session, after I’d set an all day schedule.

    What I didn’t test: Wi-Fi at all, VLAN mode, a reboot, IPv6 (guests are supposed to get none), a real phone or a real DHCP client, lease expiry, the network-wide caps, the upload caps, a voucher actually being used to join, and anything that ran longer than an hour. I created one voucher through the page (name weekend-visitor, 2880 minutes) and it showed up in the list, and that’s all I know about vouchers. The unit tests I ran pass: 22 in the network crate’s guest module, 2 in the web crate’s guest tests and 6 in the firewall rule tests. There is also a netlab lane for the guest network (the docs count 66 checks), a Wi-Fi lane on simulated radios and a Firefox test of the page. I didn’t run them.

    Where it stands

    It works in the lab: guests get internet and can’t reach anything else. The cap lands a little high. The page needs work, starting with the schedule status.

    Next: a phone joining by QR on real hardware, and a schedule left running for a full day. The status card gets fixed first.

    Patronus lives at patronus.errant.solutions.