Browse files

Fix timing attack vulnerability in the Cookie Store

Use a constant-time comparison algorithm to compare the candidate HMAC with the calculated HMAC to prevent leaking information about the calculated HMAC
  • Loading branch information...
1 parent 3cb8925 commit 674f780d59a5a7ec0301755d43a7b277a3ad2978 @NZKoz NZKoz committed Aug 23, 2009
Showing with 14 additions and 1 deletion.
  1. +14 −1 actionpack/lib/action_controller/session/cookie_store.rb
View
15 actionpack/lib/action_controller/session/cookie_store.rb
@@ -140,7 +140,7 @@ def unmarshal(cookie)
data, digest = cookie.split('--')
# Do two checks to transparently support old double-escaped data.
- unless digest == generate_digest(data) || digest == generate_digest(data = CGI.unescape(data))
+ unless secure_compare(digest, generate_digest(data)) || secure_compare(digest, generate_digest(data = CGI.unescape(data)))
delete
raise TamperedWithCookie
end
@@ -164,4 +164,17 @@ def write_cookie(options)
def clear_old_cookie_value
@session.cgi.cookies[@cookie_options['name']].clear
end
+
+ # constant-time comparison algorithm to prevent timing attacks
+ def secure_compare(a, b)
+ if a.length == b.length
+ result = 0
+ for i in 0..(a.length - 1)
+ result |= a[i] ^ b[i]
+ end
+ result == 0
+ else
+ false
+ end
+ end
end

0 comments on commit 674f780

Please sign in to comment.