class ActionDispatch::HostAuthorization

This middleware guards from DNS rebinding attacks by explicitly permitting the hosts a request can be sent to, and is passed the options set in config.host_authorization.

Requests can opt-out of Host Authorization with exclude:

config.host_authorization = { exclude: ->(request) { request.path =~ /healthcheck/ } }

When a request comes to an unauthorized host, the response_app application will be executed and rendered. If no response_app is given, a default one will run. The default response app logs blocked host info with level ‘error’ and responds with 403 Forbidden. The body of the response contains debug info if config.consider_all_requests_local is set to true, otherwise the body is empty.

Constants

ALLOWED_HOSTS_IN_DEVELOPMENT

Public Class Methods

new(app, hosts, exclude: nil, response_app: nil) click to toggle source
# File lib/action_dispatch/middleware/host_authorization.rb, line 122
def initialize(app, hosts, exclude: nil, response_app: nil)
  @app = app
  @permissions = Permissions.new(hosts)
  @exclude = exclude

  @response_app = response_app || DefaultResponseApp.new
end

Public Instance Methods

call(env) click to toggle source
# File lib/action_dispatch/middleware/host_authorization.rb, line 130
def call(env)
  return @app.call(env) if @permissions.empty?

  request = Request.new(env)
  hosts = blocked_hosts(request)

  if hosts.empty? || excluded?(request)
    mark_as_authorized(request)
    @app.call(env)
  else
    env["action_dispatch.blocked_hosts"] = hosts
    @response_app.call(env)
  end
end

Private Instance Methods

blocked_hosts(request) click to toggle source
# File lib/action_dispatch/middleware/host_authorization.rb, line 146
def blocked_hosts(request)
  hosts = []

  origin_host = request.get_header("HTTP_HOST")
  hosts << origin_host unless @permissions.allows?(origin_host)

  forwarded_host = request.x_forwarded_host&.split(/,\s?/)&.last
  hosts << forwarded_host unless forwarded_host.blank? || @permissions.allows?(forwarded_host)

  hosts
end
excluded?(request) click to toggle source
# File lib/action_dispatch/middleware/host_authorization.rb, line 158
def excluded?(request)
  @exclude && @exclude.call(request)
end
mark_as_authorized(request) click to toggle source
# File lib/action_dispatch/middleware/host_authorization.rb, line 162
def mark_as_authorized(request)
  request.set_header("action_dispatch.authorized_host", request.host)
end