Feature: Tunnel the device protocol through a reverse proxy over WebSocket

This commit is contained in:
yuanyuanxiang committed 2026-10-30 17:21:42 +01:00
1 parent de621aa555
commit d4f312c9d8
20 files changed
+1994 -63

No files matched your search

+18
View File
@@ -1153,6 +1153,22 @@ func main() {
log.Info("ConnAuth HMAC verification enabled for device sub-connections (YAMA_CONN_AUTH_KEY)")
}
// Optional WebSocket transport on the device port, for devices that can only
// reach the server through a reverse proxy on a shared port (nginx on 443).
// YAMA_WS_PATH restricts upgrades to one request path (empty = any path).
// YAMA_TRUSTED_PROXIES lists the IPs/CIDRs allowed to report a device's real
// address via X-Forwarded-For / X-Real-IP (default: loopback only).
wsPath := strings.TrimSpace(os.Getenv("YAMA_WS_PATH"))
trustedProxies := splitCSV(os.Getenv("YAMA_TRUSTED_PROXIES"))
if wsPath != "" {
log.Info("WebSocket transport on device port enabled: path=%s", wsPath)
} else {
log.Info("WebSocket transport on device port enabled: any path")
}
if len(trustedProxies) > 0 {
log.Info("Trusting forwarded client IPs from: %s", strings.Join(trustedProxies, ", "))
}
// Create servers for each port
var servers []*server.Server
for _, port := range ports {
@@ -1163,6 +1179,8 @@ func main() {
config.PerIPConnRateLimit = envInt("YAMA_PERIP_CONN_RATE", config.PerIPConnRateLimit)
config.TLSCertFile = tlsCert
config.TLSKeyFile = tlsKey
config.WSPath = wsPath
config.TrustedProxies = trustedProxies
srv := server.New(config)
srv.SetLogger(log.WithPrefix(fmt.Sprintf("Server:%d", port)))
+20
View File
@@ -61,6 +61,10 @@ type Context struct {
closed atomic.Bool
sendLock sync.Mutex
server *Manager
// peerIPOverride replaces the address derived from RemoteAddr when a
// trusted reverse proxy reports the device's real address.
peerIPOverride string
}
// FlagType represents the protocol flag type
@@ -156,12 +160,28 @@ func (c *Context) IsClosed() bool {
// GetPeerIP returns the peer IP address
func (c *Context) GetPeerIP() string {
c.mu.RLock()
override := c.peerIPOverride
c.mu.RUnlock()
if override != "" {
return override
}
if host, _, err := net.SplitHostPort(c.RemoteAddr); err == nil {
return host
}
return c.RemoteAddr
}
// SetPeerIP overrides the address reported by GetPeerIP. The server uses it
// when a trusted reverse proxy reports a device's real address, so per-IP
// accounting, logging and the ConnAuth sub-connection binding all see the
// device rather than the proxy.
func (c *Context) SetPeerIP(ip string) {
c.mu.Lock()
c.peerIPOverride = ip
c.mu.Unlock()
}
// AliveTime returns how long the connection has been alive
func (c *Context) AliveTime() time.Duration {
return time.Since(c.OnlineTime)
+76 -13
View File
@@ -42,6 +42,17 @@ type Config struct {
PerIPConnRateLimit int // max new connections per PerIPConnRateWindow per IP (0 = unlimited)
PerIPConnRateWindow time.Duration // window for PerIPConnRateLimit
// WebSocket transport. Devices that can only reach the server through a
// reverse proxy on a shared port (e.g. nginx on 443) upgrade to WebSocket;
// the device port then carries the unchanged app protocol inside binary
// frames. WSPath restricts the upgrade to one request path ("" = any).
WSPath string
// TrustedProxies lists the IPs/CIDRs whose X-Forwarded-For / X-Real-IP
// headers are believed. Only connections from these peers are allowed to
// report a different device address; empty defaults to loopback.
TrustedProxies []string
// TLSCertFile / TLSKeyFile enable optional one-way TLS on the device port.
// When both are set the server loads the cert and auto-detects TLS clients
// by their ClientHello; plaintext clients keep working unchanged. Both empty
@@ -87,6 +98,10 @@ type Server struct {
// wrapTLS consults it to sniff and wrap incoming connections.
tlsCfg *tls.Config
// trustedProxies are the peers allowed to report a device's real address
// via X-Forwarded-For / X-Real-IP (the reverse proxy in front of us).
trustedProxies []*net.IPNet
running atomic.Bool
wg sync.WaitGroup
ctx context.Context
@@ -109,6 +124,7 @@ func New(config Config) *Server {
cancel: cancel,
logger: logger.New(logger.DefaultConfig()).WithPrefix("Server"),
}
s.trustedProxies = parseTrustedProxies(config.TrustedProxies)
return s
}
@@ -356,38 +372,85 @@ func (s *Server) acceptLoop() {
continue
}
// Check connection limit before spawning goroutine
// Check connection limit before spawning goroutine.
if s.manager.Count() >= s.config.MaxConnections {
s.logger.Warn("Max connections reached, rejecting new connection from %s", conn.RemoteAddr())
_ = conn.Close()
continue
}
// Per-IP connection cap + accept rate. Rejecting here (before any
// buffer allocation or goroutine) is cheap, and a rejected device
// simply retries on its reconnect loop.
if !s.ipLimit.allow(peerIP(conn.RemoteAddr())) {
s.logger.Warn("Per-IP connection limit reached, rejecting %s", conn.RemoteAddr())
peer := peerIP(conn.RemoteAddr())
counted, allowed := s.limitDirectPeer(peer)
if !allowed {
s.logger.Warn("Per-IP connection limit reached, rejecting %s", peer)
_ = conn.Close()
continue
}
// Handle each connection in its own goroutine
go s.handleConnection(conn)
go s.handleConnection(conn, counted)
}
}
// handleConnection handles a single connection
func (s *Server) handleConnection(rawConn net.Conn) {
// limitDirectPeer applies the per-IP cap and accept rate to a freshly accepted
// peer, before the goroutine is spawned and before any sniffing read: a peer
// that opens sockets and never sends a full ClientHello / upgrade would
// otherwise hold a goroutine and a reader for up to ReadTimeout each, with no
// limit at all. Peers that are trusted proxies are exempt and report
// counted=false — every device behind a proxy arrives from the proxy's
// address, so they are limited later by the address their proxy reports.
func (s *Server) limitDirectPeer(peer string) (counted, allowed bool) {
if s.trustedProxy(peer) {
return false, true
}
if !s.ipLimit.allow(peer) {
return false, false
}
return true, true
}
// handleConnection handles a single connection. peerCapped reports whether
// acceptLoop already counted this peer against the per-IP limiter (direct
// peers only), in which case the count is released here when the connection
// ends.
func (s *Server) handleConnection(rawConn net.Conn, peerCapped bool) {
peer := peerIP(rawConn.RemoteAddr())
if peerCapped {
defer s.ipLimit.release(peer)
}
// Sniff and (when TLS is enabled) wrap TLS peers; plaintext passes through.
conn := s.wrapTLS(rawConn)
// Sniff for a WebSocket upgrade. Proxied devices (nginx on a shared port)
// arrive as a plaintext HTTP upgrade after the proxy terminated TLS.
conn, realIP := s.wrapWebSocket(conn, peer)
if conn == nil {
return
}
if !peerCapped {
// Proxied device: limit by the forwarded address so one device behind
// the proxy cannot consume the whole budget for everyone else.
limitIP := peer
if realIP != "" {
limitIP = realIP
}
if !s.ipLimit.allow(limitIP) {
s.logger.Warn("Per-IP connection limit reached, rejecting %s (peer %s)", limitIP, peer)
_ = conn.Close()
return
}
defer s.ipLimit.release(limitIP)
}
// Create context
ctx := connection.NewContext(conn, nil)
// Always release the per-IP slot on every exit path, including the
// manager.Add failure below (a rare accept/add race).
defer s.ipLimit.release(ctx.GetPeerIP())
if realIP != "" {
// Report the device's real address everywhere GetPeerIP is consulted
// (per-IP accounting, logging, ConnAuth sub-connection binding).
ctx.SetPeerIP(realIP)
}
// Add to manager
if err := s.manager.Add(ctx); err != nil {
+31 -1
View File
@@ -93,6 +93,35 @@ func TestPeerIP(t *testing.T) {
}
}
// The per-IP cap must apply to direct peers before any sniffing read, so a
// peer that connects and stays silent cannot hold unbounded goroutines and
// readers. Peers that are trusted proxies are exempt (and counted later by the
// forwarded address), because all devices behind a proxy share its address.
func TestLimitDirectPeerBeforeSniff(t *testing.T) {
cfg := DefaultConfig()
cfg.PerIPMaxConnections = 1
cfg.PerIPConnRateLimit = 0 // concurrent cap only
s := New(cfg)
if counted, ok := s.limitDirectPeer("203.0.113.5"); !ok || !counted {
t.Fatalf("first direct peer: counted=%v ok=%v, want true/true", counted, ok)
}
// A second silent socket from the same address must be refused outright.
if counted, ok := s.limitDirectPeer("203.0.113.5"); ok || counted {
t.Fatalf("second direct peer: counted=%v ok=%v, want false/false", counted, ok)
}
// Loopback is a trusted proxy by default: exempt from the peer cap here.
if counted, ok := s.limitDirectPeer("127.0.0.1"); !ok || counted {
t.Fatalf("trusted proxy: counted=%v ok=%v, want false/true", counted, ok)
}
// Releasing the slot frees capacity again.
s.ipLimit.release("203.0.113.5")
if _, ok := s.limitDirectPeer("203.0.113.5"); !ok {
t.Fatal("after release the address should be allowed again")
}
}
// A peer that sends bytes which never assemble into a complete packet (here an
// HTTP-mask envelope with no terminating CRLF CRLF) must be disconnected once
// the per-connection buffer cap is exceeded, rather than allowed to grow it
@@ -110,7 +139,8 @@ func TestHandleConnectionBufferCap(t *testing.T) {
done := make(chan struct{})
go func() {
srv.handleConnection(serverConn)
// false: acceptLoop was bypassed, so the peer was not pre-counted.
srv.handleConnection(serverConn, false)
close(done)
}()
+517
View File
@@ -0,0 +1,517 @@
package server
import (
"bufio"
"bytes"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"strings"
"sync"
"time"
)
// WebSocket transport for devices that can only reach the server through a
// reverse proxy (nginx) on a shared port such as 443.
//
// The app protocol is unchanged: the WS layer is a transparent byte-stream
// tunnel. A device connects to the proxy with a normal WebSocket upgrade,
// nginx terminates TLS and proxies the (now plaintext) upgrade to the device
// port, and this file completes the handshake and carries the existing parser
// traffic inside binary frames.
//
// Upgrade request detection happens after the TLS sniff in handleConnection,
// so a proxied wss connection (nginx terminates TLS) and a direct wss
// connection (YAMA_TLS_CERT set, client speaks wss end to end) both work.
const (
wsMagicGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
wsOpContinuation = 0x0
wsOpText = 0x1
wsOpBinary = 0x2
wsOpClose = 0x8
wsOpPing = 0x9
wsOpPong = 0xA
// wsMaxHandshakeBytes caps the upgrade request head we are willing to
// buffer before rejecting the peer.
wsMaxHandshakeBytes = 8 * 1024
// wsHandshakeTimeout bounds reading the request head once "GET " was seen.
wsHandshakeTimeout = 10 * time.Second
)
var (
errWSProtocol = errors.New("websocket: protocol error")
errWSHandshake = errors.New("websocket: bad handshake")
// wsUpgradePrefix identifies an HTTP request whose first token is GET. The
// app protocol never starts a connection with these bytes (its flags are
// "Shine"/"HELL"/"POST" variants), so this is unambiguous.
wsUpgradePrefix = []byte("GET ")
)
// wrapWebSocket sniffs the already TLS-sniffed connection for an HTTP
// WebSocket upgrade. When the peer is not upgrading, conn is returned
// unchanged. When the upgrade completes, the returned net.Conn frames all
// reads/writes, and realIP carries the client address reported by a trusted
// reverse proxy (empty otherwise). A failed upgrade returns (nil, "").
func (s *Server) wrapWebSocket(conn net.Conn, peer string) (net.Conn, string) {
br := bufio.NewReader(conn)
if s.config.ReadTimeout > 0 {
_ = conn.SetReadDeadline(time.Now().Add(s.config.ReadTimeout))
}
hdr, err := br.Peek(len(wsUpgradePrefix))
_ = conn.SetReadDeadline(time.Time{})
if err != nil {
// Peer never sent enough to identify itself; let the normal read loop
// surface EOF/timeout exactly as it would without the sniff.
return &bufferedConn{Conn: conn, r: br}, ""
}
if !bytes.Equal(hdr, wsUpgradePrefix) {
return &bufferedConn{Conn: conn, r: br}, ""
}
req, err := readWSRequest(br, conn)
if err != nil {
s.logger.Debug("wrapWebSocket: reject %s: %v", conn.RemoteAddr(), err)
writeWSReject(conn, err)
_ = conn.Close()
return nil, ""
}
if s.config.WSPath != "" && req.path != s.config.WSPath {
s.logger.Debug("wrapWebSocket: reject %s: path %q != %q", conn.RemoteAddr(), req.path, s.config.WSPath)
writeWSReject(conn, errWSProtocol)
_ = conn.Close()
return nil, ""
}
accept := wsAcceptKey(req.key)
_ = conn.SetWriteDeadline(time.Now().Add(wsHandshakeTimeout))
resp := "HTTP/1.1 101 Switching Protocols\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
"Sec-WebSocket-Accept: " + accept + "\r\n\r\n"
_, werr := io.WriteString(conn, resp)
_ = conn.SetWriteDeadline(time.Time{})
if werr != nil {
_ = conn.Close()
return nil, ""
}
realIP := ""
if s.trustedProxy(peer) {
realIP = reqForwardedIP(req.headers)
}
if realIP != "" {
s.logger.Info("WebSocket device from %s (forwarded by %s)", realIP, peer)
} else {
s.logger.Info("WebSocket device from %s", peer)
}
return newWSConn(conn, br), realIP
}
// wsRequest is the parsed subset of an upgrade request the server needs.
type wsRequest struct {
path string
key string
headers map[string]string // lower-cased names; repeated headers joined by ", "
}
// readWSRequest reads and validates the HTTP upgrade head. The buffered reader
// is left positioned at the first byte after the head so any frames the peer
// pipelined behind the request are preserved.
func readWSRequest(br *bufio.Reader, conn net.Conn) (*wsRequest, error) {
_ = conn.SetReadDeadline(time.Now().Add(wsHandshakeTimeout))
defer func() { _ = conn.SetReadDeadline(time.Time{}) }()
total := 0
line, err := readWSLine(br, &total)
if err != nil {
return nil, err
}
parts := strings.Fields(line)
if len(parts) != 3 || parts[0] != "GET" || !strings.HasPrefix(parts[2], "HTTP/1.") {
return nil, errWSHandshake
}
req := &wsRequest{headers: make(map[string]string)}
req.path = parts[1]
if i := strings.IndexByte(req.path, '?'); i >= 0 {
req.path = req.path[:i]
}
for {
line, err = readWSLine(br, &total)
if err != nil {
return nil, err
}
if line == "" {
break
}
name, value, ok := strings.Cut(line, ":")
if !ok {
return nil, errWSHandshake
}
name = strings.ToLower(strings.TrimSpace(name))
value = strings.TrimSpace(value)
if prev, dup := req.headers[name]; dup {
req.headers[name] = prev + ", " + value
} else {
req.headers[name] = value
}
}
if !headerHasToken(req.headers["upgrade"], "websocket") ||
!headerHasToken(req.headers["connection"], "upgrade") {
return nil, errWSHandshake
}
req.key = req.headers["sec-websocket-key"]
if req.key == "" {
return nil, errWSHandshake
}
return req, nil
}
// readWSLine reads one CRLF-terminated line, rejecting the peer as soon as the
// accumulated head exceeds wsMaxHandshakeBytes. The input is peer-controlled:
// a plain ReadString would buffer a newline-free line without limit.
func readWSLine(br *bufio.Reader, total *int) (string, error) {
var line []byte
for {
chunk, err := br.ReadSlice('\n')
line = append(line, chunk...)
*total += len(chunk)
if *total > wsMaxHandshakeBytes {
return "", errWSProtocol
}
if err == bufio.ErrBufferFull {
continue
}
if err != nil {
return "", err
}
return strings.TrimRight(string(line), "\r\n"), nil
}
}
// headerHasToken reports whether a comma-separated header value contains token
// (case-insensitive), as required for Connection: keep-alive, Upgrade.
func headerHasToken(value, token string) bool {
for _, part := range strings.Split(value, ",") {
if strings.EqualFold(strings.TrimSpace(part), token) {
return true
}
}
return false
}
// reqForwardedIP extracts the device's real address from a proxy's forwarded
// headers. The LAST X-Forwarded-For entry wins, not the first: nginx's
// $proxy_add_x_forwarded_for appends the address it accepted the connection
// from, so whatever a client prepends is ignored — the same rule web/ws.go's
// clientIP applies. Trusting the first entry would let a device rotate its key
// through the per-IP budget, the login throttle and the ConnAuth peer binding.
// X-Real-IP is only a fallback for proxies configured to set that and not XFF.
// Only IP literals are accepted, so a header cannot inject an arbitrary peer key.
func reqForwardedIP(headers map[string]string) string {
if xff := headers["x-forwarded-for"]; xff != "" {
last := strings.TrimSpace(xff[strings.LastIndexByte(xff, ',')+1:])
if ip := headerIP(last); ip != "" {
return ip
}
}
return headerIP(headers["x-real-ip"])
}
func headerIP(s string) string {
s = strings.TrimSpace(s)
if i := strings.LastIndexByte(s, ':'); i > 0 && strings.Count(s, ":") == 1 {
// strip an IPv4:port pair, but leave bare IPv6 literals alone
if net.ParseIP(s[:i]) != nil {
s = s[:i]
}
}
if ip := net.ParseIP(s); ip != nil {
return ip.String()
}
return ""
}
// wsAcceptKey computes Sec-WebSocket-Accept: base64(SHA1(key + magic GUID)).
func wsAcceptKey(key string) string {
h := sha1.New()
io.WriteString(h, key)
io.WriteString(h, wsMagicGUID)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func writeWSReject(conn net.Conn, reason error) {
status := "400 Bad Request"
body := "bad request"
if errors.Is(reason, errWSProtocol) {
body = "protocol error"
}
_ = conn.SetWriteDeadline(time.Now().Add(wsHandshakeTimeout))
fmt.Fprintf(conn, "HTTP/1.1 %s\r\nContent-Type: text/plain\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s",
status, len(body), body)
}
// trustedProxy reports whether peer is allowed to set the device's real IP via
// forwarded headers. Without this check any direct client could spoof its
// address and, with it, the per-IP limits and the ConnAuth peer binding.
func (s *Server) trustedProxy(peer string) bool {
ip := net.ParseIP(peer)
if ip == nil {
return false
}
for _, n := range s.trustedProxies {
if n.Contains(ip) {
return true
}
}
return false
}
// parseTrustedProxies converts configured IPs/CIDRs into networks. An empty or
// unparsable list falls back to loopback, the only sensible default for a
// proxy running on the same host as the server.
func parseTrustedProxies(list []string) []*net.IPNet {
var nets []*net.IPNet
for _, item := range list {
item = strings.TrimSpace(item)
if item == "" {
continue
}
if !strings.Contains(item, "/") {
if ip := net.ParseIP(item); ip != nil {
bits := 32
if ip.To4() == nil {
bits = 128
}
item = fmt.Sprintf("%s/%d", ip.String(), bits)
}
}
if _, n, err := net.ParseCIDR(item); err == nil {
nets = append(nets, n)
}
}
if len(nets) == 0 {
_, v4, _ := net.ParseCIDR("127.0.0.0/8")
_, v6, _ := net.ParseCIDR("::1/128")
nets = append(nets, v4, v6)
}
return nets
}
// wsConn presents a WebSocket connection as a net.Conn byte stream: each Write
// becomes one binary frame and Read returns the concatenated payload of data
// frames, transparently answering pings and closes. Frame payloads are streamed
// rather than buffered whole, so a multi-megabyte upload allocates nothing here.
type wsConn struct {
conn net.Conn
r *bufio.Reader
writeMu sync.Mutex
closeMu sync.Mutex
closed bool
// state of the data frame currently being read
remaining int64
masked bool
mask [4]byte
maskPos byte
}
func newWSConn(conn net.Conn, r *bufio.Reader) *wsConn {
return &wsConn{conn: conn, r: r}
}
// Read implements net.Conn.
func (c *wsConn) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
for {
if c.remaining > 0 {
n := len(p)
if int64(n) > c.remaining {
n = int(c.remaining)
}
nr, err := io.ReadFull(c.r, p[:n])
if nr > 0 {
if c.masked {
for i := 0; i < nr; i++ {
p[i] ^= c.mask[c.maskPos]
c.maskPos = (c.maskPos + 1) & 3
}
}
c.remaining -= int64(nr)
}
if err != nil {
return nr, err
}
return nr, nil
}
opcode, fin, length, masked, err := c.readFrameHeader()
if err != nil {
return 0, err
}
if opcode >= 0x8 {
if !fin || length > 125 {
return 0, errWSProtocol
}
payload, err := c.readControlPayload(int(length), masked)
if err != nil {
return 0, err
}
switch opcode {
case wsOpClose:
_ = c.writeFrame(wsOpClose, payload[:min(len(payload), 125)])
return 0, io.EOF
case wsOpPing:
if err := c.writeFrame(wsOpPong, payload); err != nil {
return 0, err
}
case wsOpPong:
// ignore
default:
return 0, errWSProtocol
}
continue
}
switch opcode {
case wsOpBinary, wsOpText, wsOpContinuation:
default:
return 0, errWSProtocol
}
if length == 0 {
continue
}
c.remaining = length
c.masked = masked
c.maskPos = 0
}
}
// readFrameHeader reads and validates a frame header. Frames from the client
// are normally masked; unmasked data frames are tolerated because the only
// speakers on this port are YAMA's own clients.
func (c *wsConn) readFrameHeader() (opcode byte, fin bool, length int64, masked bool, err error) {
var hdr [2]byte
if _, err = io.ReadFull(c.r, hdr[:]); err != nil {
return
}
if hdr[0]&0x70 != 0 {
return 0, false, 0, false, errWSProtocol // RSV bits set without a negotiated extension
}
fin = hdr[0]&0x80 != 0
opcode = hdr[0] & 0x0f
masked = hdr[1]&0x80 != 0
length = int64(hdr[1] & 0x7f)
switch length {
case 126:
var ext [2]byte
if _, err = io.ReadFull(c.r, ext[:]); err != nil {
return
}
length = int64(binary.BigEndian.Uint16(ext[:]))
case 127:
var ext [8]byte
if _, err = io.ReadFull(c.r, ext[:]); err != nil {
return
}
u := binary.BigEndian.Uint64(ext[:])
if u > 1<<62 {
return 0, false, 0, false, errWSProtocol
}
length = int64(u)
}
if masked {
if _, err = io.ReadFull(c.r, c.mask[:]); err != nil {
return
}
}
return opcode, fin, length, masked, nil
}
func (c *wsConn) readControlPayload(n int, masked bool) ([]byte, error) {
payload := make([]byte, n)
if _, err := io.ReadFull(c.r, payload); err != nil {
return nil, err
}
if masked {
for i := range payload {
payload[i] ^= c.mask[i&3]
}
}
return payload, nil
}
// Write implements net.Conn: one binary frame per call. The app protocol's
// sends are already whole packets (Context.Send), so this keeps writes atomic
// and lets the peer deliver each packet as it was produced.
func (c *wsConn) Write(p []byte) (int, error) {
if err := c.writeFrame(wsOpBinary, p); err != nil {
return 0, err
}
return len(p), nil
}
// writeFrame emits one FIN frame with the given opcode.
func (c *wsConn) writeFrame(opcode byte, payload []byte) error {
var hdr [10]byte
hdr[0] = 0x80 | opcode
n := 2
switch {
case len(payload) < 126:
hdr[1] = byte(len(payload))
case len(payload) <= 0xffff:
hdr[1] = 126
binary.BigEndian.PutUint16(hdr[2:], uint16(len(payload)))
n = 4
default:
hdr[1] = 127
binary.BigEndian.PutUint64(hdr[2:], uint64(len(payload)))
n = 10
}
c.writeMu.Lock()
defer c.writeMu.Unlock()
bufs := net.Buffers{hdr[:n], payload}
if _, err := bufs.WriteTo(c.conn); err != nil {
return err
}
return nil
}
// Close sends a best-effort close frame and closes the transport.
func (c *wsConn) Close() error {
c.closeMu.Lock()
if c.closed {
c.closeMu.Unlock()
return nil
}
c.closed = true
c.closeMu.Unlock()
_ = c.conn.SetWriteDeadline(time.Now().Add(time.Second))
_ = c.writeFrame(wsOpClose, nil)
return c.conn.Close()
}
func (c *wsConn) LocalAddr() net.Addr { return c.conn.LocalAddr() }
func (c *wsConn) RemoteAddr() net.Addr { return c.conn.RemoteAddr() }
func (c *wsConn) SetDeadline(t time.Time) error { return c.conn.SetDeadline(t) }
func (c *wsConn) SetReadDeadline(t time.Time) error { return c.conn.SetReadDeadline(t) }
func (c *wsConn) SetWriteDeadline(t time.Time) error { return c.conn.SetWriteDeadline(t) }
+407
View File
@@ -0,0 +1,407 @@
package server
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"io"
"net"
"strings"
"testing"
"time"
)
// wsTestPair dials a loopback listener, runs the server side of wrapWebSocket
// on the accepted connection, performs the upgrade handshake, and returns both
// ends. The loopback peer makes the test connection a trusted proxy, so the
// forwarded-address path is exercised too.
func wsTestPair(t *testing.T, s *Server, path string, extra map[string]string) (*wsConn, net.Conn, *bufio.Reader, string, string) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
defer ln.Close()
type result struct {
conn net.Conn
ip string
}
resCh := make(chan result, 1)
go func() {
srv, err := ln.Accept()
if err != nil {
resCh <- result{}
return
}
conn, ip := s.wrapWebSocket(srv, peerIP(srv.RemoteAddr()))
resCh <- result{conn, ip}
}()
cli, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatalf("dial: %v", err)
}
t.Cleanup(func() { cli.Close() })
_ = cli.SetDeadline(time.Now().Add(10 * time.Second))
// Write the upgrade request concurrently: the server blocks in its sniff
// until the first bytes arrive.
var b strings.Builder
b.WriteString("GET " + path + " HTTP/1.1\r\n")
b.WriteString("Host: yama.example.com\r\n")
b.WriteString("Upgrade: websocket\r\n")
b.WriteString("Connection: Upgrade\r\n")
b.WriteString("Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n")
b.WriteString("Sec-WebSocket-Version: 13\r\n")
for k, v := range extra {
b.WriteString(k + ": " + v + "\r\n")
}
b.WriteString("\r\n")
go func() { _, _ = io.WriteString(cli, b.String()) }()
br := bufio.NewReader(cli)
head := &strings.Builder{}
for {
line, err := br.ReadString('\n')
if err != nil {
t.Fatalf("read response: %v", err)
}
head.WriteString(line)
if line == "\r\n" || line == "\n" {
break
}
}
res := <-resCh
if res.conn == nil {
t.Fatalf("wrapWebSocket rejected the connection:\n%s", head.String())
}
t.Cleanup(func() { res.conn.Close() })
wc, ok := res.conn.(*wsConn)
if !ok {
t.Fatalf("wrapWebSocket returned %T, want *wsConn", res.conn)
}
_ = wc.SetDeadline(time.Now().Add(10 * time.Second))
return wc, cli, br, head.String(), res.ip
}
// clientFrame builds a masked client frame (the only form a server should see).
func clientFrame(opcode byte, payload []byte) []byte {
var hdr []byte
hdr = append(hdr, 0x80|opcode) // FIN + opcode
mask := [4]byte{0x37, 0xfa, 0x21, 0x3d}
n := len(payload)
switch {
case n < 126:
hdr = append(hdr, byte(n)|0x80)
case n <= 0xffff:
hdr = append(hdr, 126|0x80, byte(n>>8), byte(n))
default:
hdr = append(hdr, 127|0x80)
var ext [8]byte
binary.BigEndian.PutUint64(ext[:], uint64(n))
hdr = append(hdr, ext[:]...)
}
hdr = append(hdr, mask[:]...)
body := make([]byte, n)
for i := range payload {
body[i] = payload[i] ^ mask[i&3]
}
return append(hdr, body...)
}
// serverFrame reads one unmasked frame produced by the server.
func serverFrame(t *testing.T, br *bufio.Reader) (byte, []byte) {
t.Helper()
var hdr [2]byte
if _, err := io.ReadFull(br, hdr[:]); err != nil {
t.Fatalf("read frame header: %v", err)
}
n := int(hdr[1] & 0x7f)
switch n {
case 126:
var ext [2]byte
if _, err := io.ReadFull(br, ext[:]); err != nil {
t.Fatalf("read ext len: %v", err)
}
n = int(binary.BigEndian.Uint16(ext[:]))
case 127:
var ext [8]byte
if _, err := io.ReadFull(br, ext[:]); err != nil {
t.Fatalf("read ext len: %v", err)
}
n = int(binary.BigEndian.Uint64(ext[:]))
}
if hdr[1]&0x80 != 0 {
t.Fatalf("server frame is masked")
}
payload := make([]byte, n)
if _, err := io.ReadFull(br, payload); err != nil {
t.Fatalf("read frame payload: %v", err)
}
return hdr[0] & 0x0f, payload
}
func TestWebSocketUpgradeAndTunnel(t *testing.T) {
s := New(DefaultConfig())
// A device that prepends its own XFF entry must not be believed: nginx
// appends the address it accepted the connection from on the right.
wc, cli, br, head, realIP := wsTestPair(t, s, "/api/socket", map[string]string{
"X-Forwarded-For": "203.0.113.9, 198.51.100.20",
})
if !strings.HasPrefix(head, "HTTP/1.1 101 ") {
t.Fatalf("unexpected response head:\n%s", head)
}
// RFC 6455 sample key -> known accept value.
if !strings.Contains(head, "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=") {
t.Fatalf("missing/incorrect accept key:\n%s", head)
}
if realIP != "198.51.100.20" {
t.Fatalf("forwarded real IP = %q, want 198.51.100.20 (last XFF entry)", realIP)
}
// Client -> server: app bytes arrive as a plain stream.
payload := []byte("Shine\x00\x00\x00\x03abc")
if _, err := cli.Write(clientFrame(wsOpBinary, payload)); err != nil {
t.Fatalf("write frame: %v", err)
}
got := make([]byte, len(payload))
if _, err := io.ReadFull(wc, got); err != nil {
t.Fatalf("read tunneled bytes: %v", err)
}
if !bytes.Equal(got, payload) {
t.Fatalf("tunneled bytes = %q, want %q", got, payload)
}
// Server -> client: each Write becomes one binary frame.
if _, err := wc.Write([]byte("pong-data")); err != nil {
t.Fatalf("write: %v", err)
}
opcode, body := serverFrame(t, br)
if opcode != wsOpBinary || string(body) != "pong-data" {
t.Fatalf("server frame = opcode %d payload %q", opcode, body)
}
}
func TestWebSocketPingPongAndClose(t *testing.T) {
s := New(DefaultConfig())
wc, cli, br, _, _ := wsTestPair(t, s, "/x", nil)
// A ping is answered with a pong carrying the same payload, and the app
// stream is unaffected.
if _, err := cli.Write(clientFrame(wsOpPing, []byte("hi"))); err != nil {
t.Fatalf("write ping: %v", err)
}
readDone := make(chan error, 1)
go func() {
buf := make([]byte, 8)
_, err := wc.Read(buf)
readDone <- err
}()
opcode, body := serverFrame(t, br)
if opcode != wsOpPong || string(body) != "hi" {
t.Fatalf("pong = opcode %d payload %q", opcode, body)
}
// A close frame ends the pending Read with EOF and is echoed.
if _, err := cli.Write(clientFrame(wsOpClose, []byte{0x03, 0xe8})); err != nil {
t.Fatalf("write close: %v", err)
}
if err := <-readDone; err != io.EOF {
t.Fatalf("Read after close = %v, want io.EOF", err)
}
opcode, _ = serverFrame(t, br)
if opcode != wsOpClose {
t.Fatalf("close echo opcode = %d", opcode)
}
}
func TestWebSocketLargeFrameStreams(t *testing.T) {
s := New(DefaultConfig())
wc, cli, _, _, _ := wsTestPair(t, s, "/x", nil)
payload := bytes.Repeat([]byte("0123456789ABCDEF"), 64*1024) // 1 MiB
frame := clientFrame(wsOpBinary, payload)
go func() { _, _ = cli.Write(frame) }()
got := make([]byte, len(payload))
if _, err := io.ReadFull(wc, got); err != nil {
t.Fatalf("read large frame: %v", err)
}
if !bytes.Equal(got, payload) {
t.Fatalf("large frame corrupted")
}
}
func TestWebSocketRejectsBadHandshake(t *testing.T) {
tests := []struct {
name string
req string
path string
allow bool
}{
{
name: "not an upgrade",
req: "GET / HTTP/1.1\r\nHost: h\r\n\r\n",
},
{
name: "missing key",
req: "GET / HTTP/1.1\r\nHost: h\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n",
},
{
name: "wrong path",
req: "GET /other HTTP/1.1\r\nHost: h\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" +
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n",
path: "/api/socket",
},
{
name: "path match with query string",
req: "GET /api/socket?v=1 HTTP/1.1\r\nHost: h\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n",
path: "/api/socket",
allow: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := DefaultConfig()
cfg.WSPath = tt.path
s := New(cfg)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
defer ln.Close()
resCh := make(chan net.Conn, 1)
go func() {
srv, err := ln.Accept()
if err != nil {
resCh <- nil
return
}
conn, _ := s.wrapWebSocket(srv, peerIP(srv.RemoteAddr()))
resCh <- conn
}()
cli, err := net.Dial("tcp", ln.Addr().String())
if err != nil {
t.Fatalf("dial: %v", err)
}
defer cli.Close()
_ = cli.SetDeadline(time.Now().Add(10 * time.Second))
if _, err := io.WriteString(cli, tt.req); err != nil {
t.Fatalf("write: %v", err)
}
conn := <-resCh
if tt.allow {
if conn == nil {
t.Fatalf("connection rejected, want accepted")
}
return
}
if conn != nil {
t.Fatalf("connection accepted, want rejected")
}
br := bufio.NewReader(cli)
line, err := br.ReadString('\n')
if err != nil {
t.Fatalf("read reject response: %v", err)
}
if !strings.HasPrefix(line, "HTTP/1.1 400 ") {
t.Fatalf("reject status = %q", strings.TrimSpace(line))
}
})
}
}
func TestWSForwardedIP(t *testing.T) {
tests := []struct {
name string
headers map[string]string
want string
}{
{"x-real-ip", map[string]string{"x-real-ip": "198.51.100.7"}, "198.51.100.7"},
{"xff single", map[string]string{"x-forwarded-for": "198.51.100.8"}, "198.51.100.8"},
// The rightmost entry is the one the trusted proxy appended; a device
// that prepends a made-up address must not be able to choose its key.
{"xff chain takes rightmost", map[string]string{"x-forwarded-for": "198.51.100.9, 10.0.0.1, 10.0.0.2"}, "10.0.0.2"},
{"spoofed xff head ignored", map[string]string{"x-forwarded-for": "1.2.3.4, 198.51.100.10"}, "198.51.100.10"},
{"xff wins over x-real-ip", map[string]string{"x-real-ip": "198.51.100.7", "x-forwarded-for": "198.51.100.9"}, "198.51.100.9"},
{"garbage rightmost falls back", map[string]string{"x-forwarded-for": "198.51.100.11, not-an-ip"}, ""},
{"x-real-ip fallback", map[string]string{"x-real-ip": "198.51.100.7", "x-forwarded-for": "not-an-ip"}, "198.51.100.7"},
{"v4 with port", map[string]string{"x-real-ip": "198.51.100.7:5555"}, "198.51.100.7"},
{"ipv6 literal", map[string]string{"x-real-ip": "2001:db8::1"}, "2001:db8::1"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := reqForwardedIP(tt.headers); got != tt.want {
t.Errorf("reqForwardedIP(%v) = %q, want %q", tt.headers, got, tt.want)
}
})
}
}
// A header line that never ends must be rejected as soon as the handshake
// budget is exhausted, not buffered until the process runs out of memory.
func TestReadWSLineBounded(t *testing.T) {
br := bufio.NewReader(bytes.NewReader(bytes.Repeat([]byte{'A'}, 1<<20)))
total := 0
_, err := readWSLine(br, &total)
if !errors.Is(err, errWSProtocol) {
t.Fatalf("err = %v, want errWSProtocol", err)
}
if total > wsMaxHandshakeBytes+br.Size() {
t.Fatalf("read %d bytes, want at most %d", total, wsMaxHandshakeBytes+br.Size())
}
// A normal line still parses.
br = bufio.NewReader(strings.NewReader("GET /api/ws HTTP/1.1\r\n"))
total = 0
line, err := readWSLine(br, &total)
if err != nil || line != "GET /api/ws HTTP/1.1" {
t.Fatalf("line = %q, err = %v", line, err)
}
}
func TestTrustedProxies(t *testing.T) {
s := New(DefaultConfig())
if !s.trustedProxy("127.0.0.1") || !s.trustedProxy("::1") {
t.Fatal("loopback must be trusted by default")
}
if s.trustedProxy("203.0.113.9") {
t.Fatal("public peer must not be trusted by default")
}
cfg := DefaultConfig()
cfg.TrustedProxies = []string{"10.0.0.0/8", "203.0.113.9"}
s = New(cfg)
if !s.trustedProxy("10.1.2.3") || !s.trustedProxy("203.0.113.9") {
t.Fatal("configured proxies must be trusted")
}
if s.trustedProxy("127.0.0.1") {
t.Fatal("an explicit list replaces the loopback defaults")
}
}
func TestHeaderHasToken(t *testing.T) {
tests := []struct {
value string
token string
want bool
}{
{"Upgrade", "upgrade", true},
{"keep-alive, Upgrade", "upgrade", true},
{"upgrade, keep-alive", "upgrade", true},
{"keep-alive", "upgrade", false},
{"", "upgrade", false},
}
for _, tt := range tests {
if got := headerHasToken(tt.value, tt.token); got != tt.want {
t.Errorf("headerHasToken(%q, %q) = %v, want %v", tt.value, tt.token, got, tt.want)
}
}
}