diff --git a/server/cmd/echolot-server/main.go b/server/cmd/echolot-server/main.go index b52e0f5..a489895 100644 --- a/server/cmd/echolot-server/main.go +++ b/server/cmd/echolot-server/main.go @@ -102,7 +102,7 @@ func serve(cfg *config.Config) error { dp := &dataplane.Server{Sessions: sessions} tcpSrv := &tcpecho.Server{} - caps := []string{"udp-probe", "delayed-echo", "connect-back"} + caps := []string{"udp-probe", "delayed-echo", "connect-back", "http-echo"} if len(config.Addrs(cfg.TCPListen)) > 0 { caps = append(caps, "tcp-echo") } @@ -110,7 +110,7 @@ func serve(cfg *config.Config) error { ctl := &control.Server{ Store: st, Sessions: sessions, Name: cfg.Name, UDPPort: mustPort(firstAddr(cfg.UDPListen)), TCPPort: mustPort(firstAddr(cfg.TCPListen)), - StunPort: mustPort(firstAddr(cfg.StunListen)), PinB64: pin, + StunPort: mustPort(firstAddr(cfg.StunListen)), PinB64: pin, CertChain: cert.Certificate, DelayedEcho: dp.SendDelayedEcho, TCPRecent: func(ip string) any { return tcpSrv.RecentFor(ip) }, } @@ -189,6 +189,15 @@ func serve(cfg *config.Config) error { }(addr, ln) } + // Optional cleartext HTTP-echo (spec §4 plaintext-path test) — only + // POST /v1/echo, no auth, no secrets. Off unless configured. + var httpEchoSrvs []*http.Server + for _, addr := range config.Addrs(cfg.HTTPEchoListen) { + hs := &http.Server{Addr: addr, Handler: ctl.EchoHandler(), ReadHeaderTimeout: 10 * time.Second} + httpEchoSrvs = append(httpEchoSrvs, hs) + go func(a string, srv *http.Server) { errCh <- fmt.Errorf("http-echo %s: %w", a, srv.ListenAndServe()) }(addr, hs) + } + // STUN (spec §4) — advertises stun-5780 only with ≥2 same-family addrs. var stunSrv *stun.Server if stunAddrs := config.Addrs(cfg.StunListen); len(stunAddrs) > 0 { @@ -263,6 +272,9 @@ func serve(cfg *config.Config) error { for _, l := range dnsTCP { _ = l.Close() } + for _, hs := range httpEchoSrvs { + _ = hs.Shutdown(shutCtx) + } return nil case err := <-errCh: return err diff --git a/server/internal/config/config.go b/server/internal/config/config.go index e259a05..d268058 100644 --- a/server/internal/config/config.go +++ b/server/internal/config/config.go @@ -29,6 +29,9 @@ type Config struct { StunListen string // ECHOLOT_STUN_LISTEN / --stun-listen (spec default 3478; empty disables) DNSListen string // ECHOLOT_DNS_LISTEN / --dns-listen (canary zone; empty disables) CanaryZone string // ECHOLOT_CANARY_ZONE / --canary-zone (e.g. c.echo-lot.app) + // Optional cleartext HTTP-echo listener (spec §4 plaintext-path test). + // Default empty = off; it exposes only POST /v1/echo, no auth, no secrets. + HTTPEchoListen string // ECHOLOT_HTTP_ECHO_LISTEN / --http-echo-listen // Admin UI / health listener (spec §7: localhost-only by default) AdminListen string // ECHOLOT_ADMIN_LISTEN / --admin-listen @@ -71,6 +74,7 @@ func Load(args []string) (*Config, *Actions, error) { fs.StringVar(&c.StunListen, "stun-listen", envOr("STUN_LISTEN", ":3478"), "STUN listen address(es), comma-separated; empty disables (spec §4)") fs.StringVar(&c.DNSListen, "dns-listen", envOr("DNS_LISTEN", ""), "canary-DNS listen address(es) udp+tcp/53, comma-separated; empty disables (spec §6.1)") fs.StringVar(&c.CanaryZone, "canary-zone", envOr("CANARY_ZONE", ""), "authoritative canary zone, e.g. c.echo-lot.app") + fs.StringVar(&c.HTTPEchoListen, "http-echo-listen", envOr("HTTP_ECHO_LISTEN", ""), "optional CLEARTEXT http-echo listen address(es); empty disables (spec §4)") fs.StringVar(&c.AdminListen, "admin-listen", envOr("ADMIN_LISTEN", "127.0.0.1:8444"), "admin/health listen address (keep localhost)") fs.StringVar(&c.StateDir, "state-dir", envOr("STATE_DIR", defaultStateDir()), "state directory (device store, generated TLS)") fs.StringVar(&c.Name, "name", envOr("NAME", "echolot"), "server profile name") diff --git a/server/internal/control/control.go b/server/internal/control/control.go index a028832..e45cdfb 100644 --- a/server/internal/control/control.go +++ b/server/internal/control/control.go @@ -41,6 +41,8 @@ type Server struct { StunPort int // SPKI pin of the serving cert, for the profile's pins[] field. PinB64 string + // CertChain is the served leaf-first DER chain, for GET /v1/tls-reference. + CertChain [][]byte // Capabilities as computed at startup from what is actually wired up. Capabilities []string // TCPRecent returns recent TCP-echo connections for a source IP (may be nil). @@ -61,11 +63,21 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("DELETE /v1/sessions/{id}", s.deleteSession) mux.HandleFunc("GET /v1/sessions/{id}/observations", s.observations) mux.HandleFunc("POST /v1/sessions/{id}/actions", s.actions) - // TODO(spec §4): POST /v1/echo, GET /v1/tls-reference; TLS-echo/JA4 + mux.HandleFunc("POST /v1/echo", s.httpEcho) + mux.HandleFunc("GET /v1/tls-reference", s.tlsReference) + // TODO(spec §4): TLS-echo/JA4 (tls-echo capability, needs ClientHello capture) // TODO(spec §5): downtrain, big_send, frag_send, throughput return mux } +// EchoHandler exposes just the HTTP-echo endpoint for the optional cleartext +// listener (spec §4: plaintext-path tampering test). +func (s *Server) EchoHandler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("POST /v1/echo", s.httpEcho) + return mux +} + // sessionAuth resolves {id} and requires the bearer to be the owning device. func (s *Server) sessionAuth(w http.ResponseWriter, r *http.Request) *session.Session { dev := s.Store.DeviceByCredential(bearer(r)) diff --git a/server/internal/control/httpecho.go b/server/internal/control/httpecho.go new file mode 100644 index 0000000..67b5909 --- /dev/null +++ b/server/internal/control/httpecho.go @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: 2026 Echolot contributors +// SPDX-License-Identifier: GPL-3.0-or-later + +package control + +import ( + "crypto/tls" + "encoding/base64" + "io" + "net/http" + "strings" +) + +// httpEcho implements spec §4 HTTP echo: return the exact received request +// (request line + headers + body, base64) plus the TLS parameters the server +// observed. The client diffs this against what it sent to detect header +// injection/stripping, transparent proxying, or TLS interception +// (sec.http_echo). Served on the control HTTPS listener and, optionally, on a +// cleartext listener to test plaintext-path tampering. +func (s *Server) httpEcho(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) + + // Reconstruct the received request head verbatim (as close as net/http + // exposes it — header order is lost, but names/values and the request + // line survive, which is what tampering changes). + var head strings.Builder + head.WriteString(r.Method + " " + r.RequestURI + " " + r.Proto + "\r\n") + head.WriteString("Host: " + r.Host + "\r\n") + for name, vals := range r.Header { + for _, v := range vals { + head.WriteString(name + ": " + v + "\r\n") + } + } + head.WriteString("\r\n") + + resp := map[string]any{ + "observed_src": r.RemoteAddr, + "request_head_b64": base64.StdEncoding.EncodeToString([]byte(head.String())), + "body_b64": base64.StdEncoding.EncodeToString(body), + "body_len": len(body), + "scheme": schemeOf(r), + } + if r.TLS != nil { + resp["tls"] = tlsParams(r.TLS) + } + writeJSON(w, http.StatusOK, resp) +} + +func schemeOf(r *http.Request) string { + if r.TLS != nil { + return "https" + } + return "http" +} + +func tlsParams(cs *tls.ConnectionState) map[string]any { + return map[string]any{ + "version": tlsVersionName(cs.Version), + "cipher": tls.CipherSuiteName(cs.CipherSuite), + "sni": cs.ServerName, + "alpn": cs.NegotiatedProtocol, + "resumed": cs.DidResume, + } +} + +func tlsVersionName(v uint16) string { + switch v { + case tls.VersionTLS13: + return "TLS1.3" + case tls.VersionTLS12: + return "TLS1.2" + case tls.VersionTLS11: + return "TLS1.1" + case tls.VersionTLS10: + return "TLS1.0" + } + return "unknown" +} + +// tlsReference implements spec §4: return the exact certificate chain this +// server serves (DER, base64), so the app can compare it against a copy it +// obtained out-of-band and against what its own direct handshake yielded +// (sec.tls_reference). Not a capability — always available on the control +// plane. No auth: the chain is public information a handshake already reveals. +func (s *Server) tlsReference(w http.ResponseWriter, r *http.Request) { + chain := make([]string, 0, len(s.CertChain)) + for _, der := range s.CertChain { + chain = append(chain, base64.StdEncoding.EncodeToString(der)) + } + writeJSON(w, http.StatusOK, map[string]any{ + "pin_sha256": s.PinB64, + "chain_der": chain, // leaf first, as served + }) +} diff --git a/server/internal/control/httpecho_test.go b/server/internal/control/httpecho_test.go new file mode 100644 index 0000000..cc6e601 --- /dev/null +++ b/server/internal/control/httpecho_test.go @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: 2026 Echolot contributors +// SPDX-License-Identifier: GPL-3.0-or-later + +package control + +import ( + "encoding/base64" + "encoding/json" + "net/http/httptest" + "strings" + "testing" +) + +func TestHTTPEchoReflectsRequest(t *testing.T) { + s := &Server{} + req := httptest.NewRequest("POST", "/v1/echo", strings.NewReader("payload-bytes")) + req.Header.Set("X-Injected", "canary") + rr := httptest.NewRecorder() + s.httpEcho(rr, req) + + var resp struct { + RequestHeadB64 string `json:"request_head_b64"` + BodyB64 string `json:"body_b64"` + BodyLen int `json:"body_len"` + Scheme string `json:"scheme"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + head, _ := base64.StdEncoding.DecodeString(resp.RequestHeadB64) + if !strings.Contains(string(head), "X-Injected: canary") { + t.Fatalf("echo did not reflect the injected header:\n%s", head) + } + body, _ := base64.StdEncoding.DecodeString(resp.BodyB64) + if string(body) != "payload-bytes" || resp.BodyLen != 13 { + t.Fatalf("body mismatch: %q len=%d", body, resp.BodyLen) + } + if resp.Scheme != "http" { // httptest requests carry no TLS + t.Fatalf("scheme = %s, want http", resp.Scheme) + } +} + +func TestTLSReferenceReturnsChain(t *testing.T) { + s := &Server{PinB64: "TESTPIN", CertChain: [][]byte{{0x30, 0x82, 0x01}, {0xAA, 0xBB}}} + rr := httptest.NewRecorder() + s.tlsReference(rr, httptest.NewRequest("GET", "/v1/tls-reference", nil)) + + var resp struct { + PinSHA256 string `json:"pin_sha256"` + ChainDER []string `json:"chain_der"` + } + if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp.PinSHA256 != "TESTPIN" || len(resp.ChainDER) != 2 { + t.Fatalf("bad tls-reference: %+v", resp) + } + first, _ := base64.StdEncoding.DecodeString(resp.ChainDER[0]) + if len(first) != 3 || first[0] != 0x30 { + t.Fatalf("leaf DER not round-tripped: %x", first) + } +} +