|
| 1 | +package httpmw |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "golang.org/x/xerrors" |
| 10 | + |
| 11 | + "github.com/coder/coder/coderd/httpapi" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + headerXForwardedFor string = "X-Forwarded-For" |
| 16 | + headerXForwardedProto string = "X-Forwarded-Proto" |
| 17 | +) |
| 18 | + |
| 19 | +// RealIPConfig configures the search order for the function, which controls |
| 20 | +// which headers to consider trusted. |
| 21 | +type RealIPConfig struct { |
| 22 | + // TrustedOrigins is a list of networks that will be trusted. If |
| 23 | + // any non-trusted address supplies these headers, they will be |
| 24 | + // ignored. |
| 25 | + TrustedOrigins []*net.IPNet |
| 26 | + |
| 27 | + // TrustedHeaders lists headers that are trusted for forwarding |
| 28 | + // IP addresses. e.g. "CF-Connecting-IP", "True-Client-IP", etc. |
| 29 | + TrustedHeaders []string |
| 30 | +} |
| 31 | + |
| 32 | +// ExtractRealIP is a middleware that uses headers from reverse proxies to |
| 33 | +// propagate origin IP address information, when configured to do so. |
| 34 | +func ExtractRealIP(config *RealIPConfig) func(next http.Handler) http.Handler { |
| 35 | + return func(next http.Handler) http.Handler { |
| 36 | + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 37 | + // Preserve the original TLS connection state and RemoteAddr |
| 38 | + req = req.WithContext(context.WithValue(req.Context(), ctxKey{}, &RealIPState{ |
| 39 | + Config: config, |
| 40 | + OriginalRemoteAddr: req.RemoteAddr, |
| 41 | + })) |
| 42 | + |
| 43 | + info, err := ExtractRealIPAddress(config, req) |
| 44 | + if err != nil { |
| 45 | + httpapi.InternalServerError(w, err) |
| 46 | + return |
| 47 | + } |
| 48 | + req.RemoteAddr = info.String() |
| 49 | + |
| 50 | + next.ServeHTTP(w, req) |
| 51 | + }) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +// ExtractRealIPAddress returns the original client address according to the |
| 56 | +// configuration and headers. It does not mutate the original request. |
| 57 | +func ExtractRealIPAddress(config *RealIPConfig, req *http.Request) (net.IP, error) { |
| 58 | + if config == nil { |
| 59 | + config = &RealIPConfig{} |
| 60 | + } |
| 61 | + |
| 62 | + cf := isContainedIn(config.TrustedOrigins, getRemoteAddress(req.RemoteAddr)) |
| 63 | + if !cf { |
| 64 | + // Address is not valid or the origin is not trusted; use the |
| 65 | + // original address |
| 66 | + return getRemoteAddress(req.RemoteAddr), nil |
| 67 | + } |
| 68 | + |
| 69 | + for _, trustedHeader := range config.TrustedHeaders { |
| 70 | + addr := getRemoteAddress(req.Header.Get(trustedHeader)) |
| 71 | + if addr != nil { |
| 72 | + return addr, nil |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + return getRemoteAddress(req.RemoteAddr), nil |
| 77 | +} |
| 78 | + |
| 79 | +// FilterUntrustedOriginHeaders removes all known proxy headers from the |
| 80 | +// request for untrusted origins, and ensures that only one copy |
| 81 | +// of each proxy header is set. |
| 82 | +func FilterUntrustedOriginHeaders(config *RealIPConfig, req *http.Request) { |
| 83 | + if config == nil { |
| 84 | + config = &RealIPConfig{} |
| 85 | + } |
| 86 | + |
| 87 | + cf := isContainedIn(config.TrustedOrigins, getRemoteAddress(req.RemoteAddr)) |
| 88 | + if !cf { |
| 89 | + // Address is not valid or the origin is not trusted; clear |
| 90 | + // all known proxy headers and return |
| 91 | + for _, header := range config.TrustedHeaders { |
| 92 | + req.Header.Del(header) |
| 93 | + } |
| 94 | + return |
| 95 | + } |
| 96 | + |
| 97 | + for _, header := range config.TrustedHeaders { |
| 98 | + req.Header.Set(header, req.Header.Get(header)) |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +// EnsureXForwardedForHeader ensures that the request has an X-Forwarded-For |
| 103 | +// header. It uses the following logic: |
| 104 | +// |
| 105 | +// 1. If we have a direct connection (remoteAddr == proxyAddr), then |
| 106 | +// set it to remoteAddr |
| 107 | +// 2. If we have a proxied connection (remoteAddr != proxyAddr) and |
| 108 | +// X-Forwarded-For doesn't begin with remoteAddr, then overwrite |
| 109 | +// it with remoteAddr,proxyAddr |
| 110 | +// 3. If we have a proxied connection (remoteAddr != proxyAddr) and |
| 111 | +// X-Forwarded-For begins with remoteAddr, then append proxyAddr |
| 112 | +// to the original X-Forwarded-For header |
| 113 | +// 4. If X-Forwarded-Proto is not set, then it will be set to "https" |
| 114 | +// if req.TLS != nil, otherwise it will be set to "http" |
| 115 | +func EnsureXForwardedForHeader(req *http.Request) error { |
| 116 | + state := RealIP(req.Context()) |
| 117 | + if state == nil { |
| 118 | + return xerrors.New("request does not contain realip.State; was it processed by httpmw.ExtractRealIP?") |
| 119 | + } |
| 120 | + |
| 121 | + remoteAddr := getRemoteAddress(req.RemoteAddr) |
| 122 | + if remoteAddr == nil { |
| 123 | + return xerrors.Errorf("failed to parse remote address: %s", remoteAddr) |
| 124 | + } |
| 125 | + |
| 126 | + proxyAddr := getRemoteAddress(state.OriginalRemoteAddr) |
| 127 | + if proxyAddr == nil { |
| 128 | + return xerrors.Errorf("failed to parse original address: %s", proxyAddr) |
| 129 | + } |
| 130 | + |
| 131 | + if remoteAddr.Equal(proxyAddr) { |
| 132 | + req.Header.Set(headerXForwardedFor, remoteAddr.String()) |
| 133 | + } else { |
| 134 | + forwarded := req.Header.Get(headerXForwardedFor) |
| 135 | + if forwarded == "" || !remoteAddr.Equal(getRemoteAddress(forwarded)) { |
| 136 | + req.Header.Set(headerXForwardedFor, remoteAddr.String()+","+proxyAddr.String()) |
| 137 | + } else { |
| 138 | + req.Header.Set(headerXForwardedFor, forwarded+","+proxyAddr.String()) |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + if req.Header.Get(headerXForwardedProto) == "" { |
| 143 | + if req.TLS != nil { |
| 144 | + req.Header.Set(headerXForwardedProto, "https") |
| 145 | + } else { |
| 146 | + req.Header.Set(headerXForwardedProto, "http") |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + return nil |
| 151 | +} |
| 152 | + |
| 153 | +// getRemoteAddress extracts the IP address from the given string. If |
| 154 | +// the string contains commas, it assumes that the first part is the |
| 155 | +// original address. |
| 156 | +func getRemoteAddress(address string) net.IP { |
| 157 | + // X-Forwarded-For may contain multiple addresses, in case the |
| 158 | + // proxies are chained; the first value is the client address |
| 159 | + i := strings.IndexByte(address, ',') |
| 160 | + if i == -1 { |
| 161 | + i = len(address) |
| 162 | + } |
| 163 | + |
| 164 | + // If the address contains a port, remove it |
| 165 | + firstAddress := address[:i] |
| 166 | + host, _, err := net.SplitHostPort(firstAddress) |
| 167 | + if err != nil { |
| 168 | + // This will error if there is no port, so try to parse the address |
| 169 | + return net.ParseIP(firstAddress) |
| 170 | + } |
| 171 | + return net.ParseIP(host) |
| 172 | +} |
| 173 | + |
| 174 | +// isContainedIn checks that the given address is contained in the given |
| 175 | +// network. |
| 176 | +func isContainedIn(networks []*net.IPNet, address net.IP) bool { |
| 177 | + for _, network := range networks { |
| 178 | + if network.Contains(address) { |
| 179 | + return true |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + return false |
| 184 | +} |
| 185 | + |
| 186 | +// RealIPState is the original state prior to modification by this middleware, |
| 187 | +// useful for getting information about the connecting client if needed. |
| 188 | +type RealIPState struct { |
| 189 | + // Config is the configuration applied in the middleware. Consider |
| 190 | + // this read-only and do not modify. |
| 191 | + Config *RealIPConfig |
| 192 | + |
| 193 | + // OriginalRemoteAddr is the original RemoteAddr for the request. |
| 194 | + OriginalRemoteAddr string |
| 195 | +} |
| 196 | + |
| 197 | +type ctxKey struct{} |
| 198 | + |
| 199 | +// FromContext retrieves the state from the given context.Context. |
| 200 | +func RealIP(ctx context.Context) *RealIPState { |
| 201 | + state, ok := ctx.Value(ctxKey{}).(*RealIPState) |
| 202 | + if !ok { |
| 203 | + return nil |
| 204 | + } |
| 205 | + return state |
| 206 | +} |
| 207 | + |
| 208 | +// ParseRealIPConfig takes a raw string array of headers and origins |
| 209 | +// to produce a config. |
| 210 | +func ParseRealIPConfig(headers, origins []string) (*RealIPConfig, error) { |
| 211 | + config := &RealIPConfig{} |
| 212 | + for _, origin := range origins { |
| 213 | + _, network, err := net.ParseCIDR(origin) |
| 214 | + if err != nil { |
| 215 | + return nil, xerrors.Errorf("parse proxy origin %q: %w", origin, err) |
| 216 | + } |
| 217 | + config.TrustedOrigins = append(config.TrustedOrigins, network) |
| 218 | + } |
| 219 | + for index, header := range headers { |
| 220 | + headers[index] = http.CanonicalHeaderKey(header) |
| 221 | + } |
| 222 | + config.TrustedHeaders = headers |
| 223 | + |
| 224 | + return config, nil |
| 225 | +} |
0 commit comments