Use timing safe compare in Sodium::SecureBuffer.

This commit is contained in:
Didactic Drunk 2019-08-05 18:49:17 -07:00
parent 0d8dd544d5
commit 4be74741d5
4 changed files with 28 additions and 8 deletions

View File

@ -7,5 +7,8 @@ module Sodium
class DecryptionFailed < Error class DecryptionFailed < Error
end end
class MemcmpFailed < Error
end
end end
end end

View File

@ -45,6 +45,7 @@ module Sodium
fun crypto_generichash_blake2b_saltbytes : LibC::SizeT fun crypto_generichash_blake2b_saltbytes : LibC::SizeT
fun crypto_generichash_blake2b_personalbytes : LibC::SizeT fun crypto_generichash_blake2b_personalbytes : LibC::SizeT
fun sodium_memcmp(Pointer(LibC::UChar), Pointer(LibC::UChar), LibC::SizeT) : LibC::Int
fun sodium_memzero(Pointer(LibC::UChar), LibC::SizeT) : Nil fun sodium_memzero(Pointer(LibC::UChar), LibC::SizeT) : Nil
fun sodium_malloc(LibC::SizeT) : Pointer(LibC::UChar) fun sodium_malloc(LibC::SizeT) : Pointer(LibC::UChar)
@ -280,3 +281,25 @@ module Sodium
raise "Assumptions in this library regarding nonce sizes may not be valid" raise "Assumptions in this library regarding nonce sizes may not be valid"
end end
end end
module Sodium
def self.memcmp(a : Bytes, b : Bytes) : Bool
if a.bytesize != b.bytesize
false
elsif LibSodium.sodium_memcmp(a, b, a.bytesize) == 0
true
else
false
end
end
# Raises unless comparison succeeds.
def self.memcmp!(a, b)
raise Error::MemcmpFailed.new unless memcmp(a, b)
true
end
def self.memzero(bytes : Bytes)
LibSodium.sodium_memzero bytes, bytes.bytesize
end
end

View File

@ -82,11 +82,11 @@ module Sodium
end end
def ==(other : self) def ==(other : self)
self.to_slice == other.to_slice Sodium.memcmp self.to_slice, other.to_slice
end end
def ==(other : Bytes) def ==(other : Bytes)
self.to_slice == other Sodium.memcmp self.to_slice, other
end end
end end
end end

View File

@ -1,9 +1,3 @@
module Sodium
def self.memzero(bytes : Bytes)
LibSodium.sodium_memzero bytes, bytes.bytesize
end
end
module Sodium::Wipe module Sodium::Wipe
annotation Var annotation Var
end end