PageRenderTime 42ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/actionpack/lib/action_dispatch/middleware/remote_ip.rb

https://github.com/lihanli/rails
Ruby | 187 lines | 82 code | 18 blank | 87 comment | 5 complexity | d3980bdd110db51b61ae1562eeee8519 MD5 | raw file
  1. module ActionDispatch
  2. # This middleware calculates the IP address of the remote client that is
  3. # making the request. It does this by checking various headers that could
  4. # contain the address, and then picking the last-set address that is not
  5. # on the list of trusted IPs. This follows the precedent set by e.g.
  6. # {the Tomcat server}[https://issues.apache.org/bugzilla/show_bug.cgi?id=50453],
  7. # with {reasoning explained at length}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection]
  8. # by @gingerlime. A more detailed explanation of the algorithm is given
  9. # at GetIp#calculate_ip.
  10. #
  11. # Some Rack servers concatenate repeated headers, like {HTTP RFC 2616}[http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2]
  12. # requires. Some Rack servers simply drop preceding headers, and only report
  13. # the value that was {given in the last header}[http://andre.arko.net/2011/12/26/repeated-headers-and-ruby-web-servers].
  14. # If you are behind multiple proxy servers (like Nginx to HAProxy to Unicorn)
  15. # then you should test your Rack server to make sure your data is good.
  16. #
  17. # IF YOU DON'T USE A PROXY, THIS MAKES YOU VULNERABLE TO IP SPOOFING.
  18. # This middleware assumes that there is at least one proxy sitting around
  19. # and setting headers with the client's remote IP address. If you don't use
  20. # a proxy, because you are hosted on e.g. Heroku without SSL, any client can
  21. # claim to have any IP address by setting the X-Forwarded-For header. If you
  22. # care about that, then you need to explicitly drop or ignore those headers
  23. # sometime before this middleware runs.
  24. class RemoteIp
  25. class IpSpoofAttackError < StandardError; end
  26. # The default trusted IPs list simply includes IP addresses that are
  27. # guaranteed by the IP specification to be private addresses. Those will
  28. # not be the ultimate client IP in production, and so are discarded. See
  29. # http://en.wikipedia.org/wiki/Private_network for details.
  30. TRUSTED_PROXIES = %r{
  31. ^127\.0\.0\.1$ | # localhost IPv4
  32. ^::1$ | # localhost IPv6
  33. ^fc00: | # private IPv6 range fc00
  34. ^10\. | # private IPv4 range 10.x.x.x
  35. ^172\.(1[6-9]|2[0-9]|3[0-1])\.| # private IPv4 range 172.16.0.0 .. 172.31.255.255
  36. ^192\.168\. # private IPv4 range 192.168.x.x
  37. }x
  38. attr_reader :check_ip, :proxies
  39. # Create a new +RemoteIp+ middleware instance.
  40. #
  41. # The +check_ip_spoofing+ option is on by default. When on, an exception
  42. # is raised if it looks like the client is trying to lie about its own IP
  43. # address. It makes sense to turn off this check on sites aimed at non-IP
  44. # clients (like WAP devices), or behind proxies that set headers in an
  45. # incorrect or confusing way (like AWS ELB).
  46. #
  47. # The +custom_trusted+ argument can take a regex, which will be used
  48. # instead of +TRUSTED_PROXIES+, or a string, which will be used in addition
  49. # to +TRUSTED_PROXIES+. Any proxy setup will put the value you want in the
  50. # middle (or at the beginning) of the X-Forwarded-For list, with your proxy
  51. # servers after it. If your proxies aren't removed, pass them in via the
  52. # +custom_trusted+ parameter. That way, the middleware will ignore those
  53. # IP addresses, and return the one that you want.
  54. def initialize(app, check_ip_spoofing = true, custom_proxies = nil)
  55. @app = app
  56. @check_ip = check_ip_spoofing
  57. @proxies = case custom_proxies
  58. when Regexp
  59. custom_proxies
  60. when nil
  61. TRUSTED_PROXIES
  62. else
  63. Regexp.union(TRUSTED_PROXIES, custom_proxies)
  64. end
  65. end
  66. # Since the IP address may not be needed, we store the object here
  67. # without calculating the IP to keep from slowing down the majority of
  68. # requests. For those requests that do need to know the IP, the
  69. # GetIp#calculate_ip method will calculate the memoized client IP address.
  70. def call(env)
  71. env["action_dispatch.remote_ip"] = GetIp.new(env, self)
  72. @app.call(env)
  73. end
  74. # The GetIp class exists as a way to defer processing of the request data
  75. # into an actual IP address. If the ActionDispatch::Request#remote_ip method
  76. # is called, this class will calculate the value and then memoize it.
  77. class GetIp
  78. # This constant contains a regular expression that validates every known
  79. # form of IP v4 and v6 address, with or without abbreviations, adapted
  80. # from {this gist}[https://gist.github.com/gazay/1289635].
  81. VALID_IP = %r{
  82. (^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[0-9]{1,2})){3}$) | # ip v4
  83. (^(
  84. (([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}) | # ip v6 not abbreviated
  85. (([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4}) | # ip v6 with double colon in the end
  86. (([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4}) | # - ip addresses v6
  87. (([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4}) | # - with
  88. (([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4}) | # - double colon
  89. (([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4}) | # - in the middle
  90. (([0-9A-Fa-f]{1,4}:){6} ((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3} (\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
  91. (([0-9A-Fa-f]{1,4}:){1,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
  92. (([0-9A-Fa-f]{1,4}:){1}:([0-9A-Fa-f]{1,4}:){0,4}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
  93. (([0-9A-Fa-f]{1,4}:){0,2}:([0-9A-Fa-f]{1,4}:){0,3}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
  94. (([0-9A-Fa-f]{1,4}:){0,3}:([0-9A-Fa-f]{1,4}:){0,2}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
  95. (([0-9A-Fa-f]{1,4}:){0,4}:([0-9A-Fa-f]{1,4}:){1}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
  96. (::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d) |(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)) | # ip v6 with compatible to v4
  97. ([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4}) | # ip v6 with compatible to v4
  98. (::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4}) | # ip v6 with double colon at the beginning
  99. (([0-9A-Fa-f]{1,4}:){1,7}:) # ip v6 without ending
  100. )$)
  101. }x
  102. def initialize(env, middleware)
  103. @env = env
  104. @check_ip = middleware.check_ip
  105. @proxies = middleware.proxies
  106. end
  107. # Sort through the various IP address headers, looking for the IP most
  108. # likely to be the address of the actual remote client making this
  109. # request.
  110. #
  111. # REMOTE_ADDR will be correct if the request is made directly against the
  112. # Ruby process, on e.g. Heroku. When the request is proxied by another
  113. # server like HAProxy or Nginx, the IP address that made the original
  114. # request will be put in an X-Forwarded-For header. If there are multiple
  115. # proxies, that header may contain a list of IPs. Other proxy services
  116. # set the Client-Ip header instead, so we check that too.
  117. #
  118. # As discussed in {this post about Rails IP Spoofing}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/],
  119. # while the first IP in the list is likely to be the "originating" IP,
  120. # it could also have been set by the client maliciously.
  121. #
  122. # In order to find the first address that is (probably) accurate, we
  123. # take the list of IPs, remove known and trusted proxies, and then take
  124. # the last address left, which was presumably set by one of those proxies.
  125. def calculate_ip
  126. # Set by the Rack web server, this is a single value.
  127. remote_addr = ips_from('REMOTE_ADDR').last
  128. # Could be a CSV list and/or repeated headers that were concatenated.
  129. client_ips = ips_from('HTTP_CLIENT_IP').reverse
  130. forwarded_ips = ips_from('HTTP_X_FORWARDED_FOR').reverse
  131. # +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set.
  132. # If they are both set, it means that this request passed through two
  133. # proxies with incompatible IP header conventions, and there is no way
  134. # for us to determine which header is the right one after the fact.
  135. # Since we have no idea, we give up and explode.
  136. should_check_ip = @check_ip && client_ips.last && forwarded_ips.last
  137. if should_check_ip && !forwarded_ips.include?(client_ips.last)
  138. # We don't know which came from the proxy, and which from the user
  139. raise IpSpoofAttackError, "IP spoofing attack?! " +
  140. "HTTP_CLIENT_IP=#{@env['HTTP_CLIENT_IP'].inspect} " +
  141. "HTTP_X_FORWARDED_FOR=#{@env['HTTP_X_FORWARDED_FOR'].inspect}"
  142. end
  143. # We assume these things about the IP headers:
  144. #
  145. # - X-Forwarded-For will be a list of IPs, one per proxy, or blank
  146. # - Client-Ip is propagated from the outermost proxy, or is blank
  147. # - REMOTE_ADDR will be the IP that made the request to Rack
  148. ips = [forwarded_ips, client_ips, remote_addr].flatten.compact
  149. # If every single IP option is in the trusted list, just return REMOTE_ADDR
  150. filter_proxies(ips).first || remote_addr
  151. end
  152. # Memoizes the value returned by #calculate_ip and returns it for
  153. # ActionDispatch::Request to use.
  154. def to_s
  155. @ip ||= calculate_ip
  156. end
  157. protected
  158. def ips_from(header)
  159. # Split the comma-separated list into an array of strings
  160. ips = @env[header] ? @env[header].strip.split(/[,\s]+/) : []
  161. # Only return IPs that are valid according to the regex
  162. ips.select{ |ip| ip =~ VALID_IP }
  163. end
  164. def filter_proxies(ips)
  165. ips.reject { |ip| ip =~ @proxies }
  166. end
  167. end
  168. end
  169. end