Debian Codegraph @

realclientip.go

raw symbols SCIP
1 // SPDX: 0BSD
2
3 // Package realclientip provides strategies for obtaining the "real" client IP from HTTP requests.
4 package realclientip
5
6 import (
7 "fmt"
8 "net"
9 "net/http"
10 "strings"
11 )
12
13 // Strategy is satisfied by all of the specific strategies in this package. It can be used
14 // instead of the concrete types if the strategy is to be determined at runtime,
15 // depending on configuration, for example.
16 type Strategy interface {
17 // ClientIP returns empty string if there is no derivable IP. In many cases this
18 // should be treated as a misconfiguration error, unless the strategy is attempting to
19 // get an untrustworthy or optional value.
20 // All implementations of this method must be threadsafe.
21 ClientIP(headers http.Header, remoteAddr string) string
22 }
23
24 const (
25 // Pre-canonicalized constants to avoid typos later on
26 xForwardedForHdr = "X-Forwarded-For"
27 forwardedHdr = "Forwarded"
28 )
29
30 // Must panics if err is not nil. This can be used to make sure the strategy-making
31 // functions do not return an error. It can also facilitate calling NewChainStrategy().
32 // It can be called like Must(NewSingleIPHeaderStrategy("X-Real-IP")).
33 func Must(strat Strategy, err error) Strategy {
34 if err != nil {
35 panic(fmt.Sprintf("err is not nil: %v", err))
36 }
37 return strat
38 }
39
40 // ChainStrategy attempts to use the given strategies in order. If the first one returns
41 // an empty string, the second one is tried, and so on, until a good IP is found or the
42 // strategies are exhausted.
43 // A common use for this is if a server is both directly connected to the internet and
44 // expecting a header to check. It might be called like:
45 // NewChainStrategy(Must(LeftmostNonPrivateStrategy("X-Forwarded-For")), RemoteAddrStrategy)
46 type ChainStrategy struct {
47 strategies []Strategy
48 }
49
50 // NewChainStrategy creates a ChainStrategy that attempts to use the given strategies to
51 // derive the client IP, stopping when the first one succeeds.
52 func NewChainStrategy(strategies ...Strategy) ChainStrategy {
53 return ChainStrategy{strategies: strategies}
54 }
55
56 // ClientIP derives the client IP using this strategy.
57 // headers is expected to be like http.Request.Header.
58 // remoteAddr is expected to be like http.Request.RemoteAddr.
59 // The returned IP may contain a zone identifier.
60 // If all chained strategies fail to derive a valid IP, an empty string is returned.
61 func (strat ChainStrategy) ClientIP(headers http.Header, remoteAddr string) string {
62 for _, subStrat := range strat.strategies {
63 result := subStrat.ClientIP(headers, remoteAddr)
64 if result != "" {
65 return result
66 }
67 }
68 return ""
69 }
70
71 func (strat ChainStrategy) String() string {
72 var b strings.Builder
73 b.WriteString("{strategies:[")
74 for i, s := range strat.strategies {
75 if i > 0 {
76 b.WriteString(" ")
77 }
78 b.WriteString(fmt.Sprintf("%T%+v", s, s))
79 }
80 b.WriteString("]}")
81 return b.String()
82 }
83
84 // RemoteAddrStrategy returns the client socket IP, stripped of port.
85 // This strategy should be used if the server accept direct connections, rather than
86 // through a reverse proxy.
87 type RemoteAddrStrategy struct{}
88
89 // ClientIP derives the client IP using this strategy.
90 // remoteAddr is expected to be like http.Request.RemoteAddr.
91 // The returned IP may contain a zone identifier.
92 // If no valid IP can be derived, empty string will be returned. This should only happen
93 // if remoteAddr has been modified to something illegal, or if the server is accepting
94 // connections on a Unix domain socket (in which case RemoteAddr is "@").
95 func (strat RemoteAddrStrategy) ClientIP(_ http.Header, remoteAddr string) string {
96 ipAddr := goodIPAddr(remoteAddr)
97 if ipAddr == nil {
98 return ""
99 }
100
101 return ipAddr.String()
102 }
103
104 // SingleIPHeaderStrategy derives an IP address from a single-IP header.
105 // A non-exhaustive list of such single-IP headers is:
106 // X-Real-IP, CF-Connecting-IP, True-Client-IP, Fastly-Client-IP, X-Azure-ClientIP, X-Azure-SocketIP.
107 // This strategy should be used when the given header is added by a trusted reverse proxy.
108 // You must ensure that this header is not spoofable (as is possible with Akamai's use of
109 // True-Client-IP, Fastly's default use of Fastly-Client-IP, and Azure's X-Azure-ClientIP).
110 // See the single-IP wiki page for more info: https://github.com/realclientip/realclientip-go/wiki/Single-IP-Headers
111 type SingleIPHeaderStrategy struct {
112 headerName string
113 }
114
115 // NewSingleIPHeaderStrategy creates a SingleIPHeaderStrategy that uses the headerName
116 // request header to get the client IP.
117 func NewSingleIPHeaderStrategy(headerName string) (SingleIPHeaderStrategy, error) {
118 if headerName == "" {
119 return SingleIPHeaderStrategy{}, fmt.Errorf("SingleIPHeaderStrategy header must not be empty")
120 }
121
122 // We will be using the headerName for lookups in the http.Header map, which is keyed
123 // by canonicalized header name. We'll canonicalize here so we only have to do it once.
124 headerName = http.CanonicalHeaderKey(headerName)
125
126 if headerName == xForwardedForHdr || headerName == forwardedHdr {
127 return SingleIPHeaderStrategy{}, fmt.Errorf("SingleIPHeaderStrategy header must not be %s or %s", xForwardedForHdr, forwardedHdr)
128 }
129
130 return SingleIPHeaderStrategy{headerName: headerName}, nil
131 }
132
133 // ClientIP derives the client IP using this strategy.
134 // headers is expected to be like http.Request.Header.
135 // The returned IP may contain a zone identifier.
136 // If no valid IP can be derived, empty string will be returned.
137 func (strat SingleIPHeaderStrategy) ClientIP(headers http.Header, _ string) string {
138 // RFC 2616 does not allow multiple instances of single-IP headers (or any non-list header).
139 // It is debatable whether it is better to treat multiple such headers as an error
140 // (more correct) or simply pick one of them (more flexible). As we've already
141 // told the user tom make sure the header is not spoofable, we're going to use the
142 // last header instance if there are multiple. (Using the last is arbitrary, but
143 // in theory it should be the newest value.)
144 ipStr := lastHeader(headers, strat.headerName)
145 if ipStr == "" {
146 // There is no header
147 return ""
148 }
149
150 ipAddr := goodIPAddr(ipStr)
151 if ipAddr == nil {
152 // The header value is invalid
153 return ""
154 }
155
156 return ipAddr.String()
157 }
158
159 // LeftmostNonPrivateStrategy derives the client IP from the leftmost valid and
160 // non-private IP address in the X-Fowarded-For for Forwarded header. This
161 // strategy should be used when a valid, non-private IP closest to the client is desired.
162 // Note that this MUST NOT BE USED FOR SECURITY PURPOSES. This IP can be TRIVIALLY
163 // SPOOFED.
164 type LeftmostNonPrivateStrategy struct {
165 headerName string
166 }
167
168 // NewLeftmostNonPrivateStrategy creates a LeftmostNonPrivateStrategy. headerName must be
169 // "X-Forwarded-For" or "Forwarded".
170 func NewLeftmostNonPrivateStrategy(headerName string) (LeftmostNonPrivateStrategy, error) {
171 if headerName == "" {
172 return LeftmostNonPrivateStrategy{}, fmt.Errorf("LeftmostNonPrivateStrategy header must not be empty")
173 }
174
175 // We will be using the headerName for lookups in the http.Header map, which is keyed
176 // by canonicalized header name. We'll do that here so we only have to do it once.
177 headerName = http.CanonicalHeaderKey(headerName)
178
179 if headerName != xForwardedForHdr && headerName != forwardedHdr {
180 return LeftmostNonPrivateStrategy{}, fmt.Errorf("LeftmostNonPrivateStrategy header must be %s or %s", xForwardedForHdr, forwardedHdr)
181 }
182
183 return LeftmostNonPrivateStrategy{headerName: headerName}, nil
184 }
185
186 // ClientIP derives the client IP using this strategy.
187 // headers is expected to be like http.Request.Header.
188 // The returned IP may contain a zone identifier.
189 // If no valid IP can be derived, empty string will be returned.
190 func (strat LeftmostNonPrivateStrategy) ClientIP(headers http.Header, _ string) string {
191 ipAddrs := getIPAddrList(headers, strat.headerName)
192 for _, ip := range ipAddrs {
193 if ip != nil && !isPrivateOrLocal(ip.IP) {
194 // This is the leftmost valid, non-private IP
195 return ip.String()
196 }
197 }
198
199 // We failed to find any valid, non-private IP
200 return ""
201 }
202
203 // RightmostNonPrivateStrategy derives the client IP from the rightmost valid,
204 // non-private/non-internal IP address in the X-Fowarded-For for Forwarded header. This
205 // strategy should be used when all reverse proxies between the internet and the
206 // server have private-space IP addresses.
207 type RightmostNonPrivateStrategy struct {
208 headerName string
209 }
210
211 // NewRightmostNonPrivateStrategy creates a RightmostNonPrivateStrategy. headerName must
212 // be "X-Forwarded-For" or "Forwarded".
213 func NewRightmostNonPrivateStrategy(headerName string) (RightmostNonPrivateStrategy, error) {
214 if headerName == "" {
215 return RightmostNonPrivateStrategy{}, fmt.Errorf("RightmostNonPrivateStrategy header must not be empty")
216 }
217
218 // We will be using the headerName for lookups in the http.Header map, which is keyed
219 // by canonicalized header name. We'll do that here so we only have to do it once.
220 headerName = http.CanonicalHeaderKey(headerName)
221
222 if headerName != xForwardedForHdr && headerName != forwardedHdr {
223 return RightmostNonPrivateStrategy{}, fmt.Errorf("RightmostNonPrivateStrategy header must be %s or %s", xForwardedForHdr, forwardedHdr)
224 }
225
226 return RightmostNonPrivateStrategy{headerName: headerName}, nil
227 }
228
229 // ClientIP derives the client IP using this strategy.
230 // headers is expected to be like http.Request.Header.
231 // The returned IP may contain a zone identifier.
232 // If no valid IP can be derived, empty string will be returned.
233 func (strat RightmostNonPrivateStrategy) ClientIP(headers http.Header, _ string) string {
234 ipAddrs := getIPAddrList(headers, strat.headerName)
235 // Look backwards through the list of IP addresses
236 for i := len(ipAddrs) - 1; i >= 0; i-- {
237 if ipAddrs[i] != nil && !isPrivateOrLocal(ipAddrs[i].IP) {
238 // This is the rightmost non-private IP
239 return ipAddrs[i].String()
240 }
241 }
242
243 // We failed to find any valid, non-private IP
244 return ""
245 }
246
247 // RightmostTrustedCountStrategy derives the client IP from the valid IP address added by
248 // the first trusted reverse proxy to the X-Forwarded-For or Forwarded header. This
249 // Strategy should be used when there is a fixed number of trusted reverse proxies that
250 // are appending IP addresses to the header.
251 type RightmostTrustedCountStrategy struct {
252 headerName string
253 trustedCount int
254 }
255
256 // NewRightmostTrustedCountStrategy creates a RightmostTrustedCountStrategy. headerName
257 // must be "X-Forwarded-For" or "Forwarded". trustedCount is the number of trusted
258 // reverse proxies. The IP returned will be the (trustedCount-1)th from the right. For
259 // example, if there's only one trusted proxy, this strategy will return the last
260 // (rightmost) IP address.
261 func NewRightmostTrustedCountStrategy(headerName string, trustedCount int) (RightmostTrustedCountStrategy, error) {
262 if headerName == "" {
263 return RightmostTrustedCountStrategy{}, fmt.Errorf("RightmostTrustedCountStrategy header must not be empty")
264 }
265
266 if trustedCount <= 0 {
267 return RightmostTrustedCountStrategy{}, fmt.Errorf("RightmostTrustedCountStrategy count must be greater than zero")
268 }
269
270 // We will be using the headerName for lookups in the http.Header map, which is keyed
271 // by canonicalized header name. We'll do that here so we only have to do it once.
272 headerName = http.CanonicalHeaderKey(headerName)
273
274 if headerName != xForwardedForHdr && headerName != forwardedHdr {
275 return RightmostTrustedCountStrategy{}, fmt.Errorf("RightmostNonPrivateStrategy header must be %s or %s", xForwardedForHdr, forwardedHdr)
276 }
277
278 return RightmostTrustedCountStrategy{headerName: headerName, trustedCount: trustedCount}, nil
279 }
280
281 // ClientIP derives the client IP using this strategy.
282 // headers is expected to be like http.Request.Header.
283 // The returned IP may contain a zone identifier.
284 // If no valid IP can be derived, empty string will be returned.
285 func (strat RightmostTrustedCountStrategy) ClientIP(headers http.Header, _ string) string {
286 ipAddrs := getIPAddrList(headers, strat.headerName)
287
288 // We want the (N-1)th from the rightmost. For example, if there's only one
289 // trusted proxy, we want the last.
290 rightmostIndex := len(ipAddrs) - 1
291 targetIndex := rightmostIndex - (strat.trustedCount - 1)
292
293 if targetIndex < 0 {
294 // This is a misconfiguration error. There were fewer IPs than we expected.
295 return ""
296 }
297
298 resultIP := ipAddrs[targetIndex]
299
300 if resultIP == nil {
301 // This is a misconfiguration error. Our first trusted proxy didn't add a
302 // valid IP address to the header.
303 return ""
304 }
305
306 return resultIP.String()
307 }
308
309 // AddressesAndRangesToIPNets converts a slice of strings with IPv4 and IPv6 addresses and
310 // CIDR ranges (prefixes) to net.IPNet instances.
311 // If net.ParseCIDR or net.ParseIP fail, an error will be returned.
312 // Zones in addresses or ranges are not allowed and will result in an error. This is because:
313 // a) net.ParseCIDR will fail to parse a range with a zone, and
314 // b) netip.ParsePrefix will succeed but silently throw away the zone; then
315 // netip.Prefix.Contains will return false for any IP with a zone, causing confusion and bugs.
316 func AddressesAndRangesToIPNets(ranges ...string) ([]net.IPNet, error) {
317 var result []net.IPNet
318 for _, r := range ranges {
319 if strings.Contains(r, "%") {
320 return nil, fmt.Errorf("zones are not allowed: %q", r)
321 }
322
323 if strings.Contains(r, "/") {
324 // This is a CIDR/prefix
325 _, ipNet, err := net.ParseCIDR(r)
326 if err != nil {
327 return nil, fmt.Errorf("net.ParseCIDR failed for %q: %w", r, err)
328 }
329 result = append(result, *ipNet)
330 } else {
331 // This is a single IP; convert it to a range including only itself
332 ip := net.ParseIP(r)
333 if ip == nil {
334 return nil, fmt.Errorf("net.ParseIP failed for %q", r)
335 }
336
337 // To use the right size IP and mask, we need to know if the address is IPv4 or v6.
338 // Attempt to convert it to IPv4 to find out.
339 if ipv4 := ip.To4(); ipv4 != nil {
340 ip = ipv4
341 }
342
343 // Mask all the bits
344 mask := len(ip) * 8
345 result = append(result, net.IPNet{
346 IP: ip,
347 Mask: net.CIDRMask(mask, mask),
348 })
349 }
350 }
351
352 return result, nil
353 }
354
355 // RightmostTrustedRangeStrategy derives the client IP from the rightmost valid IP address
356 // in the X-Forwarded-For or Forwarded header which is not in a set of trusted IP ranges.
357 // This strategy should be used when the IP ranges of the reverse proxies between the
358 // internet and the server are known.
359 // If a third-party WAF, CDN, etc., is used, you SHOULD use a method of verifying its
360 // access to your origin that is stronger than checking its IP address (e.g., using
361 // authenticated pulls). Failure to do so can result in scenarios like:
362 // You use AWS CloudFront in front of a server you host elsewhere. An attacker creates a
363 // CF distribution that points at your origin server. The attacker uses Lambda@Edge to
364 // spoof the Host and X-Forwarded-For headers. Now your "trusted" reverse proxy is no
365 // longer trustworthy.
366 type RightmostTrustedRangeStrategy struct {
367 headerName string
368 trustedRanges []net.IPNet
369 }
370
371 // NewRightmostTrustedRangeStrategy creates a RightmostTrustedRangeStrategy. headerName
372 // must be "X-Forwarded-For" or "Forwarded". trustedRanges must contain all trusted
373 // reverse proxies on the path to this server. trustedRanges can be private/internal or
374 // external (for example, if a third-party reverse proxy is used).
375 func NewRightmostTrustedRangeStrategy(headerName string, trustedRanges []net.IPNet) (RightmostTrustedRangeStrategy, error) {
376 if headerName == "" {
377 return RightmostTrustedRangeStrategy{}, fmt.Errorf("RightmostTrustedRangeStrategy header must not be empty")
378 }
379
380 // We will be using the headerName for lookups in the http.Header map, which is keyed
381 // by canonicalized header name. We'll do that here so we only have to do it once.
382 headerName = http.CanonicalHeaderKey(headerName)
383
384 if headerName != xForwardedForHdr && headerName != forwardedHdr {
385 return RightmostTrustedRangeStrategy{}, fmt.Errorf("RightmostTrustedRangeStrategy header must be %s or %s", xForwardedForHdr, forwardedHdr)
386 }
387
388 return RightmostTrustedRangeStrategy{headerName: headerName, trustedRanges: trustedRanges}, nil
389 }
390
391 // ClientIP derives the client IP using this strategy.
392 // headers is expected to be like http.Request.Header.
393 // The returned IP may contain a zone identifier.
394 // If no valid IP can be derived, empty string will be returned.
395 func (strat RightmostTrustedRangeStrategy) ClientIP(headers http.Header, _ string) string {
396 ipAddrs := getIPAddrList(headers, strat.headerName)
397 // Look backwards through the list of IP addresses
398 for i := len(ipAddrs) - 1; i >= 0; i-- {
399 if ipAddrs[i] != nil && isIPContainedInRanges(ipAddrs[i].IP, strat.trustedRanges) {
400 // This IP is trusted
401 continue
402 }
403
404 // At this point we have found the first-from-the-rightmost untrusted IP
405
406 if ipAddrs[i] == nil {
407 return ""
408 }
409
410 return ipAddrs[i].String()
411 }
412
413 // Either there are no addresses or they are all in our trusted ranges
414 return ""
415 }
416
417 func (strat RightmostTrustedRangeStrategy) String() string {
418 var b strings.Builder
419 b.WriteString(fmt.Sprintf("{headerName:%v trustedRanges:[", strat.headerName))
420 for i, r := range strat.trustedRanges {
421 if i > 0 {
422 b.WriteString(" ")
423 }
424 b.WriteString(r.String())
425 }
426 b.WriteString("]")
427 return b.String()
428 }
429
430 // lastHeader returns the last header with the given name. It returns empty string if the
431 // header is not found or if the header has an empty value. No validation is done on the
432 // IP string. headerName must already be canonicalized.
433 // This should be used with single-IP headers, like X-Real-IP. Per RFC 2616, they should
434 // not have multiple headers, but if they do we can hope we're getting the newest/best by
435 // taking the last instance.
436 // This MUST NOT be used with list headers, like X-Forwarded-For and Forwarded.
437 func lastHeader(headers http.Header, headerName string) string {
438 // Note that Go's Header map uses canonicalized keys
439 matches, ok := headers[headerName]
440 if !ok || len(matches) == 0 {
441 // For our uses of this function, returning an empty string in this case is fine
442 return ""
443 }
444
445 return matches[len(matches)-1]
446 }
447
448 // getIPAddrList creates a single list of all of the X-Forwarded-For or Forwarded header
449 // values, in order. Any invalid IPs will result in nil elements. headerName must already
450 // be canonicalized.
451 func getIPAddrList(headers http.Header, headerName string) []*net.IPAddr {
452 var result []*net.IPAddr
453
454 // There may be multiple XFF headers present. We need to iterate through them all,
455 // in order, and collect all of the IPs.
456 // Note that we're not joining all of the headers into a single string and then
457 // splitting. Doing it that way would use more memory.
458 // Note that Go's Header map uses canonicalized keys.
459 for _, h := range headers[headerName] {
460 // We now have a string with comma-separated list items
461 for _, rawListItem := range strings.Split(h, ",") {
462 // The IPs are often comma-space separated, so we'll need to trim the string
463 rawListItem = strings.TrimSpace(rawListItem)
464
465 var ipAddr *net.IPAddr
466 // If this is the XFF header, rawListItem is just an IP;
467 // if it's the Forwarded header, then there's more parsing to do.
468 if headerName == forwardedHdr {
469 ipAddr = parseForwardedListItem(rawListItem)
470 } else { // == XFF
471 ipAddr = goodIPAddr(rawListItem)
472 }
473
474 // ipAddr is nil if not valid
475 result = append(result, ipAddr)
476 }
477 }
478
479 // Possible performance improvements:
480 // Here we are parsing _all_ of the IPs in the XFF headers, but we don't need all of
481 // them. Instead, we could start from the left or the right (depending on strategy),
482 // parse as we go, and stop when we've come to the one we want. But that would make
483 // the various strategies somewhat more complex.
484
485 return result
486 }
487
488 // parseForwardedListItem parses a Forwarded header list item, and returns the "for" IP
489 // address. Nil is returned if the "for" IP is absent or invalid.
490 func parseForwardedListItem(fwd string) *net.IPAddr {
491 // The header list item can look like these kinds of thing:
492 // For="[2001:db8:cafe::17%zone]:4711"
493 // For="[2001:db8:cafe::17%zone]"
494 // for=192.0.2.60;proto=http; by=203.0.113.43
495 // for=192.0.2.43
496
497 // First split up "for=", "by=", "host=", etc.
498 fwdParts := strings.Split(fwd, ";")
499
500 // Find the "for=" part, since that has the IP we want (maybe)
501 var forPart string
502 for _, fp := range fwdParts {
503 // Whitespace is allowed around the semicolons
504 fp = strings.TrimSpace(fp)
505
506 fpSplit := strings.Split(fp, "=")
507 if len(fpSplit) != 2 {
508 // There are too many or too few equal signs in this part
509 continue
510 }
511
512 if strings.EqualFold(fpSplit[0], "for") {
513 // We found the "for=" part
514 forPart = fpSplit[1]
515 break
516 }
517 }
518
519 // There shouldn't (per RFC 7239) be spaces around the semicolon or equal sign. It might
520 // be more correct to consider spaces an error, but we'll tolerate and trim them.
521 forPart = strings.TrimSpace(forPart)
522
523 // Get rid of any quotes, such as surrounding IPv6 addresses.
524 // Note that doing this without checking if the quotes are present means that we are
525 // effectively accepting IPv6 addresses that don't strictly conform to RFC 7239, which
526 // requires quotes. https://www.rfc-editor.org/rfc/rfc7239#section-4
527 // This behaviour is debatable.
528 // It also means that we will accept IPv4 addresses with quotes, which is correct.
529 forPart = trimMatchedEnds(forPart, `"`)
530
531 if forPart == "" {
532 // We failed to find a "for=" part
533 return nil
534 }
535
536 ipAddr := goodIPAddr(forPart)
537 if ipAddr == nil {
538 // The IP extracted from the "for=" part isn't valid
539 return nil
540 }
541
542 return ipAddr
543 }
544
545 // ParseIPAddr parses the given string into a net.IPAddr, which is a useful type for
546 // dealing with IPs have zones. The Go stdlib net package is lacking such a function.
547 // This will also discard any port number from the input.
548 func ParseIPAddr(ipStr string) (net.IPAddr, error) {
549 host, _, err := net.SplitHostPort(ipStr)
550 if err == nil {
551 ipStr = host
552 }
553 // We continue even if net.SplitHostPort returned an error. This is because it may
554 // complain that there are "too many colons" in an IPv6 address that has no brackets
555 // and no port. net.ParseIP will be the final arbiter of validity.
556
557 // Square brackets around IPv6 addresses may be used in the Forwarded header.
558 // net.ParseIP doesn't like them, so we'll trim them off.
559 ipStr = trimMatchedEnds(ipStr, "[]")
560
561 ipStr, zone := SplitHostZone(ipStr)
562
563 res := net.IPAddr{
564 IP: net.ParseIP(ipStr),
565 Zone: zone,
566 }
567
568 if res.IP == nil {
569 return net.IPAddr{}, fmt.Errorf("net.ParseIP failed")
570 }
571
572 return res, nil
573 }
574
575 // MustParseIPAddr panics if ParseIPAddr fails.
576 func MustParseIPAddr(ipStr string) net.IPAddr {
577 ipAddr, err := ParseIPAddr(ipStr)
578 if err != nil {
579 panic(fmt.Sprintf("ParseIPAddr failed: %v", err))
580 }
581 return ipAddr
582 }
583
584 // goodIPAddr wraps ParseIPAddr and adds a check for unspecified (like "::") and zero-value
585 // addresses (like "0.0.0.0"). These are nominally valid IPs (net.ParseIP will accept them),
586 // but they are undesirable for the purposes of this library.
587 // Note that this function should be the only use of ParseIPAddr in this library.
588 func goodIPAddr(ipStr string) *net.IPAddr {
589 ipAddr, err := ParseIPAddr(ipStr)
590 if err != nil {
591 return nil
592 }
593
594 if ipAddr.IP.IsUnspecified() {
595 return nil
596 }
597
598 return &ipAddr
599 }
600
601 // SplitHostZone splits a "host%zone" string into its components. If there is no zone,
602 // host is the original input and zone is empty.
603 func SplitHostZone(s string) (host, zone string) {
604 // This is copied from an unexported function in the Go stdlib:
605 // https://github.com/golang/go/blob/5c9b6e8e63e012513b1cb1a4a08ff23dec4137a1/src/net/ipsock.go#L219-L228
606
607 // The IPv6 scoped addressing zone identifier starts after the last percent sign.
608 if i := strings.LastIndexByte(s, '%'); i > 0 {
609 host, zone = s[:i], s[i+1:]
610 } else {
611 host = s
612 }
613 return
614 }
615
616 // mustParseCIDR panics if net.ParseCIDR fails
617 func mustParseCIDR(s string) net.IPNet {
618 _, ipNet, err := net.ParseCIDR(s)
619 if err != nil {
620 panic(err)
621 }
622 return *ipNet
623 }
624
625 // privateAndLocalRanges net.IPNets that are loopback, private, link local, default unicast.
626 // Based on https://github.com/wader/filtertransport/blob/bdd9e61eee7804e94ceb927c896b59920345c6e4/filter.go#L36-L64
627 // which is based on https://github.com/letsencrypt/boulder/blob/master/bdns/dns.go
628 var privateAndLocalRanges = []net.IPNet{
629 mustParseCIDR("10.0.0.0/8"), // RFC1918
630 mustParseCIDR("172.16.0.0/12"), // private
631 mustParseCIDR("192.168.0.0/16"), // private
632 mustParseCIDR("127.0.0.0/8"), // RFC5735
633 mustParseCIDR("0.0.0.0/8"), // RFC1122 Section 3.2.1.3
634 mustParseCIDR("169.254.0.0/16"), // RFC3927
635 mustParseCIDR("192.0.0.0/24"), // RFC 5736
636 mustParseCIDR("192.0.2.0/24"), // RFC 5737
637 mustParseCIDR("198.51.100.0/24"), // Assigned as TEST-NET-2
638 mustParseCIDR("203.0.113.0/24"), // Assigned as TEST-NET-3
639 mustParseCIDR("192.88.99.0/24"), // RFC 3068
640 mustParseCIDR("192.18.0.0/15"), // RFC 2544
641 mustParseCIDR("224.0.0.0/4"), // RFC 3171
642 mustParseCIDR("240.0.0.0/4"), // RFC 1112
643 mustParseCIDR("255.255.255.255/32"), // RFC 919 Section 7
644 mustParseCIDR("100.64.0.0/10"), // RFC 6598
645 mustParseCIDR("::/128"), // RFC 4291: Unspecified Address
646 mustParseCIDR("::1/128"), // RFC 4291: Loopback Address
647 mustParseCIDR("100::/64"), // RFC 6666: Discard Address Block
648 mustParseCIDR("2001::/23"), // RFC 2928: IETF Protocol Assignments
649 mustParseCIDR("2001:2::/48"), // RFC 5180: Benchmarking
650 mustParseCIDR("2001:db8::/32"), // RFC 3849: Documentation
651 mustParseCIDR("2001::/32"), // RFC 4380: TEREDO
652 mustParseCIDR("fc00::/7"), // RFC 4193: Unique-Local
653 mustParseCIDR("fe80::/10"), // RFC 4291: Section 2.5.6 Link-Scoped Unicast
654 mustParseCIDR("ff00::/8"), // RFC 4291: Section 2.7
655 mustParseCIDR("2002::/16"), // RFC 7526: 6to4 anycast prefix deprecated
656 }
657
658 // isIPContainedInRanges returns true if the given IP is contained in at least one of the given ranges
659 func isIPContainedInRanges(ip net.IP, ranges []net.IPNet) bool {
660 for _, r := range ranges {
661 if r.Contains(ip) {
662 return true
663 }
664 }
665 return false
666 }
667
668 // isPrivateOrLocal return true if the given IP address is private, local, or otherwise
669 // not suitable for an external client IP.
670 func isPrivateOrLocal(ip net.IP) bool {
671 return isIPContainedInRanges(ip, privateAndLocalRanges)
672 }
673
674 // trimMatchedEnds trims s if and only if the first and last bytes in s are in chars.
675 // If chars is a single character (like `"`), then the first and last bytes must match
676 // that single character. If chars is two characters (like `[]`), the first byte in s
677 // must match the first byte in chars, and the last bytes in s must match the last byte
678 // in chars.
679 // This helps us ensure that we only trim _matched_ quotes and brackets,
680 // which strings.Trim doesn't provide.
681 func trimMatchedEnds(s string, chars string) string {
682 if len(chars) != 1 && len(chars) != 2 {
683 panic("trimMatchedEnds chars must be length 1 or 2")
684 }
685
686 first, last := chars[0], chars[0]
687 if len(chars) > 1 {
688 last = chars[1]
689 }
690
691 if len(s) < 2 {
692 return s
693 }
694
695 if s[0] != first {
696 return s
697 }
698
699 if s[len(s)-1] != last {
700 return s
701 }
702
703 return s[1 : len(s)-1]
704 }