diff options
Diffstat (limited to 'activesupport/lib/active_support/message_verifier.rb')
-rw-r--r-- | activesupport/lib/active_support/message_verifier.rb | 21 |
1 files changed, 17 insertions, 4 deletions
diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb index b24acb9f47..74e080a23d 100644 --- a/activesupport/lib/active_support/message_verifier.rb +++ b/activesupport/lib/active_support/message_verifier.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/string/bytesize' + module ActiveSupport # MessageVerifier makes it easy to generate and verify messages which are signed # to prevent tampering. @@ -25,10 +27,10 @@ module ActiveSupport def verify(signed_message) data, digest = signed_message.split("--") - if digest != generate_digest(data) - raise InvalidSignature - else + if secure_compare(digest, generate_digest(data)) Marshal.load(ActiveSupport::Base64.decode64(data)) + else + raise InvalidSignature end end @@ -38,9 +40,20 @@ module ActiveSupport end private + # constant-time comparison algorithm to prevent timing attacks + def secure_compare(a, b) + return false unless a.bytesize == b.bytesize + + l = a.unpack "C#{a.bytesize}" + + res = 0 + b.each_byte { |byte| res |= byte ^ l.shift } + res == 0 + end + def generate_digest(data) require 'openssl' unless defined?(OpenSSL) - OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(@digest), @secret, data) + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@digest).new, @secret, data) end end end |