Documentation
¶
Overview ¶
Package forwarded finds the address of the client of an HTTP request that came through proxies, from the X-Forwarded-For, X-Real-IP or Forwarded (RFC 7239) header fields that the proxies add, and formats those fields for a proxy to pass on.
A client can send any of these fields itself, so they are only believed as far as the proxies that wrote them are trusted. A Resolver walks the hops from the nearest: it starts at the TCP peer and, while the hop it is at is in its set of trusted proxies, steps to the address that hop recorded, the next entry from the right. The client is the first hop that is not trusted, so that entries a client prepends are never read, or the farthest hop when all are. A Resolver reads one configured address header. Scheme and host are each trusted only when explicitly enabled.
The package parses without allocating on the common path and returns netip values; the trusted proxies are a PrefixSet built once. It depends on the standard library alone and not on net/http: a header is the map that http.Header is, so an http.Header can be passed as it is.
Index ¶
- Variables
- func AppendElement(dst []byte, e Element) []byte
- func AppendForwarded(dst []byte, prior []string, e Element) []byte
- func AppendXForwardedFor(dst []byte, prior []string, a netip.Addr) []byte
- func NormalizeAddr(a netip.Addr) netip.Addr
- func NormalizePrefix(p netip.Prefix) netip.Prefix
- func ParseNode(s string) (netip.AddrPort, bool)
- type Client
- type Element
- type Header
- type Metadata
- type PrefixSet
- type Resolver
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrInvalidPrefix = errors.New("forwarded: invalid prefix")
ErrInvalidPrefix reports an entry of ParsePrefixSet that is neither an IP prefix nor an IP address.
Functions ¶
func AppendElement ¶
AppendElement appends e to dst in the syntax of RFC 7239, such as for="[2001:db8::1]:4711";proto=https, quoting values that are not tokens.
func AppendForwarded ¶
AppendForwarded appends to dst the Forwarded value that a proxy sends on: the field lines it received, prior, joined with ", " into one, then e. Empty lines are skipped.
Example ¶
Pass the request on, recording this hop in both forwarding fields.
package main
import (
"fmt"
"net/http"
"net/netip"
"github.com/djylb/netx/forwarded"
)
func main() {
in := http.Header{"X-Forwarded-For": {"198.51.100.17"}, "Forwarded": {"for=198.51.100.17"}}
client := netip.MustParseAddrPort("[2001:db8::5]:51000")
out := http.Header{}
out.Set("X-Forwarded-For", string(forwarded.AppendXForwardedFor(nil, in["X-Forwarded-For"], client.Addr())))
out.Set("Forwarded", string(forwarded.AppendForwarded(nil, in["Forwarded"], forwarded.Element{For: client, Proto: "https"})))
fmt.Println(out.Get("X-Forwarded-For"))
fmt.Println(out.Get("Forwarded"))
}
Output: 198.51.100.17, 2001:db8::5 for=198.51.100.17, for="[2001:db8::5]:51000";proto=https
func AppendXForwardedFor ¶
AppendXForwardedFor appends to dst the X-Forwarded-For value that a proxy sends on: the field lines it received, prior, joined with ", " into one, then a, the address it received the request from, IPv4 for IPv4-mapped addresses and without a zone. Empty lines are skipped. An invalid a is written as "unknown".
func NormalizeAddr ¶
NormalizeAddr returns a as a PrefixSet compares it: without a zone, and an IPv4-mapped IPv6 address as IPv4.
func NormalizePrefix ¶
NormalizePrefix returns p as a PrefixSet keeps it: masked, and an IPv4-mapped IPv6 prefix of at least 96 bits as IPv4. Shorter IPv4-mapped prefixes, which hold more than IPv4 addresses, stay IPv6.
func ParseNode ¶
ParseNode parses an address as forwarding fields record it: an entry of X-Forwarded-For or X-Real-IP, or the unquoted value of a Forwarded for or by parameter. It takes an IPv4 address, an IPv6 address in brackets or bare, either with an optional ":port" after it (after the brackets for IPv6), where an obfuscated port such as ":_a1" (RFC 7239) counts as no port. It returns the address IPv4 for IPv4-mapped addresses and without a zone, and false for anything else, such as "unknown", an obfuscated identifier or a host name. It does not allocate.
Types ¶
type Client ¶
type Client struct {
// Addr is the address of the client, IPv4 for IPv4-mapped addresses and
// without a zone. Its port is 0 when the hop that recorded it gave none,
// as X-Forwarded-For entries usually do. It is the TCP peer when that
// is not trusted, or when it is and recorded no client.
Addr netip.AddrPort
// Proto and Host are the enabled scheme and host, or "" when disabled,
// absent or invalid. With HeaderForwarded they come from the same
// element as Addr, and are empty if the walk stops at an opaque hop.
// With HeaderXForwardedFor or HeaderXRealIP they come from the last
// entry of the last line of X-Forwarded-Proto and X-Forwarded-Host,
// respectively, when the TCP peer is trusted. They describe the request
// as received by the nearest trusted proxy and may differ from the
// scheme and host the client used at the first proxy.
Proto, Host string
// Opaque is set when the walk stopped at a hop that a trusted proxy
// recorded without a usable address: an obfuscated identifier such as
// "_hidden", "unknown", an entry that does not parse, or "unknown" for
// a Forwarded element without for. Addr is then the trusted proxy that
// recorded it, the nearest knowledge of the client.
Opaque string
// Hops is the number of trusted proxies between the client and the
// server, counting the TCP peer: 0 when Addr is the TCP peer.
Hops int
}
Client is the client of a request as a Resolver finds it.
type Element ¶
type Element struct {
// For is the address the proxy received the request from, written
// with its port when that is not 0, or "unknown" when it is invalid.
For netip.AddrPort
// By is the address the proxy received the request on, left out when
// invalid.
By netip.AddrPort
// Host is the Host of the request as received, left out when "".
Host string
// Proto is the scheme of the request as received, such as "https",
// left out when "".
Proto string
}
Element is a Forwarded element (RFC 7239) as a proxy adds it.
type Header ¶
type Header uint8
Header names the header field that a Resolver reads.
const ( // HeaderXForwardedFor is X-Forwarded-For, a comma-separated list of // addresses to which each proxy appends the address it received the // request from, in any number of field lines. HeaderXForwardedFor Header = iota // HeaderForwarded is Forwarded (RFC 7239), a list of elements such as // for=192.0.2.60;proto=https;host=example.com, one per proxy. HeaderForwarded // HeaderXRealIP is X-Real-IP, the one address of the client that the // nearest proxy sets; only the TCP peer needs to be trusted, and the // last field line is read. HeaderXRealIP )
Header fields.
type Metadata ¶
type Metadata uint8
Metadata is a set of optional forwarding fields a Resolver may trust.
type PrefixSet ¶
type PrefixSet struct {
// contains filtered or unexported fields
}
PrefixSet is an immutable set of IP prefixes, such as the addresses of trusted proxies, built once and looked up without allocating in a time logarithmic in the number of prefixes. The zero PrefixSet and a nil *PrefixSet are empty. It is safe for concurrent use.
IPv4 and IPv6 are separate: an IPv4 address is matched against the IPv4 prefixes alone, also when it comes IPv4-mapped (::ffff:192.0.2.1), and a prefix inside ::ffff:0:0/96 is taken as the IPv4 prefix it maps, so that ::ffff:10.0.0.0/104 is 10.0.0.0/8. Zones are ignored.
func NewPrefixSet ¶
NewPrefixSet builds a set from prefixes. Invalid prefixes are ignored.
func ParsePrefixSet ¶
ParsePrefixSet returns the set of the given entries, each an IP prefix such as "10.0.0.0/8" or "2001:db8::/32" or an IP address such as "192.0.2.1" for itself alone, with spaces around it ignored and empty entries skipped. Every address is "0.0.0.0/0" and "::/0".
type Resolver ¶
type Resolver struct {
// Trusted holds the proxies whose address records are believed. Metadata
// additionally controls which scheme and host fields are believed.
Trusted *PrefixSet
// Name, if set, is the field read in place of the one Header names,
// with the syntax Header gives, such as "Cf-Connecting-Ip" with
// HeaderXRealIP. It must be in canonical form, as http.Header keys
// are, since the header map is indexed with it.
Name string
// Header selects the address syntax and the source of enabled metadata.
Header Header
// Metadata independently enables TrustProto and TrustHost. The zero
// value reads only addresses. With HeaderForwarded, enable a parameter
// only if trusted proxies write it in their own Forwarded elements.
// With HeaderXForwardedFor or HeaderXRealIP, enable a field only if the
// trusted TCP peer removes any client-supplied value or writes its own
// as the last value of X-Forwarded-Proto or X-Forwarded-Host, respectively.
Metadata Metadata
}
Resolver finds the client of a request. Its fields must not change while it is in use; a Resolver is then safe for concurrent use. A nil *Resolver, or one with no trusted proxies, takes every TCP peer for the client.
Example ¶
Find the client behind a load balancer on the private network, ignoring the address that the client itself put in front.
package main
import (
"fmt"
"net/http"
"github.com/djylb/netx/forwarded"
)
func main() {
trusted, err := forwarded.ParsePrefixSet("10.0.0.0/8", "fd00::/8")
if err != nil {
panic(err)
}
r := &forwarded.Resolver{Trusted: trusted, Metadata: forwarded.TrustProto}
req, _ := http.NewRequest(http.MethodGet, "http://example.com/", nil)
req.RemoteAddr = "10.1.2.3:41000"
req.Header.Add("X-Forwarded-For", "127.0.0.1, 198.51.100.17")
req.Header.Set("X-Forwarded-Proto", "https")
peer, _ := forwarded.ParseNode(req.RemoteAddr)
c := r.Resolve(peer, req.Header)
fmt.Println(c.Addr.Addr(), c.Hops, c.Proto)
}
Output: 198.51.100.17 1 https