| 1 | // Copyright © SAS Institute Inc. |
| 2 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | // you may not use this file except in compliance with the License. |
| 4 | // You may obtain a copy of the License at |
| 5 | // |
| 6 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | // |
| 8 | // Unless required by applicable law or agreed to in writing, software |
| 9 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | // See the License for the specific language governing permissions and |
| 12 | // limitations under the License. |
| 13 | |
| 14 | package realip |
| 15 | |
| 16 | import ( |
| 17 | "context" |
| 18 | "crypto/x509" |
| 19 | "encoding/pem" |
| 20 | "fmt" |
| 21 | "net" |
| 22 | "net/http" |
| 23 | "net/url" |
| 24 | "strings" |
| 25 | |
| 26 | "github.com/sassoftware/relic/v7/internal/zhttp" |
| 27 | ) |
| 28 | |
| 29 | const ( |
| 30 | forwardedFor = "X-Forwarded-For" |
| 31 | forwardedHost = "X-Forwarded-Host" |
| 32 | forwardedProto = "X-Forwarded-Proto" |
| 33 | sslClientCert = "Ssl-Client-Cert" |
| 34 | ) |
| 35 | |
| 36 | // Middleware processes headers set by a trusted reverse proxy in front of the |
| 37 | // server. Client IPs are checked against the provided list of networks, and the |
| 38 | // "real" IP passed by the trusted proxy replaces req.RemoteAddr. |
| 39 | func Middleware(trustedProxies []string) (func(http.Handler) http.Handler, error) { |
| 40 | // parse net list |
| 41 | trustedNets, err := parseTrusted(trustedProxies) |
| 42 | if err != nil { |
| 43 | return nil, err |
| 44 | } |
| 45 | return func(next http.Handler) http.Handler { |
| 46 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 47 | remoteIP, proxied := trustedClient(trustedNets, r) |
| 48 | r.RemoteAddr = remoteIP |
| 49 | if proxied { |
| 50 | ctx := context.WithValue(r.Context(), ctxKeyTrusted, proxied) |
| 51 | r = r.WithContext(ctx) |
| 52 | } |
| 53 | next.ServeHTTP(w, r) |
| 54 | }) |
| 55 | }, nil |
| 56 | } |
| 57 | |
| 58 | // BaseURL returns an estimate of the URL that the client used to access the |
| 59 | // service. Headers like X-Forwarded-Host are taken into account if the |
| 60 | // connection is from a trusted proxy. |
| 61 | func BaseURL(req *http.Request) *url.URL { |
| 62 | u := &url.URL{Scheme: "http", Host: req.Host} |
| 63 | if req.TLS != nil { |
| 64 | u.Scheme = "https" |
| 65 | } |
| 66 | if requestTrusted(req) { |
| 67 | if host := req.Header.Get(forwardedHost); host != "" { |
| 68 | u.Host = host |
| 69 | } |
| 70 | if scheme := req.Header.Get(forwardedProto); scheme != "" { |
| 71 | u.Scheme = scheme |
| 72 | } |
| 73 | } |
| 74 | return u |
| 75 | } |
| 76 | |
| 77 | // PeerCertificates returns the unverified set of certificates provided by the |
| 78 | // client, using the Ssl-Client-Cert header if the connection is from a trusted |
| 79 | // proxy. |
| 80 | func PeerCertificates(req *http.Request) ([]*x509.Certificate, error) { |
| 81 | if !requestTrusted(req) { |
| 82 | // direct untrusted connection |
| 83 | if req.TLS != nil { |
| 84 | return req.TLS.PeerCertificates, nil |
| 85 | } |
| 86 | return nil, nil |
| 87 | } |
| 88 | certString := req.Header.Get(sslClientCert) |
| 89 | if certString == "" { |
| 90 | return nil, nil |
| 91 | } |
| 92 | certString, err := url.PathUnescape(certString) |
| 93 | if err != nil { |
| 94 | return nil, fmt.Errorf("%s: invalid URL encoding: %w", sslClientCert, err) |
| 95 | } |
| 96 | pemBytes := []byte(certString) |
| 97 | var ret []*x509.Certificate |
| 98 | for { |
| 99 | var b *pem.Block |
| 100 | b, pemBytes = pem.Decode(pemBytes) |
| 101 | if b == nil { |
| 102 | break |
| 103 | } else if b.Type != "CERTIFICATE" { |
| 104 | continue |
| 105 | } |
| 106 | cert, err := x509.ParseCertificate(b.Bytes) |
| 107 | if err != nil { |
| 108 | return nil, fmt.Errorf("%s: parsing certificate %d: %w", sslClientCert, len(ret), err) |
| 109 | } |
| 110 | ret = append(ret, cert) |
| 111 | } |
| 112 | return ret, nil |
| 113 | } |
| 114 | |
| 115 | func parseTrusted(trustedProxies []string) ([]*net.IPNet, error) { |
| 116 | var trustedNets []*net.IPNet |
| 117 | for _, v := range trustedProxies { |
| 118 | var ipnet *net.IPNet |
| 119 | if strings.ContainsRune(v, '/') { |
| 120 | var err error |
| 121 | _, ipnet, err = net.ParseCIDR(v) |
| 122 | if err != nil { |
| 123 | return nil, fmt.Errorf("trusted_proxies %q: %w", v, err) |
| 124 | } |
| 125 | } else { |
| 126 | ip := net.ParseIP(v) |
| 127 | if ip == nil { |
| 128 | return nil, fmt.Errorf("trusted_proxies %q: invalid IP or IP network", v) |
| 129 | } |
| 130 | ipnet = &net.IPNet{IP: ip} |
| 131 | if ip.To4() != nil { |
| 132 | ipnet.Mask = net.CIDRMask(32, 32) |
| 133 | } else { |
| 134 | ipnet.Mask = net.CIDRMask(128, 128) |
| 135 | } |
| 136 | } |
| 137 | trustedNets = append(trustedNets, ipnet) |
| 138 | } |
| 139 | return trustedNets, nil |
| 140 | } |
| 141 | |
| 142 | func trustedClient(trustedNets []*net.IPNet, req *http.Request) (string, bool) { |
| 143 | remoteIP := zhttp.StripPort(req.RemoteAddr) |
| 144 | if !hopTrusted(trustedNets, remoteIP) { |
| 145 | // first hop is not trusted |
| 146 | return remoteIP, false |
| 147 | } |
| 148 | // Parse all XFF headers into a single list of hops |
| 149 | var hops []string |
| 150 | for _, xff := range req.Header.Values(forwardedFor) { |
| 151 | for _, hop := range strings.Split(xff, ",") { |
| 152 | hop = strings.TrimSpace(hop) |
| 153 | if hop != "" { |
| 154 | hops = append(hops, hop) |
| 155 | } |
| 156 | } |
| 157 | } |
| 158 | // Check each hop, starting from the closest one to us |
| 159 | for i := len(hops) - 1; i >= 0; i-- { |
| 160 | nextHop := strings.TrimSpace(hops[i]) |
| 161 | if !hopTrusted(trustedNets, nextHop) { |
| 162 | // The previous hop is trusted but this one is not, so this is the |
| 163 | // best client IP |
| 164 | return nextHop, true |
| 165 | } |
| 166 | } |
| 167 | // No untrusted hops were found, so whatever the last one in the chain is is |
| 168 | // the client IP. |
| 169 | if len(hops) != 0 { |
| 170 | return hops[0], true |
| 171 | } |
| 172 | return remoteIP, false |
| 173 | } |
| 174 | |
| 175 | func hopTrusted(trustedNets []*net.IPNet, addr string) bool { |
| 176 | if addr == "@" { |
| 177 | // UNIX socket |
| 178 | return true |
| 179 | } |
| 180 | ip := net.ParseIP(addr) |
| 181 | if ip == nil { |
| 182 | return false |
| 183 | } |
| 184 | for _, p := range trustedNets { |
| 185 | if p.Contains(ip) { |
| 186 | return true |
| 187 | } |
| 188 | } |
| 189 | return false |
| 190 | } |
| 191 | |
| 192 | type ctxKey int |
| 193 | |
| 194 | var ctxKeyTrusted ctxKey = 1 |
| 195 | |
| 196 | func requestTrusted(req *http.Request) bool { |
| 197 | trusted, _ := req.Context().Value(ctxKeyTrusted).(bool) |
| 198 | return trusted |
| 199 | } |