Skip to content

Commit

Permalink
Merge pull request #1672 from 18F/margolis-host-headers
Browse files Browse the repository at this point in the history
Remove HTTP Host header entirely
  • Loading branch information
zachmargolis authored Sep 14, 2017
2 parents 577cdf2 + b43c871 commit 1f6afcd
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 1 deletion.
3 changes: 2 additions & 1 deletion config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ class Application < Rails::Application
event.payload.except(:params, :headers)
end

config.middleware.insert_before 0, Rack::HeadersFilter
require 'headers_filter'
config.middleware.insert_before 0, HeadersFilter

config.middleware.insert_before 0, Rack::Cors do
allow do
Expand Down
21 changes: 21 additions & 0 deletions lib/headers_filter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
require 'rack/headers_filter'

# Expands on Rack::HeadersFilter to delete additional headers
class HeadersFilter
HEADERS_TO_DELETE = Rack::HeadersFilter::SENSITIVE_HEADERS + %w[
HTTP_HOST
]

def initialize(app)
@app = app
end

def call(env)
HEADERS_TO_DELETE.each { |header| env.delete(header) }
app.call(env)
end

private

attr_reader :app
end
21 changes: 21 additions & 0 deletions spec/lib/headers_filter_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
require 'rails_helper'

RSpec.describe HeadersFilter do
let(:app) { double('App', call: nil) }

let(:middleware) { HeadersFilter.new(app) }

describe '#call' do
it 'removes untrusted headers from the env' do
env = {
'HTTP_HOST' => 'foobar.com',
'HTTP_X_FORWARDED_HOST' => 'evil.com',
}

middleware.call(env)

expect(env).to_not have_key('HTTP_HOST')
expect(env).to_not have_key('HTTP_X_FORWARDED_HOST')
end
end
end
6 changes: 6 additions & 0 deletions spec/requests/headers_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,10 @@

expect(response.body).to_not include('evil.com')
end

it 'does not blow up with a malicious host value' do
get root_path, headers: { 'Host' => "mTpvPME6'));select pg_sleep(9); --" }

expect(response.code.to_i).to eq(200)
end
end

0 comments on commit 1f6afcd

Please sign in to comment.