Skip to content
This repository has been archived by the owner on Mar 16, 2022. It is now read-only.

Commit

Permalink
Add constant-time comparison for Sodium::Buffer
Browse files Browse the repository at this point in the history
Lots of crypto operations will require comparing Sodium::Buffers. Since
we haven't already defined Sodium::Buffer#==, we have now done so in a
way that ensures timing attacks are avoided.
  • Loading branch information
stouset committed Jun 20, 2013
1 parent 34291b8 commit ba1735e
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
13 changes: 13 additions & 0 deletions lib/sodium/buffer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,19 @@ def initialize(bytes)
self.freeze
end

def ==(bytes)
bytes = Sodium::Buffer.new(bytes)

return false unless
self.bytesize == bytes.bytesize

Sodium::FFI::Crypto.sodium_memcmp(
self.to_str,
bytes.to_str,
bytes.bytesize
) == 0
end

def +(bytes)
Sodium::Buffer.empty(self.bytesize + bytes.bytesize) do |buffer|
buffer[0, self .bytesize] = self
Expand Down
5 changes: 3 additions & 2 deletions lib/sodium/ffi/crypto.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,9 @@ module Sodium::FFI::Crypto

ffi_lib 'sodium'

attach_function 'sodium_init', [], :void
attach_function 'sodium_memzero', [:pointer, :size_t], :void
attach_function 'sodium_init', [], :void
attach_function 'sodium_memzero', [:pointer, :size_t], :void
attach_function 'sodium_memcmp', [:pointer, :pointer, :size_t], :int

sodium_init

Expand Down
9 changes: 9 additions & 0 deletions test/sodium/buffer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,15 @@
it '#initialize must wipe the buffer during finalization'
it '#initialize must prevent the string from being paged to disk'

it '#== must compare equality of two buffers' do
subject.new('xyz').==('xyz') .must_equal true
subject.new('xyz').==('xy') .must_equal false
subject.new('xyz').==('xyzz').must_equal false
subject.new('xyz').==('abc') .must_equal false
end

it '#== must compare equality of two buffers in constant time'

it '#+ must append two buffers' do
subject.new('xyz').+('abc').to_str.must_equal 'xyzabc'
end
Expand Down

0 comments on commit ba1735e

Please sign in to comment.