carlos / platform Public

proxyproto: PPv2 header parser

ReadHeader parses one PROXY protocol v2 header (LOCAL, PROXY, INET,
INET6, UNSPEC, TLVs skipped, 512-byte cap); UsableSource rejects
loopback, unspecified, link-local and multicast sources.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 21eda903b4aa9729214ba28899494df7d322bbae parent b809005
2 files changed, +394 −0
  • internal/proxyproto/header.go +130 −0
  • internal/proxyproto/header_test.go +264 −0
diff --git a/internal/proxyproto/header.go b/internal/proxyproto/header.go
new file mode 100644
index 000000000..9c13a665b
--- /dev/null
+++ b/internal/proxyproto/header.go
@@ -0,0 +1,130 @@
+// Package proxyproto reads PROXY protocol version 2 headers, the binary
+// header an AWS Network Load Balancer puts in front of a TCP stream to
+// carry the client's address. Only v2 is parsed; v1 (text) is not.
+//
+// Limits (spec §4.4): version 2; command LOCAL or PROXY; family and
+// protocol UNSPEC, INET/STREAM or INET6/STREAM; the declared length at
+// least the address block for the family; at most 512 bytes in total,
+// TLVs included. TLVs are skipped unread. Exactly one header is consumed.
+package proxyproto
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "net/netip"
+)
+
+// Signature is the 12 bytes every PPv2 header starts with.
+const Signature = "\r\n\r\n\x00\r\nQUIT\n"
+
+// Command is the low nibble of the version/command byte.
+type Command uint8
+
+const (
+ // CommandLocal: the connection was made by the proxy itself (an NLB
+ // health check). Any address block is ignored.
+ CommandLocal Command = 0
+ // CommandProxy: the connection is relayed for a client.
+ CommandProxy Command = 1
+)
+
+// Header is one parsed PPv2 header.
+type Header struct {
+ Command Command
+ Source netip.AddrPort
+ Destination netip.AddrPort
+ // HasAddresses is true only for PROXY with family INET or INET6; it is
+ // false for LOCAL and for UNSPEC, and Source and Destination are then
+ // the zero value.
+ HasAddresses bool
+}
+
+// ErrMalformed is wrapped by every error ReadHeader returns.
+var ErrMalformed = errors.New("proxyproto: malformed header")
+
+const (
+ fixedLen = 16 // signature, version/command, family, length
+ maxTotal = 512 // fixedLen + declared length, TLVs included
+
+ version = 0x2
+
+ familyUnspec = 0x00
+ familyInet = 0x11 // AF_INET, STREAM
+ familyInet6 = 0x21 // AF_INET6, STREAM
+
+ inetAddrLen = 12 // 4 + 4 + 2 + 2
+ inet6AddrLen = 36 // 16 + 16 + 2 + 2
+)
+
+// ReadHeader reads exactly one PPv2 header from r: the 12-byte signature
+// (which the caller has seen but which is read and checked again), the
+// 4-byte fixed part, then the declared length. It never reads past the
+// declared length, and reads nothing past the fixed part when the fixed part
+// is refused. Every error wraps ErrMalformed; a read error is wrapped too, so
+// errors.Is also finds it (a deadline, for example).
+func ReadHeader(r io.Reader) (Header, error) {
+ var fixed [fixedLen]byte
+ if _, err := io.ReadFull(r, fixed[:]); err != nil {
+ return Header{}, fmt.Errorf("%w: reading fixed part: %w", ErrMalformed, err)
+ }
+ if !bytes.Equal(fixed[:12], []byte(Signature)) {
+ return Header{}, fmt.Errorf("%w: bad signature", ErrMalformed)
+ }
+ if v := fixed[12] >> 4; v != version {
+ return Header{}, fmt.Errorf("%w: version %d", ErrMalformed, v)
+ }
+ cmd := Command(fixed[12] & 0x0f)
+ if cmd != CommandLocal && cmd != CommandProxy {
+ return Header{}, fmt.Errorf("%w: command %d", ErrMalformed, cmd)
+ }
+ fam := fixed[13]
+ var addrLen int
+ switch fam {
+ case familyUnspec:
+ addrLen = 0
+ case familyInet:
+ addrLen = inetAddrLen
+ case familyInet6:
+ addrLen = inet6AddrLen
+ default:
+ return Header{}, fmt.Errorf("%w: family 0x%02x", ErrMalformed, fam)
+ }
+ length := int(binary.BigEndian.Uint16(fixed[14:16]))
+ if fixedLen+length > maxTotal {
+ return Header{}, fmt.Errorf("%w: total length %d over %d", ErrMalformed, fixedLen+length, maxTotal)
+ }
+ if length < addrLen {
+ return Header{}, fmt.Errorf("%w: length %d under the %d-byte address block for family 0x%02x", ErrMalformed, length, addrLen, fam)
+ }
+
+ var buf [maxTotal - fixedLen]byte
+ body := buf[:length]
+ if _, err := io.ReadFull(r, body); err != nil {
+ return Header{}, fmt.Errorf("%w: reading %d-byte body: %w", ErrMalformed, length, err)
+ }
+
+ h := Header{Command: cmd}
+ if cmd != CommandProxy || fam == familyUnspec {
+ return h, nil
+ }
+ ipLen := (addrLen - 4) / 2
+ src, _ := netip.AddrFromSlice(body[:ipLen])
+ dst, _ := netip.AddrFromSlice(body[ipLen : 2*ipLen])
+ ports := body[2*ipLen:]
+ h.Source = netip.AddrPortFrom(src, binary.BigEndian.Uint16(ports[0:2]))
+ h.Destination = netip.AddrPortFrom(dst, binary.BigEndian.Uint16(ports[2:4]))
+ h.HasAddresses = true
+ return h, nil
+}
+
+// UsableSource reports whether a is a client address a real load balancer
+// could send: unicast, and not loopback, unspecified, link-local or
+// multicast (nor the IPv4 broadcast address). An IPv4-mapped IPv6 address is
+// judged as the IPv4 address it carries.
+func UsableSource(a netip.Addr) bool {
+ a = a.Unmap()
+ return a.IsValid() && a.IsGlobalUnicast()
+}
diff --git a/internal/proxyproto/header_test.go b/internal/proxyproto/header_test.go
new file mode 100644
index 000000000..2066f5c87
--- /dev/null
+++ b/internal/proxyproto/header_test.go
@@ -0,0 +1,264 @@
+package proxyproto
+
+import (
+ "bytes"
+ "encoding/binary"
+ "errors"
+ "io"
+ "net/netip"
+ "testing"
+ "testing/iotest"
+)
+
+// build returns a PPv2 header: the signature, version 2 with cmd, family
+// fam, the address block for src and dst (empty when both are ""), then tlv.
+// The declared length covers the address block and tlv.
+func build(cmd, fam byte, src, dst string, tlv []byte) []byte {
+ var addrs []byte
+ if src != "" || dst != "" {
+ s := netip.MustParseAddrPort(src)
+ d := netip.MustParseAddrPort(dst)
+ addrs = append(addrs, s.Addr().AsSlice()...)
+ addrs = append(addrs, d.Addr().AsSlice()...)
+ addrs = binary.BigEndian.AppendUint16(addrs, s.Port())
+ addrs = binary.BigEndian.AppendUint16(addrs, d.Port())
+ }
+ body := append(addrs, tlv...)
+ h := []byte(Signature)
+ h = append(h, 0x20|cmd, fam)
+ h = binary.BigEndian.AppendUint16(h, uint16(len(body)))
+ return append(h, body...)
+}
+
+// withLength rewrites the declared length of a built header and pads or
+// trims the body to match, so only the length check can refuse it.
+func withLength(h []byte, n int) []byte {
+ out := append([]byte(nil), h[:16]...)
+ binary.BigEndian.PutUint16(out[14:16], uint16(n))
+ body := append([]byte(nil), h[16:]...)
+ for len(body) < n {
+ body = append(body, 0)
+ }
+ return append(out, body[:n]...)
+}
+
+func TestReadHeaderProxyV4(t *testing.T) {
+ h, err := ReadHeader(bytes.NewReader(build(0x1, 0x11, "203.0.113.7:51000", "54.77.110.223:443", nil)))
+ if err != nil {
+ t.Fatalf("ReadHeader: %v", err)
+ }
+ if h.Command != CommandProxy {
+ t.Errorf("Command = %d, want CommandProxy", h.Command)
+ }
+ if want := netip.MustParseAddrPort("203.0.113.7:51000"); h.Source != want {
+ t.Errorf("Source = %v, want %v", h.Source, want)
+ }
+ if want := netip.MustParseAddrPort("54.77.110.223:443"); h.Destination != want {
+ t.Errorf("Destination = %v, want %v", h.Destination, want)
+ }
+ if !h.HasAddresses {
+ t.Error("HasAddresses = false, want true")
+ }
+}
+
+func TestReadHeaderProxyV6(t *testing.T) {
+ h, err := ReadHeader(bytes.NewReader(build(0x1, 0x21, "[2001:db8::1]:51000", "[2001:db8::2]:443", nil)))
+ if err != nil {
+ t.Fatalf("ReadHeader: %v", err)
+ }
+ if h.Command != CommandProxy {
+ t.Errorf("Command = %d, want CommandProxy", h.Command)
+ }
+ if want := netip.MustParseAddrPort("[2001:db8::1]:51000"); h.Source != want {
+ t.Errorf("Source = %v, want %v", h.Source, want)
+ }
+ if want := netip.MustParseAddrPort("[2001:db8::2]:443"); h.Destination != want {
+ t.Errorf("Destination = %v, want %v", h.Destination, want)
+ }
+ if !h.HasAddresses {
+ t.Error("HasAddresses = false, want true")
+ }
+}
+
+func TestReadHeaderLocal(t *testing.T) {
+ raw := build(0x0, 0x00, "", "", nil)
+ if got := binary.BigEndian.Uint16(raw[14:16]); got != 0 {
+ t.Fatalf("declared length = %d, want 0", got)
+ }
+ h, err := ReadHeader(bytes.NewReader(raw))
+ if err != nil {
+ t.Fatalf("ReadHeader: %v", err)
+ }
+ if h.Command != CommandLocal {
+ t.Errorf("Command = %d, want CommandLocal", h.Command)
+ }
+ if h.HasAddresses {
+ t.Error("HasAddresses = true, want false")
+ }
+}
+
+func TestReadHeaderUnspecProxy(t *testing.T) {
+ h, err := ReadHeader(bytes.NewReader(build(0x1, 0x00, "", "", nil)))
+ if err != nil {
+ t.Fatalf("ReadHeader: %v", err)
+ }
+ if h.Command != CommandProxy {
+ t.Errorf("Command = %d, want CommandProxy", h.Command)
+ }
+ if h.HasAddresses {
+ t.Error("HasAddresses = true, want false")
+ }
+}
+
+func TestReadHeaderSkipsTLVs(t *testing.T) {
+ // PP2_TYPE_AWS (0xEA), length 7, then 7 value bytes: 10 bytes in all.
+ tlv := []byte{0xEA, 0x00, 0x07, 0x01, 'v', 'p', 'c', 'e', '-', '1'}
+ if len(tlv) != 10 {
+ t.Fatalf("tlv is %d bytes, want 10", len(tlv))
+ }
+ raw := build(0x1, 0x11, "203.0.113.7:51000", "54.77.110.223:443", tlv)
+ payload := []byte("GET / HTTP/1.1\r\n")
+
+ for _, tc := range []struct {
+ name string
+ wrap func(io.Reader) io.Reader
+ }{
+ {"whole", func(r io.Reader) io.Reader { return r }},
+ {"byte at a time", iotest.OneByteReader},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ r := tc.wrap(bytes.NewReader(append(append([]byte(nil), raw...), payload...)))
+ h, err := ReadHeader(r)
+ if err != nil {
+ t.Fatalf("ReadHeader: %v", err)
+ }
+ if want := netip.MustParseAddrPort("203.0.113.7:51000"); h.Source != want || !h.HasAddresses {
+ t.Errorf("Source = %v (HasAddresses %v), want %v", h.Source, h.HasAddresses, want)
+ }
+ next := make([]byte, 1)
+ if _, err := io.ReadFull(r, next); err != nil {
+ t.Fatalf("reading the byte after the header: %v", err)
+ }
+ if next[0] != payload[0] {
+ t.Errorf("next byte = %q, want %q (payload start)", next[0], payload[0])
+ }
+ })
+ }
+}
+
+// A second header after the first is left in the reader as payload.
+func TestReadHeaderConsumesExactlyOne(t *testing.T) {
+ first := build(0x1, 0x11, "203.0.113.7:51000", "54.77.110.223:443", nil)
+ second := build(0x1, 0x11, "198.51.100.9:1234", "54.77.110.223:443", nil)
+ r := bytes.NewReader(append(append([]byte(nil), first...), second...))
+ if _, err := ReadHeader(r); err != nil {
+ t.Fatalf("ReadHeader: %v", err)
+ }
+ rest, _ := io.ReadAll(r)
+ if !bytes.Equal(rest, second) {
+ t.Errorf("left %d bytes, want the second header (%d bytes) untouched", len(rest), len(second))
+ }
+}
+
+func TestReadHeaderRefuses(t *testing.T) {
+ v4 := build(0x1, 0x11, "203.0.113.7:51000", "54.77.110.223:443", nil)
+ v6 := build(0x1, 0x21, "[2001:db8::1]:51000", "[2001:db8::2]:443", nil)
+
+ setByte := func(h []byte, i int, b byte) []byte {
+ out := append([]byte(nil), h...)
+ out[i] = b
+ return out
+ }
+
+ for _, tc := range []struct {
+ name string
+ raw []byte
+ }{
+ {"bad signature", setByte(v4, 11, 'X')},
+ {"version nibble 1", setByte(v4, 12, 0x11)},
+ {"command 2", setByte(v4, 12, 0x22)},
+ {"family 0x12 INET/DGRAM", setByte(v4, 13, 0x12)},
+ {"family 0x31 UNIX", setByte(v4, 13, 0x31)},
+ {"family 0x01 UNSPEC/STREAM", setByte(v4, 13, 0x01)},
+ {"INET length 11", withLength(v4, 11)},
+ {"INET6 length 35", withLength(v6, 35)},
+ {"total length 513", withLength(v4, 497)},
+ {"truncated in the signature", v4[:6]},
+ {"truncated after the fixed part", v4[:16]},
+ {"truncated inside the addresses", v4[:16+5]},
+ {"empty", nil},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ _, err := ReadHeader(bytes.NewReader(tc.raw))
+ if !errors.Is(err, ErrMalformed) {
+ t.Fatalf("err = %v, want ErrMalformed", err)
+ }
+ })
+ }
+}
+
+// The largest header allowed, 512 bytes in total, parses.
+func TestReadHeaderAcceptsLimit(t *testing.T) {
+ raw := withLength(build(0x1, 0x11, "203.0.113.7:51000", "54.77.110.223:443", nil), 512-16)
+ if len(raw) != 512 {
+ t.Fatalf("header is %d bytes, want 512", len(raw))
+ }
+ if _, err := ReadHeader(bytes.NewReader(raw)); err != nil {
+ t.Fatalf("ReadHeader: %v", err)
+ }
+}
+
+// Over the limit, the body is not read: the bytes after the fixed part stay
+// in the reader.
+func TestReadHeaderOverLimitReadsNoBody(t *testing.T) {
+ raw := withLength(build(0x1, 0x11, "203.0.113.7:51000", "54.77.110.223:443", nil), 497)
+ br := bytes.NewReader(raw)
+ if _, err := ReadHeader(br); !errors.Is(err, ErrMalformed) {
+ t.Fatalf("err = %v, want ErrMalformed", err)
+ }
+ rest, _ := io.ReadAll(br)
+ if len(rest) != 497 {
+ t.Errorf("%d bytes left after refusal, want 497", len(rest))
+ }
+}
+
+// A read error other than EOF (a deadline, say) stays visible through the
+// wrap, so the caller can tell a timeout from bad bytes.
+func TestReadHeaderKeepsReadError(t *testing.T) {
+ boom := errors.New("boom")
+ raw := build(0x1, 0x11, "203.0.113.7:51000", "54.77.110.223:443", nil)
+ r := io.MultiReader(bytes.NewReader(raw[:20]), iotest.ErrReader(boom))
+ _, err := ReadHeader(r)
+ if !errors.Is(err, ErrMalformed) || !errors.Is(err, boom) {
+ t.Fatalf("err = %v, want both ErrMalformed and the read error", err)
+ }
+}
+
+func TestUsableSource(t *testing.T) {
+ for _, tc := range []struct {
+ addr string
+ want bool
+ }{
+ {"203.0.113.7", true},
+ {"2001:db8::1", true},
+ {"10.1.2.3", true},
+ {"127.0.0.1", false},
+ {"0.0.0.0", false},
+ {"169.254.1.1", false},
+ {"224.0.0.1", false},
+ {"::1", false},
+ {"fe80::1", false},
+ {"::", false},
+ {"ff02::1", false},
+ {"255.255.255.255", false},
+ {"::ffff:127.0.0.1", false},
+ {"::ffff:203.0.113.7", true},
+ } {
+ if got := UsableSource(netip.MustParseAddr(tc.addr)); got != tc.want {
+ t.Errorf("UsableSource(%s) = %v, want %v", tc.addr, got, tc.want)
+ }
+ }
+ if UsableSource(netip.Addr{}) {
+ t.Error("UsableSource(zero Addr) = true, want false")
+ }
+}