package main import ( "fmt" "net" "net/http" "strings" ) // parseTrustedProxies reads TRUSTED_PROXIES, a comma-separated list of IP // addresses and CIDR ranges for reverse proxies whose forwarding headers may be // believed. An empty value trusts no proxy. func parseTrustedProxies(value string) ([]*net.IPNet, error) { var networks []*net.IPNet for _, entry := range strings.Split(value, ",") { entry = strings.TrimSpace(entry) if entry == "" { continue } if ip := net.ParseIP(entry); ip != nil { if v4 := ip.To4(); v4 != nil { ip = v4 } networks = append(networks, &net.IPNet{IP: ip, Mask: net.CIDRMask(8*len(ip), 8*len(ip))}) continue } _, network, err := net.ParseCIDR(entry) if err != nil { return nil, fmt.Errorf("TRUSTED_PROXIES entry %q is neither an IP address nor a CIDR range", entry) } networks = append(networks, network) } return networks, nil } // clientIP returns the address a request is attributed to, for rate limits and // logs. The socket peer is used unless it is a trusted proxy. Only then is // X-Forwarded-For read, walking from the nearest hop outwards and stopping at // the first address that is not itself a trusted proxy. A malformed chain falls // back to the peer, so an unknown caller cannot choose the address it appears as. func clientIP(r *http.Request, trusted []*net.IPNet) string { peer := remoteHost(r.RemoteAddr) peerIP := net.ParseIP(peer) if peerIP == nil || !inNetworks(peerIP, trusted) { return peer } hops := strings.Split(r.Header.Get("X-Forwarded-For"), ",") var leftmost net.IP for i := len(hops) - 1; i >= 0; i-- { hop := net.ParseIP(strings.TrimSpace(hops[i])) if hop == nil { return peer } if !inNetworks(hop, trusted) { return hop.String() } leftmost = hop } if leftmost != nil { return leftmost.String() } return peer } // requestIsHTTPS reports whether the client's connection was encrypted: either // TLS terminated in this process, or a trusted proxy reported https through // X-Forwarded-Proto. The header is ignored from any other peer. func requestIsHTTPS(r *http.Request, trusted []*net.IPNet) bool { if r.TLS != nil { return true } peerIP := net.ParseIP(remoteHost(r.RemoteAddr)) if peerIP == nil || !inNetworks(peerIP, trusted) { return false } protos := strings.Split(r.Header.Get("X-Forwarded-Proto"), ",") return strings.EqualFold(strings.TrimSpace(protos[len(protos)-1]), "https") } func remoteHost(remoteAddr string) string { host, _, err := net.SplitHostPort(remoteAddr) if err != nil { return remoteAddr } return host } func inNetworks(ip net.IP, networks []*net.IPNet) bool { for _, network := range networks { if network.Contains(ip) { return true } } return false }