Skip to content

fix(start-wrt): answer plain HTTP at the public address with a redirect to HTTPS while 443 is published - #4000

Merged
dr-bonez merged 12 commits into
masterfrom
feat/wrt-http-redirect
Sep 27, 2026
Merged

dr-bonez merged 12 commits into
masterfrom
feat/wrt-http-redirect

Conversation

@Dominion5254

@Dominion5254 Dominion5254 commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

Why

StartOS publishes only port 443 through its gateway and expects the gateway to answer plain HTTP at the public address with a redirect to HTTPS. StartWRT never did. From inside the network, http://sub.example.com hairpinned to the router's own port 80 and got the router UI; from the Internet it was refused unless Remote Access admitted the source.

What

  • A per-request layer on the daemon's existing [::]:80 listener (http_redirect.rs), outermost on the router. It serves the UI to a client on a connected subnet off the WAN, at an address that is not the WAN's. Every other IPv4 request gets a 307 to the same authority and path over HTTPS, with no body. No new sockets.
  • A WAN ACCEPT rule on tcp/80 so the Internet side reaches the layer under every Remote Access mode. Port control reconciles it with the SNI admission rules: present while WAN 443 leaves the router (an enabled DNAT covering tcp/443, or a hostname route on 443), absent while a DNAT or a hostname route holds tcp/80.
  • The rule matches the wan zone, not a destination, so a WAN-side host that routes the LAN subnet through the router arrives at the LAN address. The layer therefore checks the client's subnet as well as the address it dialed.
  • The rule carries the SNI label, so a build without the redirect purges it on start rather than leaving port 80 open to a daemon with no layer. Its name tells it from a hostname route's rule on 80.
  • The gate opens before the rule is written, shuts after the reload that removes it, and is seeded before the listener binds from any SNI rule on 80. Addresses are read at seeding, on every sweep and WAN hotplug, and again (throttled to 5 s) before a redirect is answered. Unreadable addresses or an unreadable firewall redirect.
  • Port 80 is reserved while the redirect holds it: a hostname route or a PCP/UPnP grant for external 80 conflicts, and the Published Ports prompt reports it as a router service, not a hostname route.
  • start-core: TcpMetadata.local_addr on a plain TcpListener is now the connection's destination (stream.local_addr()), as WildcardListener already reports it. Nothing else reads that field off a wildcard TcpListener.

Remote Access is unchanged: who may reach the router UI or SSH from the WAN is decided by the existing rules. The one surface change is that, while 443 is published, port 80 at the WAN address answers a 307 under every mode, "Never" included.

Testing

Unit tests cover desired (DNAT, protocol, range, disabled, hostname routes, port-80 precedence), the per-request decision (shut gate, WAN address, connected clients, WAN-side clients at a LAN address, unread addresses, WAN down, v4-mapped, IPv6), the layer's response, the rule reconcile (settle, withdraw, change of holder, purge by a build without the redirect), and the port-80 reservation.

Benched on a K1 behind another NAT (Remote Access "Never") at 3f1fa0d38, all pass; 181bbcdf3 after it is comment- and docs-only:

  • WAN-side and LAN-hairpin http://<WAN>/ → 307 with the client's own Host; router.lan and the LAN address serve the UI
  • Reboot: LAN UI answers 200 on the first request; WAN-side never sees a 200
  • WAN unplugged: the LAN still gets the UI
  • Unpublish and republish 443 in a loop: only 307 or refused, never the UI
  • A port-80 Published Port takes precedence; a StartOS hostname route on 443 activates the redirect
  • A host on the outer LAN routing the inner LAN subnet through the router → 307 at the LAN address

Known gaps

  • A subnet that comes up after the last address read is redirected until the next reread, at most 5 s after its first request.
  • IPv6 is outside the admission rule and the layer.

Start here

http_redirect.rs redirects and desired; port_control.rs sync_sni_rules_inner and reconcile_sni_rules_uci.

Shadowy Super Coder added 2 commits September 17, 2026 12:47
… 443 is published

StartOS asks its IPv4 gateway for no port-80 mapping: it publishes only 443
and expects the gateway to answer plain HTTP at the public address with a
redirect to HTTPS, as StartTunnel does. StartWRT never implemented its half,
so a LAN client opening http://sub.example.com for a domain pointing at the
WAN address hairpinned to the router's own port 80 and got the router UI.

Port control now binds a listener to <WAN IPv4>:80 beside the daemon's
wildcard :80 (both SO_REUSEPORT; the kernel delivers a connection to the
most specific socket) and hands each connection to start-core's shared
handle_http_on_https, a 307 to the same host and path over HTTPS. The socket
is never wired into the axum app, so it can serve nothing but the redirect,
and the LAN gateway addresses and router.lan still reach the UI.

No firewall rule is touched: who may reach WAN:80 remains the Remote Access
policy; this changes only what answers there. The listener is bound only
while WAN 443 leaves the router (an enabled WAN DNAT covering tcp/443, or a
live hostname route on 443) and yields to a DNAT on tcp/80, so a router
publishing nothing on 443 behaves exactly as before. Reconciled at port
control startup, on the sweep, on hostname route changes, and when a manual
published port is saved.
… DNAT

The redirect listener on WAN:80 answered only connections the wan zone
already admitted, so under Remote Access "Never" (or "When behind NAT"
with a public address) a client on the Internet opening
http://sub.example.com was refused. StartOS publishes only 443 and leaves
port 80 to its gateway, and that half of the contract was unmet from
outside.

An ACCEPT on wan tcp/80 would be fail-open: UCI rules persist across a
daemon restart and fw4 loads them before the daemon binds, so the UI's
wildcard :80 socket would answer in that window or after a failed bind.
Instead, port control writes a wan-zone DNAT (`startwrt_http_redirect`,
no dest_ip, which fw4 renders as an nft `redirect to :8880`) while 443 is
published, and the redirect binds 0.0.0.0:8880 beside its WAN:80 socket.
fw4 accepts DNAT'd connections at input, so no ACCEPT rule opens 80, and
with the daemon down the DNAT lands on a closed port.

The section carries its own marker option rather than `_apf_label`,
which the sweep would lease and collect and the UI would list as an
automatic forward. `wan_dnat_covers` ignores it so the redirect does not
gate itself off, `apply_forward_uci` still counts it so PCP/UPnP grants
for external 80 conflict while it is active, and `sni_port_conflicts`
reserves 8880 so no hostname route can out-rank the wildcard socket. The
section's presence no longer depends on knowing the WAN address, which
avoids a remove-and-re-add firewall reload at every boot; only the WAN:80
hairpin socket needs the address.

Reconciliation runs under `write_serial`. Callers that already hold it
use the serialized variant, and `published_ports::set` skips the
redirect's own firewall reload since it reloads anyway. A settled section
is never rewritten, so the sweep does not reload fw4 every minute.

Under "Never", port 80 now answers a 307 instead of rejecting while 443
is published. It echoes the requested Host and can serve nothing else.
@helix-white

Copy link
Copy Markdown
Member

@Dominion5254 — dr-bonez raised a design question on this in Matrix: why bind separate listeners (the wan:80 hairpin socket and the 0.0.0.0:8880 socket behind a DNAT) rather than decide per request from the connection's destination address on the listener the daemon already has, the way StartOS does on its own port 80? I went through the code with that in mind; here is the proposal in full so you can make the call. dr-bonez's read is that it's probably the cleaner solution, but he wants it to be your decision.

The proposal

One outermost Router::layer on the daemon's existing wildcard [::]:80 listener, and no new sockets:

if listener is Http
   && to_canonical(dst) ∈ current WAN IPv4 set
   && WAN 443 is published (the same predicate as `http_redirect::desired`)
→ 307 to https://<Host><path>  (`startos::net::http::https_redirect_uri` / `request_authority`)
else → next.run(req)
  • LAN hairpin (http://<WAN IP> from inside): arrives via the lan zone at the wildcard socket with dst = WAN IP. No firewall change.
  • Internet side under Remote Access "Never" / "When behind NAT": one input ACCEPT for wan tcp/80, present only while 443 is published and yielding to a user's port-80 DNAT — the same shape as desired_sni_rule and reconciled the way reconcile_sni_rules_uci does (write on the gate flipping on, remove on flipping off, purge in run()). Under "Always" the startwrt_remote_80 rule already admits it; the layer does the work in every mode.
  • The gate state (WAN address set + "443 published") lives in a cache port control already effectively maintains (wan_ipv4(), wan_dnat_covers, the SNI snapshot), read per request. PORT_CONTROL is set at daemon.rs:370, before the :80 bind at :456.

Why the plumbing already exists

  • WebServer visits the acceptor metadata into every request's extensions (shared-libs/crates/start-core/src/net/web_server.rs, SwappableRouter::call), and start-wrt's SessionAuth already reads TcpMetadata.peer_addr out of them (middleware/auth.rs:116-130); local_addr is the other field of the same struct.
  • The direct StartOS precedent is net/domain_redirect.rs: an outer layer on startd's [::]:80 wildcard that reads GatewayInfo from the request extensions and answers a 307 with https_redirect_uri (wired at static_server.rs, apply_outer_layers).
  • start-wrt's own wildcard 443 TlsListener already makes a same-socket decision: plain HTTP on 443 gets a 307 from handle_http_on_https (net/tls.rs:136-160) — the helper http_redirect.rs calls from its raw sockets.

One snag

impl Accept for TcpListener (web_server.rs:118) fills local_addr with self.local_addr() — the listener's bound address — so on [::]:80 it reads [::]:80, not the connection's destination. WildcardListener (net/gateway.rs:3232) uses stream.local_addr(). It's a one-line change in start-core: nothing reads TcpMetadata.local_addr off a wildcard TcpListener today (served_name and arrival only see vhost/WildcardListener metadata; the tunnel and registry handlers ignore it), and for a specifically-bound listener the two are equal. Alternatively a start-wrt-local acceptor modelled on WildcardListener, with zero shared blast radius. Either way compare after to_canonical(), since the socket is dual-stack and IPv4 clients arrive v4-mapped.

On the fail-open argument

The body rejects an ACCEPT rule because "fw4 loads UCI before the daemon binds, so the UI would answer in that window". Traced: the UI wildcard binds at daemon.rs:456, while wan:80 / :8880 bind only once port_control::run (spawned at :371) has purged the SNI rules, reloaded the firewall and reached sync_http_redirect. With an ACCEPT rule, the UI socket would answer WAN:80 in that gap — that is what forced the DNAT. But the gap exists because the redirect is a second socket bound later. With the decision in the request path it is live from the first accept; there is no second bind to wait for. The one obligation is to fail closed while the cache is unseeded — a request whose dst is not a LAN/loopback address gets the 307 (or a refusal), never the UI. The current design keeps the same shape of window for LAN hairpins anyway: between the UI bind and Redirect::bind, http://<WAN IP> from the LAN gets the UI.

What it costs — stated plainly

  • Rollback flips from fail-closed to fail-open. A stale startwrt_http_redirect DNAT on a build without the marker resets WAN:80 (your Known gaps); a stale ACCEPT on a build without the layer serves the plaintext UI on WAN:80 under "Never". That is the same class the SNI admission rules on 443 carry today — a persisted apf_sni_443 plus the wildcard 443 bound before run()'s purge means the TLS UI answers WAN:443 under "Never" across every daemon restart on the current build — so either it is acceptable for both or it is a pre-existing gap independent of this PR. dr-bonez considers the trade acceptable.
  • The special-casing moves rather than vanishes. The rule needs its own label (the SNI reconcile purges any KIND_SNI rule whose port isn't in the demux's set) and exclusions in wan_reserved_overlaps / sni_port_conflicts so it isn't reported as a router-service reservation. PCP/UPnP grants on external 80 conflict either way, via reserves_wan_port — which the code treats as desired.
  • Isolation. The strongest argument for the current design is "never wired into the axum app, so it can serve nothing but a 307". A layer has to be outermost and correct for every route (LuCI proxy, /rest, /ws, fallback). StartOS already makes that trade the other way in domain_redirect, so it's a judgement call, not a blocker.

What goes away

Port 8880 and its reservation (and router.lan:8880 answering 307s), the hairpin socket and rebind_hairpin on every WAN-address change, the _startwrt_http_redirect marker, the family field on FirewallRedirect, the impostor-replacement logic in reconcile_section_uci, and wan_dnat_covers' self-exclusion — most of the ~900 lines, replaced by a layer, a labelled rule reconcile, and the one-line acceptor change.

A defect in the current design, independent of the decision

desired() gates on a DNAT covering 80 but not on a hostname route on 80, and sni_port_conflicts(80) is false while the section is active (the section is excluded from wan_dnat_covers). So a UPnP client can be granted an SNI route on external 80 while the redirect is up. WAN-side that route is dead — the prerouting DNAT to 8880 runs before the demux's input ACCEPT — and LAN-side the demux's <WAN>:80 reuseport socket sits at equal specificity beside the hairpin <WAN>:80 socket, so the kernel splits LAN hairpins between a 307 and the demux. Low incidence (StartOS only asks for 443), but silent. Under the dst-based design the same sni_port_conflicts exclusion is what would need adding for the ACCEPT rule, so it's worth settling in either shape.

Also noting for accuracy: the body's "as StartTunnel does" is correct — tunnel/redirect.rs binds a socket per public IPv4 — but StartTunnel's UI listens on a specific ctx.listen address, so there is no shared wildcard to decide on. StartWRT's UI is on [::]:80, which is exactly the case the per-request check fits.

Your call. If you'd rather I prototype the layer on a branch so the two can be compared on the K1, say so and I'll do that rather than leave it as prose.

Shadowy Super Coder added 3 commits September 18, 2026 21:25
…path

The redirect bound two sockets of its own — <WAN>:80 for LAN hairpins and
0.0.0.0:8880 behind a wan-zone tcp/80 DNAT for the Internet side — because a
socket bound after the UI's wildcard :80 cannot be admitted by an ACCEPT rule
without the UI answering in the gap between the two binds. Deciding per
request removes the gap and with it the reason for both sockets: an outermost
layer on the router answers a request whose destination is the WAN address
with a 307 and passes everything else through, live from the first accepted
connection. StartOS makes the same trade in net/domain_redirect.rs.

Gone with them: port 8880 and its reservation, the hairpin rebind on every WAN
renumber, the startwrt_http_redirect section and its marker, the family field
on FirewallRedirect, the impostor-replacement logic, and wan_dnat_covers'
exclusion of its own section.

The Internet side is now a WAN ACCEPT rule on tcp/80, carried in the SNI
admission set rather than reconciled separately, so sync_sni_rules is the one
place the redirect is decided. It keeps the SNI label deliberately: a label
older builds do not know is a rule older builds never purge, and such a rule
outliving a downgrade would admit plain HTTP to a daemon with no layer behind
it. Sharing the label means a rollback purges it on its first run, as it
already does for a stale apf_sni_443.

The gate the layer reads is that rule's presence, not "443 is published". The
two disagree exactly at startup — a hostname route does not survive a restart
but the rule it earned does — so the gate is seeded from UCI before the
listener binds and tracks what the firewall actually admits. Until port
control resolves the WAN address the layer redirects rather than falling
through, since a double-NAT WAN is not separable from the LAN by address
class.

TcpMetadata.local_addr now comes from the accepted stream rather than the
listener, which is the connection's destination on a wildcard socket and
identical to the old value on a specifically bound one. served_name and
arrival are its only readers and both want the destination.

Also reserves port 80 against hostname routes while the redirect is up, which
the DNAT did not: a UPnP grant could take external 80 and be silently dead
WAN-side.
…ination alone

The port-80 admission rule matches the wan zone, not a destination, and the
layer redirected only a request whose destination was the WAN address. Four
consequences, found auditing b700399 against the PR discussion:

A WAN-side host that routes the LAN subnet through the router's WAN address
arrives at the LAN address and was served the plaintext UI under "Never". The
DNAT this replaced caught all wan-zone tcp/80, so that was a regression. The
layer now serves the UI only to a client on a subnet the router is connected
to off the WAN, at an address that is not the WAN's; every other IPv4 request
gets the 307. The gate carries every WAN address rather than the first.

After a restart the gate was seeded admitted with no WAN address, which
redirected every plain-HTTP request, LAN included, until the first 60 s sweep
and for as long as the WAN had no address. Addresses are now read before the
listener binds, when port control starts, on every sweep and WAN hotplug, and
once more (at most every 5 s) before a redirect is answered, so a bridge that
comes up after the daemon is trusted on its first request. With the WAN down
there is no WAN subnet to exclude and the LAN keeps the UI.

The gate was set to the wanted state before the rule was reconciled, so
unpublishing 443 shut it while fw4 still admitted WAN:80 — the UI answered
there until the reload finished, or indefinitely if it failed. It now opens
before the rule is written and shuts only after the reload that removes it.

A hostname route on 80 writes the same section under the same label, and the
redirect's rule was identified by port alone: the route's own rule read as
the redirect's, so its renewal was refused as taken and a manual port-80
forward was refused rather than displacing it. The rule's name now tells the
two apart, the redirect yields to a live route on 80, and the rule is
rewritten when the port changes hands. The seed still opens the gate on any
SNI rule on 80, since a lapsed route's rule admits the same traffic. The
label stays shared, so a build without the redirect still purges the rule.

Not migrated: the startwrt_http_redirect section written by 7207775. It
reads as a user's port-80 forward and holds the redirect off, but no build on
master ever wrote it; a bench router that ran that commit needs
`uci delete firewall.startwrt_http_redirect`.
…he facts

Review on #3999 asked for the mannered prose to go throughout, and this branch
carried the same habits: a 23-line module doc, doc comments that argued their
rationale and named their callers, tests narrating what their names state, and
user docs saying the same thing three times.

Each comment is now one fact. The changelog entry, release note,
`published-ports.md` and `settings.md` state the behavior once.

`ARCHITECTURE.md` also described the layer as keyed on the connection's
destination, stale since 3f1fa0d, and omitted the per-request reread of stale
addresses.

Comment-only in every `.rs` file.
@Dominion5254

Dominion5254 commented Sep 21, 2026 •

Copy link
Copy Markdown
Member Author

@helix-nine — took the proposal. The branch now decides port 80 per request on the existing listener; the head is 181bbcdf3 and the PR body is rewritten to match.

Adopted as proposed (b700399fb): the outermost layer, the wan tcp/80 ACCEPT reconciled with the SNI admission rules and purged in run(), the gate read per request, stream.local_addr() in start-core's TcpListener acceptor, and comparison after to_canonical(). Gone with it: port 8880, the hairpin socket and rebind_hairpin, the _startwrt_http_redirect marker, family on FirewallRedirect, and wan_dnat_covers' self-exclusion.

The defect you flagged is fixed: desired() yields to a hostname route on 80, and sni_port_conflicts(80) is true while the redirect's rule is present.

Where it departs from the proposal (3f1fa0d38, from an audit of the refactor):

  1. The decision is not on the destination alone. The ACCEPT matches the wan zone, so a WAN-side host that routes the LAN subnet through the router's WAN address arrives with dst = LAN address and would have been served the plaintext UI under "Never". The layer serves the UI only to a client on a connected subnet off the WAN, at a non-WAN address. Benched from a box on the outer LAN: 307 at the LAN address.
  2. The rule keeps the SNI label rather than getting its own. That answers the rollback cost you listed: a build without the layer purges any SNI rule whose port the demux doesn't want, so a rollback removes the rule instead of leaving port 80 open. The rule's name tells the redirect's hold on 80 from a hostname route's; without that, a route on 80 could not be renewed and was reported as a router service.
  3. Gate ordering. It opens before the rule is written and shuts only after the reload that removes it, so turning the redirect off never leaves a window with the rule live and the layer off.
  4. Seeding. The gate is seeded before the listener binds, from any SNI rule on 80 and the router's current addresses. The first cut seeded without addresses and redirected all LAN HTTP for up to a minute after boot, and for as long as the WAN was down. Addresses are also reread, throttled, before a redirect is answered, so a bridge that comes up after the daemon is trusted on its first request.

181bbcdf3 cuts the comments, changelog, release note and book text to the facts, per dr-bonez's review on #3999. It changes no code.

Anyone who ran the earlier head (720777534) on a router still has firewall.startwrt_http_redirect, which holds the redirect off as a port-80 DNAT until uci delete firewall.startwrt_http_redirect && fw4 reload. It was never on master, so there is no migration.

@helix-white

Copy link
Copy Markdown
Member

Read 181bbcdf3 against master and checked each departure against the code.

Verified: cargo test -p startwrt-core -p uciedit -p uciedit_macros on the head — 598 + 18 passed, 0 failed; prettier clean on the five .md files; the start-core change is the one line in TcpListener's Accept impl plus its doc, and nothing reads TcpMetadata.local_addr off a wildcard TcpListener elsewhere, so the tunnel, registry and vhost paths are unaffected.

On the departures:

  1. Client subnet rather than destination alone — right, and it's the correct fix for the zone-scoped ACCEPT: a WAN-side host routing the LAN subnet through the router arrives with a LAN dst, and redirects() handles it by requiring the peer to be on a connected off-WAN subnet. The fail-closed cases read correctly too: unknown addresses → 307, WAN down + LAN peer → UI, IPv6 → never (outside the family ipv4 rule).
  2. Keeping the SNI label — this closes the rollback cost I listed. a_build_without_the_redirect_purges_its_rule exercises exactly what an older sync_sni_rules_to asks for, and the rule name as the discriminator lets reconcile_sni_rules_uci rewrite the section when port 80 changes hands between a route and the redirect (port_80_changing_hands_rewrites_its_rule). Cleaner than a separate label.
  3. Gate ordering — confirmed in sync_sni_rules_inner: set_admitted(true) before the write, set_admitted(false) only on the reload == true path after reload_firewall_wait. One consequence worth knowing, not a blocker: sync_sni_rules_before_reload (from published_ports::set) passes reload = false, so when a user's own rule withdraws the redirect — publishing 80, or unpublishing 443 — the gate stays open until the next reload = true sync, i.e. the 60 s sweep or the next SNI change. That's the safe direction (WAN-side the rule is already gone after the caller's reload; a LAN hairpin to WAN:80 gets a 307 instead of the UI for up to a minute), and shutting it inside that call would reopen the window (3) avoids, so I'd leave it. Just noting that "shuts only after the reload that removes it" holds by way of the sweep for that one caller.
  4. Seeding — seed() counting any SNI-labelled rule on 80 as admitting, a hostname route's persisted rule included, is the right direction: after a reboot the route is gone from memory but its rule survives until run() purges, and in that gap WAN:80 should 307 rather than serve the UI.

Nothing else from me. Reads ready to merge from my side; approval is dr-bonez's call.

Dominion5254 added 3 commits September 21, 2026 16:55
…the UI

`redirect()` returned `None` when the request carried no usable `Host`, and
`respond()` read that as "not the redirect's request" and fell through to the
UI. A WAN-side client could reach the plaintext router UI while 443 is
published with `printf 'GET / HTTP/1.0\r\n\r\n' | nc <WAN> 80`, under every
Remote Access setting.

Once the layer has decided a request redirects, it now always answers: a 307
with an authority, a `400 Host header required` without one, which is what the
standalone redirect socket this layer replaced answered.
…alone

The redirect's admission rule matched the wan zone with no destination, so
the firewall also admitted a WAN-side packet for the router's LAN address to
the daemon, and only the layer's client-subnet check kept it from the UI. The
rule now carries `dest_ip` set to the WAN address, so such a packet is
rejected at the firewall as it was before the redirect existed; the layer's
check stays as the second line.

Port control rewrites the rule when the WAN address changes (the sweep and
the WAN hotplug already invalidate the cached address) and writes none while
the address is unknown. The gate still opens whenever the redirect is wanted,
so a LAN hairpin to the WAN address redirects with or without the rule.
@Dominion5254

Copy link
Copy Markdown
Member Author

Two more commits since the reply above, from a bench walk-through of the layer:

  1. A Host-less request fell through to the UI (0ede56dbc). redirect() returned None without a usable Host, and respond() read that as "not mine" and passed the request to the UI. printf 'GET / HTTP/1.0\r\n\r\n' | nc <WAN> 80 served the plaintext UI WAN-side under "Never" while 443 was published. Once the layer decides a request redirects it now always answers: 307 with an authority, 400 Host header required without one, as the standalone socket did.

  2. The admission rule carries dest_ip <WAN> (826688284). Zone-only, it also admitted a WAN-side packet for the router's LAN address, leaving the layer's client-subnet check as the only thing between it and the UI. The rule now admits the WAN address alone and the firewall rejects such a packet as it did before the redirect; the layer's check stays as the second line. Port control rewrites the rule when the WAN address changes and writes none while it is unknown.

Benched on the K1 (double NAT, Remote Access "Never", Linux probe on the outer LAN): Host-less and malformed-Host probes get 400; a routed packet for the LAN address is refused; the LAN still gets the UI with or without a Host; the hairpin still redirects; unpublishing 443 withdraws the rule and WAN:80 is refused again. The rewrite on WAN-address change is unit-tested only.

@helix-white

Copy link
Copy Markdown
Member

Read 0ede56dbc and 826688284 on the head (826688284), plus the merge.

Verified: cargo test -p startwrt-core -p uciedit -p uciedit_macros — 603 + 18 passed, 0 failed; prettier clean. The merge commit differs from a mechanical git merge-tree of its parents only in CHANGELOG.md, where the markers came out with both sides kept — diff of master's vs HEAD's CHANGELOG is exactly the PR's 8 lines, and origin/master...HEAD is still the 11 intended files. On the fw4 half of 6 I have only your bench: a src wan rule with no dest lands in input_wan and dest_ip renders as ip daddr, so I'm taking "a routed packet for the LAN address is refused" as measured rather than something I can confirm from this repo.

5 and 6 both hold. respond() now returns Some for everything redirects() accepts — I tried HTTP/1.0 without Host, an unparseable Host, absolute-form targets, *, and h2c prior-knowledge with no :authority; every one lands on 307 or 400, and a missing TcpMetadata still redirects. The dest_ip reconcile is tight: keep requires the name and dest_ip to match, seen only records kept rules, and scope = None drops 80 from want, so a stale-address rule is always replaced, never left beside a new one.

Two things the walk-through turned up. Neither is introduced by these two commits — both have been in the branch since b700399fb — but the first is the upgrade path for every router that already publishes 443, so I'd fix it before merge.

1. Boot race: run() is spawned before seed(), and seed() can lower the gate

daemon.rs:376-377 spawns port_control::run inside !setup_mode; seed() runs at :463-464, ~90 lines later, and the :80 listener binds at :469. run() (port_control.rs:1716-1724) does refresh_addrs → sync_sni_rules → sync_sni_rules_inner, which calls set_admitted(true) before writing the rule and reloading. seed() does refresh_addrs → parse → set_admitted(port_admitted(..)), and that sets false when no SNI-labelled rule on 80 is on disk yet. The two refresh_addrs calls serialise on REFRESHED, which puts seed's parse right around run's write. If seed's parse lands before run's UCI write and seed's set_admitted(false) lands after run's set_admitted(true), the result is: rule live (ip daddr <WAN> tcp dport 80 accept), gate shut, listener bound → WAN:80 serves the UI under "Never" until the next set_admitted(true) — the first sweep, which fires at 60 s (run_sweep consumes the immediate tick).

Precondition: desired() true with no rule on disk when seed parses — i.e. the first start on this build for anyone who already has a 443 Published Port (the SNI snapshot is empty at boot, so the DNAT is what makes desired() true), or any start after a rollback build purged the rule. A plain restart with the rule already in UCI is fine, and so is an upgrade from 181bbcdf3's zone-only rule, which seed counts.

Fix is a reorder — seed before the spawn, both under !setup_mode:

        // daemon.rs, in the `if !setup_mode {` block at :360, before PORT_CONTROL.set / tokio::spawn(run)
        crate::http_redirect::seed("/etc/config".into()).await;

and drop the block at :462-465. Seeded first, the worst boot state is "rule absent, gate shut" → refused at the firewall, and run() raises the gate before it writes. (Making seed only ever raise the gate would also close it, but the ordering says why.)

2. An ubus failure makes the gate trust the WAN subnet

read_addrs() (http_redirect.rs:83-100): wan = spawn_blocking(wan_ipv4_addrs).await.unwrap_or_default(), and wan_ipv4_addrs() returns Vec::new() on any ubus failure (system.rs:260-281). With wan empty, off_wan filters nothing, so gate.local includes the WAN interface's own subnet. If the rule is live — written from a cached wan_ipv4() (≤30 s) or a prior sync — a peer on the WAN subnet (the outer LAN under double NAT, or a shared ISP segment) dialling <WAN>:80 gets redirects() == false (dst ∉ wan, peer ∈ local) → the UI, until the next successful read (≤60 s). That contradicts "unreadable, they leave no client trusted" (http_redirect.rs:65, ARCHITECTURE.md): it's true of ip addr failing and false of ubus failing.

wan_ipv4_addrs has eight other callers that want the Vec, so rather than change its signature I'd give the gate a checked variant — Option<Vec<Ipv4Addr>>, None when ubus fails — and in read_addrs take None to local = Vec::new() (nobody trusted, 307 for all, fail closed) while Some(vec![]) keeps today's WAN-down behaviour (LAN still gets the UI at the LAN address, which unresolved_addresses_fail_closed_without_a_wan pins).

Minor, non-blocking

  • dest_ip admits /ipv4-address/0 only (get_wan_ipv4), while the gate lists every WAN IPv4; on a multi-address WAN the second address is now refused on 80 rather than redirected. Fail-closed narrowing — fine, just naming it.
  • A transient scope = None on a sweep deletes the rule and reloads, then re-adds and reloads next sweep — two reloads per ubus hiccup, fail-closed.
  • Host: name:80 → Location: https://name:80/, a dead redirect. Same as start-core's handle_http_on_https, where :443 on the TLS port is right; on 80 it isn't. Browsers omit the default port so it rarely bites; not this PR's to fix unless you want to strip :80 locally.
  • The sync_sni_rules_before_reload path (reload=false) still leaves the gate open ≤60 s after an unpublish, as noted before — LAN hairpins get a 307 to a now-unpublished https instead of the UI. WAN side is closed.

Happy to push the reorder (and the checked-read variant if you want that shape) to the branch, or leave both to you — say which.

Shadowy Super Coder added 2 commits September 22, 2026 15:03
`port_control::run` was spawned before `http_redirect::seed` ran. `run`
raises the gate before writing the admission rule; `seed` sets the gate
to whether an SNI rule on 80 is already on disk. On the first boot of a
router that already publishes 443, no such rule exists yet, so `seed`'s
parse could read the old firewall and its `set_admitted(false)` land
after `run`'s `set_admitted(true)`: rule live, gate shut, listener
bound, and WAN:80 served the plaintext UI until the first sweep at 60 s.

Seeding before the spawn leaves "rule absent, gate shut" as the worst
boot state, which the firewall refuses.

Found by helix-nine in review of #4000.
`wan_ipv4_addrs` returns an empty list on a ubus failure, which the gate
could not tell from a WAN with no address. With no WAN address to
subtract, the WAN interface's own subnet stayed in the trusted set, so a
peer on that subnet dialling `<WAN>:80` got the UI instead of a 307
while the admission rule was still live from a cached lookup, until the
next successful read.

`read_wan_ipv4_addrs` returns `None` on a ubus failure and the gate then
trusts no subnet; an empty list still means the WAN is down and keeps
serving the LAN at its own address.

Found by helix-nine in review of #4000.
@Dominion5254

Copy link
Copy Markdown
Member Author

Both confirmed and fixed. Head is now e1eb9e9.

  1. Boot race — 42dce4f. seed() runs before the port_control::run spawn, in the same !setup_mode block; the call before the bind is gone. Bench on the K1 (double NAT, Remote Access "Never"): deleted apf_sni_80 and restarted the daemon three times under a WAN-side probe loop. Each restart: about a second refused, then 307. No 200.

  2. ubus failure — e1eb9e9. read_wan_ipv4_addrs() -> Option<Vec<Ipv4Addr>> is None on a ubus failure; wan_ipv4_addrs() wraps it, so its callers are unchanged. off_wan trusts no subnet on None; an empty list still means WAN down. Bench: bind-mounted /bin/false over /bin/ubus; the first WAN-subnet probe after the 5 s floor got 307. The sweep then withdrew the rule and port 80 was refused until the sweep after the unmount.

Minor items left as they are. 603 + 18 tests pass.

@helix-white

Copy link
Copy Markdown
Member

Read 42dce4f66 and e1eb9e92c on the head (e1eb9e92c); both close what I described.

  • Boot race: seed() now sits at daemon.rs:376, ahead of PORT_CONTROL.set / the run spawn at :379, inside the same !setup_mode block, and the pre-bind call is gone. Worst boot state is now "rule absent, gate shut" → refused at the firewall, and run() raises the gate before it writes. Your three-restart bench (~1 s refused, then 307, never 200) is the sequence I'd expect.
  • ubus failure: read_wan_ipv4_addrs() -> Option<Vec<Ipv4Addr>> with wan_ipv4_addrs() as the unwrap_or_default() wrapper leaves the eight other callers untouched; off_wan(_, None) returns nothing trusted while Some(vec![]) keeps the WAN-down behaviour unresolved_addresses_fail_closed_without_a_wan pins. The /bin/false-over-ubus bench matches: 307 for the WAN-subnet probe after the 5 s floor, then the sweep withdrawing the rule. The doc line "unreadable, they leave no client trusted" is now true of both reads.

Verified on the head: cargo test -p startwrt-core -p uciedit -p uciedit_macros — 603 + 18 passed, 0 failed; prettier clean on ARCHITECTURE.md.

Nothing further from me — ready to merge from my side; approval is dr-bonez's call.

@dr-bonez
dr-bonez merged commit 0fb466c into master Sep 27, 2026
32 checks passed
@dr-bonez
dr-bonez deleted the feat/wrt-http-redirect branch September 27, 2026 20:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants