SaltDns.ProxyIP (Salt v1.0.0)

Finds the real client address behind a reverse proxy. Pure.

Behind a proxy every connection comes from the proxy's address, so the per-address rate limits would all share one counter. When the connection comes from a trusted proxy (a CIDR list the operator configures), the client is read from a header the proxy sets, walking the list from the right and skipping further trusted hops (the proxy chain), as for X-Forwarded-For. A header from an address that is not a trusted proxy is ignored: a client cannot choose its own address by sending the header.

Anything unreadable in the header returns the connection's own address (fail safe: never trust garbage).

A listener on a dual-stack socket reports an IPv4 peer as an IPv4-mapped IPv6 address (::ffff:10.0.27.4). That is the same host as 10.0.27.4, so normalize/1 turns it into the plain IPv4 tuple before anything is compared (without that, a trusted proxy range written as 10.0.0.0/16 never matches its own connections and the header is ignored), and client_ip/3 always returns the plain form.

Summary

Functions

The client address for a connection from remote_ip with these header values (one string per header line; comma-separated lists are fine).

An IPv4-mapped IPv6 address (::ffff:a.b.c.d) as the IPv4 address; anything else unchanged.

Parses a CIDR such as 10.0.0.0/8, a single address such as 192.0.2.1, or an IPv6 form.

Parses a list, returning only valid entries.

True when ip is inside one of the ranges (an IPv4-mapped address counts as its IPv4 address).

Types

cidr()

@type cidr() :: {:inet.ip_address(), 0..128}

Functions

client_ip(remote_ip, header_values, trusted)

@spec client_ip(:inet.ip_address(), [String.t()], [cidr()]) :: :inet.ip_address()

The client address for a connection from remote_ip with these header values (one string per header line; comma-separated lists are fine).

normalize(ip)

@spec normalize(:inet.ip_address()) :: :inet.ip_address()

An IPv4-mapped IPv6 address (::ffff:a.b.c.d) as the IPv4 address; anything else unchanged.

parse_cidr(text)

@spec parse_cidr(String.t()) :: {:ok, cidr()} | :error

Parses a CIDR such as 10.0.0.0/8, a single address such as 192.0.2.1, or an IPv6 form.

parse_cidrs(list)

@spec parse_cidrs([String.t()]) :: [cidr()]

Parses a list, returning only valid entries.

trusted?(ip, cidrs)

@spec trusted?(:inet.ip_address(), [cidr()]) :: boolean()

True when ip is inside one of the ranges (an IPv4-mapped address counts as its IPv4 address).