Skip to content

Commit

Permalink
Add test to ensure constant time comparison stays constant
Browse files Browse the repository at this point in the history
Co-authored-by: arrtchiu <arrtchiu@gmail.com>
  • Loading branch information
bdewater and arrtchiu committed Aug 29, 2019
1 parent 4169467 commit 7891469
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions test/test_ossl.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# frozen_string_literal: true
require_relative "utils"

require 'benchmark'

if defined?(OpenSSL)

class OpenSSL::OSSL < OpenSSL::SSLTestCase
Expand All @@ -23,6 +25,21 @@ def test_memcmp?
refute OpenSSL.memcmp?("aaa", "bbb")
assert_raises(ArgumentError) { OpenSSL.memcmp?("aaa", "bbbb") }
end

def test_memcmp_timing
# Ensure using memcmp? 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.
# NOTE: this test may be susceptible to noise if the system running the tests is otherwise under load.
a = "x" * 512_000
b = "#{a}y"
c = "y#{a}"
a = "#{a}x"

n = 10_000
a_b_time = Benchmark.measure { n.times { OpenSSL.memcmp?(a, b) } }.real
a_c_time = Benchmark.measure { n.times { OpenSSL.memcmp?(a, c) } }.real
assert_in_delta(a_b_time, a_c_time, 0.25, "memcmp? timing test failed")
end
end

end

0 comments on commit 7891469

Please sign in to comment.