| 1 |
// Copyright 2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"encoding/binary" |
| 18 |
"errors" |
| 19 |
"fmt" |
| 20 |
"io" |
| 21 |
"net" |
| 22 |
"strconv" |
| 23 |
"strings" |
| 24 |
"time" |
| 25 |
) |
| 26 |
|
| 27 |
// PROXY protocol v2 constants |
| 28 |
const ( |
| 29 |
// Protocol signature (12 bytes) |
| 30 |
proxyProtoV2Sig = "\x0D\x0A\x0D\x0A\x00\x0D\x0A\x51\x55\x49\x54\x0A" |
| 31 |
|
| 32 |
// Version and command byte format: version(4 bits) | command(4 bits) |
| 33 |
proxyProtoV2VerMask = 0xF0 |
| 34 |
proxyProtoV2Ver = 0x20 // Version 2 |
| 35 |
|
| 36 |
// Commands |
| 37 |
proxyProtoCmdMask = 0x0F |
| 38 |
proxyProtoCmdLocal = 0x00 // LOCAL command (health check, use original connection) |
| 39 |
proxyProtoCmdProxy = 0x01 // PROXY command (proxied connection) |
| 40 |
|
| 41 |
// Address family and protocol byte format: family(4 bits) | protocol(4 bits) |
| 42 |
proxyProtoFamilyMask = 0xF0 |
| 43 |
proxyProtoFamilyUnspec = 0x00 // Unspecified |
| 44 |
proxyProtoFamilyInet = 0x10 // IPv4 |
| 45 |
proxyProtoFamilyInet6 = 0x20 // IPv6 |
| 46 |
proxyProtoFamilyUnix = 0x30 // Unix socket |
| 47 |
proxyProtoProtoMask = 0x0F |
| 48 |
proxyProtoProtoUnspec = 0x00 // Unspecified |
| 49 |
proxyProtoProtoStream = 0x01 // TCP/STREAM |
| 50 |
proxyProtoProtoDatagram = 0x02 // UDP/DGRAM |
| 51 |
|
| 52 |
// Address sizes |
| 53 |
proxyProtoAddrSizeIPv4 = 12 // 4 (src IP) + 4 (dst IP) + 2 (src port) + 2 (dst port) |
| 54 |
proxyProtoAddrSizeIPv6 = 36 // 16 (src IP) + 16 (dst IP) + 2 (src port) + 2 (dst port) |
| 55 |
|
| 56 |
// Header sizes |
| 57 |
proxyProtoV2HeaderSize = 16 // Fixed header: 12 (sig) + 1 (ver/cmd) + 1 (fam/proto) + 2 (addr len) |
| 58 |
|
| 59 |
// Timeout for reading PROXY protocol header |
| 60 |
proxyProtoReadTimeout = 5 * time.Second |
| 61 |
) |
| 62 |
|
| 63 |
// PROXY protocol v1 constants |
| 64 |
const ( |
| 65 |
proxyProtoV1Prefix = "PROXY " |
| 66 |
proxyProtoV1MaxLineLen = 107 // Maximum line length including CRLF |
| 67 |
proxyProtoV1TCP4 = "TCP4" |
| 68 |
proxyProtoV1TCP6 = "TCP6" |
| 69 |
proxyProtoV1Unknown = "UNKNOWN" |
| 70 |
) |
| 71 |
|
| 72 |
var ( |
| 73 |
// Errors |
| 74 |
errProxyProtoInvalid = errors.New("invalid PROXY protocol header") |
| 75 |
errProxyProtoUnsupported = errors.New("unsupported PROXY protocol feature") |
| 76 |
errProxyProtoTimeout = errors.New("timeout reading PROXY protocol header") |
| 77 |
errProxyProtoUnrecognized = errors.New("unrecognized PROXY protocol format") |
| 78 |
) |
| 79 |
|
| 80 |
// proxyProtoAddr contains the address information extracted from PROXY protocol header |
| 81 |
type proxyProtoAddr struct { |
| 82 |
srcIP net.IP |
| 83 |
srcPort uint16 |
| 84 |
dstIP net.IP |
| 85 |
dstPort uint16 |
| 86 |
} |
| 87 |
|
| 88 |
// String implements net.Addr interface |
| 89 |
func (p *proxyProtoAddr) String() string { |
| 90 |
return net.JoinHostPort(p.srcIP.String(), fmt.Sprintf("%d", p.srcPort)) |
| 91 |
} |
| 92 |
|
| 93 |
// Network implements net.Addr interface |
| 94 |
func (p *proxyProtoAddr) Network() string { |
| 95 |
if p.srcIP.To4() != nil { |
| 96 |
return "tcp4" |
| 97 |
} |
| 98 |
return "tcp6" |
| 99 |
} |
| 100 |
|
| 101 |
// proxyConn wraps a net.Conn to override RemoteAddr() with the address |
| 102 |
// extracted from the PROXY protocol header |
| 103 |
type proxyConn struct { |
| 104 |
net.Conn |
| 105 |
remoteAddr net.Addr |
| 106 |
} |
| 107 |
|
| 108 |
// RemoteAddr returns the original client address extracted from PROXY protocol |
| 109 |
func (pc *proxyConn) RemoteAddr() net.Addr { |
| 110 |
return pc.remoteAddr |
| 111 |
} |
| 112 |
|
| 113 |
// detectProxyProtoVersion reads the first bytes and determines protocol version. |
| 114 |
// Returns 1 for v1, 2 for v2, or error. |
| 115 |
// The first 6 bytes read are returned so they can be used by the parser. |
| 116 |
func detectProxyProtoVersion(conn net.Conn) (version int, header []byte, err error) { |
| 117 |
// Read first 6 bytes to check for "PROXY " or v2 signature |
| 118 |
header = make([]byte, 6) |
| 119 |
if _, err = io.ReadFull(conn, header); err != nil { |
| 120 |
return 0, nil, fmt.Errorf("failed to read protocol version: %w", err) |
| 121 |
} |
| 122 |
switch bytesToString(header) { |
| 123 |
case proxyProtoV1Prefix: |
| 124 |
return 1, header, nil |
| 125 |
case proxyProtoV2Sig[:6]: |
| 126 |
return 2, header, nil |
| 127 |
default: |
| 128 |
// Return the consumed bytes so the caller can replay them into the |
| 129 |
// next protocol layer instead of discarding them. |
| 130 |
return 0, header, errProxyProtoUnrecognized |
| 131 |
} |
| 132 |
} |
| 133 |
|
| 134 |
// readProxyProtoV1Header parses PROXY protocol v1 text format. |
| 135 |
// Expects the "PROXY " prefix (6 bytes) to have already been consumed. |
| 136 |
// Returns any bytes that were read past the trailing CRLF so the caller can |
| 137 |
// replay them into the next protocol layer. |
| 138 |
func readProxyProtoV1Header(conn net.Conn) (*proxyProtoAddr, []byte, error) { |
| 139 |
// Read rest of line (max 107 bytes total, already read 6) |
| 140 |
maxRemaining := proxyProtoV1MaxLineLen - 6 |
| 141 |
|
| 142 |
// Read up to maxRemaining bytes at once (more efficient than byte-by-byte) |
| 143 |
buf := make([]byte, maxRemaining) |
| 144 |
var line []byte |
| 145 |
var remaining []byte |
| 146 |
|
| 147 |
for len(line) < maxRemaining { |
| 148 |
// Read available data |
| 149 |
n, err := conn.Read(buf[len(line):]) |
| 150 |
if err != nil { |
| 151 |
return nil, nil, fmt.Errorf("failed to read v1 line: %w", err) |
| 152 |
} |
| 153 |
|
| 154 |
line = buf[:len(line)+n] |
| 155 |
|
| 156 |
// Look for CRLF in what we've read so far |
| 157 |
for i := 0; i < len(line)-1; i++ { |
| 158 |
if line[i] == '\r' && line[i+1] == '\n' { |
| 159 |
// Found CRLF - keep any over-read bytes for the client parser. |
| 160 |
remaining = append(remaining, line[i+2:]...) |
| 161 |
line = line[:i] |
| 162 |
goto foundCRLF |
| 163 |
} |
| 164 |
} |
| 165 |
} |
| 166 |
|
| 167 |
// Exceeded max length without finding CRLF |
| 168 |
return nil, nil, fmt.Errorf("%w: v1 line too long", errProxyProtoInvalid) |
| 169 |
|
| 170 |
foundCRLF: |
| 171 |
// Get parts from the protocol |
| 172 |
parts := strings.Fields(string(line)) |
| 173 |
|
| 174 |
// Validate format |
| 175 |
if len(parts) < 1 { |
| 176 |
return nil, nil, fmt.Errorf("%w: invalid v1 format", errProxyProtoInvalid) |
| 177 |
} |
| 178 |
|
| 179 |
// Handle UNKNOWN (health check, like v2 LOCAL) |
| 180 |
if parts[0] == proxyProtoV1Unknown { |
| 181 |
return nil, remaining, nil |
| 182 |
} |
| 183 |
|
| 184 |
// Must have exactly 5 parts: protocol, src-ip, dst-ip, src-port, dst-port |
| 185 |
if len(parts) != 5 { |
| 186 |
return nil, nil, fmt.Errorf("%w: invalid v1 format", errProxyProtoInvalid) |
| 187 |
} |
| 188 |
|
| 189 |
protocol := parts[0] |
| 190 |
srcIP := net.ParseIP(parts[1]) |
| 191 |
dstIP := net.ParseIP(parts[2]) |
| 192 |
|
| 193 |
if srcIP == nil || dstIP == nil { |
| 194 |
return nil, nil, fmt.Errorf("%w: invalid address", errProxyProtoInvalid) |
| 195 |
} |
| 196 |
|
| 197 |
// Parse ports |
| 198 |
srcPort, err := strconv.ParseUint(parts[3], 10, 16) |
| 199 |
if err != nil { |
| 200 |
return nil, nil, fmt.Errorf("invalid source port: %w", err) |
| 201 |
} |
| 202 |
|
| 203 |
dstPort, err := strconv.ParseUint(parts[4], 10, 16) |
| 204 |
if err != nil { |
| 205 |
return nil, nil, fmt.Errorf("invalid dest port: %w", err) |
| 206 |
} |
| 207 |
|
| 208 |
// Validate protocol matches IP version. The textual form determines the |
| 209 |
// family: TCP4 requires dotted-quad addresses, TCP6 requires IPv6 |
| 210 |
// addresses. IPv4-mapped IPv6 addresses (e.g. "::ffff:192.0.2.1") are |
| 211 |
// valid for TCP6 since dual-stack proxies can emit those for IPv4 |
| 212 |
// clients on IPv6 sockets, matching the v2 parser behavior. |
| 213 |
srcIsV6 := strings.Contains(parts[1], ":") |
| 214 |
dstIsV6 := strings.Contains(parts[2], ":") |
| 215 |
if protocol == proxyProtoV1TCP4 && (srcIsV6 || dstIsV6) { |
| 216 |
return nil, nil, fmt.Errorf("%w: TCP4 with IPv6 address", errProxyProtoInvalid) |
| 217 |
} |
| 218 |
if protocol == proxyProtoV1TCP6 && (!srcIsV6 || !dstIsV6) { |
| 219 |
return nil, nil, fmt.Errorf("%w: TCP6 with IPv4 address", errProxyProtoInvalid) |
| 220 |
} |
| 221 |
if protocol != proxyProtoV1TCP4 && protocol != proxyProtoV1TCP6 { |
| 222 |
return nil, nil, fmt.Errorf("%w: invalid protocol %s", errProxyProtoInvalid, protocol) |
| 223 |
} |
| 224 |
|
| 225 |
return &proxyProtoAddr{ |
| 226 |
srcIP: srcIP, |
| 227 |
srcPort: uint16(srcPort), |
| 228 |
dstIP: dstIP, |
| 229 |
dstPort: uint16(dstPort), |
| 230 |
}, remaining, nil |
| 231 |
} |
| 232 |
|
| 233 |
// readProxyProtoHeader reads and parses PROXY protocol (v1 or v2) from the connection. |
| 234 |
// Automatically detects version and routes to appropriate parser. |
| 235 |
// If the command is LOCAL/UNKNOWN (health check), it returns nil for addr and no error. |
| 236 |
// If the command is PROXY, it returns the parsed address information. |
| 237 |
// It also returns any bytes that were read past the v1 header terminator so the |
| 238 |
// caller can replay them into the normal client parser. |
| 239 |
// The connection must be fresh (no data read yet). |
| 240 |
func readProxyProtoHeader(conn net.Conn) (*proxyProtoAddr, []byte, error) { |
| 241 |
// Set read deadline to prevent hanging on slow/malicious clients |
| 242 |
if err := conn.SetReadDeadline(time.Now().Add(proxyProtoReadTimeout)); err != nil { |
| 243 |
return nil, nil, err |
| 244 |
} |
| 245 |
defer conn.SetReadDeadline(time.Time{}) |
| 246 |
|
| 247 |
// Detect version. |
| 248 |
// On errProxyProtoUnrecognized, firstBytes holds the bytes that were |
| 249 |
// consumed so the caller can replay them. |
| 250 |
version, firstBytes, err := detectProxyProtoVersion(conn) |
| 251 |
if err != nil { |
| 252 |
return nil, firstBytes, err |
| 253 |
} |
| 254 |
|
| 255 |
switch version { |
| 256 |
case 1: |
| 257 |
// v1 parser expects "PROXY " prefix already consumed |
| 258 |
return readProxyProtoV1Header(conn) |
| 259 |
case 2: |
| 260 |
// Read rest of v2 signature (bytes 6-11, total 6 more bytes) |
| 261 |
remaining := make([]byte, 6) |
| 262 |
if _, err := io.ReadFull(conn, remaining); err != nil { |
| 263 |
return nil, nil, fmt.Errorf("failed to read v2 signature: %w", err) |
| 264 |
} |
| 265 |
|
| 266 |
// Verify full signature |
| 267 |
fullSig := string(firstBytes) + string(remaining) |
| 268 |
if fullSig != proxyProtoV2Sig { |
| 269 |
return nil, nil, fmt.Errorf("%w: invalid signature", errProxyProtoInvalid) |
| 270 |
} |
| 271 |
|
| 272 |
// Read rest of header: ver/cmd, fam/proto, addr-len (4 bytes) |
| 273 |
header := make([]byte, 4) |
| 274 |
if _, err := io.ReadFull(conn, header); err != nil { |
| 275 |
return nil, nil, fmt.Errorf("failed to read v2 header: %w", err) |
| 276 |
} |
| 277 |
|
| 278 |
// Continue with parsing |
| 279 |
addr, err := parseProxyProtoV2Header(conn, header) |
| 280 |
return addr, nil, err |
| 281 |
default: |
| 282 |
return nil, nil, fmt.Errorf("unsupported PROXY protocol version: %d", version) |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
// readProxyProtoV2Header is kept for backward compatibility and direct testing. |
| 287 |
// It reads and parses a PROXY protocol v2 header from the connection. |
| 288 |
// If the command is LOCAL (health check), it returns nil for addr and no error. |
| 289 |
// If the command is PROXY, it returns the parsed address information. |
| 290 |
// The connection must be fresh (no data read yet). |
| 291 |
func readProxyProtoV2Header(conn net.Conn) (*proxyProtoAddr, error) { |
| 292 |
// Set read deadline to prevent hanging on slow/malicious clients |
| 293 |
if err := conn.SetReadDeadline(time.Now().Add(proxyProtoReadTimeout)); err != nil { |
| 294 |
return nil, err |
| 295 |
} |
| 296 |
defer conn.SetReadDeadline(time.Time{}) |
| 297 |
|
| 298 |
// Read fixed header (16 bytes) |
| 299 |
header := make([]byte, proxyProtoV2HeaderSize) |
| 300 |
if _, err := io.ReadFull(conn, header); err != nil { |
| 301 |
if ne, ok := err.(net.Error); ok && ne.Timeout() { |
| 302 |
return nil, errProxyProtoTimeout |
| 303 |
} |
| 304 |
return nil, fmt.Errorf("failed to read PROXY protocol header: %w", err) |
| 305 |
} |
| 306 |
|
| 307 |
// Validate signature (first 12 bytes) |
| 308 |
if string(header[:12]) != proxyProtoV2Sig { |
| 309 |
return nil, fmt.Errorf("%w: invalid signature", errProxyProtoInvalid) |
| 310 |
} |
| 311 |
|
| 312 |
// Continue with parsing after signature |
| 313 |
return parseProxyProtoV2Header(conn, header[12:16]) |
| 314 |
} |
| 315 |
|
| 316 |
// parseProxyProtoV2Header parses v2 protocol after signature has been validated. |
| 317 |
// header contains the 4 bytes: ver/cmd, fam/proto, addr-len (2 bytes). |
| 318 |
func parseProxyProtoV2Header(conn net.Conn, header []byte) (*proxyProtoAddr, error) { |
| 319 |
// Parse version and command |
| 320 |
verCmd := header[0] |
| 321 |
version := verCmd & proxyProtoV2VerMask |
| 322 |
command := verCmd & proxyProtoCmdMask |
| 323 |
|
| 324 |
if version != proxyProtoV2Ver { |
| 325 |
return nil, fmt.Errorf("%w: invalid version 0x%02x", errProxyProtoInvalid, version) |
| 326 |
} |
| 327 |
|
| 328 |
// Parse address family and protocol |
| 329 |
famProto := header[1] |
| 330 |
family := famProto & proxyProtoFamilyMask |
| 331 |
protocol := famProto & proxyProtoProtoMask |
| 332 |
|
| 333 |
// Parse address length (big-endian uint16) |
| 334 |
addrLen := binary.BigEndian.Uint16(header[2:4]) |
| 335 |
|
| 336 |
// Handle LOCAL command (health check) |
| 337 |
if command == proxyProtoCmdLocal { |
| 338 |
// For LOCAL, we should skip the address data if any |
| 339 |
if addrLen > 0 { |
| 340 |
// Discard the address data |
| 341 |
if _, err := io.CopyN(io.Discard, conn, int64(addrLen)); err != nil { |
| 342 |
return nil, fmt.Errorf("failed to discard LOCAL command address data: %w", err) |
| 343 |
} |
| 344 |
} |
| 345 |
return nil, nil // nil addr indicates LOCAL command |
| 346 |
} |
| 347 |
|
| 348 |
// Handle PROXY command |
| 349 |
if command != proxyProtoCmdProxy { |
| 350 |
return nil, fmt.Errorf("unknown PROXY protocol command: 0x%02x", command) |
| 351 |
} |
| 352 |
|
| 353 |
// Validate protocol (we only support STREAM/TCP) |
| 354 |
if protocol != proxyProtoProtoStream { |
| 355 |
return nil, fmt.Errorf("%w: only STREAM protocol supported", errProxyProtoUnsupported) |
| 356 |
} |
| 357 |
|
| 358 |
// Parse address data based on family |
| 359 |
var addr *proxyProtoAddr |
| 360 |
var err error |
| 361 |
switch family { |
| 362 |
case proxyProtoFamilyInet: |
| 363 |
addr, err = parseIPv4Addr(conn, addrLen) |
| 364 |
case proxyProtoFamilyInet6: |
| 365 |
addr, err = parseIPv6Addr(conn, addrLen) |
| 366 |
case proxyProtoFamilyUnspec: |
| 367 |
// UNSPEC family with PROXY command is valid but rare |
| 368 |
// Just skip the address data |
| 369 |
if addrLen > 0 { |
| 370 |
if _, err := io.CopyN(io.Discard, conn, int64(addrLen)); err != nil { |
| 371 |
return nil, fmt.Errorf("failed to discard UNSPEC address address data: %w", err) |
| 372 |
} |
| 373 |
} |
| 374 |
return nil, nil |
| 375 |
default: |
| 376 |
return nil, fmt.Errorf("%w: unsupported address family 0x%02x", errProxyProtoUnsupported, family) |
| 377 |
} |
| 378 |
return addr, err |
| 379 |
} |
| 380 |
|
| 381 |
// parseIPv4Addr parses IPv4 address data from PROXY protocol header |
| 382 |
func parseIPv4Addr(conn net.Conn, addrLen uint16) (*proxyProtoAddr, error) { |
| 383 |
// IPv4: 4 (src IP) + 4 (dst IP) + 2 (src port) + 2 (dst port) = 12 bytes minimum |
| 384 |
if addrLen < proxyProtoAddrSizeIPv4 { |
| 385 |
return nil, fmt.Errorf("IPv4 address data too short: %d bytes", addrLen) |
| 386 |
} |
| 387 |
addrData := make([]byte, addrLen) |
| 388 |
if _, err := io.ReadFull(conn, addrData); err != nil { |
| 389 |
return nil, fmt.Errorf("failed to read IPv4 address data: %w", err) |
| 390 |
} |
| 391 |
return &proxyProtoAddr{ |
| 392 |
srcIP: net.IP(addrData[0:4]), |
| 393 |
dstIP: net.IP(addrData[4:8]), |
| 394 |
srcPort: binary.BigEndian.Uint16(addrData[8:10]), |
| 395 |
dstPort: binary.BigEndian.Uint16(addrData[10:12]), |
| 396 |
}, nil |
| 397 |
} |
| 398 |
|
| 399 |
// parseIPv6Addr parses IPv6 address data from PROXY protocol header |
| 400 |
func parseIPv6Addr(conn net.Conn, addrLen uint16) (*proxyProtoAddr, error) { |
| 401 |
// IPv6: 16 (src IP) + 16 (dst IP) + 2 (src port) + 2 (dst port) = 36 bytes minimum |
| 402 |
if addrLen < proxyProtoAddrSizeIPv6 { |
| 403 |
return nil, fmt.Errorf("IPv6 address data too short: %d bytes", addrLen) |
| 404 |
} |
| 405 |
addrData := make([]byte, addrLen) |
| 406 |
if _, err := io.ReadFull(conn, addrData); err != nil { |
| 407 |
return nil, fmt.Errorf("failed to read IPv6 address data: %w", err) |
| 408 |
} |
| 409 |
return &proxyProtoAddr{ |
| 410 |
srcIP: net.IP(addrData[0:16]), |
| 411 |
dstIP: net.IP(addrData[16:32]), |
| 412 |
srcPort: binary.BigEndian.Uint16(addrData[32:34]), |
| 413 |
dstPort: binary.BigEndian.Uint16(addrData[34:36]), |
| 414 |
}, nil |
| 415 |
} |