client_ip.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package request // import "miniflux.app/v2/internal/http/request"
  4. import (
  5. "net"
  6. "net/http"
  7. "strings"
  8. )
  9. // IsTrustedIP reports whether the given remote IP address belongs to one of the trusted networks.
  10. func IsTrustedIP(remoteIP string, trustedNetworks []string) bool {
  11. if len(trustedNetworks) == 0 {
  12. return false
  13. }
  14. ip := net.ParseIP(remoteIP)
  15. if ip == nil {
  16. return false
  17. }
  18. for _, cidr := range trustedNetworks {
  19. _, network, err := net.ParseCIDR(cidr)
  20. if err != nil {
  21. continue
  22. }
  23. if network.Contains(ip) {
  24. return true
  25. }
  26. }
  27. return false
  28. }
  29. // FindClientIP returns the real client IP address using trusted reverse-proxy headers when allowed.
  30. func FindClientIP(r *http.Request, isTrustedProxyClient bool, trustedNetworks []string) string {
  31. if isTrustedProxyClient {
  32. headers := [...]string{"X-Forwarded-For", "X-Real-Ip"}
  33. for _, header := range headers {
  34. value := strings.Join(r.Header.Values(header), ",")
  35. if value != "" {
  36. // Proxies append to the list, so skip trusted hops from the right.
  37. addresses := strings.Split(value, ",")
  38. i := len(addresses) - 1
  39. for i > 0 && IsTrustedIP(dropIPv6zone(strings.TrimSpace(addresses[i])), trustedNetworks) {
  40. i--
  41. }
  42. address := strings.TrimSpace(addresses[i])
  43. address = dropIPv6zone(address)
  44. if net.ParseIP(address) != nil {
  45. return address
  46. }
  47. }
  48. }
  49. }
  50. // Fallback to TCP/IP source IP address.
  51. return FindRemoteIP(r)
  52. }
  53. // FindRemoteIP returns the parsed remote IP address from the request,
  54. // falling back to 127.0.0.1 if the address is empty, a unix socket, or invalid.
  55. func FindRemoteIP(r *http.Request) string {
  56. if r.RemoteAddr == "@" || r.RemoteAddr == "" {
  57. return "127.0.0.1"
  58. }
  59. // If it looks like it has a port (IPv4:port or [IPv6]:port), try to split it.
  60. ip, _, err := net.SplitHostPort(r.RemoteAddr)
  61. if err != nil {
  62. // No port — could be a bare IPv4, IPv6, or IPv6 with zone.
  63. ip = r.RemoteAddr
  64. }
  65. // Strip IPv6 zone identifier if present (e.g., %eth0).
  66. ip = dropIPv6zone(ip)
  67. // Validate the IP address.
  68. if net.ParseIP(ip) == nil {
  69. return "127.0.0.1"
  70. }
  71. return ip
  72. }
  73. func dropIPv6zone(address string) string {
  74. idx := strings.IndexByte(address, '%')
  75. if idx != -1 {
  76. address = address[:idx]
  77. }
  78. return address
  79. }