Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent timing attacks #32

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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