Files
free-turn-proxy-orig/internal/wrap/wrap.go
T
samosvalishe 322e8db4fa refactor: вынести wrap в internal/wrap
Объединяет client/wrap.go + server/wrap.go в internal/wrap с экспортируемым
API: State (общий AEAD), Conn (per-stream RTP-состояние), WrapInto/Unwrap,
Listen (серверный PacketListener), RelayPacketConn (клиентская обёртка
TURN-relay), хелперы GenKeyHex/DecodeKey. Wire-формат сохранён побитово.

relayPacketConn переезжает из client/main.go в пакет wrap как RelayPacketConn
(его единственный осмысленный дом — он владеет *wrap.Conn).

-573 строки (client/wrap.go, server/wrap.go, client/wrap_test.go удалены).
2026-05-19 09:28:24 +03:00

202 lines
5.6 KiB
Go

// SPDX-License-Identifier: MIT
// Package wrap implements an SRTP-mimicry AEAD framing used to bypass
// the VK TURN content filter.
//
// Wire format:
//
// [12B RTP header | 12B explicit nonce | AEAD ciphertext | 16B tag]
//
// RTP header (RFC 3550):
//
// byte 0: 0x80 V=2, P=0, X=0, CC=0
// byte 1: 0x6F M=0, PT=111 (opus, typical voice PT)
// byte 2-3: seq16 BE monotonic, init random
// byte 4-7: ts32 BE monotonic, init random, increments by 960 (20ms @ 48kHz)
// byte 8-11: SSRC random per conn, MSB encodes direction
//
// 12B explicit nonce = 4B sessionID || 8B counter (BE). sessionID MSB
// matches SSRC MSB (direction bit). counter starts at a random uint64.
// AAD = first 24 bytes (RTP header || nonce).
//
// Wire format is frozen — bit-exact compatibility with deployed peers is required.
package wrap
import (
"crypto/cipher"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"sync/atomic"
"golang.org/x/crypto/chacha20poly1305"
)
const (
KeyLen = 32
rtpHdrLen = 12
nonceLen = 12
tagLen = 16
headerLen = rtpHdrLen + nonceLen // 24
Overhead = headerLen + tagLen // 40
rtpVersion = 0x80 // V=2, P=0, X=0, CC=0
rtpPT = 0x6F // M=0, PT=111 (opus)
tsStep = 960 // 20ms @ 48kHz
)
// MaxWire returns max wire bytes for a given payload size.
func MaxWire(payloadLen int) int { return Overhead + payloadLen }
// State holds an AEAD instance derived from the shared key.
// One State can be shared across many Conns (e.g. server-side listener).
type State struct {
aead cipher.AEAD
}
func NewState(key []byte) (*State, error) {
if len(key) != KeyLen {
return nil, fmt.Errorf("wrap: key must be %d bytes (got %d)", KeyLen, len(key))
}
aead, err := chacha20poly1305.New(key)
if err != nil {
return nil, fmt.Errorf("wrap: aead init: %w", err)
}
return &State{aead: aead}, nil
}
// Conn carries per-stream RTP state (seq/timestamp/SSRC/counter) plus a
// reference to the shared AEAD State.
type Conn struct {
state *State
sessionID [4]byte // 4B prefix for nonce; MSB encodes direction
ssrc [4]byte // SSRC for RTP header; MSB encodes direction
counter atomic.Uint64
seq atomic.Uint32 // RTP sequence (used as uint16)
timestamp atomic.Uint32 // RTP timestamp
}
// NewConn allocates a fresh State from key and a Conn bound to it.
func NewConn(key []byte, isServer bool) (*Conn, error) {
s, err := NewState(key)
if err != nil {
return nil, err
}
return NewConnFromState(s, isServer)
}
// NewConnFromState builds a Conn with random per-stream RTP fields,
// reusing the supplied State.
func NewConnFromState(state *State, isServer bool) (*Conn, error) {
if state == nil {
return nil, errors.New("wrap: nil state")
}
c := &Conn{state: state}
var rnd [16]byte
if _, err := rand.Read(rnd[:]); err != nil {
return nil, fmt.Errorf("wrap: rand init: %w", err)
}
copy(c.sessionID[:], rnd[0:4])
copy(c.ssrc[:], rnd[4:8])
if isServer {
c.sessionID[0] |= 0x80
c.ssrc[0] |= 0x80
} else {
c.sessionID[0] &^= 0x80
c.ssrc[0] &^= 0x80
}
c.seq.Store(uint32(binary.BigEndian.Uint16(rnd[8:10])))
c.timestamp.Store(binary.BigEndian.Uint32(rnd[10:14]))
var cb [8]byte
if _, err := rand.Read(cb[:]); err != nil {
return nil, fmt.Errorf("wrap: counter rand: %w", err)
}
c.counter.Store(binary.BigEndian.Uint64(cb[:]))
return c, nil
}
// WrapInto encodes payload into dst (must be at least MaxWire(len(payload)) bytes)
// and returns the number of wire bytes written.
func (c *Conn) WrapInto(dst, payload []byte) (int, error) {
wireLen := Overhead + len(payload)
if len(dst) < wireLen {
return 0, errors.New("wrap: dst buffer too small")
}
// RTP header.
dst[0] = rtpVersion
dst[1] = rtpPT
seq := uint16(c.seq.Add(1) - 1)
binary.BigEndian.PutUint16(dst[2:4], seq)
ts := c.timestamp.Add(tsStep) - tsStep
binary.BigEndian.PutUint32(dst[4:8], ts)
copy(dst[8:12], c.ssrc[:])
// Explicit nonce.
noncePos := rtpHdrLen
copy(dst[noncePos:noncePos+4], c.sessionID[:])
ctr := c.counter.Add(1) - 1
binary.BigEndian.PutUint64(dst[noncePos+4:noncePos+nonceLen], ctr)
nonce := dst[noncePos : noncePos+nonceLen]
aad := dst[:headerLen]
ctPos := headerLen
copy(dst[ctPos:], payload)
c.state.aead.Seal(dst[ctPos:ctPos], nonce, dst[ctPos:ctPos+len(payload)], aad)
return wireLen, nil
}
// Unwrap decodes a wire packet into dst and returns the plaintext length.
func (c *Conn) Unwrap(wire, dst []byte) (int, error) {
if len(wire) < Overhead {
return 0, errors.New("wrap: packet too short")
}
nonce := wire[rtpHdrLen : rtpHdrLen+nonceLen]
aad := wire[:headerLen]
ct := wire[headerLen:]
plain, err := c.state.aead.Open(ct[:0], nonce, ct, aad)
if err != nil {
return 0, fmt.Errorf("wrap: AEAD open: %w", err)
}
if len(plain) > len(dst) {
return 0, errors.New("wrap: dst buffer too small")
}
copy(dst[:len(plain)], plain)
return len(plain), nil
}
// --- Key helpers ---
// GenKeyHex returns a fresh hex-encoded random key.
func GenKeyHex() (string, error) {
key := make([]byte, KeyLen)
if _, err := rand.Read(key); err != nil {
return "", fmt.Errorf("wrap: key gen: %w", err)
}
return hex.EncodeToString(key), nil
}
// DecodeKey decodes a hex key and validates length when enabled.
// When enabled is false, returns (nil, nil).
func DecodeKey(enabled bool, raw string) ([]byte, error) {
if !enabled {
return nil, nil
}
if raw == "" {
return nil, errors.New("-wrap requires -wrap-key")
}
key, err := hex.DecodeString(raw)
if err != nil {
return nil, fmt.Errorf("-wrap-key invalid hex: %w", err)
}
if len(key) != KeyLen {
return nil, fmt.Errorf("-wrap-key must decode to %d bytes (got %d)", KeyLen, len(key))
}
return key, nil
}