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

Needless measures to against timing attack #43

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 1 addition & 12 deletions lib/jwt.rb
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def signature_algorithm_and_key(header, key, &keyfinder)
def verify_signature(algo, key, signing_input, signature)
begin
if ["HS256", "HS384", "HS512"].include?(algo)
raise JWT::DecodeError.new("Signature verification failed") unless secure_compare(signature, sign_hmac(algo, signing_input, key))
raise JWT::DecodeError.new("Signature verification failed") unless signature == sign_hmac(algo, signing_input, key)
elsif ["RS256", "RS384", "RS512"].include?(algo)
raise JWT::DecodeError.new("Signature verification failed") unless verify_rsa(algo, key, signing_input, signature)
else
Expand All @@ -129,15 +129,4 @@ def verify_signature(algo, key, signing_input, signature)
end
end

# From devise
# constant-time comparison algorithm to prevent timing attacks
def secure_compare(a, b)
return false if a.nil? || b.nil? || a.empty? || b.empty? || a.bytesize != b.bytesize
l = a.unpack "C#{a.bytesize}"

res = 0
b.each_byte { |byte| res |= byte ^ l.shift }
res == 0
end

end
30 changes: 0 additions & 30 deletions spec/jwt_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,36 +109,6 @@
expect { JWT.decode(jwt, nil, true) }.to raise_error(JWT::DecodeError)
end

it "does not use == to compare digests" do
secret = "secret"
jwt = JWT.encode(@payload, secret)
crypto_segment = jwt.split(".").last

signature = JWT.base64url_decode(crypto_segment)
expect(signature).not_to receive('==')
expect(JWT).to receive(:base64url_decode).with(crypto_segment).once.and_return(signature)
expect(JWT).to receive(:base64url_decode).at_least(:once).and_call_original

JWT.decode(jwt, secret)
end

describe "secure comparison" do
it "returns true if strings are equal" do
expect(JWT.secure_compare("Foo", "Foo")).to be_true
end

it "returns false if either input is nil or empty" do
[nil, ""].each do |bad|
expect(JWT.secure_compare(bad, "Foo")).to be_false
expect(JWT.secure_compare("Foo", bad)).to be_false
end
end

it "retuns false if the strings are different" do
expect(JWT.secure_compare("Foo", "Bar")).to be_false
end
end

# no method should leave OpenSSL.errors populated
after do
expect(OpenSSL.errors).to be_empty
Expand Down