determineTrustedProxy parses the remote IP address of the request, and determines (if the server configured it) if the client is a trusted proxy. If trusted, also returns the real client IP if possible.
(r *http.Request, s *Server)
| 1027 | // if the client is a trusted proxy. If trusted, also returns |
| 1028 | // the real client IP if possible. |
| 1029 | func determineTrustedProxy(r *http.Request, s *Server) (bool, string) { |
| 1030 | // If there's no server, then we can't check anything |
| 1031 | if s == nil { |
| 1032 | return false, "" |
| 1033 | } |
| 1034 | |
| 1035 | if s.TrustedProxiesUnix && r.RemoteAddr == "@" { |
| 1036 | if s.TrustedProxiesStrict > 0 { |
| 1037 | ipRanges := []netip.Prefix{} |
| 1038 | if s.trustedProxies != nil { |
| 1039 | ipRanges = s.trustedProxies.GetIPRanges(r) |
| 1040 | } |
| 1041 | return true, strictUntrustedClientIp(r, s.ClientIPHeaders, ipRanges, "@") |
| 1042 | } else { |
| 1043 | return true, trustedRealClientIP(r, s.ClientIPHeaders, "@") |
| 1044 | } |
| 1045 | } |
| 1046 | // Parse the remote IP, ignore the error as non-fatal, |
| 1047 | // but the remote IP is required to continue, so we |
| 1048 | // just return early. This should probably never happen |
| 1049 | // though, unless some other module manipulated the request's |
| 1050 | // remote address and used an invalid value. |
| 1051 | clientIP, _, err := net.SplitHostPort(r.RemoteAddr) |
| 1052 | if err != nil { |
| 1053 | return false, "" |
| 1054 | } |
| 1055 | |
| 1056 | // Client IP may contain a zone if IPv6, so we need |
| 1057 | // to pull that out before parsing the IP |
| 1058 | clientIP, _, _ = strings.Cut(clientIP, "%") |
| 1059 | ipAddr, err := netip.ParseAddr(clientIP) |
| 1060 | if err != nil { |
| 1061 | return false, "" |
| 1062 | } |
| 1063 | |
| 1064 | // Check if the client is a trusted proxy |
| 1065 | if s.trustedProxies == nil { |
| 1066 | return false, ipAddr.String() |
| 1067 | } |
| 1068 | |
| 1069 | if isTrustedClientIP(ipAddr, s.trustedProxies.GetIPRanges(r)) { |
| 1070 | if s.TrustedProxiesStrict > 0 { |
| 1071 | return true, strictUntrustedClientIp(r, s.ClientIPHeaders, s.trustedProxies.GetIPRanges(r), ipAddr.String()) |
| 1072 | } |
| 1073 | return true, trustedRealClientIP(r, s.ClientIPHeaders, ipAddr.String()) |
| 1074 | } |
| 1075 | |
| 1076 | return false, ipAddr.String() |
| 1077 | } |
| 1078 | |
| 1079 | // isTrustedClientIP returns true if the given IP address is |
| 1080 | // in the list of trusted IP ranges. |