2009-09-25 01:43:23 -04:00
|
|
|
require 'active_support/core_ext/string/bytesize'
|
|
|
|
|
2008-11-23 09:29:11 -05:00
|
|
|
module ActiveSupport
|
|
|
|
# MessageVerifier makes it easy to generate and verify messages which are signed
|
|
|
|
# to prevent tampering.
|
|
|
|
#
|
|
|
|
# This is useful for cases like remember-me tokens and auto-unsubscribe links where the
|
|
|
|
# session store isn't suitable or available.
|
|
|
|
#
|
|
|
|
# Remember Me:
|
2008-11-23 10:33:56 -05:00
|
|
|
# cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now])
|
2008-11-23 09:29:11 -05:00
|
|
|
#
|
|
|
|
# In the authentication filter:
|
|
|
|
#
|
2008-11-23 10:33:56 -05:00
|
|
|
# id, time = @verifier.verify(cookies[:remember_me])
|
2008-11-23 09:29:11 -05:00
|
|
|
# if time < Time.now
|
|
|
|
# self.current_user = User.find(id)
|
|
|
|
# end
|
|
|
|
#
|
|
|
|
class MessageVerifier
|
|
|
|
class InvalidSignature < StandardError; end
|
|
|
|
|
|
|
|
def initialize(secret, digest = 'SHA1')
|
|
|
|
@secret = secret
|
|
|
|
@digest = digest
|
|
|
|
end
|
|
|
|
|
2008-11-23 10:33:56 -05:00
|
|
|
def verify(signed_message)
|
2009-10-05 08:27:54 -04:00
|
|
|
raise InvalidSignature if signed_message.blank?
|
|
|
|
|
2008-11-23 09:29:11 -05:00
|
|
|
data, digest = signed_message.split("--")
|
2009-10-08 21:26:08 -04:00
|
|
|
if data.present? && digest.present? && secure_compare(digest, generate_digest(data))
|
2008-11-23 09:29:11 -05:00
|
|
|
Marshal.load(ActiveSupport::Base64.decode64(data))
|
2009-08-13 13:03:08 -04:00
|
|
|
else
|
|
|
|
raise InvalidSignature
|
2008-11-23 09:29:11 -05:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2008-11-23 10:33:56 -05:00
|
|
|
def generate(value)
|
2008-11-23 09:29:11 -05:00
|
|
|
data = ActiveSupport::Base64.encode64s(Marshal.dump(value))
|
|
|
|
"#{data}--#{generate_digest(data)}"
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
2009-09-13 03:32:30 -04:00
|
|
|
# constant-time comparison algorithm to prevent timing attacks
|
|
|
|
def secure_compare(a, b)
|
|
|
|
return false unless a.bytesize == b.bytesize
|
2009-09-12 15:35:03 -04:00
|
|
|
|
2009-09-13 03:32:30 -04:00
|
|
|
l = a.unpack "C#{a.bytesize}"
|
|
|
|
|
|
|
|
res = 0
|
2009-09-13 08:56:21 -04:00
|
|
|
b.each_byte { |byte| res |= byte ^ l.shift }
|
2009-09-13 03:32:30 -04:00
|
|
|
res == 0
|
2009-08-13 13:03:08 -04:00
|
|
|
end
|
|
|
|
|
2008-11-23 09:29:11 -05:00
|
|
|
def generate_digest(data)
|
2008-11-23 18:29:03 -05:00
|
|
|
require 'openssl' unless defined?(OpenSSL)
|
2009-09-25 01:43:45 -04:00
|
|
|
OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@digest).new, @secret, data)
|
2008-11-23 09:29:11 -05:00
|
|
|
end
|
|
|
|
end
|
2008-11-23 18:29:03 -05:00
|
|
|
end
|