|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# This module is copied from activesupport |
| 4 | +# https://github.com/rails/rails/blob/3235827585d87661942c91bc81f64f56d710f0b2/activesupport/lib/active_support/security_utils.rb |
| 5 | +module Slack |
| 6 | + module Utils |
| 7 | + # rubocop:disable Naming/MethodParameterName |
| 8 | + module Security |
| 9 | + # Constant time string comparison, for fixed length strings. |
| 10 | + # |
| 11 | + # The values compared should be of fixed length, such as strings |
| 12 | + # that have already been processed by HMAC. Raises in case of length mismatch. |
| 13 | + |
| 14 | + if defined?(OpenSSL.fixed_length_secure_compare) |
| 15 | + def fixed_length_secure_compare(a, b) |
| 16 | + OpenSSL.fixed_length_secure_compare(a, b) |
| 17 | + end |
| 18 | + else |
| 19 | + def fixed_length_secure_compare(a, b) |
| 20 | + raise ArgumentError, 'inputs must be of equal length' unless a.bytesize == b.bytesize |
| 21 | + |
| 22 | + l = a.unpack "C#{a.bytesize}" |
| 23 | + |
| 24 | + res = 0 |
| 25 | + b.each_byte { |byte| res |= byte ^ l.shift } |
| 26 | + res.zero? |
| 27 | + end |
| 28 | + end |
| 29 | + module_function :fixed_length_secure_compare |
| 30 | + |
| 31 | + # Secure string comparison for strings of variable length. |
| 32 | + # |
| 33 | + # While a timing attack would not be able to discern the content of |
| 34 | + # a secret compared via secure_compare, it is possible to determine |
| 35 | + # the secret length. This should be considered when using secure_compare |
| 36 | + # to compare weak, short secrets to user input. |
| 37 | + def secure_compare(a, b) |
| 38 | + a.bytesize == b.bytesize && fixed_length_secure_compare(a, b) |
| 39 | + end |
| 40 | + module_function :secure_compare |
| 41 | + end |
| 42 | + # rubocop:enable Naming/MethodParameterName |
| 43 | + end |
| 44 | +end |
0 commit comments