Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent timing attack on CSRF #123

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 12 additions & 1 deletion lib/omniauth/strategies/oauth2.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def callback_phase # rubocop:disable AbcSize, CyclomaticComplexity, MethodLength
error = request.params["error_reason"] || request.params["error"]
if error
fail!(error, CallbackError.new(request.params["error"], request.params["error_description"] || request.params["error_reason"], request.params["error_uri"]))
elsif !options.provider_ignores_state && (request.params["state"].to_s.empty? || request.params["state"] != session.delete("omniauth.state"))
elsif !options.provider_ignores_state && (request.params["state"].to_s.empty? || !secure_compare(request.params["state"], session.delete("omniauth.state")))
fail!(:csrf_detected, CallbackError.new(:csrf_detected, "CSRF detected"))
else
self.access_token = build_access_token
Expand Down Expand Up @@ -105,6 +105,17 @@ def options_for(option)
hash
end

# constant-time comparison algorithm to prevent timing attacks
def secure_compare(string_a, string_b)
return false unless string_a.bytesize == string_b.bytesize

l = string_a.unpack "C#{string_a.bytesize}"

res = 0
string_b.each_byte { |byte| res |= byte ^ l.shift }
res.zero?
end

# An error that is indicated in the OAuth 2.0 callback.
# This could be a `redirect_uri_mismatch` or other
class CallbackError < StandardError
Expand Down
10 changes: 10 additions & 0 deletions spec/omniauth/strategies/oauth2_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ def app
instance.callback_phase
end
end

describe "#secure_params" do

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
describe "#secure_params" do
describe "#secure_compare" do

subject { fresh_strategy }

it "returns true when the two inputs are the same and false otherwise" do
instance = subject.new("abc", "def")
expect(instance.send(:secure_compare, "a", "a")).to be true
expect(instance.send(:secure_compare, "b", "a")).to be false
end
end
end

describe OmniAuth::Strategies::OAuth2::CallbackError do
Expand Down