Author: canutethegreat

  • Mutual TLS between services: short-lived certificates and SPIFFE-style identity

    Mutual TLS between services: short-lived certificates and SPIFFE-style identity

    Most mTLS rollouts I’ve seen go the same way. Someone turns on client certificate verification, the handshake works in staging, and a year later nobody knows who holds the CA key, the certificates last ten years, and the “authorization” amounts to the caller having a cert from the right CA. That’s a bouncer checking that your ticket is a real ticket, without checking whether it’s for this show.

    This post covers the version that holds up. The certificates live for an hour, the identities mean something, and there’s an authorization check after the handshake.

    What mutual TLS adds

    Sequence diagram: workloads obtain one-hour certificates from an issuer, web and billing perform a TLS 1.3 mutual handshake, then billing checks the SPIFFE ID against an allow list before serving the request

    The diagram shows the full flow: issuance, the mutual handshake, and the authorization check that comes after it.

    In a normal TLS 1.3 handshake (RFC 8446) only the server proves who it is. With mTLS the server sends a CertificateRequest, and the client answers with its own Certificate and a CertificateVerify signature over the handshake transcript. If the client has no certificate or the chain doesn’t validate, the server aborts with an alert. You can see the failure directly if you point a client without a cert at a server that demands one:

    tlsv13 alert certificate required ... SSL alert number 116

    You get two things from this. The channel is encrypted, and the server learns a cryptographically proven identity for the caller. Most people underuse the second part. A source IP is a weak identity once you have autoscaling, NAT and shared nodes. A certificate chain you control is much better, as long as the identity inside it is something a policy can reason about.

    Put a workload identity in the certificate, not a hostname

    Service certificates have traditionally carried a DNS name, because browsers care about DNS names. Services calling each other care which workload is calling, and that isn’t the same thing as the host it runs on. SPIFFE defines a URI for this, in the form spiffe://trust-domain/path, and the X.509-SVID format carries it in a URI subject alternative name. The SPIFFE spec asks for exactly one URI SAN on a leaf, CA:FALSE, and no keyCertSign or cRLSign usage, so a workload certificate can’t be used to mint more certificates.

    I built a small throwaway CA in a container to show what a leaf should look like. The identity is spiffe://demo.test/ns/prod/sa/billing, and the validity window is one hour.

    Terminal output of openssl x509 for a demo workload certificate: subject CN billing, validity of exactly one hour, key usage Digital Signature, and the URI subject alternative name spiffe://demo.test/ns/prod/sa/billing

    This is a synthetic demo PKI I generated for the post with OpenSSL 3.0.13. It isn’t anyone’s production setup. Two things to notice: the identity lives in the URI SAN, so the subject CN doesn’t matter, and notAfter is sixty minutes after notBefore.

    Why short lifetimes beat revocation

    In practice, revocation for internal services mostly doesn’t work. CRLs and OCSP need infrastructure that every client has to reach, and when clients can’t reach it, most of them fail open, because failing closed would take production down. SPIRE sidesteps the problem. Its default X.509-SVID lifetime is one hour (default_x509_svid_ttl), agents rotate well before expiry, and “revoking” a workload means stopping issuance. Istio’s default workload certificate lifetime is 24 hours. That’s a looser setting, same idea.

    The math is simple. If a key is stolen from a compromised pod, the attacker’s useful window is at most the remaining lifetime of that one certificate, and they have to keep re-compromising the workload to renew it. With a three-year certificate, you end up planning a CA rotation in the middle of an incident.

    Short lifetimes move the risk somewhere else, though. The issuer is now on the critical path for rotation, even though it isn’t on the path of each request. If your CA or SPIRE server stays down longer than the remaining lifetime, services start failing handshakes. So alert on the remaining validity of the certs in use, not just on the CA’s health, and make rotation a hot reload. Restarting a process to pick up a new certificate turns a one-hour TTL into an outage generator.

    Verification is not authorization

    The handshake only tells you the peer holds a certificate your CA signed. Every workload in the mesh has one, so any of them can call the billing service unless you say otherwise. Teams skip this step all the time, and it’s why I get wary when someone says “we have mTLS” as if that settled the security question.

    In Go, requiring and verifying the client certificate is one config flag. The authorization decision is still yours to write:

    cfg := &tls.Config{
    	MinVersion: tls.VersionTLS13,
    	ClientAuth: tls.RequireAndVerifyClientCert,
    	ClientCAs:  caPool,
    	GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
    		return certs.Current() // reloaded from disk on rotation
    	},
    }
    
    func allowed(r *http.Request) bool {
    	if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
    		return false
    	}
    	for _, u := range r.TLS.PeerCertificates[0].URIs {
    		if u.String() == "spiffe://demo.test/ns/prod/sa/web" {
    			return true
    		}
    	}
    	return false
    }

    Here certs.Current() stands in for whatever holds your reloaded certificate. The GetCertificate callback is what makes rotation painless, because it runs on each new handshake. A hard-coded allow list is fine for a demo and falls apart at scale. Real deployments push the policy into the mesh (Istio AuthorizationPolicy, Envoy RBAC) or into an authorization service, keyed on the same SPIFFE ID. The thing that matters is that the policy names identities and the default is deny.

    Trust domains and the CA you forgot about

    Four failure modes come up again and again.

    Over-broad CAs. If dev, staging and prod share one CA, a dev workload can present a valid chain to prod. Use a separate trust domain per environment, and have the verifier check the trust domain in the SPIFFE ID, not just the chain.

    Everything is trusted. Plenty of clients fall back to the system trust store when no pool is set, so any public CA can vouch for an internal caller. Set the pool explicitly to your own CA bundle.

    Wrong key usage. A leaf that carries keyCertSign turns one compromised service into a CA. Check this in your issuance pipeline and fail the build if it shows up.

    Proxies that terminate TLS. If an ingress or sidecar terminates the mTLS and forwards plain HTTP with an X-Client-Cert header, the application must only accept that header from the proxy, and the hop between them needs to be locally trusted. I’ve watched a header spoofing bug wipe out the benefit of an otherwise excellent certificate scheme.

    What I’d do on day one

    Pick one internal call path that matters, usually the one that reaches a database or a payment system. Issue short-lived certs with a SPIFFE-style URI SAN, require client certs on the server, and write an explicit allow list of caller identities. Then test the negative case on purpose. That’s the test that shows whether it works.

    Terminal output of two openssl s_client runs against an mTLS server: with a client certificate verification is OK on TLSv1.3, without one the server sends tlsv13 alert certificate required, alert number 116

    Same throwaway CA, this time against a server that requires a client certificate. With a valid one the handshake completes on TLS 1.3 and verification is OK. Without one, the server sends alert 116 and closes the connection. I filtered the output with grep and trimmed the error prefix to fit the width.

  • 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.

  • Patronus: I put two web servers behind the router and killed one

    Patronus: I put two web servers behind the router and killed one

    Full disclosure: I make Patronus, a router and firewall OS built on Gentoo. The reverse proxy page is one of the newer things in it. It went into main on November 25 and isn’t in a tagged release yet (the newest tag is v0.2.0).

    The idea is that the router itself can take requests from the internet on port 80 and hand them to servers on your LAN, picking the server by host name and skipping the ones that are down. It runs HAProxy underneath. I wanted to know what a server dying looks like from the outside, so on November 29 I put two web servers behind one name in a lab and killed one. Then I froze one instead of killing it.

    The lab

    A lab, not my house. One container with a handful of network namespaces: the router (the real patronus-web and the apply step, built from main at commit 2e57b8ae, 29 minutes 49 seconds cold in a capped container on a CI host that was already at a load average of 25 to 36, about nine of those minutes spent on package installs and crate downloads before the first compile), a LAN with three tiny Python web servers, a fake ISP and an “internet” host that runs curl against the router’s WAN address. I drove the admin page with a real browser from the LAN side.

    The servers are called wiki-a, wiki-b and notes. Each one answers with its own name and the client address the proxy passed along, and a plain ok on /health. Things that are fake: the host names are under example.test, there’s no real internet and no real load, and the lab’s HAProxy is Debian’s 2.6.12 because that’s what the container had. I didn’t check which version the Gentoo image carries, so timings could differ a little there. The page also shows a “This router has not been set up yet” banner because I never ran the setup wizard in the lab, and the sidebar footer says @PATRONUS_VERSION@ because my dev build never substituted it.

    Publishing one server

    The proxy is off until you use it. Before I touched anything, a request from the internet host to the router’s port 80 sat there until curl gave up (exit 28). The firewall drops it.

    The page has a button, “Publish a LAN service”, and it asks five questions through the browser’s own popup boxes: a name, the server’s LAN address, its port, a host name and the public port. I answered notes, 192.168.50.13, 8080, notes.example.test and 80. The page said published 1.8 seconds after the click in one run and 2.6 in another, and the next curl got an answer.

    The live status card of the reverse proxy page: enabled, installed and running all yes, and a statistics table with a frontend and one backend server, both up
    The status card after publishing. One frontend, one backend, one server.

    That one step made a listener, a backend with one server, a routing rule for the host name and a firewall rule. The rule is iifname "rtr-wan" tcp dport 80 accept with a comment naming the service. HAProxy itself listens on 0.0.0.0:80, so the firewall rule is what keeps it to the WAN side. The server saw the internet host’s address in X-Forwarded-For, so the proxy passes the client address along.

    One thing I didn’t expect. I sent a request for a name nobody published (whatever.example.test) straight to the router’s address, and the notes server answered. A frontend sends everything that matches no rule to its default backend, and publish makes the service you publish the default backend of its listener. The docs say the default backend takes the rest, so it’s behaving as written, but I’d have guessed a 404.

    Two servers, one name

    For the pool I used the forms on the page instead of the button: a backend called pool with an HTTP health check on /health, two servers in it, and a rule sending pool.example.test to it. The backend name in the server and rule forms is a plain text box. I typed it right, and I didn’t try a typo.

    The backend servers table listing notes-1 at 192.168.50.13 and the pool servers wiki-a and wiki-b at 192.168.50.11 and 192.168.50.12, port 8080, with Edit and Delete buttons and an empty add form below
    The servers table, with the add form under it.

    Six requests in a row went wiki-a, wiki-b, wiki-a, wiki-b, wiki-a, wiki-b. The generated config is short. Every server line is check inter 2s rise 2 fall 3: a check every two seconds, two good ones to come up, three bad ones to go down. The defaults block has timeout connect 5s, retries 2 and option redispatch.

    Terminal output: the first request to the published name times out with curl exit 28, then works, a made-up host name is answered by the same server, and six requests to the pool alternate between wiki-a and wiki-b
    From the top: the request before publishing, after publishing, the unknown host name, then the pool.

    Killing one, then freezing one

    I measured both with the same script. The internet host sends ten requests a second for 45 seconds, one curl process per request. At 8 seconds I break wiki-a, at 28 seconds I fix it. First test: kill -9 on the server process. Second test: SIGSTOP, which leaves the process there but silent, the way a hung app or a stuck disk looks. I poll the proxy’s own statistics every quarter second to see when it notices.

    FaultRequestsNo answerDown after
    killed42606.1 s
    frozen420510.4 s

    The killed server first, and no request failed. A killed process refuses connections at once, and HAProxy retries a refused connection on another server, so every one of the 426 requests came back 200 and the slowest took 56 milliseconds. That includes the six seconds before the health checks caught up. For the 20 seconds wiki-a was gone, all 194 requests went to wiki-b. After the restart it took four seconds to come back, and then traffic spread again: 58 requests to wiki-a and 96 to wiki-b in the last 17 seconds.

    Terminal output: the wiki-a process is killed and twelve requests over ten seconds are all answered by wiki-b
    The terminal log from the start of that session. The kill and the twelve requests are at the bottom, one request every half second. A separate run from the table.

    The frozen server went worse. The first five requests after the freeze got no answer at all before curl’s ten second limit. After that, 47 requests came back from wiki-b but each took 5.0 seconds, which is the backend connect timeout, a setting on the page that defaults to 5. It took 10.4 seconds for the checks to mark wiki-a down, and only then did the delays stop. Over the whole run the median was 10 milliseconds and the 95th percentile was 5.01 seconds.

    My guess at the mechanism: the kernel keeps accepting connections for a stopped process until its listen queue fills, and after that the connections just hang, so HAProxy waits out the connect timeout before trying the other server. The five that got nothing probably used up their retries on the frozen one. I didn’t confirm either in HAProxy’s logs.

    The live statistics table with be_pool wiki-a marked DOWN after 9 sessions in total and wiki-b UP after 15
    The statistics table after the kill. wiki-a is DOWN with 9 requests in total; wiki-b has 15.

    The statistics table is HAProxy’s own numbers. I pressed “Live statistics” to refresh it each time. Reading the page’s script I don’t see a timer, so I think it doesn’t update by itself, but I didn’t leave it open to check.

    The clip below is the kill and the restart from another run of the same lab, 44 seconds, real time. Router page on top, terminal underneath. The two panes were recorded separately, so don’t read anything into sub-second timing. After the loop ends I press the statistics button, which is when the table on top changes.

    wiki-a killed, requests keep working, wiki-a started again, traffic spreads. Top: router page. Bottom: terminal.

    Changes the page should refuse

    Two attempts. First I added a listener on port 8443, which is where the admin page lives in my lab. The page refused it and said why: the web UI already uses that port, move it or pick another. Then I added a TLS listener pointing at a certificate file that doesn’t exist. Patronus writes the new config as a candidate, runs haproxy -c on it and only swaps it in if that passes. The page showed HAProxy’s own error and said the running proxy was left alone. After the first refusal I checked that the pool still answered, and it did. After the second I didn’t, so for that one I only have the page’s word.

    A red message above the settings card reading Not applied: Invalid Frontend admin-clash wants port 8443 on 0.0.0.0, which the Patronus web UI already uses, with advice to move the web UI or pick another port
    A listener on the admin port is refused.
    A red message reading Not applied: Invalid reverse proxy configuration, haproxy -c refused it and the running proxy was left alone, followed by haproxy's own alert lines about a missing certificate file
    A missing certificate file. The red box is HAProxy’s raw output.

    What the docs say about the design

    From docs/REVERSE-PROXY.md: publishing creates the listener, the backend, the rule and the firewall rule together, a config that HAProxy refuses is undone, and the statistics come from HAProxy’s local admin socket with nothing exposed on the network. The page isn’t in the small embedded router images because of flash size, and the System page says so. The parity table in the repo lists the HAProxy packages that pfSense and OPNsense ship as the thing being matched, and lists what’s still missing: certificates from an ACME manager, TLS to the backend with verification, the PROXY protocol, rate limiting and a WAF.

    The docs don’t say why HAProxy and not nginx or Caddy, beyond that parity row.

    What doesn’t work (yet)

    The frozen server is the main one. With the defaults, a hung backend costs about ten seconds of five second waits, and some requests get nothing. The knobs are on the page (connect timeout, check interval, how many bad checks), but nothing on the page tells you the defaults behave like this, and I didn’t test other values. I’d start by trying a shorter connect timeout and see what it does to the numbers above.

    Publish gives its backend a plain TCP check, not an HTTP one. The generated config for notes has no httpchk line. So an app that accepts connections but answers every request with an error stays marked up. I read that in the config and didn’t test an app returning errors. The forms let you pick an HTTP check and a path, which is what I did for the pool.

    The catch-all from earlier matters more on a router that faces the internet: a scanner that sends an odd host name gets whatever you published first.

    Smaller things. After pressing “Live statistics” the Actions card fills with the raw JSON from HAProxy, a long block of it, above the table that is actually readable. The breadcrumb says “Home / Svc-revproxy”. The enable checkboxes float away from their labels. The five publish questions are browser popups. The missing certificate error is HAProxy’s alert lines pasted into one red box. On a 390 pixel phone the page itself doesn’t scroll sideways, but the statistics table is wider than the screen and scrolls inside its card, so the Sessions column and the ones after it are off to the right.

    The live status card on a 390 pixel wide phone with the statistics table cut off at the Sessions column
    The statistics table on a phone. It scrolls sideways inside the card.

    Not tested: a TLS listener that serves traffic, tcp mode, path rules, sticky cookies, other balancing modes, backup servers, a reboot, IPv6, real load, anything longer than a few minutes. I ran no unit tests and none of the repo’s netlab lanes this time. The docs list a netlab lane for the proxy and a Firefox test of the page, but I haven’t run either.

    Where it stands

    In the plain case it works in the lab: a dead server costs the visitor nothing. A hung one costs seconds and a few failed requests until the checks catch up, and I’d want that better before anything I care about sits behind it.

    Next: the same test with a shorter connect timeout and a faster check, to see what the best case is, and a TLS listener with a real certificate.

    Patronus lives at patronus.errant.solutions.