X-Forwarded-For parsing and trusted proxy detection
README.md

xff #

X-Forwarded-For and Forwarded parsing and trusted proxy detection for OCaml.

Behind a load balancer, a server sees the balancer's address on every connection, and the client's address comes in the X-Forwarded-For header, to which each proxy appends an entry. A client can also send that header itself, and a server that believes it lets anyone pick the address it logs or rate-limits. This library parses the header and believes it only when the connection comes from a proxy in one of the trusted CIDR ranges the caller gives. X-Forwarded-For is a de facto standard. Its replacement, the Forwarded header, is defined by RFC 7239, and Xff.parse_forwarded parses it by the grammar of sections 4 and 6.

Xff.client_ip reads the header from the right and returns the first address that is not a trusted proxy. Since every proxy appends the address it received the request from, that entry was written by a trusted proxy; the entries further left may have been written by the client (RFC 7239 sections 5.2 and 8.1). Xff.client_ip_forwarded applies the same rule to the for= nodes of a Forwarded header. It returns no client when the first untrusted node is unknown or obfuscated, or when the header is malformed.

Installation #

$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam install xff

Usage #

Here the load balancers in 10.0.0.0/8 and the local host are the trusted proxies. client_ip looks at the header only when the socket peer is one of them:

let trusted =
  List.map Xff.parse_cidr_exn [ "10.0.0.0/8"; "127.0.0.1/32" ]

let socket_ip = Ipaddr.of_string_exn "10.0.0.12"

let client =
  Xff.client_ip
    ~socket_ip:(Some socket_ip)
    ~xff_header:(Some "203.0.113.7, 10.0.0.12, 127.0.0.1")
    ~trusted_proxies:(Some trusted)
(* client = Some 203.0.113.7 *)

Invalid or missing data #

parse_xff skips the entries that are not addresses, and client_ip returns None when the socket peer is not known:

let () =
  let ips = Xff.parse_xff "203.0.113.7, not-an-ip, 10.0.0.12" in
  List.iter (fun ip -> Fmt.pr "%a@." Ipaddr.pp ip) ips
  (* prints 203.0.113.7 and 10.0.0.12; "not-an-ip" is dropped *)

let no_peer =
  Xff.client_ip
    ~socket_ip:None
    ~xff_header:(Some "203.0.113.7")
    ~trusted_proxies:(Some trusted)
(* no_peer = None -- never trust an XFF header without a socket peer *)

let bad_cidr =
  match Xff.parse_cidr "not-a-cidr" with
  | Ok p -> Some p
  | Error (`Msg msg) ->
      Fmt.epr "bad CIDR: %s@." msg;
      None

For logs, client_ip_string returns a string, with "unknown" where client_ip would give None. Xff.private_ranges and Xff.cloudflare_ranges are lists of trusted ranges ready to use.

License #

ISC. See LICENSE.md.