oficina / equipo Public

hostedproxy: review round 1 (expiry, bounds, address guard, logs)

Task 6 review round 1, all seven findings: a certificate's monotonic
deadline is fixed at first sight per serial; request line and headers
are bounded at both parse points; the log holds only a canonical
destination; service hosts resolve once to checked public addresses,
dialled directly; bootstrap decisions are logged; origin TLS has
regression tests; only HTTP/1.1 is accepted at both boundaries.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev cf65db7f71f3e6cbcf1f929196c91284c26e666a parent 0b4ee6b
9 files changed, +840 −94
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +26 −0
  • internal/hostedproxy/boot.go +39 −17
  • internal/hostedproxy/egress.go +119 −19
  • internal/hostedproxy/egress_test.go +392 −8
  • internal/hostedproxy/feed.go +54 −23
  • internal/hostedproxy/log.go +75 −15
  • internal/hostedproxy/origin.go +80 −7
  • internal/hostedproxy/policy.go +9 −0
  • internal/hostedproxy/policy_test.go +46 −5
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index d0186f13..90a01366 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -244,3 +244,29 @@ Mutation checks (each applied by script, the named test run, then restored and c
9. (extra) Wildcard listeners allowed, in both layers (`checkListen`'s `IsUnspecified` check and `NewServer`'s). Command: `CGO_ENABLED=0 go test ./cmd/equipo-hosted-proxy -run 'TestConfigRefusesWildcardListen' -count=1`. Observed: FAIL, `config_test.go:111: listeners on "0.0.0.0" were accepted`, `"[::]"`, `"[::ffff:0.0.0.0]"`. Restored. (Either layer alone still refuses; the test first gave the wildcard to one listener only, where the one-address rule refused it, and now gives it to both.)
Also run: `go test ./internal/hostedproxy ./cmd/equipo-hosted-proxy -count=1 -race` once, ok (2.3 s and 1.1 s); `go test ./internal/isolatedjob -run TestProviderTypesStayInAdapter -count=1` ok; staticcheck v0.7.0 on both packages ok; gofmt clean; `make budget build vet` ok (126 directories within budget).
+
+### Task 6 review round 1 (t6-r1.md: all seven findings)
+
+1. Certificate expiry no longer moves with a feed. `Feed.certEnd` fixes each serial's NotAfter on the monotonic clock the first time the serial is judged (normally the egress handshake's CONNECT check), against the wall clock read then, and keeps it; `Install` no longer records a wall anchor and only prunes serials more than 24 h past their deadline. TestDecideCertExpiryFixedAtFirstSight: a 2-minute certificate, a minute on the wall clock goes back 30 s and a fresh feed arrives; the deadline stays at first sight plus 2 min, it is allowed 1 ms before and `cert_expired` 1 ms after, and stays expired after another feed with the wall clock an hour back. TestStaleFeedDeniesAll now sees the certificate at receipt, as the handshake would, before its wall clock jumps.
+2. Header bounds at both parse points. `headerLimit` sits between the connection and the `bufio.Reader`: while `readRequest` parses one request line and its headers it lets through at most `maxHeaderBytes` (16 KiB, the bootstrap server's `MaxHeaderBytes`), then reports EOF; between parses it is unlimited, so bodies, the ClientHello after the CONNECT and piped bytes pass and nothing buffered is lost. Past the bound: 431, logged `bad_request` with status 431, and a lingering close (stop writing, drop input for at most 500 ms or 1 MiB) so the refusal is read before a reset. The CONNECT bound applies before any launch check, so a revoked certificate is bounded the same way. TestHeaderBounds: a 64 KiB CONNECT line and a MiB of CONNECT headers, each with a current and a revoked certificate; a 64 KiB request line and a MiB of headers inside a tunnel; each 431, the origin sees nothing; an 8 KiB header still passes twice on one tunnel.
+3. The log holds only a canonical destination. `canonicalDestination` rebuilds host:port from a valid DNS name (lower-cased) or IP and a decimal port; anything else, user info, a path, a query, an underscore, is `invalid`. TestLogHasNoSecrets adds five refused CONNECT targets carrying secrets in user info, a path, a query, after an `@` and in a non-DNS name; each is logged as `invalid` and none of the secrets appears.
+4. Resolved-address guard (ruling: now). `Config.Resolver` (nil: `net.DefaultResolver`). `dialOrigin` looks the service host up once; every answer must pass `allowedOriginAddr` (IPv4-mapped judged as IPv4; refused: loopback, link-local, private RFC 1918 and ULA, unspecified, multicast, broadcast and any non-global-unicast, 100.64/10, 0/8, `::/96`, the NAT64 prefixes `64:ff9b::/96` and `64:ff9b:1::/48`, 6to4 `2002::/16`), and an answer mixing an allowed address with a refused one is refused whole (`ErrOriginAddress`). It then dials the checked addresses themselves (`DialOrigin` gets `ip:443`), never the name, with TLS still verified for the name. A refusal answers 502, logged `origin_address`. TestOriginAddressGuard: IPv4, IPv6, mapped and dual answers dial only checked addresses with one lookup each; 25 refused answers (IPv4, IPv6, mapped, compatible, NAT64, 6to4, mixed both ways) dial nothing; through tunnels, an answer that changes from public to loopback gives 200 then 502, one origin hit, two lookups, and only address dials.
+5. Bootstrap decisions are logged: one line per request on `/redeem`, `/renew`, `/cert-report` with destination `controller`, path class `bootstrap`, the route, allow (forwarded; the controller's status) or deny with the proxy's code (`bad_request`, `no_certificate`, `bad_certificate`, a feed reason, `serial_mismatch`, `controller_unavailable`), the status, and body sizes in and out. Identity only from a certificate TLS verified; a redemption without one is logged with none. TestBootLogs covers a redemption (no identity), a renewal without a certificate, a renewal of another serial (identity from the certificate) and a report, with secret-bearing codes, CSRs, reports and signatures that never reach the log.
+6. Origin TLS regression: TestOriginTLSVerified, an origin certificate for another name and one from an untrusted CA each give 502 with an Authorization header in the request, and the origin receives no request; the right certificate then gives 200.
+7. HTTP/1.1 only at both boundaries: `readRequest` refuses any other version with 505, logged `bad_request` with status 505. TestHTTP11Required: HTTP/1.0, 1.2, 2.0 and 0.9 for the CONNECT and inside a tunnel offering ALPN `http/1.1`; each 505, the origin sees nothing.
+
+New reasons outside `Decide` (please confirm): `bad_request` (oversized or wrong version) and `origin_address`. Opaque bytes in a tunnel stay `nested_tunnel`. Test environment: testHost resolves through a fake resolver to 203.0.113.10 (or 2001:db8::10), which the test dialer sends to the origin listener; the origin certificate can be swapped.
+
+Mutation checks (each applied by script, the named test run, then restored and checked byte for byte with `cmp`; `git status` clean of mutations after):
+
+10. Recompute a certificate's deadline on every judgement (`ok && false` on the `certEnds` lookup, `feed.go`). Command: `CGO_ENABLED=0 go test ./internal/hostedproxy -run '^TestDecideCertExpiryFixedAtFirstSight$' -count=1`. Observed: FAIL, `policy_test.go:364: Deadline after the jump and the fresh feed = 1h2m30s, want the first sight's 1h2m0s`, `policy_test.go:372: 1 ms after the deadline (wall clock 30 s behind): {Allow:true ...}, want cert_expired`, `policy_test.go:380: after another feed and the wall clock an hour back: {Allow:true ...}, want cert_expired`. Restored.
+11. No header bound (`lim.remain` set to `math.MaxInt64` for the parse, `egress.go`). Command: `... -run '^TestHeaderBounds$' -count=1`. Observed: FAIL, `egress_test.go:889: a long CONNECT line: answered "HTTP/1.1 403 Forbidden", want 431`, `CONNECT with a MiB of headers: answered "HTTP/1.1 200 Connection established"`, both revoked-certificate rows `403`, `egress_test.go:903: in a tunnel, a MiB of headers: answered "HTTP/1.1 200 OK", want 431`, `egress_test.go:908: the origin saw 1 requests, want 0`. Restored.
+12. Log the raw CONNECT target (`Destination: e.destination`, `log.go`). Command: `... -run '^TestLogHasNoSecrets$' -count=1`. Observed: FAIL, `egress_test.go:650: refused CONNECT logged with destination "user:SECRET-USERINFO@instance.example.test:443", want "invalid"` (and the four others), `egress_test.go:658: the decision log holds SECRET-USERINFO` (and SECRET-CONNECT-PATH, SECRET-CONNECT-QUERY, SECRET-AT, SECRET_UNDERSCORE). Restored.
+13. No address check (`if false && !allowedOriginAddr(a)`, `origin.go`). Command: `... -run '^TestOriginAddressGuard$' -count=1`. Observed: FAIL, `egress_test.go:1000: answer [127.0.0.1]: test origin dial to 127.0.0.1:443, want ErrOriginAddress`, `egress_test.go:1003: answer [127.0.0.1]: dialled [127.0.0.1:443]`, the same for every refused answer down to `[2001:db8::10 fd00::1]`, and `egress_test.go:1024: no decision line for the loopback answer`. Restored.
+14. Dial the name, not the checked address (`net.JoinHostPort(host, "443")`). Same command. Observed: FAIL, `egress_test.go:969: answer [203.0.113.10]: test origin dial to instance.example.test:443` (each allowed answer), `egress_test.go:1017: statuses [502 502], origin hits 0, lookups 2; want [200 502], 1, 2`, `egress_test.go:1022: the proxy dialled "instance.example.test:443", not an address`. Restored. (A first version of this mutation did not compile, `declared and not used: a`; it was rewritten to keep `a` used.)
+15. No bootstrap log line (the deferred `s.log.write(e)` removed, `boot.go`). Command: `... -run '^TestBootLogs$' -count=1`. Observed: FAIL, `egress_test.go:788: no decision line for the redemption`. Restored.
+16. Log the bootstrap body (the forwarded decision's reason set to the body). Same command. Observed: FAIL, `egress_test.go:818: the decision log holds SECRETPROXYCODE: {... "route":"redeem","decision":"allow","reason":"{\"launch_id\":\"l-1\",...\"proxy_code\":\"SECRETPROXYCODE\"...` and `holds U0VDUkVU`. Restored. (A first version put the body in the route; it failed only on the missing `redeem` line, so it was replaced by this one.)
+17. Disable origin verification (`InsecureSkipVerify: true` in `dialOrigin`). Command: `... -run '^TestOriginTLSVerified$' -count=1`. Observed: FAIL, `egress_test.go:1045: origin certificate for another name: 200, want 502`, `egress_test.go:1049: origin certificate from an untrusted CA: 200, want 502`, `egress_test.go:1052: the origin received 2 requests, want 0`. Restored.
+18. No version check (`if false && ...` in `readRequest`). Command: `... -run '^TestHTTP11Required$' -count=1`. Observed: FAIL, `egress_test.go:938: CONNECT over HTTP/1.0: answered "HTTP/1.1 200 Connection established", want 505`, `egress_test.go:946: a request over HTTP/1.0 in a tunnel: answered "HTTP/1.1 200 OK", want 505` (and 1.2, 2.0, 0.9), `egress_test.go:951: the origin saw 4 requests, want 0`. Restored.
+
+Also run: `go test ./internal/hostedproxy ./cmd/equipo-hosted-proxy -count=1 -race` ok (3.1 s and 1.2 s); the brief's green command ok; staticcheck v0.7.0 ok; gofmt clean; `make budget build vet` ok (126 directories within budget; `internal/hostedproxy` 1818 source and 1533 test lines, default budgets).
diff --git a/internal/hostedproxy/boot.go b/internal/hostedproxy/boot.go
index dbc12b25..7c56547a 100644
--- a/internal/hostedproxy/boot.go
+++ b/internal/hostedproxy/boot.go
@@ -193,53 +193,75 @@ func (s *Server) newBootServer(ctx context.Context) *http.Server {
}
}
-// forwardBoot reads and checks one bootstrap request and forwards it.
-// check decodes the body strictly and returns the serial it names; when
-// needCert, that serial must be the current certificate's.
+// bootRoutes names each controller route in the decision log.
+var bootRoutes = map[string]string{routeRedeem: "redeem", routeRenew: "renew", routeCertReport: "cert-report"}
+
+// forwardBoot reads and checks one bootstrap request and forwards it,
+// then logs one decision line: the route, the status answered, the
+// refusal's code, and the body sizes in and out. The identity comes only
+// from a client certificate TLS verified, never from the body; a
+// redemption without one is logged with none. Bodies, codes and keys are
+// never logged. check decodes the body strictly and returns the serial it
+// names; when needCert, that serial must be the current certificate's.
func (s *Server) forwardBoot(w http.ResponseWriter, r *http.Request, route string, needCert bool,
check func([]byte) (string, error)) {
+ e := entry{route: bootRoutes[route], method: r.Method}
+ if r.TLS != nil && len(r.TLS.VerifiedChains) > 0 && len(r.TLS.VerifiedChains[0]) > 0 {
+ if id, err := IdentityFromCert(r.TLS.VerifiedChains[0][0]); err == nil {
+ e.id = id
+ }
+ }
+ defer func() { s.log.write(e) }()
+ refuse := func(status int, code string) {
+ e.status, e.decision = status, deny(code)
+ e.out = bootError(w, status, code)
+ }
body, err := io.ReadAll(io.LimitReader(r.Body, hostedwire.MaxBody+1))
+ e.in = int64(len(body))
if err != nil || len(body) > hostedwire.MaxBody {
- bootError(w, http.StatusBadRequest, "bad_request")
+ refuse(http.StatusBadRequest, "bad_request")
return
}
serial, err := check(body)
if err != nil {
- bootError(w, http.StatusBadRequest, "bad_request")
+ refuse(http.StatusBadRequest, "bad_request")
return
}
if needCert {
if r.TLS == nil || len(r.TLS.VerifiedChains) == 0 || len(r.TLS.VerifiedChains[0]) == 0 {
- bootError(w, http.StatusUnauthorized, "no_certificate")
+ refuse(http.StatusUnauthorized, "no_certificate")
return
}
- id, err := IdentityFromCert(r.TLS.VerifiedChains[0][0])
- if err != nil {
- bootError(w, http.StatusForbidden, "bad_certificate")
+ if e.id.Serial == "" {
+ refuse(http.StatusForbidden, "bad_certificate")
return
}
- if _, reason := s.feed.current(id, s.clock.Mono()); reason != "" {
- bootError(w, http.StatusForbidden, reason)
+ if _, reason := s.feed.current(e.id, s.clock.Mono()); reason != "" {
+ refuse(http.StatusForbidden, reason)
return
}
- if serial != id.Serial {
- bootError(w, http.StatusForbidden, "serial_mismatch")
+ if serial != e.id.Serial {
+ refuse(http.StatusForbidden, "serial_mismatch")
return
}
}
status, out, err := s.ctl.call(r.Context(), http.MethodPost, route, body)
if err != nil {
- bootError(w, http.StatusBadGateway, "controller_unavailable")
+ refuse(http.StatusBadGateway, "controller_unavailable")
return
}
+ e.status, e.decision = status, Decision{Allow: true}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
- _, _ = w.Write(out)
+ n, _ := w.Write(out)
+ e.out = int64(n)
}
-func bootError(w http.ResponseWriter, status int, code string) {
+// bootError answers with an ErrorResponse and returns its size.
+func bootError(w http.ResponseWriter, status int, code string) int64 {
raw, _ := json.Marshal(hostedwire.ErrorResponse{Code: code, Message: http.StatusText(status)})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
- _, _ = w.Write(raw)
+ n, _ := w.Write(raw)
+ return int64(n)
}
diff --git a/internal/hostedproxy/egress.go b/internal/hostedproxy/egress.go
index 935039a2..0b2aec18 100644
--- a/internal/hostedproxy/egress.go
+++ b/internal/hostedproxy/egress.go
@@ -10,6 +10,7 @@ import (
"errors"
"fmt"
"io"
+ "math"
"net"
"net/http"
"net/netip"
@@ -26,7 +27,7 @@ import (
)
// Config is one proxy's configuration. Every field is required but
-// OriginRoots, Log, Clock and DialOrigin.
+// OriginRoots, Log, Clock, DialOrigin and Resolver.
type Config struct {
// Egress is the CONNECT listener, Boot the bootstrap listener: each a
// specific address (never a wildcard), port 0 only in tests.
@@ -58,6 +59,11 @@ type Config struct {
// plain net.Dialer. Tests set both.
Clock Clock
DialOrigin func(ctx context.Context, network, addr string) (net.Conn, error)
+ // Resolver looks service hosts up; nil means net.DefaultResolver.
+ // Every address it answers must pass allowedOriginAddr, and the proxy
+ // dials the checked address (DialOrigin gets "ip:443"), never the
+ // name.
+ Resolver Resolver
}
// PollInterval is how often the proxy asks the controller for the feed.
@@ -259,9 +265,20 @@ func (s *Server) serveEgress(ctx context.Context, raw net.Conn, cfg *tls.Config)
if err != nil {
return
}
- br := bufio.NewReader(outer)
- req, err := http.ReadRequest(br)
- if err != nil {
+ br, lim := newRequestReader(outer)
+ req, err := readRequest(br, lim)
+ switch {
+ case errors.Is(err, errHeaderTooLarge):
+ s.log.write(entry{id: id, decision: deny(ReasonBadRequest), status: http.StatusRequestHeaderFieldsTooLarge})
+ writeStatus(outer, http.StatusRequestHeaderFieldsTooLarge)
+ lingerClose(raw)
+ return
+ case errors.Is(err, errVersion):
+ s.log.write(entry{id: id, destination: req.RequestURI, method: req.Method, decision: deny(ReasonBadRequest),
+ status: http.StatusHTTPVersionNotSupported})
+ writeStatus(outer, http.StatusHTTPVersionNotSupported)
+ return
+ case err != nil:
return
}
_ = raw.SetDeadline(time.Time{})
@@ -292,6 +309,75 @@ func writeStatus(w io.Writer, code int) {
_, _ = fmt.Fprintf(w, "HTTP/1.1 %d %s\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", code, http.StatusText(code))
}
+// maxHeaderBytes bounds a request line and its headers together, at
+// both parse points (the CONNECT and each request in a tunnel). The
+// bufio.Reader above the limit may hold up to its own size more.
+const maxHeaderBytes = 16 << 10
+
+var (
+ errHeaderTooLarge = errors.New("hostedproxy: request line and headers too large")
+ errVersion = errors.New("hostedproxy: not HTTP/1.1")
+)
+
+// headerLimit sits between a connection and the bufio.Reader requests are
+// parsed from: while a request's line and headers are read it lets
+// through at most remain bytes, then reports EOF and marks hit. Between
+// parses it is unlimited, so bodies and tunnel bytes pass, and bytes the
+// bufio.Reader already holds are never lost.
+type headerLimit struct {
+ r io.Reader
+ remain int64
+ hit bool
+}
+
+func (l *headerLimit) Read(p []byte) (int, error) {
+ if l.remain <= 0 {
+ l.hit = true
+ return 0, io.EOF
+ }
+ if int64(len(p)) > l.remain {
+ p = p[:l.remain]
+ }
+ n, err := l.r.Read(p)
+ l.remain -= int64(n)
+ return n, err
+}
+
+func newRequestReader(r io.Reader) (*bufio.Reader, *headerLimit) {
+ lim := &headerLimit{r: r, remain: math.MaxInt64}
+ return bufio.NewReader(lim), lim
+}
+
+// readRequest reads one request's line and headers within maxHeaderBytes
+// (errHeaderTooLarge past it). A request that parses but is not HTTP/1.1
+// is returned with errVersion.
+func readRequest(br *bufio.Reader, lim *headerLimit) (*http.Request, error) {
+ lim.remain, lim.hit = maxHeaderBytes, false
+ req, err := http.ReadRequest(br)
+ lim.remain = math.MaxInt64
+ if err != nil {
+ if lim.hit {
+ return nil, errHeaderTooLarge
+ }
+ return nil, err
+ }
+ if req.ProtoMajor != 1 || req.ProtoMinor != 1 {
+ return req, errVersion
+ }
+ return req, nil
+}
+
+// lingerClose ends a refused connection whose peer may still be sending:
+// it stops writing, then reads and drops what arrives for a moment, so
+// the refusal is read before the connection is reset.
+func lingerClose(raw net.Conn) {
+ if tc, ok := raw.(interface{ CloseWrite() error }); ok {
+ _ = tc.CloseWrite()
+ }
+ _ = raw.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
+ _, _ = io.Copy(io.Discard, io.LimitReader(raw, 1<<20))
+}
+
// bufferedConn reads through r, which may hold bytes already read from
// Conn.
type bufferedConn struct {
@@ -429,7 +515,7 @@ func (t *tunnel) serve(c net.Conn) {
_ = c.SetDeadline(time.Time{})
t.onClose(func() { inner.Close() })
ic := &countConn{Conn: inner, in: &t.in, out: &t.out}
- br := bufio.NewReader(ic)
+ br, lim := newRequestReader(ic)
transport := &http.Transport{
DialTLSContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return t.s.dialOrigin(ctx, t.svc.Host) },
TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{},
@@ -440,8 +526,18 @@ func (t *tunnel) serve(c net.Conn) {
for {
in0, out0 := t.in.Load(), t.out.Load()
_ = inner.SetReadDeadline(time.Now().Add(idleTimeout))
- req, err := http.ReadRequest(br)
- if err != nil {
+ req, err := readRequest(br, lim)
+ switch {
+ case errors.Is(err, errHeaderTooLarge):
+ writeStatus(ic, http.StatusRequestHeaderFieldsTooLarge)
+ t.logDecision("", "", deny(ReasonBadRequest), http.StatusRequestHeaderFieldsTooLarge, t.in.Load()-in0, t.out.Load()-out0)
+ lingerClose(t.raw)
+ return
+ case errors.Is(err, errVersion):
+ writeStatus(ic, http.StatusHTTPVersionNotSupported)
+ t.logDecision(req.Method, "", deny(ReasonBadRequest), http.StatusHTTPVersionNotSupported, t.in.Load()-in0, t.out.Load()-out0)
+ return
+ case err != nil:
if !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) && !isTimeout(err) && t.ctx.Err() == nil {
t.logDecision("", "", deny(ReasonNestedTunnel), 0, t.in.Load()-in0, t.out.Load()-out0)
}
@@ -460,10 +556,10 @@ func (t *tunnel) serve(c net.Conn) {
t.logDecision(req.Method, class, d, 0, t.in.Load()-in0, t.out.Load()-out0)
return
}
- status, keep := t.forward(transport, req, ic, br, r.Upgrade)
+ status, refused, keep := t.forward(transport, req, ic, br, r.Upgrade)
rd := d
- if status == -http.StatusBadGateway {
- rd, status = Decision{Reason: ReasonRedirectRefused, Service: t.svc}, http.StatusBadGateway
+ if refused != "" {
+ rd = Decision{Reason: refused, Service: t.svc}
}
t.logDecision(req.Method, class, rd, status, t.in.Load()-in0, t.out.Load()-out0)
if !keep {
@@ -524,10 +620,11 @@ func websocketAsked(h http.Header) bool {
}
// forward sends req to the service host over the proxy's own TLS and
-// writes the answer to the VM. It returns the status written and whether
-// the tunnel may carry another request; -502 means a redirect to another
-// authority was refused (and a bare 502 written).
-func (t *tunnel) forward(rt http.RoundTripper, req *http.Request, ic net.Conn, br *bufio.Reader, upgrade bool) (int, bool) {
+// writes the answer to the VM. It returns the status written, the reason
+// when the proxy refused the exchange after Decide (a redirect to another
+// authority, or an origin address it never dials; a bare 502 is written
+// for either), and whether the tunnel may carry another request.
+func (t *tunnel) forward(rt http.RoundTripper, req *http.Request, ic net.Conn, br *bufio.Reader, upgrade bool) (int, string, bool) {
header := dropHop(req.Header)
if upgrade {
header.Set("Connection", "Upgrade")
@@ -542,23 +639,26 @@ func (t *tunnel) forward(rt http.RoundTripper, req *http.Request, ic net.Conn, b
resp, err := rt.RoundTrip(out)
if err != nil {
writeStatus(ic, http.StatusBadGateway)
- return http.StatusBadGateway, false
+ if errors.Is(err, ErrOriginAddress) {
+ return http.StatusBadGateway, ReasonOriginAddress, false
+ }
+ return http.StatusBadGateway, "", false
}
defer resp.Body.Close()
if rd := decideResponse(t.svc, resp.StatusCode, resp.Header.Values("Location")); !rd.Allow {
writeStatus(ic, http.StatusBadGateway)
- return -http.StatusBadGateway, false
+ return http.StatusBadGateway, rd.Reason, false
}
if resp.StatusCode == http.StatusSwitchingProtocols {
- return t.pipe(resp, ic, br, upgrade), false
+ return t.pipe(resp, ic, br, upgrade), "", false
}
resp.Header = dropHop(resp.Header)
if err := resp.Write(ic); err != nil {
- return resp.StatusCode, false
+ return resp.StatusCode, "", false
}
// A body that ends only when the connection does ends the tunnel too.
framed := resp.ContentLength >= 0 || slices.Contains(resp.TransferEncoding, "chunked")
- return resp.StatusCode, framed && !req.Close && !resp.Close
+ return resp.StatusCode, "", framed && !req.Close && !resp.Close
}
// pipe joins an upgraded connection to the VM until either side ends or
diff --git a/internal/hostedproxy/egress_test.go b/internal/hostedproxy/egress_test.go
index 700eeead..49cc24c2 100644
--- a/internal/hostedproxy/egress_test.go
+++ b/internal/hostedproxy/egress_test.go
@@ -23,6 +23,7 @@ import (
"net/http/httptest"
"net/netip"
"net/url"
+ "slices"
"strings"
"sync"
"sync/atomic"
@@ -223,10 +224,76 @@ type env struct {
origin *httptest.Server
hits atomic.Int64 // requests the origin saw
handler atomic.Value // http.Handler for the origin
+ originCA *testCA
+ leaf atomic.Pointer[tls.Certificate] // the origin's certificate
+ dns *fakeResolver
+ dials *dialLog
srv *Server
log *syncBuffer
}
+// publicV4 and publicV6 are what testHost resolves to by default; the
+// test dialer sends both to the origin listener.
+const (
+ publicV4 = "203.0.113.10"
+ publicV6 = "2001:db8::10"
+)
+
+// fakeResolver answers from a list per call: the last answer repeats.
+type fakeResolver struct {
+ mu sync.Mutex
+ answers [][]netip.Addr
+ calls int
+}
+
+func (r *fakeResolver) set(answers ...[]string) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.answers, r.calls = nil, 0
+ for _, a := range answers {
+ var addrs []netip.Addr
+ for _, s := range a {
+ addrs = append(addrs, netip.MustParseAddr(s))
+ }
+ r.answers = append(r.answers, addrs)
+ }
+}
+
+func (r *fakeResolver) LookupNetIP(_ context.Context, network, host string) ([]netip.Addr, error) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if host != testHost || network != "ip" {
+ return nil, fmt.Errorf("lookup %s %s: no such host", network, host)
+ }
+ i := min(r.calls, len(r.answers)-1)
+ r.calls++
+ return slices.Clone(r.answers[i]), nil
+}
+
+func (r *fakeResolver) lookups() int {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return r.calls
+}
+
+// dialLog records every address the proxy dials.
+type dialLog struct {
+ mu sync.Mutex
+ addrs []string
+}
+
+func (d *dialLog) add(a string) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.addrs = append(d.addrs, a)
+}
+
+func (d *dialLog) all() []string {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return slices.Clone(d.addrs)
+}
+
func newEnv(t *testing.T) *env {
t.Helper()
e := &env{t: t, clock: newFakeClock(), clientCA: newTestCA(t, "client CA"), intercept: newTestCA(t, "intercept CA"),
@@ -235,9 +302,8 @@ func newEnv(t *testing.T) *env {
e.ctl = newFakeController(t, e.clock, pub)
e.ctl.setFeed(testFeed())
- originCA := newTestCA(t, "origin CA")
- leaf := originCA.issue(t, &x509.Certificate{DNSNames: []string{testHost}, NotBefore: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
- NotAfter: time.Date(2040, 1, 1, 0, 0, 0, 0, time.UTC), ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}})
+ e.originCA = newTestCA(t, "origin CA")
+ e.setOriginCert(e.originCA, testHost)
e.handler.Store(http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, "protocol 39")
})))
@@ -245,19 +311,22 @@ func newEnv(t *testing.T) *env {
e.hits.Add(1)
e.handler.Load().(http.Handler).ServeHTTP(w, r)
}))
- e.origin.TLS = &tls.Config{Certificates: []tls.Certificate{leaf}}
+ e.origin.TLS = &tls.Config{GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return e.leaf.Load(), nil }}
e.origin.StartTLS()
t.Cleanup(e.origin.Close)
originAddr := e.origin.Listener.Addr().String()
+ e.dns, e.dials = &fakeResolver{}, &dialLog{}
+ e.dns.set([]string{publicV4})
srv, err := NewServer(Config{
Egress: netip.MustParseAddrPort("127.0.0.1:0"), Boot: netip.MustParseAddrPort("127.0.0.1:0"),
ControllerURL: e.ctl.srv.URL, ControllerKey: e.ctl.key.Public().(ed25519.PublicKey),
ControllerTLSPin: spkiPin(e.ctl.srv.Certificate()), KeyID: "proxy-1", Key: key,
- ClientCA: e.clientCA.pool, InterceptCA: e.intercept.pair, OriginRoots: originCA.pool, Log: e.log,
- Clock: e.clock,
+ ClientCA: e.clientCA.pool, InterceptCA: e.intercept.pair, OriginRoots: e.originCA.pool, Log: e.log,
+ Clock: e.clock, Resolver: e.dns,
DialOrigin: func(ctx context.Context, network, addr string) (net.Conn, error) {
- if addr != testLocal {
+ e.dials.add(addr)
+ if addr != publicV4+":443" && addr != "["+publicV6+"]:443" {
return nil, fmt.Errorf("test origin dial to %s", addr)
}
var d net.Dialer
@@ -285,6 +354,13 @@ func newEnv(t *testing.T) *env {
return e
}
+// setOriginCert makes the origin present a certificate for name from ca.
+func (e *env) setOriginCert(ca *testCA, name string) {
+ leaf := ca.issue(e.t, &x509.Certificate{DNSNames: []string{name}, NotBefore: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC),
+ NotAfter: time.Date(2040, 1, 1, 0, 0, 0, 0, time.UTC), ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}})
+ e.leaf.Store(&leaf)
+}
+
// vmCert is a client certificate for l-1 under the controller's CA, or
// under ca when given.
func (e *env) vmCert(serial int64, ca *testCA) tls.Certificate {
@@ -549,9 +625,35 @@ func TestLogHasNoSecrets(t *testing.T) {
e.log.waitLog(t, "the enrol", func(l logLine) bool { return l.Decision == "allow" && l.Method == "POST" })
e.log.waitLog(t, "the query", func(l logLine) bool { return l.Reason == ReasonBadPath && l.Method == "GET" })
e.log.waitLog(t, "the leases path", func(l logLine) bool { return l.Reason == ReasonBadPath && l.Method == "POST" })
+ // Refused CONNECT targets carrying user info, a path, a query or an
+ // odd host are logged as "invalid", never as sent.
+ for i, target := range []string{"user:SECRET-USERINFO@" + testLocal, testLocal + "/SECRET-CONNECT-PATH",
+ testLocal + "?SECRET-CONNECT-QUERY", "x@SECRET-AT.example.test:443", "SECRET_UNDERSCORE.example.test:443"} {
+ _, status, err := e.connect(&cert, target)
+ if err != nil || status != http.StatusForbidden {
+ t.Errorf("CONNECT %s = %d, %v; want 403", target, status, err)
+ continue
+ }
+ want := i + 1
+ e.log.waitLog(t, target, func(logLine) bool {
+ n := 0
+ for _, l := range e.log.lines(t) {
+ if l.Method == "CONNECT" && l.Decision == "deny" {
+ n++
+ }
+ }
+ return n >= want
+ })
+ }
+ for _, l := range e.log.lines(t) {
+ if l.Method == "CONNECT" && l.Destination != destInvalid {
+ t.Errorf("refused CONNECT logged with destination %q, want %q", l.Destination, destInvalid)
+ }
+ }
got := e.log.String()
for _, secret := range []string{"SECRET-AUTHORIZATION", "SECRET-COOKIE", "SECRET-HEADER", "SECRET-BODY", "SECRET-QUERY",
- "SECRET-PATH", "SECRET-DENIED-BODY", "SECRET-SET-COOKIE", "SECRET-RESPONSE-BODY", "SECRET-PROXY-AUTH", "Bearer"} {
+ "SECRET-PATH", "SECRET-DENIED-BODY", "SECRET-SET-COOKIE", "SECRET-RESPONSE-BODY", "SECRET-PROXY-AUTH", "Bearer",
+ "SECRET-USERINFO", "SECRET-CONNECT-PATH", "SECRET-CONNECT-QUERY", "SECRET-AT", "SECRET_UNDERSCORE"} {
if strings.Contains(got, secret) {
t.Errorf("the decision log holds %s:\n%s", secret, got)
}
@@ -677,3 +779,285 @@ func TestBootForwardsUnderTheProxySignature(t *testing.T) {
t.Errorf("controller got %d renewals, want 1", len(got))
}
}
+
+// TestBootLogs: every bootstrap request leaves one decision line with its
+// route, status, reason and sizes; identity only from a verified
+// certificate; no body, code or key (review round 1, finding 5).
+func TestBootLogs(t *testing.T) {
+ e := newEnv(t)
+ cert := e.vmCert(0x61, nil)
+ redeem := `{"launch_id":"l-1","vm_ref":"vm-1","proxy_code":"SECRETPROXYCODE","csr":"U0VDUkVUQ1NS"}`
+ if status, _ := e.boot("/redeem", nil, redeem); status != 200 {
+ t.Fatalf("redeem = %d", status)
+ }
+ l := e.log.waitLog(t, "the redemption", func(l logLine) bool { return l.Route == "redeem" })
+ if l.Decision != "allow" || l.Status != 200 || l.VM != "" || l.Launch != "" || l.Destination != destController ||
+ l.PathClass != classBootstrap || l.BytesIn != int64(len(redeem)) || l.BytesOut == 0 {
+ t.Errorf("redemption line = %+v", l)
+ }
+ if status, _ := e.boot("/renew", nil, `{"serial":"61","csr":"U0VDUkVUQ1NS"}`); status != http.StatusUnauthorized {
+ t.Errorf("renewal without a certificate = %d", status)
+ }
+ l = e.log.waitLog(t, "the renewal without a certificate", func(l logLine) bool { return l.Reason == "no_certificate" })
+ if l.Route != "renew" || l.Decision != "deny" || l.Status != http.StatusUnauthorized || l.VM != "" {
+ t.Errorf("renewal without a certificate: line %+v", l)
+ }
+ if status, _ := e.boot("/renew", &cert, `{"serial":"99","csr":"U0VDUkVUQ1NS"}`); status != http.StatusForbidden {
+ t.Errorf("renewal of another serial = %d", status)
+ }
+ l = e.log.waitLog(t, "the other serial", func(l logLine) bool { return l.Reason == "serial_mismatch" })
+ if l.Route != "renew" || l.Decision != "deny" || l.Status != http.StatusForbidden || l.VM != "vm-1" || l.Launch != "l-1" {
+ t.Errorf("renewal of another serial: line %+v", l)
+ }
+ report := `{"serial":"61","report":"U0VDUkVUUkVQT1JU","sig":"U0VDUkVUU0lH"}`
+ if status, _ := e.boot("/cert-report", &cert, report); status != 200 {
+ t.Errorf("report = %d", status)
+ }
+ l = e.log.waitLog(t, "the report", func(l logLine) bool { return l.Route == "cert-report" })
+ if l.Decision != "allow" || l.Status != 200 || l.VM != "vm-1" || l.BytesIn != int64(len(report)) {
+ t.Errorf("report line = %+v", l)
+ }
+ got := e.log.String()
+ for _, secret := range []string{"SECRETPROXYCODE", "U0VDUkVU", "serial\":\"99"} {
+ if strings.Contains(got, secret) {
+ t.Errorf("the decision log holds %s:\n%s", secret, got)
+ }
+ }
+}
+
+// rawExchange opens mutual TLS to the egress listener with cert, writes
+// what write sends (in the background, ignoring errors once the proxy
+// stops reading), and returns the first response's status line.
+func (e *env) rawExchange(cert *tls.Certificate, write func(io.Writer) error) string {
+ e.t.Helper()
+ c, err := e.outer(e.srv.EgressAddr(), cert)
+ if err != nil {
+ e.t.Fatal(err)
+ }
+ defer c.Close()
+ go func() { _ = write(c) }()
+ return e.statusLine(c)
+}
+
+func (e *env) statusLine(c net.Conn) string {
+ _ = c.SetReadDeadline(time.Now().Add(5 * time.Second))
+ line, err := bufio.NewReader(c).ReadString('\n')
+ if err != nil {
+ return "error: " + err.Error()
+ }
+ return strings.TrimSpace(line)
+}
+
+// manyHeaders writes head, then a MiB of headers, then the blank line.
+func manyHeaders(head string) func(io.Writer) error {
+ return func(w io.Writer) error {
+ if _, err := io.WriteString(w, head); err != nil {
+ return err
+ }
+ pad := strings.Repeat("a", 1000)
+ for i := 0; i < 1024; i++ {
+ if _, err := fmt.Fprintf(w, "X-Pad-%d: %s\r\n", i, pad); err != nil {
+ return err
+ }
+ }
+ _, err := io.WriteString(w, "\r\n")
+ return err
+ }
+}
+
+func longLine(line string) func(io.Writer) error {
+ return func(w io.Writer) error { _, err := io.WriteString(w, line); return err }
+}
+
+// TestHeaderBounds: the request line and headers are bounded at both
+// parse points, before any launch check (review round 1, finding 2).
+func TestHeaderBounds(t *testing.T) {
+ e := newEnv(t)
+ f := testFeed()
+ f.Revoked = append(f.Revoked, "62")
+ e.ctl.setFeed(f)
+ if err := e.srv.Poll(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ cert, revoked := e.vmCert(0x63, nil), e.vmCert(0x62, nil)
+ long := "CONNECT " + strings.Repeat("a", 64<<10) + ".example.test:443 HTTP/1.1\r\nHost: x\r\n\r\n"
+ for name, tc := range map[string]struct {
+ cert *tls.Certificate
+ write func(io.Writer) error
+ }{
+ "a long CONNECT line": {&cert, longLine(long)},
+ "CONNECT with a MiB of headers": {&cert, manyHeaders("CONNECT " + testLocal + " HTTP/1.1\r\nHost: " + testLocal + "\r\n")},
+ "a revoked certificate's long line": {&revoked, longLine(long)},
+ "a revoked certificate's MiB of headers": {&revoked, manyHeaders("CONNECT " + testLocal + " HTTP/1.1\r\nHost: " + testLocal + "\r\n")},
+ } {
+ if got := e.rawExchange(tc.cert, tc.write); !strings.HasPrefix(got, "HTTP/1.1 431 ") {
+ t.Errorf("%s: answered %q, want 431", name, got)
+ }
+ }
+ // Inside a tunnel: the same bounds, and the origin sees nothing.
+ for name, write := range map[string]func(io.Writer) error{
+ "a long request line": longLine("GET /" + strings.Repeat("a", 64<<10) + " HTTP/1.1\r\nHost: " + testHost + "\r\n\r\n"),
+ "a MiB of headers": manyHeaders("GET /api/runner/protocol HTTP/1.1\r\nHost: " + testHost + "\r\n"),
+ } {
+ inner, err := e.tunnel(&cert, testLocal, testHost, []string{ALPNHTTP11})
+ if err != nil {
+ t.Fatal(err)
+ }
+ go func() { _ = write(inner) }()
+ if got := e.statusLine(inner); !strings.HasPrefix(got, "HTTP/1.1 431 ") {
+ t.Errorf("in a tunnel, %s: answered %q, want 431", name, got)
+ }
+ inner.Close()
+ }
+ if n := e.hits.Load(); n != 0 {
+ t.Errorf("the origin saw %d requests, want 0", n)
+ }
+ e.log.waitLog(t, "the oversized requests", func(l logLine) bool {
+ return l.Reason == ReasonBadRequest && l.Status == http.StatusRequestHeaderFieldsTooLarge && l.Destination == testLocal
+ })
+ // A header well inside the bound still passes, in the same tunnel as
+ // the request after it.
+ c := e.client(&cert)
+ for i := 0; i < 2; i++ {
+ req, _ := http.NewRequest("GET", "https://"+testHost+"/api/runner/protocol", nil)
+ req.Header.Set("X-Pad", strings.Repeat("a", 8<<10))
+ resp, err := c.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != 200 {
+ t.Errorf("an 8 KiB header: %d", resp.StatusCode)
+ }
+ }
+}
+
+// TestHTTP11Required: any version but HTTP/1.1 is refused at both parse
+// points, whatever ALPN said (review round 1, finding 7).
+func TestHTTP11Required(t *testing.T) {
+ e := newEnv(t)
+ cert := e.vmCert(0x64, nil)
+ for _, v := range []string{"HTTP/1.0", "HTTP/1.2", "HTTP/2.0", "HTTP/0.9"} {
+ got := e.rawExchange(&cert, longLine("CONNECT "+testLocal+" "+v+"\r\nHost: "+testLocal+"\r\n\r\n"))
+ if !strings.HasPrefix(got, "HTTP/1.1 505 ") {
+ t.Errorf("CONNECT over %s: answered %q, want 505", v, got)
+ }
+ inner, err := e.tunnel(&cert, testLocal, testHost, []string{ALPNHTTP11})
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, _ = io.WriteString(inner, "GET /api/runner/protocol "+v+"\r\nHost: "+testHost+"\r\n\r\n")
+ if got := e.statusLine(inner); !strings.HasPrefix(got, "HTTP/1.1 505 ") {
+ t.Errorf("a request over %s in a tunnel: answered %q, want 505", v, got)
+ }
+ inner.Close()
+ }
+ if n := e.hits.Load(); n != 0 {
+ t.Errorf("the origin saw %d requests, want 0", n)
+ }
+ e.log.waitLog(t, "a version refusal", func(l logLine) bool {
+ return l.Reason == ReasonBadRequest && l.Status == http.StatusHTTPVersionNotSupported && l.Method == "GET"
+ })
+}
+
+// TestOriginAddressGuard: a service host is resolved once, every answer
+// must be a public address, and the proxy dials the checked address, never
+// the name (review round 1, finding 4).
+func TestOriginAddressGuard(t *testing.T) {
+ e := newEnv(t)
+ ctx := context.Background()
+ for _, answer := range [][]string{{publicV4}, {publicV6}, {"::ffff:" + publicV4}, {publicV4, publicV6}} {
+ e.dns.set(answer)
+ before := len(e.dials.all())
+ c, err := e.srv.dialOrigin(ctx, testHost)
+ if err != nil {
+ t.Errorf("answer %v: %v", answer, err)
+ continue
+ }
+ c.Close()
+ if n := e.dns.lookups(); n != 1 {
+ t.Errorf("answer %v: %d lookups, want 1", answer, n)
+ }
+ for _, a := range e.dials.all()[before:] {
+ if ap, err := netip.ParseAddrPort(a); err != nil || ap.Addr().Is4In6() || ap.Port() != 443 {
+ t.Errorf("answer %v: dialled %q, want a checked address on 443", answer, a)
+ }
+ }
+ }
+ for _, answer := range [][]string{
+ {"127.0.0.1"}, {"10.1.2.3"}, {"172.16.0.1"}, {"192.168.1.1"}, {"169.254.169.254"}, {"0.0.0.0"}, {"0.1.2.3"},
+ {"224.0.0.1"}, {"255.255.255.255"}, {"100.64.0.1"},
+ {"::1"}, {"::"}, {"fe80::1"}, {"fd00::1"}, {"ff02::1"}, {"::ffff:127.0.0.1"}, {"::ffff:169.254.169.254"},
+ {"::ffff:10.0.0.1"}, {"::127.0.0.1"}, {"64:ff9b::a9fe:a9fe"}, {"2002:7f00:1::1"},
+ {publicV4, "10.0.0.1"}, {"10.0.0.1", publicV4}, {publicV6, "::1"}, {publicV6, "fd00::1"},
+ } {
+ e.dns.set(answer)
+ before := len(e.dials.all())
+ if c, err := e.srv.dialOrigin(ctx, testHost); !errors.Is(err, ErrOriginAddress) {
+ if c != nil {
+ c.Close()
+ }
+ t.Errorf("answer %v: %v, want ErrOriginAddress", answer, err)
+ }
+ if got := e.dials.all()[before:]; len(got) != 0 {
+ t.Errorf("answer %v: dialled %v", answer, got)
+ }
+ }
+
+ // Through a tunnel: the first answer is public, the next loopback.
+ // Each connection to the origin looks up once and dials what it
+ // checked.
+ e.dns.set([]string{publicV4}, []string{"127.0.0.1"})
+ cert := e.vmCert(0x65, nil)
+ statuses := []int{}
+ for i := 0; i < 2; i++ {
+ resp, err := e.client(&cert).Get("https://" + testHost + "/api/runner/protocol")
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ statuses = append(statuses, resp.StatusCode)
+ }
+ if !slices.Equal(statuses, []int{200, 502}) || e.hits.Load() != 1 || e.dns.lookups() != 2 {
+ t.Errorf("statuses %v, origin hits %d, lookups %d; want [200 502], 1, 2", statuses, e.hits.Load(), e.dns.lookups())
+ }
+ e.log.waitLog(t, "the loopback answer", func(l logLine) bool { return l.Reason == ReasonOriginAddress && l.Status == 502 })
+ for _, a := range e.dials.all() {
+ if _, err := netip.ParseAddrPort(a); err != nil {
+ t.Errorf("the proxy dialled %q, not an address", a)
+ }
+ }
+}
+
+// TestOriginTLSVerified: an origin certificate for another name, or from a
+// CA the proxy does not trust, ends the exchange before any request
+// reaches the origin (review round 1, finding 6).
+func TestOriginTLSVerified(t *testing.T) {
+ e := newEnv(t)
+ cert := e.vmCert(0x66, nil)
+ get := func() int {
+ req, _ := http.NewRequest("GET", "https://"+testHost+"/api/runner/protocol", nil)
+ req.Header.Set("Authorization", "Bearer SECRET-RUNNER-TOKEN")
+ resp, err := e.client(&cert).Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ return resp.StatusCode
+ }
+ e.setOriginCert(e.originCA, "other.example.test")
+ if status := get(); status != http.StatusBadGateway {
+ t.Errorf("origin certificate for another name: %d, want 502", status)
+ }
+ e.setOriginCert(newTestCA(t, "untrusted CA"), testHost)
+ if status := get(); status != http.StatusBadGateway {
+ t.Errorf("origin certificate from an untrusted CA: %d, want 502", status)
+ }
+ if n := e.hits.Load(); n != 0 {
+ t.Errorf("the origin received %d requests, want 0", n)
+ }
+ e.setOriginCert(e.originCA, testHost)
+ if status := get(); status != 200 {
+ t.Errorf("the right certificate: %d, want 200", status)
+ }
+}
diff --git a/internal/hostedproxy/feed.go b/internal/hostedproxy/feed.go
index 2b4d66b4..03e15bac 100644
--- a/internal/hostedproxy/feed.go
+++ b/internal/hostedproxy/feed.go
@@ -40,29 +40,63 @@ var ErrFeed = errors.New("hostedproxy: feed is not valid")
//
// A feed is usable from its receipt (Install) until its TTL has passed on
// the monotonic clock, and never longer than ctlproxy.FeedLifetime (plan
-// decision S2-3). At receipt the feed also records the wall clock beside
-// the monotonic one; a certificate's NotAfter is turned into monotonic
-// time through that pair, so a later wall clock jump moves no deadline.
+// decision S2-3).
+//
+// A certificate's NotAfter is a wall time. The first time a serial is
+// judged, its NotAfter is turned into monotonic time once, against the
+// wall clock read then, and that deadline is kept for the serial: no
+// later feed, wall clock jump or second sight of the same serial moves
+// it.
type Feed struct {
clock Clock
- mu sync.RWMutex
- have bool
- received time.Duration // Mono at receipt
- ttl time.Duration
- anchorWall time.Time // Wall at receipt
- launches map[string]hostedwire.FeedLaunch
- revoked map[string]bool
- changed chan struct{} // closed by the next Install
+ mu sync.RWMutex
+ have bool
+ received time.Duration // Mono at receipt
+ ttl time.Duration
+ launches map[string]hostedwire.FeedLaunch
+ revoked map[string]bool
+ changed chan struct{} // closed by the next Install
+
+ certMu sync.Mutex
+ certEnds map[string]time.Duration // serial -> NotAfter on the monotonic clock
}
+// certKeep is how long past its deadline a serial's monotonic deadline is
+// kept: long after any wall clock could pass its NotAfter again.
+const certKeep = 24 * time.Hour
+
// NewFeed returns an empty feed: until a feed is installed every request
// is refused as stale_feed.
func NewFeed(c Clock) *Feed {
if c == nil {
c = SystemClock()
}
- return &Feed{clock: c, changed: make(chan struct{})}
+ return &Feed{clock: c, changed: make(chan struct{}), certEnds: map[string]time.Duration{}}
+}
+
+// certEnd is id's NotAfter on the monotonic clock, fixed the first time
+// its serial is seen (at mono, against the wall clock then).
+func (f *Feed) certEnd(id Identity, mono time.Duration) time.Duration {
+ f.certMu.Lock()
+ defer f.certMu.Unlock()
+ if end, ok := f.certEnds[id.Serial]; ok {
+ return end
+ }
+ end := mono + id.NotAfter.Sub(f.clock.Wall())
+ f.certEnds[id.Serial] = end
+ return end
+}
+
+// pruneCerts forgets serials whose deadline passed more than certKeep ago.
+func (f *Feed) pruneCerts(mono time.Duration) {
+ f.certMu.Lock()
+ defer f.certMu.Unlock()
+ for s, end := range f.certEnds {
+ if mono-end > certKeep {
+ delete(f.certEnds, s)
+ }
+ }
}
// Install takes pf, which the caller has verified as the controller's
@@ -89,10 +123,12 @@ func (f *Feed) Install(pf hostedwire.ProxyFeed) error {
if pf.TTLMS < ttl.Milliseconds() {
ttl = time.Duration(pf.TTLMS) * time.Millisecond
}
+ now := f.clock.Mono()
+ f.pruneCerts(now)
f.mu.Lock()
defer f.mu.Unlock()
f.have, f.ttl, f.launches, f.revoked = true, ttl, launches, revoked
- f.received, f.anchorWall = f.clock.Mono(), f.clock.Wall()
+ f.received = now
close(f.changed)
f.changed = make(chan struct{})
return nil
@@ -114,7 +150,7 @@ func (f *Feed) current(id Identity, mono time.Duration) (hostedwire.FeedLaunch,
if !f.have || mono-f.received >= f.ttl || mono < f.received {
return hostedwire.FeedLaunch{}, ReasonStaleFeed
}
- if mono >= f.certEnd(id) {
+ if mono >= f.certEnd(id, mono) {
return hostedwire.FeedLaunch{}, ReasonCertExpired
}
if f.revoked[id.Serial] {
@@ -130,12 +166,6 @@ func (f *Feed) current(id Identity, mono time.Duration) (hostedwire.FeedLaunch,
return l, ""
}
-// certEnd is id's NotAfter on the monotonic clock, through the receipt's
-// clock pair. f.mu must be held.
-func (f *Feed) certEnd(id Identity) time.Duration {
- return f.received + id.NotAfter.Sub(f.anchorWall)
-}
-
// Decide judges one request in a tunnel at mono: the identity (current),
// then the CONNECT target, the inner TLS, the Host header and the path
// class, in that order. Only an allowed decision names a Service.
@@ -174,13 +204,14 @@ func (f *Feed) decideTarget(id Identity, connect string, mono time.Duration) Dec
}
// Deadline is when id's tunnels must close, on the monotonic clock: the
-// earlier of its certificate's NotAfter and the current feed's expiry. A
-// fresher feed moves the second on; with no feed it is mono itself.
+// earlier of its certificate's NotAfter (fixed at first sight) and the
+// current feed's expiry. A fresher feed moves only the second on; with no
+// feed it is mono itself.
func (f *Feed) Deadline(id Identity, mono time.Duration) time.Duration {
f.mu.RLock()
defer f.mu.RUnlock()
if !f.have {
return mono
}
- return min(f.received+f.ttl, f.certEnd(id))
+ return min(f.received+f.ttl, f.certEnd(id, mono))
}
diff --git a/internal/hostedproxy/log.go b/internal/hostedproxy/log.go
index b65bffa8..099f461e 100644
--- a/internal/hostedproxy/log.go
+++ b/internal/hostedproxy/log.go
@@ -3,15 +3,20 @@ package hostedproxy
import (
"encoding/json"
"io"
+ "net"
+ "net/netip"
+ "strconv"
+ "strings"
"sync"
"time"
)
-// logLine is one decision in the log: who (VM, launch, attempt, epoch),
-// where (the CONNECT target), what (method and path class, never the
-// path), the decision and its reason, the origin's status when it
-// answered, and the plaintext bytes from the VM (in) and to it (out).
-// It never holds a header, body, query, path or token.
+// logLine is one decision in the log: who (VM, launch, attempt, epoch,
+// only ever from a verified certificate), where (the canonical CONNECT
+// destination, or "controller" for the bootstrap listener), what (method,
+// path class or bootstrap route, never the path), the decision and its
+// reason, the status answered, and the bytes from the VM (in) and to it
+// (out). It never holds a header, body, query, path, code or token.
type logLine struct {
Time string `json:"time"`
VM string `json:"vm"`
@@ -21,6 +26,7 @@ type logLine struct {
Destination string `json:"destination"`
Method string `json:"method"`
PathClass string `json:"path_class"`
+ Route string `json:"route,omitempty"`
Decision string `json:"decision"`
Reason string `json:"reason,omitempty"`
Status int `json:"status,omitempty"`
@@ -35,18 +41,25 @@ type decisionLog struct {
clock Clock
}
-// maxDestination bounds a logged CONNECT target: a DNS name and a port.
-const maxDestination = 253 + 6
-
// knownMethods are the methods logged by name; any other is "other", so
// a made-up method cannot carry text into the log.
var knownMethods = map[string]bool{"GET": true, "HEAD": true, "POST": true, "PUT": true, "PATCH": true,
"DELETE": true, "OPTIONS": true, "CONNECT": true, "TRACE": true}
-// entry is what a caller knows of one decision.
+// Fixed destinations: a CONNECT target that is not a plain host:port, and
+// the bootstrap listener's one destination.
+const (
+ destInvalid = "invalid"
+ destController = "controller"
+ classBootstrap = "bootstrap"
+)
+
+// entry is what a caller knows of one decision. route is set for the
+// bootstrap listener only.
type entry struct {
id Identity
destination string
+ route string
method string
pathClass string
decision Decision
@@ -59,13 +72,12 @@ func (l *decisionLog) write(e entry) {
if !knownMethods[method] {
method = "other"
}
- dest := e.destination
- if len(dest) > maxDestination {
- dest = dest[:maxDestination]
- }
line := logLine{Time: l.clock.Wall().UTC().Format(time.RFC3339Nano), VM: string(e.id.VMRef), Launch: e.id.LaunchID,
- Attempt: e.id.AttemptID, Epoch: e.id.Epoch, Destination: dest, Method: method, PathClass: e.pathClass,
- Decision: "deny", Reason: e.decision.Reason, Status: e.status, BytesIn: e.in, BytesOut: e.out}
+ Attempt: e.id.AttemptID, Epoch: e.id.Epoch, Destination: canonicalDestination(e.destination), Method: method,
+ PathClass: e.pathClass, Decision: "deny", Reason: e.decision.Reason, Status: e.status, BytesIn: e.in, BytesOut: e.out}
+ if e.route != "" {
+ line.Destination, line.PathClass, line.Route = destController, classBootstrap, e.route
+ }
if e.decision.Allow {
line.Decision = "allow"
}
@@ -77,3 +89,51 @@ func (l *decisionLog) write(e entry) {
defer l.mu.Unlock()
_, _ = l.w.Write(append(raw, '\n'))
}
+
+// canonicalDestination is target as the log may show it: a lower-case DNS
+// name or an IP address, and a decimal port, rebuilt from its parts; or
+// "" for none; or destInvalid for anything else. Userinfo, a path, a
+// query or any other text in the target never survives.
+func canonicalDestination(target string) string {
+ if target == "" {
+ return ""
+ }
+ host, port, err := net.SplitHostPort(target)
+ if err != nil {
+ return destInvalid
+ }
+ n, err := strconv.ParseUint(port, 10, 16)
+ if err != nil || n == 0 || strconv.FormatUint(n, 10) != port {
+ return destInvalid
+ }
+ if a, err := netip.ParseAddr(host); err == nil {
+ if a.Zone() != "" {
+ return destInvalid
+ }
+ return netip.AddrPortFrom(a, uint16(n)).String()
+ }
+ if !dnsName(host) {
+ return destInvalid
+ }
+ return strings.ToLower(host) + ":" + port
+}
+
+// dnsName: 1 to 253 bytes of dot-separated labels, each 1 to 63 letters,
+// digits and inner hyphens.
+func dnsName(s string) bool {
+ if s == "" || len(s) > 253 {
+ return false
+ }
+ for _, label := range strings.Split(s, ".") {
+ if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
+ return false
+ }
+ for i := 0; i < len(label); i++ {
+ c := label[i] | 0x20
+ if !(c >= 'a' && c <= 'z' || label[i] >= '0' && label[i] <= '9' || label[i] == '-') {
+ return false
+ }
+ }
+ }
+ return true
+}
diff --git a/internal/hostedproxy/origin.go b/internal/hostedproxy/origin.go
index 82afef8f..c46e976f 100644
--- a/internal/hostedproxy/origin.go
+++ b/internal/hostedproxy/origin.go
@@ -14,7 +14,6 @@ import (
"math/big"
"net"
"net/netip"
- "strconv"
"sync"
"time"
)
@@ -104,20 +103,94 @@ func (ca *interceptCA) leaf(key string, name func(*x509.Certificate)) (*tls.Cert
// originTimeout bounds dialling an origin and its TLS handshake.
const originTimeout = 15 * time.Second
-// dialOrigin opens the proxy's own TLS to exactly host on ServicePort:
-// SNI host, the certificate checked against OriginRoots (system roots
-// when nil) for host, HTTP/1.1 only.
+// Resolver looks up a service host's addresses; *net.Resolver is one.
+type Resolver interface {
+ LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)
+}
+
+// ErrOriginAddress is a service host whose DNS answer holds an address
+// the proxy never dials.
+var ErrOriginAddress = errors.New("hostedproxy: the service host resolves to an address the proxy never dials")
+
+// refusedPrefixes are ranges beyond what netip's predicates name: shared
+// address space (RFC 6598), "this network" (0/8), the IPv4-compatible
+// and NAT64 forms that embed an IPv4 address, and 6to4.
+var refusedPrefixes = []netip.Prefix{
+ netip.MustParsePrefix("100.64.0.0/10"),
+ netip.MustParsePrefix("0.0.0.0/8"),
+ netip.MustParsePrefix("::/96"),
+ netip.MustParsePrefix("64:ff9b::/96"),
+ netip.MustParsePrefix("64:ff9b:1::/48"),
+ netip.MustParsePrefix("2002::/16"),
+}
+
+// allowedOriginAddr reports whether the proxy may dial a: a global
+// unicast address, IPv4-mapped forms judged as their IPv4 address, and
+// none of loopback, link-local, private (RFC 1918, ULA), unspecified,
+// multicast or refusedPrefixes.
+func allowedOriginAddr(a netip.Addr) bool {
+ a = a.Unmap()
+ if !a.IsValid() || a.Zone() != "" || !a.IsGlobalUnicast() || a.IsPrivate() || a.IsLoopback() ||
+ a.IsLinkLocalUnicast() || a.IsMulticast() || a.IsUnspecified() {
+ return false
+ }
+ for _, p := range refusedPrefixes {
+ if p.Contains(a) {
+ return false
+ }
+ }
+ return true
+}
+
+// resolveOrigin looks host up once and returns its addresses, every one
+// of them allowed, or ErrOriginAddress when any is not: an answer mixing
+// a public address with an internal one is not trusted at all.
+func (s *Server) resolveOrigin(ctx context.Context, host string) ([]netip.Addr, error) {
+ r := s.cfg.Resolver
+ if r == nil {
+ r = net.DefaultResolver
+ }
+ addrs, err := r.LookupNetIP(ctx, "ip", host)
+ if err != nil {
+ return nil, err
+ }
+ if len(addrs) == 0 {
+ return nil, fmt.Errorf("hostedproxy: %s has no address", host)
+ }
+ out := make([]netip.Addr, 0, len(addrs))
+ for _, a := range addrs {
+ if !allowedOriginAddr(a) {
+ return nil, ErrOriginAddress
+ }
+ out = append(out, a.Unmap())
+ }
+ return out, nil
+}
+
+// dialOrigin opens the proxy's own TLS to exactly host on ServicePort. It
+// resolves host once (resolveOrigin), dials the checked addresses
+// themselves, never the name, so no second lookup can answer otherwise,
+// and runs TLS with SNI host, the certificate checked against OriginRoots
+// (system roots when nil) for host, HTTP/1.1 only.
func (s *Server) dialOrigin(ctx context.Context, host string) (net.Conn, error) {
ctx, cancel := context.WithTimeout(ctx, originTimeout)
defer cancel()
- addr := net.JoinHostPort(host, strconv.Itoa(ServicePort))
+ addrs, err := s.resolveOrigin(ctx, host)
+ if err != nil {
+ return nil, err
+ }
dial := s.cfg.DialOrigin
if dial == nil {
d := &net.Dialer{}
dial = d.DialContext
}
- raw, err := dial(ctx, "tcp", addr)
- if err != nil {
+ var raw net.Conn
+ for _, a := range addrs {
+ if raw, err = dial(ctx, "tcp", netip.AddrPortFrom(a, ServicePort).String()); err == nil {
+ break
+ }
+ }
+ if raw == nil {
return nil, err
}
c := tls.Client(raw, &tls.Config{ServerName: host, RootCAs: s.cfg.OriginRoots, NextProtos: []string{ALPNHTTP11},
diff --git a/internal/hostedproxy/policy.go b/internal/hostedproxy/policy.go
index fbb7ee59..b708fa87 100644
--- a/internal/hostedproxy/policy.go
+++ b/internal/hostedproxy/policy.go
@@ -53,6 +53,15 @@ const (
ReasonNestedTunnel = "nested_tunnel"
)
+// Reasons outside Decide (review round 1): ReasonBadRequest is a request
+// line or header past maxHeaderBytes, or a version other than HTTP/1.1,
+// at either parse point; ReasonOriginAddress is a service host whose DNS
+// answer holds an address the proxy never dials (allowedOriginAddr).
+const (
+ ReasonBadRequest = "bad_request"
+ ReasonOriginAddress = "origin_address"
+)
+
// ServicePort is the one port a VM may reach.
const ServicePort = 443
diff --git a/internal/hostedproxy/policy_test.go b/internal/hostedproxy/policy_test.go
index a19266d3..3a14dca0 100644
--- a/internal/hostedproxy/policy_test.go
+++ b/internal/hostedproxy/policy_test.go
@@ -163,7 +163,7 @@ func TestDecideTable(t *testing.T) {
{name: "just inside the feed's lifetime", at: ctlproxy.FeedLifetime - time.Millisecond},
{name: "stale feed", at: ctlproxy.FeedLifetime + time.Millisecond, reason: ReasonStaleFeed},
- {name: "certificate expired", id: func(id *Identity) { id.NotAfter = wall.Add(time.Minute) }, at: time.Minute, reason: ReasonCertExpired},
+ {name: "certificate expired", id: func(id *Identity) { id.Serial, id.NotAfter = "short", wall.Add(-time.Second) }, reason: ReasonCertExpired},
{name: "unknown launch", id: func(id *Identity) { id.LaunchID = "l-9" }, reason: ReasonUnknownLaunch},
{name: "another launch's attempt", id: func(id *Identity) { id.AttemptID = "a-2" }, reason: ReasonUnknownLaunch},
{name: "another VM", id: func(id *Identity) { id.VMRef = "vm-2" }, reason: ReasonUnknownLaunch},
@@ -279,8 +279,9 @@ func TestDecideDeadline(t *testing.T) {
if got, want := f.Deadline(id, mono), mono+ctlproxy.FeedLifetime; got != want {
t.Errorf("Deadline with a 15 minute certificate = %v, want the feed's expiry %v", got, want)
}
- id.NotAfter = wall.Add(2 * time.Minute)
- if got, want := f.Deadline(id, mono), mono+2*time.Minute; got != want {
+ short := testIdentity(wall)
+ short.Serial, short.NotAfter = "short", wall.Add(2*time.Minute)
+ if got, want := f.Deadline(short, mono), mono+2*time.Minute; got != want {
t.Errorf("Deadline with a 2 minute certificate = %v, want its NotAfter %v", got, want)
}
// A fresher feed moves the feed's part on.
@@ -288,7 +289,6 @@ func TestDecideDeadline(t *testing.T) {
if err := f.Install(testFeed()); err != nil {
t.Fatal(err)
}
- id = testIdentity(wall)
if got, want := f.Deadline(id, mono), mono+time.Minute+ctlproxy.FeedLifetime; got != want {
t.Errorf("Deadline after a fresher feed = %v, want %v", got, want)
}
@@ -319,7 +319,9 @@ func TestStaleFeedDeniesAll(t *testing.T) {
}
}
}
- // The wall clock jumps an hour forward: nothing changes.
+ // The certificate is first seen now, as at its handshake. Then the
+ // wall clock jumps an hour forward: nothing changes.
+ decideAll("at receipt", true)
c.Advance(time.Minute)
c.JumpWall(time.Hour)
decideAll("1 min on, wall clock an hour ahead", true)
@@ -340,6 +342,45 @@ func TestStaleFeedDeniesAll(t *testing.T) {
decideAll("a feed claiming an hour, at the lifetime and 1 ms", false)
}
+// TestDecideCertExpiryFixedAtFirstSight: a certificate's deadline is set
+// on the monotonic clock when its serial is first judged, and neither a
+// wall clock jump nor a fresher feed moves it (review round 1, finding 1).
+func TestDecideCertExpiryFixedAtFirstSight(t *testing.T) {
+ c := newFakeClock()
+ f := installed(t, c)
+ first := c.Mono()
+ id := testIdentity(c.Wall())
+ id.NotAfter = c.Wall().Add(2 * time.Minute)
+ if d := f.Decide(id, okRequest(), c.Mono()); !d.Allow {
+ t.Fatalf("at first sight: %+v", d)
+ }
+ // A minute on, the wall clock goes back 30 s and a fresh feed arrives.
+ c.Advance(time.Minute)
+ c.JumpWall(-30 * time.Second)
+ if err := f.Install(testFeed()); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := f.Deadline(id, c.Mono()), first+2*time.Minute; got != want {
+ t.Errorf("Deadline after the jump and the fresh feed = %v, want the first sight's %v", got, want)
+ }
+ c.Advance(time.Minute - time.Millisecond)
+ if d := f.Decide(id, okRequest(), c.Mono()); !d.Allow {
+ t.Errorf("1 ms before the deadline: %+v", d)
+ }
+ c.Advance(2 * time.Millisecond)
+ if d := f.Decide(id, okRequest(), c.Mono()); d.Reason != ReasonCertExpired {
+ t.Errorf("1 ms after the deadline (wall clock 30 s behind): %+v, want %s", d, ReasonCertExpired)
+ }
+ // Another fresh feed, and the wall clock back further: still expired.
+ c.JumpWall(-time.Hour)
+ if err := f.Install(testFeed()); err != nil {
+ t.Fatal(err)
+ }
+ if d := f.Decide(id, okRequest(), c.Mono()); d.Reason != ReasonCertExpired {
+ t.Errorf("after another feed and the wall clock an hour back: %+v, want %s", d, ReasonCertExpired)
+ }
+}
+
// TestPathClassCoversRunner reads the runner and wire sources for the
// instance paths a hosted runner uses, and fails on one the instance class
// does not hold. A path counts when it is a wire path constant the runner