From 72e9cda9d5fe760ff922a4abefeda6c077ccde8d Mon Sep 17 00:00:00 2001 From: annel0 Date: Sun, 28 Jun 2026 11:33:49 +0300 Subject: [PATCH] Make RTP obfuscation hot path allocation-free The per-packet wrap/unwrap path allocated a fresh output buffer, a key string for the AEAD cache lookup, and a nonce slice on every datagram (~1.3 KB / 3 allocs per packet). Under load this produced steady GC pressure on the server. Cache the cipher.AEAD on the wrapPacketConn at key-selection time and reuse per-conn rx/tx buffers, with the nonce built on the stack. The wire format is unchanged (verified by round-trip and old<->new cross-compat tests), so existing clients keep working without updates. Result: 1328 B/3 allocs -> 16 B/1 alloc per packet (the residual 16 B is the nonce escaping through the cipher.AEAD interface, payload-independent). Adds obfs_test.go covering nonce equivalence, round-trip across sizes, old/new wire compatibility, wrong-key rejection, key-store selection, an end-to-end wrapPacketConn exchange, and an allocation-bound regression guard (skipped under -race, which distorts alloc counts). --- obfs_noraceflag_test.go | 5 + obfs_raceflag_test.go | 8 + obfs_test.go | 435 ++++++++++++++++++++++++++++++++++++++++ server.go | 162 ++++++++++----- 4 files changed, 563 insertions(+), 47 deletions(-) create mode 100644 obfs_noraceflag_test.go create mode 100644 obfs_raceflag_test.go create mode 100644 obfs_test.go diff --git a/obfs_noraceflag_test.go b/obfs_noraceflag_test.go new file mode 100644 index 0000000..94aee52 --- /dev/null +++ b/obfs_noraceflag_test.go @@ -0,0 +1,5 @@ +//go:build !race + +package main + +const raceEnabled = false diff --git a/obfs_raceflag_test.go b/obfs_raceflag_test.go new file mode 100644 index 0000000..8c9fcf6 --- /dev/null +++ b/obfs_raceflag_test.go @@ -0,0 +1,8 @@ +//go:build race + +package main + +// raceEnabled is true when the test binary is built with -race. The race +// detector instruments allocations, so per-packet alloc-count assertions are +// meaningless under it and are skipped. +const raceEnabled = true diff --git a/obfs_test.go b/obfs_test.go new file mode 100644 index 0000000..c96abc6 --- /dev/null +++ b/obfs_test.go @@ -0,0 +1,435 @@ +package main + +import ( + "bytes" + "crypto/rand" + "io" + "net" + "sync" + "testing" + "time" +) + +// --- helpers ----------------------------------------------------------------- + +func testKey(t testing.TB, password string) []byte { + t.Helper() + k, err := deriveWrapKey(password) + if err != nil { + t.Fatalf("deriveWrapKey: %v", err) + } + return k +} + +func randPayload(t testing.TB, n int) []byte { + t.Helper() + p := make([]byte, n) + if _, err := rand.Read(p); err != nil { + t.Fatalf("rand: %v", err) + } + return p +} + +// --- nonce ------------------------------------------------------------------- + +// The stack-based nonce builder must produce bytes identical to the legacy +// allocating one — the nonce is part of the AEAD contract, any drift breaks +// Poly1305 auth against the iOS WRAP-A client. +func TestObfsBuildNonceEquiv(t *testing.T) { + cases := []struct { + ssrc uint32 + seq uint16 + ts uint32 + }{ + {0, 0, 0}, + {0xDEADBEEF, 0x1234, 0xCAFEBABE}, + {1, 65535, 0xFFFFFFFF}, + } + for _, c := range cases { + want := obfsBuildNonce(c.ssrc, c.seq, c.ts) + var got [12]byte + obfsBuildNonceInto(&got, c.ssrc, c.seq, c.ts) + if !bytes.Equal(want, got[:]) { + t.Errorf("nonce mismatch ssrc=%x seq=%x ts=%x: want %x got %x", + c.ssrc, c.seq, c.ts, want, got[:]) + } + // Bytes [6:8] must be zero (part of the wire format). + if got[6] != 0 || got[7] != 0 { + t.Errorf("nonce [6:8] not zero: %x", got[:]) + } + } +} + +// --- wire format ------------------------------------------------------------- + +// Wrapping then unwrapping with the alloc-free path must recover the payload +// exactly, across a range of sizes including odd lengths. +func TestObfsRoundTrip(t *testing.T) { + key := testKey(t, "round-trip-pass") + aead, err := getAEAD(key) + if err != nil { + t.Fatalf("getAEAD: %v", err) + } + cfg := NewObfsConfig() + state := NewObfsState() + + for _, n := range []int{1, 13, 64, 100, 1000, 1280, 1400} { + payload := randPayload(t, n) + dst := make([]byte, obfsWrapWireLen(n, cfg)) + wn, err := obfsWrapPacketInto(dst, aead, payload, cfg, state) + if err != nil { + t.Fatalf("wrap n=%d: %v", n, err) + } + wire := dst[:wn] + + // Wire sanity: RTP v2, P bit set, PT 111 → looks like a VK media packet. + if wire[0] != 0xA0 { + t.Errorf("n=%d byte0=%#x, want 0xA0 (V=2,P=1)", n, wire[0]) + } + if wire[1]&0x7F != 111 { + t.Errorf("n=%d PT=%d, want 111", n, wire[1]&0x7F) + } + if !obfsIsRTPPacket(wire) { + t.Errorf("n=%d: obfsIsRTPPacket=false", n) + } + + out := make([]byte, n+64) + m, err := obfsUnwrapPacketAEAD(aead, wire, out) + if err != nil { + t.Fatalf("unwrap n=%d: %v", n, err) + } + if !bytes.Equal(out[:m], payload) { + t.Errorf("n=%d: payload mismatch after round trip", n) + } + } +} + +// The refactor must not change the wire format: a packet produced by the OLD +// allocating path must decode with the NEW alloc-free path and vice versa. +// This is the core compatibility guarantee for the iOS WRAP-A client. +func TestObfsWireCompatOldNew(t *testing.T) { + key := testKey(t, "compat-pass") + aead, err := getAEAD(key) + if err != nil { + t.Fatalf("getAEAD: %v", err) + } + payload := randPayload(t, 512) + + // OLD wrap -> NEW unwrap + { + cfg := NewObfsConfig() + state := NewObfsState() + wire, err := obfsWrapPacket(key, payload, cfg, state) + if err != nil { + t.Fatalf("old wrap: %v", err) + } + out := make([]byte, len(payload)+64) + m, err := obfsUnwrapPacketAEAD(aead, wire, out) + if err != nil { + t.Fatalf("new unwrap of old wrap: %v", err) + } + if !bytes.Equal(out[:m], payload) { + t.Fatal("old->new payload mismatch") + } + } + + // NEW wrap -> OLD unwrap + { + cfg := NewObfsConfig() + state := NewObfsState() + dst := make([]byte, obfsWrapWireLen(len(payload), cfg)) + n, err := obfsWrapPacketInto(dst, aead, payload, cfg, state) + if err != nil { + t.Fatalf("new wrap: %v", err) + } + out := make([]byte, len(payload)+64) + m, err := obfsUnwrapPacket(key, dst[:n], out) + if err != nil { + t.Fatalf("old unwrap of new wrap: %v", err) + } + if !bytes.Equal(out[:m], payload) { + t.Fatal("new->old payload mismatch") + } + } +} + +// A packet authenticated under one password must NOT decrypt under another. +func TestObfsWrongKeyFails(t *testing.T) { + aeadA, _ := getAEAD(testKey(t, "alice")) + aeadB, _ := getAEAD(testKey(t, "bob")) + cfg := NewObfsConfig() + state := NewObfsState() + payload := randPayload(t, 200) + + dst := make([]byte, obfsWrapWireLen(len(payload), cfg)) + n, err := obfsWrapPacketInto(dst, aeadA, payload, cfg, state) + if err != nil { + t.Fatalf("wrap: %v", err) + } + out := make([]byte, len(payload)+64) + if _, err := obfsUnwrapPacketAEAD(aeadB, dst[:n], out); err == nil { + t.Fatal("expected auth failure with wrong key, got nil") + } +} + +// dst smaller than the wrapped size must be rejected, not overflow. +func TestObfsWrapDstTooSmall(t *testing.T) { + aead, _ := getAEAD(testKey(t, "small")) + cfg := NewObfsConfig() + state := NewObfsState() + payload := randPayload(t, 500) + tiny := make([]byte, 50) + if _, err := obfsWrapPacketInto(tiny, aead, payload, cfg, state); err == nil { + t.Fatal("expected error for too-small dst") + } +} + +// --- key store --------------------------------------------------------------- + +// A packet wrapped with a derived key must be recognised by the key store +// (the first-packet key-selection probe the server runs per connection). +func TestWrapKeyStoreUnwrapSelectsKey(t *testing.T) { + ks := newWrapKeyStore() + if err := ks.SetPasswords("main-pw", []string{"gen-pw-1", "gen-pw-2"}); err != nil { + t.Fatalf("SetPasswords: %v", err) + } + + for _, pw := range []string{"main-pw", "gen-pw-1", "gen-pw-2"} { + key := testKey(t, pw) + aead, _ := getAEAD(key) + cfg := NewObfsConfig() + state := NewObfsState() + payload := randPayload(t, 128) + dst := make([]byte, obfsWrapWireLen(len(payload), cfg)) + n, _ := obfsWrapPacketInto(dst, aead, payload, cfg, state) + + out := make([]byte, len(payload)+64) + gotKey, m, err := ks.Unwrap(dst[:n], out) + if err != nil { + t.Fatalf("pw=%s Unwrap: %v", pw, err) + } + if !bytes.Equal(gotKey, key) { + t.Errorf("pw=%s: store selected wrong key", pw) + } + if !bytes.Equal(out[:m], payload) { + t.Errorf("pw=%s: payload mismatch", pw) + } + } + + // Unknown password must not authenticate against any stored key. + badKey := testKey(t, "not-registered") + badAead, _ := getAEAD(badKey) + cfg := NewObfsConfig() + state := NewObfsState() + dst := make([]byte, obfsWrapWireLen(16, cfg)) + n, _ := obfsWrapPacketInto(dst, badAead, randPayload(t, 16), cfg, state) + out := make([]byte, 128) + if _, _, err := ks.Unwrap(dst[:n], out); err == nil { + t.Fatal("expected Unwrap failure for unregistered password") + } +} + +// --- end-to-end wrapPacketConn ---------------------------------------------- + +type fakeAddr string + +func (fakeAddr) Network() string { return "fake" } +func (a fakeAddr) String() string { return string(a) } + +// fakePacketConn is an in-memory net.PacketConn. Two are wired together by +// crossing their rx/tx channels, modelling the UDP/TURN path under the wrap. +type fakePacketConn struct { + rx chan []byte + tx chan []byte + local fakeAddr + remote fakeAddr + once sync.Once +} + +func newFakePair() (*fakePacketConn, *fakePacketConn) { + a2b := make(chan []byte, 32) + b2a := make(chan []byte, 32) + a := &fakePacketConn{rx: b2a, tx: a2b, local: "A", remote: "B"} + b := &fakePacketConn{rx: a2b, tx: b2a, local: "B", remote: "A"} + return a, b +} + +func (c *fakePacketConn) ReadFrom(p []byte) (int, net.Addr, error) { + pkt, ok := <-c.rx + if !ok { + return 0, c.remote, io.EOF + } + return copy(p, pkt), c.remote, nil +} + +func (c *fakePacketConn) WriteTo(p []byte, _ net.Addr) (int, error) { + b := make([]byte, len(p)) + copy(b, p) + c.tx <- b + return len(p), nil +} + +func (c *fakePacketConn) Close() error { c.once.Do(func() { close(c.tx) }); return nil } +func (c *fakePacketConn) LocalAddr() net.Addr { return c.local } +func (c *fakePacketConn) SetDeadline(time.Time) error { return nil } +func (c *fakePacketConn) SetReadDeadline(time.Time) error { return nil } +func (c *fakePacketConn) SetWriteDeadline(time.Time) error { return nil } + +// Full path: a client (raw obfs over a fake conn) drives the server-side +// wrapPacketConn through key selection, server->client wrapped writes, and +// repeated client->server wrapped reads — all over the reused buffers. +func TestWrapPacketConnEndToEnd(t *testing.T) { + const pw = "e2e-main" + ks := newWrapKeyStore() + if err := ks.SetPasswords(pw, nil); err != nil { + t.Fatalf("SetPasswords: %v", err) + } + clientRaw, serverRaw := newFakePair() + server := &wrapPacketConn{inner: serverRaw, keys: ks} + + key := testKey(t, pw) + clientAead, _ := getAEAD(key) + clientCfg := NewObfsConfig() + clientState := NewObfsState() + + clientSend := func(payload []byte) { + dst := make([]byte, obfsWrapWireLen(len(payload), clientCfg)) + n, err := obfsWrapPacketInto(dst, clientAead, payload, clientCfg, clientState) + if err != nil { + t.Fatalf("client wrap: %v", err) + } + if _, err := clientRaw.WriteTo(dst[:n], clientRaw.remote); err != nil { + t.Fatalf("client write: %v", err) + } + } + + // 1) First packet triggers key selection on the server. + first := []byte("GETCONF:51820|deadbeef|" + pw) + clientSend(first) + rbuf := make([]byte, 2048) + n, _, err := server.ReadFrom(rbuf) + if err != nil { + t.Fatalf("server ReadFrom (select): %v", err) + } + if !bytes.Equal(rbuf[:n], first) { + t.Fatalf("first payload mismatch: got %q", rbuf[:n]) + } + + // 2) Server -> client: the client must decode using the SSRC carried on + // the wire (server picked its own ObfsConfig at selection time). + resp := randPayload(t, 800) + if _, err := server.WriteTo(resp, serverRaw.remote); err != nil { + t.Fatalf("server WriteTo: %v", err) + } + wire := make([]byte, 2048) + wn, _, err := clientRaw.ReadFrom(wire) + if err != nil { + t.Fatalf("client ReadFrom: %v", err) + } + cout := make([]byte, 2048) + cm, err := obfsUnwrapPacketAEAD(clientAead, wire[:wn], cout) + if err != nil { + t.Fatalf("client unwrap server resp: %v", err) + } + if !bytes.Equal(cout[:cm], resp) { + t.Fatal("server->client payload mismatch") + } + + // 3) Many client -> server packets over the reused server rxBuf. + for i := 0; i < 50; i++ { + msg := randPayload(t, 200+i) + clientSend(msg) + rn, _, err := server.ReadFrom(rbuf) + if err != nil { + t.Fatalf("server ReadFrom #%d: %v", i, err) + } + if !bytes.Equal(rbuf[:rn], msg) { + t.Fatalf("client->server payload mismatch #%d", i) + } + } +} + +// --- allocations ------------------------------------------------------------- + +// The hot paths must not allocate the per-packet output/key buffers anymore. +// A single residual 16-byte allocation per call is unavoidable: the [12]byte +// nonce escapes to the heap when sliced into the cipher.AEAD interface method +// (the compiler can't prove Seal/Open don't retain it). That is a tiny fixed +// cost independent of payload size — the churn that mattered (the full output +// buffer + key string + nonce slice, ~1.3 KB / 3 allocs per packet) is gone. +const obfsHotPathMaxAllocs = 1.0 + +func TestObfsHotPathAllocsBounded(t *testing.T) { + if raceEnabled { + t.Skip("race instrumentation distorts allocation counts") + } + key := testKey(t, "alloc-pass") + aead, _ := getAEAD(key) + cfg := NewObfsConfig() + state := NewObfsState() + payload := randPayload(t, 1200) + dst := make([]byte, obfsWrapWireLen(len(payload), cfg)) + out := make([]byte, len(payload)+64) + + wrapAllocs := testing.AllocsPerRun(200, func() { + if _, err := obfsWrapPacketInto(dst, aead, payload, cfg, state); err != nil { + t.Fatal(err) + } + }) + if wrapAllocs > obfsHotPathMaxAllocs { + t.Errorf("obfsWrapPacketInto: %.1f allocs/op, want <= %.0f", wrapAllocs, obfsHotPathMaxAllocs) + } + + // Build one valid packet to repeatedly unwrap. + wn, _ := obfsWrapPacketInto(dst, aead, payload, cfg, state) + wire := append([]byte(nil), dst[:wn]...) + unwrapAllocs := testing.AllocsPerRun(200, func() { + if _, err := obfsUnwrapPacketAEAD(aead, wire, out); err != nil { + t.Fatal(err) + } + }) + if unwrapAllocs > obfsHotPathMaxAllocs { + t.Errorf("obfsUnwrapPacketAEAD: %.1f allocs/op, want <= %.0f", unwrapAllocs, obfsHotPathMaxAllocs) + } + + // Regression guard: the new path must allocate strictly less than the old + // allocating wrapper (which mallocs the whole output buffer every packet). + oldAllocs := testing.AllocsPerRun(200, func() { + if _, err := obfsWrapPacket(key, payload, cfg, state); err != nil { + t.Fatal(err) + } + }) + if wrapAllocs >= oldAllocs { + t.Errorf("new wrap (%.1f allocs) not better than old (%.1f allocs)", wrapAllocs, oldAllocs) + } +} + +func BenchmarkObfsWrapInto(b *testing.B) { + key := testKey(b, "bench") + aead, _ := getAEAD(key) + cfg := NewObfsConfig() + state := NewObfsState() + payload := randPayload(b, 1200) + dst := make([]byte, obfsWrapWireLen(len(payload), cfg)) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if _, err := obfsWrapPacketInto(dst, aead, payload, cfg, state); err != nil { + b.Fatal(err) + } + } +} + +func BenchmarkObfsWrapOldAllocating(b *testing.B) { + key := testKey(b, "bench") + cfg := NewObfsConfig() + state := NewObfsState() + payload := randPayload(b, 1200) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if _, err := obfsWrapPacket(key, payload, cfg, state); err != nil { + b.Fatal(err) + } + } +} diff --git a/server.go b/server.go index a06e004..d4aa679 100644 --- a/server.go +++ b/server.go @@ -76,8 +76,6 @@ type PasswordEntry struct { IsDeactivated bool `json:"is_deactivated,omitempty"` } - - type Database struct { MainPassword string `json:"main_password"` AdminID string `json:"admin_id"` @@ -459,7 +457,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { } else { txt += "🟢 Статус: *АКТИВЕН*\n" } - + if entry.ExpiresAt > 0 { expireTime := time.Unix(entry.ExpiresAt, 0) remaining := time.Until(expireTime) @@ -471,7 +469,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { } else { txt += "⏰ Бессрочный ♾\n" } - + txt += fmt.Sprintf("\n📊 *Трафик:*\n• Скачано: %.2f MB\n• Отдано: %.2f MB\n", float64(entry.DownBytes)/(1024*1024), float64(entry.UpBytes)/(1024*1024)) txt += "\n📱 *Привязанное устройство:*\n" var kb []map[string]interface{} @@ -638,7 +636,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { continue } tempDays = days - + var keyboard [][]map[string]interface{} keyboard = append(keyboard, []map[string]interface{}{ {"text": "Да", "callback_data": "ports_def"}, @@ -657,7 +655,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { p1 := strings.TrimSpace(parts[0]) p2 := strings.TrimSpace(parts[1]) p3 := strings.TrimSpace(parts[2]) - + if _, err := strconv.Atoi(p1); err != nil { sendTelegram(token, adminID, "❌ Неверный порт. Повторите ввод:", nil) continue @@ -670,7 +668,7 @@ func botLoop(token string, adminIDstr string, wgDev *device.Device) { sendTelegram(token, adminID, "❌ Неверный порт. Повторите ввод:", nil) continue } - + waitingForPorts = false tempPorts = fmt.Sprintf("%s,%s,%s", p1, p2, p3) waitingForHash = true @@ -1554,8 +1552,6 @@ func handleConn(ctx context.Context, clientConn net.Conn, wgEndpoint string, wgD } atomic.AddInt64(&totalBytesFromClient, int64(len(firstPacket))) - - pctx, pcancel := context.WithCancel(ctx) defer pcancel() @@ -1708,20 +1704,44 @@ func NewObfsState() *ObfsState { } } +// obfsBuildNonceInto writes the 12-byte implicit nonce SSRC||seq||0x0000||ts +// into dst without allocating. The two zero bytes at [6:8] are part of the +// wire format. This is the hot-path variant; obfsBuildNonce wraps it for +// callers that still want a freshly allocated slice. +func obfsBuildNonceInto(dst *[12]byte, ssrc uint32, seq uint16, ts uint32) { + binary.BigEndian.PutUint32(dst[0:4], ssrc) + binary.BigEndian.PutUint16(dst[4:6], seq) + dst[6] = 0 + dst[7] = 0 + binary.BigEndian.PutUint32(dst[8:12], ts) +} + func obfsBuildNonce(ssrc uint32, seq uint16, ts uint32) []byte { n := make([]byte, 12) - binary.BigEndian.PutUint32(n[0:4], ssrc) - binary.BigEndian.PutUint16(n[4:6], seq) - binary.BigEndian.PutUint32(n[8:12], ts) + var tmp [12]byte + obfsBuildNonceInto(&tmp, ssrc, seq, ts) + copy(n, tmp[:]) return n } -func obfsWrapPacket(key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]byte, error) { - if len(key) != wrapKeyLen { - return nil, fmt.Errorf("obfs: key must be %d bytes (got %d)", wrapKeyLen, len(key)) +// obfsWrapWireLen returns the maximum wire size for wrapping a payload of +// payloadLen bytes with the given config (RTP header + ciphertext + tag + +// worst-case padding + pad-length byte). Used to size reusable TX buffers. +func obfsWrapWireLen(payloadLen int, cfg *ObfsConfig) int { + pad := cfg.PaddingMax + if pad < 1 { + pad = 1 } + return 12 + payloadLen + chacha20poly1305.Overhead + pad +} + +// obfsWrapPacketInto wraps payload into dst (which must be at least +// obfsWrapWireLen(len(payload), cfg) bytes) using a pre-built AEAD cipher, +// and returns the number of bytes written. Alloc-free on the hot path: the +// nonce lives on the stack and the output is sealed directly into dst. +func obfsWrapPacketInto(dst []byte, aead cipher.AEAD, payload []byte, cfg *ObfsConfig, state *ObfsState) (int, error) { if len(payload) == 0 { - return nil, errors.New("obfs: empty payload") + return 0, errors.New("obfs: empty payload") } state.mu.Lock() c := state.count @@ -1731,7 +1751,6 @@ func obfsWrapPacket(key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]b seq := state.initSeq + uint16(c) ts := state.initTs + uint32(c)*960 + uint32(c>>16) - nonce := obfsBuildNonce(cfg.SSRC, seq, ts) padRand := 0 if cfg.PaddingMax > 0 { var rndBuf [1]byte @@ -1740,31 +1759,47 @@ func obfsWrapPacket(key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]b } padTotal := padRand + 1 outLen := 12 + len(payload) + chacha20poly1305.Overhead + padTotal - out := make([]byte, outLen) + if outLen > len(dst) { + return 0, fmt.Errorf("obfs: dst too small (%d > %d)", outLen, len(dst)) + } - out[0] = 0x80 | 0x20 - out[1] = cfg.PayloadType & 0x7F - binary.BigEndian.PutUint16(out[2:4], seq) - binary.BigEndian.PutUint32(out[4:8], ts) - binary.BigEndian.PutUint32(out[8:12], cfg.SSRC) + dst[0] = 0x80 | 0x20 + dst[1] = cfg.PayloadType & 0x7F + binary.BigEndian.PutUint16(dst[2:4], seq) + binary.BigEndian.PutUint32(dst[4:8], ts) + binary.BigEndian.PutUint32(dst[8:12], cfg.SSRC) + var nonce [12]byte + obfsBuildNonceInto(&nonce, cfg.SSRC, seq, ts) + sealed := aead.Seal(dst[12:12], nonce[:], payload, dst[:12]) + padStart := 12 + len(sealed) + if padRand > 0 { + rand.Read(dst[padStart : padStart+padRand]) + } + dst[outLen-1] = byte(padTotal) + return outLen, nil +} + +func obfsWrapPacket(key, payload []byte, cfg *ObfsConfig, state *ObfsState) ([]byte, error) { + if len(key) != wrapKeyLen { + return nil, fmt.Errorf("obfs: key must be %d bytes (got %d)", wrapKeyLen, len(key)) + } aead, err := getAEAD(key) if err != nil { return nil, fmt.Errorf("obfs: cipher init: %w", err) } - sealed := aead.Seal(out[12:12], nonce, payload, out[:12]) - padStart := 12 + len(sealed) - if padRand > 0 { - rand.Read(out[padStart : padStart+padRand]) + out := make([]byte, obfsWrapWireLen(len(payload), cfg)) + n, err := obfsWrapPacketInto(out, aead, payload, cfg, state) + if err != nil { + return nil, err } - out[outLen-1] = byte(padTotal) - return out, nil + return out[:n], nil } -func obfsUnwrapPacket(key, wire, dst []byte) (int, error) { - if len(key) != wrapKeyLen { - return 0, fmt.Errorf("obfs: key must be %d bytes (got %d)", wrapKeyLen, len(key)) - } +// obfsUnwrapPacketAEAD unwraps a wire packet into dst using a pre-built AEAD +// cipher and returns the plaintext length. Alloc-free: the nonce is built on +// the stack and decryption lands directly in dst. +func obfsUnwrapPacketAEAD(aead cipher.AEAD, wire, dst []byte) (int, error) { if len(wire) < 13 { return 0, errors.New("obfs: packet too short") } @@ -1790,18 +1825,26 @@ func obfsUnwrapPacket(key, wire, dst []byte) (int, error) { if ciphertextLen-chacha20poly1305.Overhead > len(dst) { return 0, errors.New("obfs: dst buffer too small") } - nonce := obfsBuildNonce(ssrc, seq, ts) - aead, err := getAEAD(key) - if err != nil { - return 0, fmt.Errorf("obfs: cipher init: %w", err) - } - plain, err := aead.Open(dst[:0], nonce, wire[12:payloadEnd], wire[:12]) + var nonce [12]byte + obfsBuildNonceInto(&nonce, ssrc, seq, ts) + plain, err := aead.Open(dst[:0], nonce[:], wire[12:payloadEnd], wire[:12]) if err != nil { return 0, fmt.Errorf("obfs: auth: %w", err) } return len(plain), nil } +func obfsUnwrapPacket(key, wire, dst []byte) (int, error) { + if len(key) != wrapKeyLen { + return 0, fmt.Errorf("obfs: key must be %d bytes (got %d)", wrapKeyLen, len(key)) + } + aead, err := getAEAD(key) + if err != nil { + return 0, fmt.Errorf("obfs: cipher init: %w", err) + } + return obfsUnwrapPacketAEAD(aead, wire, dst) +} + func obfsIsRTPPacket(wire []byte) bool { if len(wire) < 13 { return false @@ -1847,15 +1890,32 @@ type wrapPacketConn struct { inner net.PacketConn keys *wrapKeyStore key []byte + aead cipher.AEAD // cached at key selection; nil until selected selected int32 authLog int32 obfsCfg *ObfsConfig obfsWrite *ObfsState + + // rxBuf/txBuf are reused per packet to keep the hot path alloc-free. + // The RX path is single-reader in pion (one read loop) but guarded for + // safety; pion/dtls may write from several goroutines during handshake, + // so the TX path must be serialized. + rxMu sync.Mutex + rxBuf []byte + txMu sync.Mutex + txBuf []byte } func (c *wrapPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { + c.rxMu.Lock() + defer c.rxMu.Unlock() + // Extra space for RTP header (12) + AEAD tag (16) + padding. - buf := make([]byte, len(p)+80) + need := len(p) + 80 + if cap(c.rxBuf) < need { + c.rxBuf = make([]byte, need) + } + buf := c.rxBuf[:need] n, addr, err := c.inner.ReadFrom(buf) if err != nil { return 0, addr, err @@ -1870,7 +1930,12 @@ func (c *wrapPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { } return 0, addr, uErr } + aead, aErr := getAEAD(key) + if aErr != nil { + return 0, addr, fmt.Errorf("wrap: cipher init: %w", aErr) + } c.key = key + c.aead = aead c.obfsCfg = NewObfsConfig() c.obfsWrite = NewObfsState() atomic.StoreInt32(&c.selected, 1) @@ -1880,7 +1945,7 @@ func (c *wrapPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { return m, addr, nil } - m, uErr := obfsUnwrapPacket(c.key, raw, p) + m, uErr := obfsUnwrapPacketAEAD(c.aead, raw, p) if uErr != nil { return 0, addr, fmt.Errorf("obfs unwrap: %w", uErr) } @@ -1888,18 +1953,21 @@ func (c *wrapPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { } func (c *wrapPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) { - if atomic.LoadInt32(&c.selected) == 0 || len(c.key) != wrapKeyLen { + if atomic.LoadInt32(&c.selected) == 0 || c.aead == nil { return 0, errors.New("wrap: key not selected") } - if c.obfsCfg == nil || c.obfsWrite == nil { - c.obfsCfg = NewObfsConfig() - c.obfsWrite = NewObfsState() + c.txMu.Lock() + defer c.txMu.Unlock() + + need := obfsWrapWireLen(len(p), c.obfsCfg) + if cap(c.txBuf) < need { + c.txBuf = make([]byte, need) } - wrapped, wErr := obfsWrapPacket(c.key, p, c.obfsCfg, c.obfsWrite) + n, wErr := obfsWrapPacketInto(c.txBuf[:need], c.aead, p, c.obfsCfg, c.obfsWrite) if wErr != nil { return 0, fmt.Errorf("obfs wrap: %w", wErr) } - if _, err := c.inner.WriteTo(wrapped, addr); err != nil { + if _, err := c.inner.WriteTo(c.txBuf[:n], addr); err != nil { return 0, err } return len(p), nil