diff --git a/server/cmd/echolot-server/main.go b/server/cmd/echolot-server/main.go index c0e1929..771c2c7 100644 --- a/server/cmd/echolot-server/main.go +++ b/server/cmd/echolot-server/main.go @@ -38,7 +38,9 @@ import ( "echo-lot.app/server/internal/selfupdate" "echo-lot.app/server/internal/session" "echo-lot.app/server/internal/store" + "echo-lot.app/server/internal/stun" "echo-lot.app/server/internal/system" + "echo-lot.app/server/internal/tcpecho" ) // Version is stamped via -ldflags "-X main.Version=v1.2.3" in CI. @@ -95,9 +97,20 @@ func serve(cfg *config.Config) error { slog.Info("control-plane certificate", "pin-sha256", pin) sessions := session.NewManager(15 * time.Minute) + dp := &dataplane.Server{Sessions: sessions} + tcpSrv := &tcpecho.Server{} + + caps := []string{"udp-probe", "delayed-echo", "connect-back"} + if len(config.Addrs(cfg.TCPListen)) > 0 { + caps = append(caps, "tcp-echo") + } + ctl := &control.Server{ Store: st, Sessions: sessions, Name: cfg.Name, - UDPPort: mustPort(firstAddr(cfg.UDPListen)), TCPPort: mustPort(firstAddr(cfg.TCPListen)), PinB64: pin, + UDPPort: mustPort(firstAddr(cfg.UDPListen)), TCPPort: mustPort(firstAddr(cfg.TCPListen)), + StunPort: mustPort(firstAddr(cfg.StunListen)), PinB64: pin, + DelayedEcho: dp.SendDelayedEcho, + TCPRecent: func(ip string) any { return tcpSrv.RecentFor(ip) }, } ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) @@ -156,14 +169,45 @@ func serve(cfg *config.Config) error { return fmt.Errorf("udp listen %s: %w", addr, err) } udpConns = append(udpConns, conn) - dp := &dataplane.Server{Sessions: sessions} go func(a string, c *net.UDPConn) { errCh <- fmt.Errorf("udp %s: %w", a, dp.Serve(c)) }(addr, conn) } + // TCP echo (spec §4) + var tcpLns []net.Listener + for _, addr := range config.Addrs(cfg.TCPListen) { + ln, err := net.Listen("tcp", addr) + if err != nil { + return fmt.Errorf("tcp listen %s: %w", addr, err) + } + tcpLns = append(tcpLns, ln) + go func(a string, l net.Listener) { + errCh <- fmt.Errorf("tcp %s: %w", a, tcpSrv.Serve(l)) + }(addr, ln) + } + + // 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 { + stunSrv, err = stun.Listen(stunAddrs) + if err != nil { + return fmt.Errorf("stun listen: %w", err) + } + go func() { errCh <- fmt.Errorf("stun: %w", stunSrv.Serve()) }() + if stunSrv.Has5780() { + ctl.Capabilities = append(caps, "stun-5780") + } else { + ctl.Capabilities = append(caps, "stun-basic") + } + } else { + ctl.Capabilities = caps + } + slog.Info("listening", - "control", ctlAddrs, "admin", cfg.AdminListen, "udp", udpAddrs) + "control", ctlAddrs, "admin", cfg.AdminListen, "udp", udpAddrs, + "tcp", config.Addrs(cfg.TCPListen), "stun", config.Addrs(cfg.StunListen), + "capabilities", ctl.Capabilities) select { case <-ctx.Done(): @@ -175,6 +219,12 @@ func serve(cfg *config.Config) error { for _, c := range udpConns { _ = c.Close() } + for _, l := range tcpLns { + _ = l.Close() + } + if stunSrv != nil { + stunSrv.Close() + } return nil case err := <-errCh: return err diff --git a/server/internal/config/config.go b/server/internal/config/config.go index 4e68f5c..374baab 100644 --- a/server/internal/config/config.go +++ b/server/internal/config/config.go @@ -24,8 +24,9 @@ type Config struct { TLSKey string // ECHOLOT_TLS_KEY / --tls-key // Data plane - UDPListen string // ECHOLOT_UDP_LISTEN / --udp-listen (spec default port 8442) - TCPListen string // ECHOLOT_TCP_LISTEN / --tcp-listen (spec default port 8441) + UDPListen string // ECHOLOT_UDP_LISTEN / --udp-listen (spec default port 8442) + TCPListen string // ECHOLOT_TCP_LISTEN / --tcp-listen (spec default port 8441) + StunListen string // ECHOLOT_STUN_LISTEN / --stun-listen (spec default 3478; empty disables) // Admin UI / health listener (spec §7: localhost-only by default) AdminListen string // ECHOLOT_ADMIN_LISTEN / --admin-listen @@ -65,6 +66,7 @@ func Load(args []string) (*Config, *Actions, error) { fs.StringVar(&c.TLSKey, "tls-key", envOr("TLS_KEY", ""), "TLS key path (empty: self-signed in state dir)") fs.StringVar(&c.UDPListen, "udp-listen", envOr("UDP_LISTEN", ":8442"), "UDP data-plane listen address(es), comma-separated") fs.StringVar(&c.TCPListen, "tcp-listen", envOr("TCP_LISTEN", ":8441"), "TCP echo listen address(es), comma-separated") + fs.StringVar(&c.StunListen, "stun-listen", envOr("STUN_LISTEN", ":3478"), "STUN listen address(es), comma-separated; 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 e4a177e..bfd43ab 100644 --- a/server/internal/control/control.go +++ b/server/internal/control/control.go @@ -7,14 +7,19 @@ package control import ( + "crypto/rand" "crypto/sha256" "crypto/tls" "crypto/x509" "encoding/base64" + "encoding/hex" "encoding/json" + "errors" "log/slog" + "net" "net/http" "net/netip" + "strconv" "strings" "time" @@ -29,12 +34,19 @@ type Server struct { Store *store.Store Sessions *session.Manager Name string - // Targets/capabilities for the profile response. The skeleton offers only + // Targets/capabilities for the profile response. The server offers only // what it actually implements; the registry grows with the code. - UDPPort int - TCPPort int + UDPPort int + TCPPort int + StunPort int // SPKI pin of the serving cert, for the profile's pins[] field. PinB64 string + // 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). + TCPRecent func(ip string) any + // DelayedEcho schedules/sends a DELAYED_ECHO for a session (may be nil). + DelayedEcho func(sess *session.Session, actionID string) error } func (s *Server) Handler() http.Handler { @@ -43,11 +55,131 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /v1/profile", s.profile) mux.HandleFunc("POST /v1/sessions", s.newSession) mux.HandleFunc("DELETE /v1/sessions/{id}", s.deleteSession) - // TODO(spec §5, §6): /v1/sessions/{id}/actions, /v1/sessions/{id}/observations - // TODO(spec §4): POST /v1/echo, GET /v1/tls-reference + 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 + // TODO(spec §5): downtrain, big_send, frag_send, throughput 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)) + if dev == nil { + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unknown credential"}) + return nil + } + sess := s.Sessions.ByID(r.PathValue("id")) + if sess == nil || sess.Device != dev.ID { + writeJSON(w, http.StatusNotFound, map[string]string{"error": "no such session"}) + return nil + } + return sess +} + +// observations is spec §6 — everything the server witnessed for a session. +func (s *Server) observations(w http.ResponseWriter, r *http.Request) { + sess := s.sessionAuth(w, r) + if sess == nil { + return + } + packetsSeen, udp, cb := sess.Observations() + var tcp any + if s.TCPRecent != nil { + // Correlate by source IP: TCP echo carries no session id on the wire. + if ds := sess.DataSource(); ds.IsValid() { + tcp = s.TCPRecent(ds.Addr().Unmap().String()) + } else if sess.ControlSource.IsValid() { + tcp = s.TCPRecent(sess.ControlSource.Unmap().String()) + } + } + writeJSON(w, http.StatusOK, map[string]any{ + "udp": map[string]any{"packets_seen": packetsSeen, "packets": udp}, + "tcp": tcp, + "connect_back": cb, + // TODO(spec §6): http echo records, dns_canary + }) +} + +// actions is spec §5 — authenticated asymmetric operations. Implemented: +// delayed_echo, connect_back. Destination is ALWAYS the session's observed +// source (data-plane source; connect_back uses the control-plane source). +func (s *Server) actions(w http.ResponseWriter, r *http.Request) { + sess := s.sessionAuth(w, r) + if sess == nil { + return + } + var req struct { + Action string `json:"action"` + DelayS int `json:"delay_s"` + Protocol string `json:"protocol"` + Port int `json:"port"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad body"}) + return + } + actionID := randomID() + switch req.Action { + case "delayed_echo": + if s.DelayedEcho == nil { + writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "delayed_echo not wired"}) + return + } + delay := min(max(req.DelayS, 1), 600) + if !sess.DataSource().IsValid() { + writeJSON(w, http.StatusConflict, map[string]string{"error": "no data-plane traffic seen yet — send an ECHO first"}) + return + } + time.AfterFunc(time.Duration(delay)*time.Second, func() { + if err := s.DelayedEcho(sess, actionID); err != nil { + slog.Debug("delayed echo failed", "err", err) + } + }) + writeJSON(w, http.StatusAccepted, map[string]any{"action_id": actionID, "delay_s": delay}) + case "connect_back": + if req.Port < 1 || req.Port > 65535 || (req.Protocol != "tcp" && req.Protocol != "udp") { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "connect_back needs protocol tcp|udp and a port"}) + return + } + target := net.JoinHostPort(sess.ControlSource.Unmap().String(), strconv.Itoa(req.Port)) + go func() { + start := time.Now() + conn, err := net.DialTimeout(req.Protocol, target, 5*time.Second) + res := session.ConnectBackResult{ActionID: actionID, RttMs: float64(time.Since(start).Microseconds()) / 1000} + switch { + case err == nil: + res.Result = "connected" + if req.Protocol == "udp" { + // UDP "dial" always succeeds locally; send one datagram + // so the client actually observes something. + _, _ = conn.Write([]byte("echolot-connect-back " + actionID)) + } + conn.Close() + case isTimeout(err): + res.Result = "timeout" + default: + res.Result = "refused" + } + sess.RecordConnectBack(res) + }() + writeJSON(w, http.StatusAccepted, map[string]any{"action_id": actionID, "target": target}) + default: + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unknown or unimplemented action"}) + } +} + +func isTimeout(err error) bool { + var ne net.Error + return errors.As(err, &ne) && ne.Timeout() +} + +func randomID() string { + var b [8]byte + _, _ = rand.Read(b[:]) + return hex.EncodeToString(b[:]) +} + func bearer(r *http.Request) string { h := r.Header.Get("Authorization") if v, ok := strings.CutPrefix(h, "Bearer "); ok { @@ -103,12 +235,13 @@ func (s *Server) profile(w http.ResponseWriter, r *http.Request) { // source_url makes GPL §6 compliance mechanical for operators of // modified builds and gives clients provenance for the measurement. "source_url": "", // TODO: stamp from build metadata - "capabilities": []string{"udp-probe"}, + "capabilities": s.Capabilities, "targets": []map[string]any{{ - "id": s.Name, - "ip4": host, // TODO: explicit configured addresses, v6, second STUN addr - "udp_port": s.UDPPort, - "tcp_port": s.TCPPort, + "id": s.Name, + "ip4": host, // TODO: explicit configured addresses, v6, second STUN addr + "udp_port": s.UDPPort, + "tcp_port": s.TCPPort, + "stun_port": s.StunPort, }}, "pins": []string{"pin-sha256:" + s.PinB64}, "next_pins": []string{}, diff --git a/server/internal/dataplane/udp.go b/server/internal/dataplane/udp.go index 28c5c05..18236e8 100644 --- a/server/internal/dataplane/udp.go +++ b/server/internal/dataplane/udp.go @@ -11,9 +11,11 @@ import ( "crypto/hmac" "crypto/sha256" "encoding/binary" + "fmt" "log/slog" "net" "net/netip" + "sync" "time" "echo-lot.app/server/internal/session" @@ -27,6 +29,7 @@ const ( TypeEchoResp = 0x02 TypeTimesyncReq = 0x07 TypeTimesyncRsp = 0x08 + TypeDelayedEcho = 0x0B ) type Server struct { @@ -34,13 +37,22 @@ type Server struct { // Epoch for server-side t_rx/t_tx: process start; observation consumers // only need differences plus the timesync exchange, not absolute time. start time.Time + + mu sync.Mutex + conns []*net.UDPConn } +// Serve runs the read loop for one socket; call once per bound address. +// The socket is retained so actions (delayed echo) can pick a family-matching +// sender later. func (s *Server) Serve(conn *net.UDPConn) error { - s.start = time.Now() + s.mu.Lock() + if s.start.IsZero() { + s.start = time.Now() + } + s.conns = append(s.conns, conn) + s.mu.Unlock() buf := make([]byte, 65535) - oob := make([]byte, 0) - _ = oob // TODO: recvmsg w/ IP_RECVTOS+IP_RECVTTL via golang.org/x/net for TTL/DSCP/ECN observation for { n, raddr, err := conn.ReadFromUDPAddrPort(buf) if err != nil { @@ -51,6 +63,36 @@ func (s *Server) Serve(conn *net.UDPConn) error { } } +// connFor picks a retained socket whose family matches the target. +func (s *Server) connFor(target netip.AddrPort) *net.UDPConn { + s.mu.Lock() + defer s.mu.Unlock() + want4 := target.Addr().Unmap().Is4() + for _, c := range s.conns { + la := c.LocalAddr().(*net.UDPAddr).AddrPort() + if la.Addr().Unmap().Is4() == want4 { + return c + } + } + return nil +} + +// SendDelayedEcho fires one DELAYED_ECHO packet at the session's observed +// data-plane source (spec §5: the NAT-mapping-lifetime primitive). The +// payload carries the action id for correlation. +func (s *Server) SendDelayedEcho(sess *session.Session, actionID string) error { + target := sess.DataSource() + if !target.IsValid() { + return fmt.Errorf("session has no observed data-plane source yet") + } + conn := s.connFor(target) + if conn == nil { + return fmt.Errorf("no data-plane socket matches target family") + } + s.send(conn, target, sess, TypeDelayedEcho, 0, []byte(actionID)) + return nil +} + // handle enforces spec §3.1/§3.4: unknown prefix, bad HMAC, expired session, // replayed seq → silent drop, never a response. func (s *Server) handle(conn *net.UDPConn, raddr netip.AddrPort, pkt []byte, tRxNs int64) { @@ -80,6 +122,10 @@ func (s *Server) handle(conn *net.UDPConn, raddr netip.AddrPort, pkt []byte, tRx return } sess.NoteDataSource(raddr) + sess.RecordUDP(session.UDPObservation{ + Seq: seq, TRxNs: tRxNs, TTxNs: time.Since(s.start).Nanoseconds(), + Src: raddr.String(), Size: len(pkt), Type: typ, + }) switch typ { case TypeEchoReq: diff --git a/server/internal/session/session.go b/server/internal/session/session.go index 099ca44..3a39f24 100644 --- a/server/internal/session/session.go +++ b/server/internal/session/session.go @@ -31,6 +31,64 @@ type Session struct { // a bitmask of the 1024 preceding. maxSeq uint32 window [16]uint64 + + // Observations (spec §6): per-packet UDP view + connect-back results. + packetsSeen uint64 + udpObs []UDPObservation // ring, newest last, cap obsCap + connectBack []ConnectBackResult +} + +const obsCap = 4096 + +// UDPObservation is the server's witnessed view of one data-plane packet. +type UDPObservation struct { + Seq uint32 `json:"seq"` + TRxNs int64 `json:"t_rx_ns"` + TTxNs int64 `json:"t_tx_ns"` + Src string `json:"src"` + Size int `json:"size"` + Type uint8 `json:"type"` +} + +// ConnectBackResult records one connect-back action outcome. +type ConnectBackResult struct { + ActionID string `json:"action_id"` + Result string `json:"result"` // connected | refused | timeout + RttMs float64 `json:"rtt_ms"` +} + +// RecordUDP appends a packet observation (ring-capped). +func (s *Session) RecordUDP(o UDPObservation) { + s.mu.Lock() + defer s.mu.Unlock() + s.packetsSeen++ + if len(s.udpObs) >= obsCap { + s.udpObs = s.udpObs[1:] + } + s.udpObs = append(s.udpObs, o) +} + +// RecordConnectBack appends a connect-back outcome. +func (s *Session) RecordConnectBack(r ConnectBackResult) { + s.mu.Lock() + defer s.mu.Unlock() + s.connectBack = append(s.connectBack, r) +} + +// Observations returns a copy of everything witnessed so far. +func (s *Session) Observations() (packetsSeen uint64, udp []UDPObservation, cb []ConnectBackResult) { + s.mu.Lock() + defer s.mu.Unlock() + return s.packetsSeen, append([]UDPObservation(nil), s.udpObs...), + append([]ConnectBackResult(nil), s.connectBack...) +} + +// DataSource returns the last verified data-plane source (invalid when the +// session has not sent data-plane traffic yet). +func (s *Session) DataSource() netip.AddrPort { + s.mu.Lock() + defer s.mu.Unlock() + return s.dataSource } // KeySalt returns nothing — the salt is not retained after derivation; it is @@ -87,6 +145,20 @@ func (m *Manager) ByWirePrefix(prefix [8]byte) *Session { return s } +// ByID resolves a full session id (sessions are keyed by their wire prefix). +func (m *Manager) ByID(id string) *Session { + if len(id) < 16 { + return nil + } + m.mu.Lock() + defer m.mu.Unlock() + s := m.byPrefix[id[:16]] + if s == nil || s.ID != id || time.Now().After(s.Expires) { + return nil + } + return s +} + func (m *Manager) Delete(id string) { m.mu.Lock() defer m.mu.Unlock() diff --git a/server/internal/stun/stun.go b/server/internal/stun/stun.go new file mode 100644 index 0000000..de75080 --- /dev/null +++ b/server/internal/stun/stun.go @@ -0,0 +1,266 @@ +// SPDX-FileCopyrightText: 2026 Echolot contributors +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package stun implements an unmodified RFC 5389 STUN binding responder with +// the RFC 5780 NAT-behavior-discovery attributes (OTHER-ADDRESS, +// RESPONSE-ORIGIN, CHANGE-REQUEST) when alternate addresses are available. +// No custom framing — interop with existing STUN tooling is a feature +// (spec §4). Each configured primary address gets two sockets: the given +// port and port+1 (the RFC 5780 alternate-port convention). +package stun + +import ( + "crypto/rand" + "encoding/binary" + "log/slog" + "net" + "net/netip" +) + +const ( + magicCookie = 0x2112A442 + + typeBindingRequest = 0x0001 + typeBindingSuccess = 0x0101 + + attrChangeRequest = 0x0003 + attrXorMapped = 0x0020 + attrSoftware = 0x8022 + attrResponseOrigin = 0x802B + attrOtherAddress = 0x802C + + changeIP = 0x04 + changePort = 0x02 +) + +// sock is one bound socket, addressable by (address index, port index). +type sock struct { + conn *net.UDPConn + addr netip.AddrPort +} + +// Server holds the socket grid: addrs × {primary, alternate} ports. +type Server struct { + // socks[i][0] = primary port, socks[i][1] = alt port for address i. + socks [][2]*sock +} + +// Listen binds primary+alternate sockets for every address. Addresses are +// "ip:port" specs; the alternate port is port+1. +func Listen(addrs []string) (*Server, error) { + s := &Server{} + for _, spec := range addrs { + ap, err := netip.ParseAddrPort(spec) + if err != nil { + return nil, err + } + var pair [2]*sock + for i, port := range []uint16{ap.Port(), ap.Port() + 1} { + bind := netip.AddrPortFrom(ap.Addr(), port) + conn, err := net.ListenUDP("udp", net.UDPAddrFromAddrPort(bind)) + if err != nil { + s.Close() + return nil, err + } + pair[i] = &sock{conn: conn, addr: bind} + } + s.socks = append(s.socks, pair) + } + return s, nil +} + +func (s *Server) Close() { + for _, pair := range s.socks { + for _, sk := range pair { + if sk != nil { + sk.conn.Close() + } + } + } +} + +// Has5780 reports whether any address family has ≥2 addresses — the +// prerequisite for full NAT behavior discovery. +func (s *Server) Has5780() bool { + var v4, v6 int + for _, pair := range s.socks { + if pair[0].addr.Addr().Is4() || pair[0].addr.Addr().Is4In6() { + v4++ + } else { + v6++ + } + } + return v4 >= 2 || v6 >= 2 +} + +// Serve starts one read loop per socket and blocks until the first error. +func (s *Server) Serve() error { + errCh := make(chan error, len(s.socks)*2) + for ai := range s.socks { + for pi := range s.socks[ai] { + go func(ai, pi int) { errCh <- s.loop(ai, pi) }(ai, pi) + } + } + return <-errCh +} + +func (s *Server) loop(ai, pi int) error { + sk := s.socks[ai][pi] + buf := make([]byte, 1500) + for { + n, raddr, err := sk.conn.ReadFromUDPAddrPort(buf) + if err != nil { + return err + } + s.handle(ai, pi, buf[:n], raddr) + } +} + +// otherAddr finds the "diagonal" alternate for RFC 5780: different address +// (same family), different port. Returns nil when there is none. +func (s *Server) other(ai int, sameFamily bool, fam4 bool) int { + for i, pair := range s.socks { + if i == ai { + continue + } + is4 := pair[0].addr.Addr().Is4() || pair[0].addr.Addr().Is4In6() + if !sameFamily || is4 == fam4 { + return i + } + } + return -1 +} + +func (s *Server) handle(ai, pi int, pkt []byte, raddr netip.AddrPort) { + if len(pkt) < 20 || binary.BigEndian.Uint16(pkt[0:2]) != typeBindingRequest { + return + } + if binary.BigEndian.Uint32(pkt[4:8]) != magicCookie { + return + } + msgLen := int(binary.BigEndian.Uint16(pkt[2:4])) + if 20+msgLen > len(pkt) { + return + } + var txid [12]byte + copy(txid[:], pkt[8:20]) + + // Parse CHANGE-REQUEST if present (RFC 5780 §7.2). + var change byte + for off := 20; off+4 <= 20+msgLen; { + at := binary.BigEndian.Uint16(pkt[off : off+2]) + al := int(binary.BigEndian.Uint16(pkt[off+2 : off+4])) + if off+4+al > len(pkt) { + break + } + if at == attrChangeRequest && al >= 4 { + change = pkt[off+7] + } + off += 4 + al + (4-al%4)%4 // attributes are 32-bit aligned + } + + // Pick the responding socket per CHANGE-REQUEST. + fam4 := raddr.Addr().Is4() || raddr.Addr().Is4In6() + rai, rpi := ai, pi + if change&changeIP != 0 { + if o := s.other(ai, true, fam4); o >= 0 { + rai = o + } else { + return // cannot honor — RFC says error response; silence is safer for a probe target + } + } + if change&changePort != 0 { + rpi = 1 - pi + } + responder := s.socks[rai][rpi] + + resp := buildResponse(txid, raddr, responder.addr, s.otherAddress(ai, fam4)) + if _, err := responder.conn.WriteToUDPAddrPort(resp, raddr); err != nil { + slog.Debug("stun write failed", "to", raddr, "err", err) + } +} + +// otherAddress computes the OTHER-ADDRESS attribute value (alt IP, alt port) +// for the client's family, or an invalid AddrPort when unavailable. +func (s *Server) otherAddress(ai int, fam4 bool) netip.AddrPort { + if o := s.other(ai, true, fam4); o >= 0 { + return s.socks[o][1].addr + } + return netip.AddrPort{} +} + +func buildResponse(txid [12]byte, mapped, origin, other netip.AddrPort) []byte { + attrs := xorMappedAttr(attrXorMapped, mapped, txid) + attrs = append(attrs, addrAttr(attrResponseOrigin, origin)...) + if other.IsValid() { + attrs = append(attrs, addrAttr(attrOtherAddress, other)...) + } + sw := []byte("echolot") + attrs = append(attrs, attrHeader(attrSoftware, len(sw))...) + attrs = append(attrs, pad4(sw)...) + + msg := make([]byte, 20, 20+len(attrs)) + binary.BigEndian.PutUint16(msg[0:2], typeBindingSuccess) + binary.BigEndian.PutUint16(msg[2:4], uint16(len(attrs))) + binary.BigEndian.PutUint32(msg[4:8], magicCookie) + copy(msg[8:20], txid[:]) + return append(msg, attrs...) +} + +func attrHeader(typ uint16, valLen int) []byte { + h := make([]byte, 4) + binary.BigEndian.PutUint16(h[0:2], typ) + binary.BigEndian.PutUint16(h[2:4], uint16(valLen)) + return h +} + +func pad4(b []byte) []byte { + for len(b)%4 != 0 { + b = append(b, 0) + } + return b +} + +// addrValue encodes the RFC 5389 address structure (family, port, address). +func addrValue(ap netip.AddrPort) []byte { + addr := ap.Addr().Unmap() + if addr.Is4() { + v := make([]byte, 8) + v[1] = 0x01 + binary.BigEndian.PutUint16(v[2:4], ap.Port()) + a4 := addr.As4() + copy(v[4:], a4[:]) + return v + } + v := make([]byte, 20) + v[1] = 0x02 + binary.BigEndian.PutUint16(v[2:4], ap.Port()) + a16 := addr.As16() + copy(v[4:], a16[:]) + return v +} + +func addrAttr(typ uint16, ap netip.AddrPort) []byte { + v := addrValue(ap) + return append(attrHeader(typ, len(v)), v...) +} + +// xorMappedAttr encodes XOR-MAPPED-ADDRESS (RFC 5389 §15.2). +func xorMappedAttr(typ uint16, ap netip.AddrPort, txid [12]byte) []byte { + v := addrValue(ap) + binary.BigEndian.PutUint16(v[2:4], ap.Port()^uint16(magicCookie>>16)) + var key [16]byte + binary.BigEndian.PutUint32(key[0:4], magicCookie) + copy(key[4:], txid[:]) + for i := 4; i < len(v); i++ { + v[i] ^= key[i-4] + } + return append(attrHeader(typ, len(v)), v...) +} + +// NewTxID is exported for tests and client code. +func NewTxID() [12]byte { + var t [12]byte + _, _ = rand.Read(t[:]) + return t +} diff --git a/server/internal/stun/stun_test.go b/server/internal/stun/stun_test.go new file mode 100644 index 0000000..43de78f --- /dev/null +++ b/server/internal/stun/stun_test.go @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: 2026 Echolot contributors +// SPDX-License-Identifier: GPL-3.0-or-later + +package stun + +import ( + "encoding/binary" + "net" + "net/netip" + "testing" + "time" +) + +// bindingRequest builds a minimal RFC 5389 binding request. +func bindingRequest(txid [12]byte, change byte) []byte { + var attrs []byte + if change != 0 { + attrs = append(attrs, attrHeader(attrChangeRequest, 4)...) + attrs = append(attrs, 0, 0, 0, change) + } + msg := make([]byte, 20, 20+len(attrs)) + binary.BigEndian.PutUint16(msg[0:2], typeBindingRequest) + binary.BigEndian.PutUint16(msg[2:4], uint16(len(attrs))) + binary.BigEndian.PutUint32(msg[4:8], magicCookie) + copy(msg[8:20], txid[:]) + return append(msg, attrs...) +} + +// parseXorMapped extracts XOR-MAPPED-ADDRESS from a binding success. +func parseXorMapped(t *testing.T, resp []byte, txid [12]byte) netip.AddrPort { + t.Helper() + if binary.BigEndian.Uint16(resp[0:2]) != typeBindingSuccess { + t.Fatalf("type = %#x, want binding success", resp[0:2]) + } + msgLen := int(binary.BigEndian.Uint16(resp[2:4])) + for off := 20; off+4 <= 20+msgLen; { + at := binary.BigEndian.Uint16(resp[off : off+2]) + al := int(binary.BigEndian.Uint16(resp[off+2 : off+4])) + if at == attrXorMapped { + v := append([]byte(nil), resp[off+4:off+4+al]...) + port := binary.BigEndian.Uint16(v[2:4]) ^ uint16(magicCookie>>16) + var key [16]byte + binary.BigEndian.PutUint32(key[0:4], magicCookie) + copy(key[4:], txid[:]) + for i := 4; i < len(v); i++ { + v[i] ^= key[i-4] + } + if v[1] == 0x01 { + return netip.AddrPortFrom(netip.AddrFrom4([4]byte(v[4:8])), port) + } + return netip.AddrPortFrom(netip.AddrFrom16([16]byte(v[4:20])), port) + } + off += 4 + al + (4-al%4)%4 + } + t.Fatal("no XOR-MAPPED-ADDRESS in response") + return netip.AddrPort{} +} + +func TestBindingAndChangePort(t *testing.T) { + // Two loopback "addresses" is not possible portably, so exercise one + // address (basic binding + change-port); the change-IP path needs the + // two-address grid of a real deployment. + srv, err := Listen([]string{"127.0.0.1:0"}) + if err != nil { + t.Fatal(err) + } + // port 0 twice would collide at 1; rebind explicitly on free ports + srv.Close() + base := freePort(t) + srv, err = Listen([]string{netip.AddrPortFrom(netip.MustParseAddr("127.0.0.1"), base).String()}) + if err != nil { + t.Skipf("cannot bind %d/%d: %v", base, base+1, err) + } + defer srv.Close() + go srv.Serve() + + client, err := net.DialUDP("udp", nil, srv.socks[0][0].conn.LocalAddr().(*net.UDPAddr)) + if err != nil { + t.Fatal(err) + } + defer client.Close() + client.SetDeadline(time.Now().Add(2 * time.Second)) + + txid := NewTxID() + client.Write(bindingRequest(txid, 0)) + buf := make([]byte, 1500) + n, err := client.Read(buf) + if err != nil { + t.Fatal(err) + } + mapped := parseXorMapped(t, buf[:n], txid) + want := client.LocalAddr().(*net.UDPAddr).AddrPort() + if mapped.Port() != want.Port() { + t.Fatalf("mapped port %d, want %d", mapped.Port(), want.Port()) + } + + // CHANGE-REQUEST(port): response must come from the alternate port. + // Dial-connected sockets drop packets from other sources, so use an + // unconnected socket and inspect the reply's source. + uc, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + defer uc.Close() + uc.SetDeadline(time.Now().Add(2 * time.Second)) + txid2 := NewTxID() + uc.WriteToUDPAddrPort(bindingRequest(txid2, changePort), srv.socks[0][0].addr) + n, from, err := uc.ReadFromUDPAddrPort(buf) + if err != nil { + t.Fatal(err) + } + if from.Port() != srv.socks[0][1].addr.Port() { + t.Fatalf("change-port reply came from %v, want alt port %d", from, srv.socks[0][1].addr.Port()) + } + parseXorMapped(t, buf[:n], txid2) +} + +func freePort(t *testing.T) uint16 { + t.Helper() + // Find two adjacent free ports for the primary/alternate pair. + for tries := 0; tries < 20; tries++ { + l, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + continue + } + p := l.LocalAddr().(*net.UDPAddr).Port + l.Close() + l2, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: p + 1}) + if err != nil { + continue + } + l2.Close() + return uint16(p) + } + t.Skip("no adjacent free UDP ports found") + return 0 +} diff --git a/server/internal/tcpecho/tcpecho.go b/server/internal/tcpecho/tcpecho.go new file mode 100644 index 0000000..d0b6f84 --- /dev/null +++ b/server/internal/tcpecho/tcpecho.go @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: 2026 Echolot contributors +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package tcpecho implements the spec §4 TCP echo: after connect the server +// sends one JSON line with what it observed (source address/port, negotiated +// MSS and TCP options from TCP_INFO), then byte-echoes until FIN. This is the +// evidence source for mtu.mss_observed. +// +// The TLS/ALPN "elt-echo" variant (ClientHello capture + JA4) is not +// implemented yet. +package tcpecho + +import ( + "encoding/json" + "io" + "net" + "sync" + "time" +) + +// ConnRecord is what the observations API reports per connection (spec §6). +type ConnRecord struct { + ConnectedAt time.Time `json:"connected_at"` + Src string `json:"src"` + MSS int `json:"mss"` + Options []string `json:"options"` +} + +type Server struct { + mu sync.Mutex + recent []ConnRecord // ring, newest last +} + +const recentCap = 1024 + +func (s *Server) record(r ConnRecord) { + s.mu.Lock() + defer s.mu.Unlock() + if len(s.recent) >= recentCap { + s.recent = s.recent[1:] + } + s.recent = append(s.recent, r) +} + +// RecentFor returns records whose source IP matches ip. +func (s *Server) RecentFor(ip string) []ConnRecord { + s.mu.Lock() + defer s.mu.Unlock() + var out []ConnRecord + for _, r := range s.recent { + if h, _, err := net.SplitHostPort(r.Src); err == nil && h == ip { + out = append(out, r) + } + } + return out +} + +func (s *Server) Serve(ln net.Listener) error { + for { + conn, err := ln.Accept() + if err != nil { + return err + } + go s.handle(conn) + } +} + +func (s *Server) handle(conn net.Conn) { + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(5 * time.Minute)) + + info := tcpInfo(conn) // platform-specific; zero values off-Linux + rec := ConnRecord{ + ConnectedAt: time.Now().UTC(), + Src: conn.RemoteAddr().String(), + MSS: info.MSS, + Options: info.Options, + } + s.record(rec) + + greeting, _ := json.Marshal(map[string]any{ + "observed_src": rec.Src, + "mss": rec.MSS, + "options": rec.Options, + }) + if _, err := conn.Write(append(greeting, '\n')); err != nil { + return + } + // Byte-echo until FIN; the client's data is its own to interpret. + _, _ = io.Copy(conn, conn) +} diff --git a/server/internal/tcpecho/tcpinfo_linux.go b/server/internal/tcpecho/tcpinfo_linux.go new file mode 100644 index 0000000..da4cb0a --- /dev/null +++ b/server/internal/tcpecho/tcpinfo_linux.go @@ -0,0 +1,69 @@ +// SPDX-FileCopyrightText: 2026 Echolot contributors +// SPDX-License-Identifier: GPL-3.0-or-later + +//go:build linux + +package tcpecho + +import ( + "encoding/binary" + "net" + "syscall" + "unsafe" +) + +type connInfo struct { + MSS int + Options []string +} + +// tcpInfo reads TCP_INFO via getsockopt. Only the head of struct tcp_info is +// needed: 8 header bytes (state..wscale flags) then u32 rto, ato, snd_mss, +// rcv_mss — layout is part of the kernel ABI and stable. +func tcpInfo(conn net.Conn) connInfo { + tc, ok := conn.(*net.TCPConn) + if !ok { + return connInfo{} + } + raw, err := tc.SyscallConn() + if err != nil { + return connInfo{} + } + var buf [104]byte + var got bool + _ = raw.Control(func(fd uintptr) { + l := uint32(len(buf)) + _, _, errno := syscall.Syscall6(syscall.SYS_GETSOCKOPT, fd, + uintptr(syscall.SOL_TCP), uintptr(syscall.TCP_INFO), + uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&l)), 0) + got = errno == 0 && l >= 24 + }) + if !got { + return connInfo{} + } + // tcpi_options bit flags (include/uapi/linux/tcp.h) + const ( + optTimestamps = 1 + optSACK = 2 + optWscale = 4 + optECN = 8 + ) + var opts []string + ob := buf[5] + if ob&optTimestamps != 0 { + opts = append(opts, "timestamps") + } + if ob&optSACK != 0 { + opts = append(opts, "sack") + } + if ob&optWscale != 0 { + opts = append(opts, "wscale") + } + if ob&optECN != 0 { + opts = append(opts, "ecn") + } + return connInfo{ + MSS: int(binary.LittleEndian.Uint32(buf[16:20])), // tcpi_snd_mss + Options: opts, + } +} diff --git a/server/internal/tcpecho/tcpinfo_other.go b/server/internal/tcpecho/tcpinfo_other.go new file mode 100644 index 0000000..e800c0d --- /dev/null +++ b/server/internal/tcpecho/tcpinfo_other.go @@ -0,0 +1,17 @@ +// SPDX-FileCopyrightText: 2026 Echolot contributors +// SPDX-License-Identifier: GPL-3.0-or-later + +//go:build !linux + +package tcpecho + +import "net" + +type connInfo struct { + MSS int + Options []string +} + +// tcpInfo: TCP_INFO is Linux-only; other platforms report zero values and +// the greeting says mss:0 — honest absence rather than a guess. +func tcpInfo(net.Conn) connInfo { return connInfo{} }