Netskin Logo

Security and the & operator in Ruby

#ruby
#security
by Corin Langosch on 16.08.2023

In Ruby, the & operator is commonly known as a bitwise AND operator used for binary operations. However, it can also be used as a logical operator and be very useful in certain applications, such as security. Here’s an exploration of why using & might be useful in preventing timing attacks, contrasting it with the more typical logical && operator.

& as a bitwise operator

The & operator is usually used to perform bitwise AND operations between two integers. For example:

a = 5   # binary 101
b = 3   # binary 011
puts a & b  # binary 001, output: 1

& as a logical operator

When dealing with boolean values, & can also be used as a logical AND operator, without the short-circuiting behavior of &&. This makes it useful in contexts like preventing timing attacks.

What is short-circuiting?

Short-circuiting occurs when, for instance, in a boolean condition like true || something, the interpreter can immediately cease evaluation after the first part because the final result is already determined.

What is a timing attack?

A timing attack is a side-channel attack where an attacker attempts to compromise a system by analyzing the time taken to execute cryptographic algorithms. Even a tiny difference in execution time can provide clues to the attacker.

Why use & over && in security context?

Using & ensures that all the comparisons are made, regardless of whether the previous ones were false, whereas && short-circuits if any comparison returns false. By not short-circuiting, the & operator ensures that the comparison takes a consistent amount of time, regardless of the input.

Example code

Here’s an example of how to protect the sidekiq web admin with basic auth:

  Sidekiq::Web.use(Rack::Auth::Basic) do |username, password|
    ActiveSupport::SecurityUtils.secure_compare(username, Settings.sidekiq.admin_username) & ActiveSupport::SecurityUtils.secure_compare(password, Settings.sidekiq.admin_password)
  end

This code takes the same amount of time to run, regardless of where the credentails start to differ, making it more resistant to timing attacks.

Happy coding!

❮ Mini-Tip: Temporary Patch
Netskin Logo