Skip to content

Commit

Permalink
Add OpenSSL.secure_compare with same semantics as Active Support >= 5.2
Browse files Browse the repository at this point in the history
secure_compare is for user input, fixed_length_secure_compare for already processed data that is known to have the same length
  • Loading branch information
bdewater committed Oct 26, 2019
1 parent 446b8e2 commit c2a6aaf
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/openssl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,18 @@
require 'openssl/x509'
require 'openssl/ssl'
require 'openssl/pkcs5'

module OpenSSL
# call-seq:
# OpenSSL.secure_compare(string, string) -> boolean
#
# Constant time memory comparison. Inputs are hashed using SHA-256 to prevent
# leaking the length of the secret. Returns +true+ if the strings are
# identical, +false+ otherwise.
def secure_compare(a, b)
hashed_a = OpenSSL::Digest::SHA256.digest(a)
hashed_b = OpenSSL::Digest::SHA256.digest(b)
OpenSSL.fixed_length_secure_compare(hashed_a, hashed_b) && a == b
end
module_function :secure_compare
end
17 changes: 17 additions & 0 deletions test/test_ossl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,23 @@ def test_fixed_length_secure_compare
assert_raises(ArgumentError) { OpenSSL.fixed_length_secure_compare("aaa", "bbbb") }
end

def test_secure_compare
refute OpenSSL.secure_compare("aaa", "a")
refute OpenSSL.secure_compare("aaa", "aa")

assert OpenSSL.secure_compare("aaa", "aaa")

refute OpenSSL.secure_compare("aaa", "aaaa")
refute OpenSSL.secure_compare("aaa", "baa")
refute OpenSSL.secure_compare("aaa", "aba")
refute OpenSSL.secure_compare("aaa", "aab")
refute OpenSSL.secure_compare("aaa", "aaab")
refute OpenSSL.secure_compare("aaa", "b")
refute OpenSSL.secure_compare("aaa", "bb")
refute OpenSSL.secure_compare("aaa", "bbb")
refute OpenSSL.secure_compare("aaa", "bbbb")
end

def test_memcmp_timing
# Ensure using fixed_length_secure_compare takes almost exactly the same amount of time to compare two different strings.
# Regular string comparison will short-circuit on the first non-matching character, failing this test.
Expand Down

0 comments on commit c2a6aaf

Please sign in to comment.