server: Go skeleton — control plane, UDP data plane, Docker + systemd modes

Pure stdlib. Implements the spec's core: enrollment (single-use tokens),
profile (SPKI pin, only real capabilities advertised), sessions with the
§2.4 HKDF-SHA256 key schedule; UDP data plane with the 32-byte ELT1
header, 4-byte HMAC gate, 1024-wide anti-replay window, ECHO_RESP with
observation block, TIMESYNC, and the §3.4 anti-amplification cap. Wire
format has tests (roundtrip + silent-drop cases); enroll→profile→session
smoke-tested live.

Modes: container (autodetect /.dockerenv|/run/.containerenv|cgroup, or
--docker/ECHOLOT_DOCKER=1; config via ECHOLOT_* env; distroless image;
network_mode host required — Docker NAT would falsify observed sources)
and native (--install-systemd/--uninstall-systemd with a hardened unit,
opt-in --self-update from Gitea releases; refused in containers).

CI: tests on any server/ push; server-v* tags build+push the image to the
Gitea registry and attach linux amd64/arm64 binaries + SHA256SUMS to a
release — the artifact self-update consumes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
mrambossek
2026-07-30 13:09:08 +02:00
co-authored by Claude Opus 5
parent ee66648e3c
commit 8a80026d49
15 changed files with 1502 additions and 0 deletions
+171
View File
@@ -0,0 +1,171 @@
// SPDX-FileCopyrightText: 2026 Echolot contributors
// SPDX-License-Identifier: GPL-3.0-or-later
// Package dataplane implements the binary UDP probe protocol (spec §3):
// 32-byte header, HMAC gate, anti-replay, ECHO with observation block.
// Skeleton scope: ECHO_REQ/ECHO_RESP and TIMESYNC only; trains, MTU probes
// and delayed echo land with the corresponding client tests.
package dataplane
import (
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
"log/slog"
"net"
"net/netip"
"time"
"echo-lot.app/server/internal/session"
)
const (
Magic = "ELT1"
HeaderSize = 32
TypeEchoReq = 0x01
TypeEchoResp = 0x02
TypeTimesyncReq = 0x07
TypeTimesyncRsp = 0x08
)
type Server struct {
Sessions *session.Manager
// 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
}
func (s *Server) Serve(conn *net.UDPConn) error {
s.start = time.Now()
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 {
return err
}
tRx := time.Since(s.start).Nanoseconds()
s.handle(conn, raddr, buf[:n], tRx)
}
}
// 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) {
if len(pkt) < HeaderSize || string(pkt[0:4]) != Magic {
return
}
typ := pkt[4]
payloadLen := binary.BigEndian.Uint16(pkt[6:8])
if int(HeaderSize+payloadLen) > len(pkt) {
return
}
var prefix [8]byte
copy(prefix[:], pkt[8:16])
seq := binary.BigEndian.Uint32(pkt[16:20])
sess := s.Sessions.ByWirePrefix(prefix)
if sess == nil {
return
}
mac := hmac.New(sha256.New, sess.Key[:])
mac.Write(pkt[0:28])
mac.Write(pkt[HeaderSize : HeaderSize+int(payloadLen)])
if !hmac.Equal(mac.Sum(nil)[:4], pkt[28:32]) {
return
}
if !sess.CheckSeq(seq) {
return
}
sess.NoteDataSource(raddr)
switch typ {
case TypeEchoReq:
s.echoResp(conn, raddr, sess, pkt, seq, tRxNs)
case TypeTimesyncReq:
s.timesyncResp(conn, raddr, sess, pkt, seq, tRxNs)
default:
slog.Debug("unhandled data-plane type", "type", typ)
}
}
// Observation block (spec §3.3), fixed 40 bytes appended to the RESP header:
// 0 8 t_rx_ns (server clock, process epoch)
// 8 8 t_tx_ns
// 16 16 observed source IP (v4-mapped when v4)
// 32 2 observed source port
// 34 1 received TTL (0xFF = not observed yet; needs recvmsg cmsgs)
// 35 1 received DSCP/ECN byte (0xFF = not observed)
// 36 4 received size
func observation(tRxNs, tTxNs int64, src netip.AddrPort, rcvd int) []byte {
b := make([]byte, 40)
binary.BigEndian.PutUint64(b[0:8], uint64(tRxNs))
binary.BigEndian.PutUint64(b[8:16], uint64(tTxNs))
a16 := src.Addr().As16()
copy(b[16:32], a16[:])
binary.BigEndian.PutUint16(b[32:34], src.Port())
b[34], b[35] = 0xFF, 0xFF
binary.BigEndian.PutUint32(b[36:40], uint32(rcvd))
return b
}
// echoResp mirrors the request header (type flipped), appends the observation
// block, and re-HMACs with the session key. Anti-amplification: the response
// is capped at the request size (spec §3.4) — the observation block replaces
// padding rather than growing the datagram; if the request was smaller than
// header+observation, the block is truncated to fit.
func (s *Server) echoResp(conn *net.UDPConn, raddr netip.AddrPort, sess *session.Session, req []byte, seq uint32, tRxNs int64) {
obs := observation(tRxNs, time.Since(s.start).Nanoseconds(), raddr, len(req))
max := len(req)
if max < HeaderSize {
return
}
payload := obs
if HeaderSize+len(payload) > max {
payload = payload[:max-HeaderSize]
}
s.send(conn, raddr, sess, TypeEchoResp, seq, payload)
}
// timesyncResp: payload = client t1 (echoed back) + t2 (rx) + t3 (tx), spec §3.2.
func (s *Server) timesyncResp(conn *net.UDPConn, raddr netip.AddrPort, sess *session.Session, req []byte, seq uint32, tRxNs int64) {
payload := make([]byte, 24)
copy(payload[0:8], req[20:28]) // client's t_ns from the request header
binary.BigEndian.PutUint64(payload[8:16], uint64(tRxNs))
binary.BigEndian.PutUint64(payload[16:24], uint64(time.Since(s.start).Nanoseconds()))
s.send(conn, raddr, sess, TypeTimesyncRsp, seq, payload)
}
func (s *Server) send(conn *net.UDPConn, raddr netip.AddrPort, sess *session.Session, typ byte, seq uint32, payload []byte) {
pkt := make([]byte, HeaderSize+len(payload))
copy(pkt[0:4], Magic)
pkt[4] = typ
binary.BigEndian.PutUint16(pkt[6:8], uint16(len(payload)))
idBytes := sess.ID[:16] // hex chars of the 8-byte prefix
for i := 0; i < 8; i++ {
pkt[8+i] = hexByte(idBytes[i*2], idBytes[i*2+1])
}
binary.BigEndian.PutUint32(pkt[16:20], seq)
binary.BigEndian.PutUint64(pkt[20:28], uint64(time.Since(s.start).Nanoseconds()))
copy(pkt[HeaderSize:], payload)
mac := hmac.New(sha256.New, sess.Key[:])
mac.Write(pkt[0:28])
mac.Write(payload)
copy(pkt[28:32], mac.Sum(nil)[:4])
_, _ = conn.WriteToUDPAddrPort(pkt, raddr)
}
func hexByte(hi, lo byte) byte {
h := func(c byte) byte {
switch {
case c >= '0' && c <= '9':
return c - '0'
case c >= 'a' && c <= 'f':
return c - 'a' + 10
}
return 0
}
return h(hi)<<4 | h(lo)
}
+144
View File
@@ -0,0 +1,144 @@
// SPDX-FileCopyrightText: 2026 Echolot contributors
// SPDX-License-Identifier: GPL-3.0-or-later
package dataplane
import (
"crypto/hmac"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"net"
"net/netip"
"testing"
"time"
"echo-lot.app/server/internal/session"
)
// craft builds a spec-§3.1 packet for a session the way the Android client will.
func craft(t *testing.T, sess *session.Session, typ byte, seq uint32, payload []byte) []byte {
t.Helper()
pkt := make([]byte, HeaderSize+len(payload))
copy(pkt[0:4], Magic)
pkt[4] = typ
binary.BigEndian.PutUint16(pkt[6:8], uint16(len(payload)))
prefix, err := hex.DecodeString(sess.ID[:16])
if err != nil {
t.Fatal(err)
}
copy(pkt[8:16], prefix)
binary.BigEndian.PutUint32(pkt[16:20], seq)
binary.BigEndian.PutUint64(pkt[20:28], uint64(time.Now().UnixNano()))
copy(pkt[HeaderSize:], payload)
mac := hmac.New(sha256.New, sess.Key[:])
mac.Write(pkt[0:28])
mac.Write(payload)
copy(pkt[28:32], mac.Sum(nil)[:4])
return pkt
}
func startServer(t *testing.T) (*session.Manager, netip.AddrPort) {
t.Helper()
mgr := session.NewManager(time.Minute)
conn, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.Close() })
go (&Server{Sessions: mgr}).Serve(conn)
return mgr, conn.LocalAddr().(*net.UDPAddr).AddrPort()
}
func TestEchoRoundtripObservationAndAntiAmplification(t *testing.T) {
mgr, addr := startServer(t)
sess, _, err := mgr.New("dev1", "credential-ikm", netip.MustParseAddr("127.0.0.1"))
if err != nil {
t.Fatal(err)
}
client, err := net.DialUDP("udp", nil, net.UDPAddrFromAddrPort(addr))
if err != nil {
t.Fatal(err)
}
defer client.Close()
client.SetDeadline(time.Now().Add(2 * time.Second))
padding := make([]byte, 64) // request: 32 hdr + 64 payload = 96 bytes
req := craft(t, sess, TypeEchoReq, 1, padding)
if _, err := client.Write(req); err != nil {
t.Fatal(err)
}
resp := make([]byte, 1500)
n, err := client.Read(resp)
if err != nil {
t.Fatalf("no ECHO_RESP: %v", err)
}
if n > len(req) {
t.Fatalf("anti-amplification violated: resp %d > req %d", n, len(req))
}
if resp[4] != TypeEchoResp {
t.Fatalf("type = %#x, want ECHO_RESP", resp[4])
}
// Verify the server's HMAC with the same derived key.
mac := hmac.New(sha256.New, sess.Key[:])
mac.Write(resp[0:28])
mac.Write(resp[HeaderSize:n])
if !hmac.Equal(mac.Sum(nil)[:4], resp[28:32]) {
t.Fatal("response HMAC does not verify")
}
// Observation block: observed source port must match our socket.
obs := resp[HeaderSize:n]
if len(obs) < 40 {
t.Fatalf("observation block truncated to %d (req was big enough for 40)", len(obs))
}
gotPort := binary.BigEndian.Uint16(obs[32:34])
wantPort := client.LocalAddr().(*net.UDPAddr).AddrPort().Port()
if gotPort != wantPort {
t.Fatalf("observed port %d, want %d", gotPort, wantPort)
}
if rcvd := binary.BigEndian.Uint32(obs[36:40]); rcvd != uint32(len(req)) {
t.Fatalf("observed size %d, want %d", rcvd, len(req))
}
}
func TestDropsReplayBadHmacAndUnknownPrefix(t *testing.T) {
mgr, addr := startServer(t)
sess, _, err := mgr.New("dev1", "credential-ikm", netip.MustParseAddr("127.0.0.1"))
if err != nil {
t.Fatal(err)
}
client, err := net.DialUDP("udp", nil, net.UDPAddrFromAddrPort(addr))
if err != nil {
t.Fatal(err)
}
defer client.Close()
// Valid packet once...
req := craft(t, sess, TypeEchoReq, 7, make([]byte, 48))
client.SetDeadline(time.Now().Add(2 * time.Second))
client.Write(req)
buf := make([]byte, 1500)
if _, err := client.Read(buf); err != nil {
t.Fatalf("first send should get a response: %v", err)
}
drop := func(name string, pkt []byte) {
t.Helper()
client.SetDeadline(time.Now().Add(300 * time.Millisecond))
client.Write(pkt)
if _, err := client.Read(buf); err == nil {
t.Fatalf("%s: got a response, want silent drop", name)
}
}
// ...replayed seq: silence.
drop("replay", req)
// Bad HMAC: silence.
bad := craft(t, sess, TypeEchoReq, 8, make([]byte, 48))
bad[31] ^= 0xFF
drop("bad hmac", bad)
// Unknown session prefix: silence.
unk := craft(t, sess, TypeEchoReq, 9, make([]byte, 48))
unk[8] ^= 0xFF
drop("unknown prefix", unk)
}