Skip to content

Commit 8aa6c42

Browse files
jeltzZachary Scott
authored and
Zachary Scott
committed
Use secure_compare when checking CSRF token
Since string comparisions may return early we want to use a constant time comparsion function to protect the CSRF token against timing attacks. Rack::Utils provides a such function.
1 parent c419868 commit 8aa6c42

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
lines changed

Diff for: rack-protection/lib/rack/protection/authenticity_token.rb

+2-2
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ def accepts?(env)
2323
session = session env
2424
token = session[:csrf] ||= session['_csrf_token'] || random_string
2525
safe?(env) ||
26-
env['HTTP_X_CSRF_TOKEN'] == token ||
27-
Request.new(env).params[options[:authenticity_param]] == token
26+
secure_compare(env['HTTP_X_CSRF_TOKEN'], token) ||
27+
secure_compare(Request.new(env).params[options[:authenticity_param]], token)
2828
end
2929
end
3030
end

Diff for: rack-protection/lib/rack/protection/base.rb

+5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
require 'rack/protection'
2+
require 'rack/utils'
23
require 'digest'
34
require 'logger'
45
require 'uri'
@@ -110,6 +111,10 @@ def encrypt(value)
110111
options[:encryptor].hexdigest value.to_s
111112
end
112113

114+
def secure_compare(a, b)
115+
Rack::Utils.secure_compare(a.to_s, b.to_s)
116+
end
117+
113118
alias default_reaction deny
114119

115120
def html?(headers)

0 commit comments

Comments
 (0)