Skip to content

Commit

Permalink
Prevent timming attacks
Browse files Browse the repository at this point in the history
  • Loading branch information
jonduarte committed Nov 21, 2018
1 parent d3a6fe5 commit 930918b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
17 changes: 17 additions & 0 deletions lib/zhong/util.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require "digest"

module Zhong
module Util
def safe_mget(keys)
Expand All @@ -9,5 +11,20 @@ def safe_mget(keys)
end

module_function :safe_mget

# Avoid timming attacks
# Based on: https://thisdata.com/blog/timing-attacks-against-string-comparison/
def safe_compare(a, b)
a = ::Digest::SHA256.hexdigest(a)
b = ::Digest::SHA256.hexdigest(b)

l = a.unpack "C#{a.bytesize}"

res = 0
b.each_byte { |byte| res |= byte ^ l.shift }
res == 0
end
module_function :safe_compare

end
end
2 changes: 1 addition & 1 deletion lib/zhong/web.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class Web < Sinatra::Base
if ENV["ZHONG_WEB_USERNAME"] && ENV["ZHONG_WEB_PASSWORD"]
# :nocov:
use Rack::Auth::Basic, "Sorry." do |username, password|
username == ENV["ZHONG_WEB_USERNAME"] and password == ENV["ZHONG_WEB_PASSWORD"]
Zhong::Util.safe_compare(username, ENV["ZHONG_WEB_USERNAME"]) & Zhong::Util.safe_compare(password, ENV["ZHONG_WEB_PASSWORD"])
end
# :nocov:
end
Expand Down

0 comments on commit 930918b

Please sign in to comment.