diff --git a/CHANGELOG.md b/CHANGELOG.md index 050bf286..894d0d7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # CHANGELOG +## v7.8.3 (2026-12-04) + +- Fixes `validate_webhook` comparing HMAC signatures with a non-constant-time `==`, which could leak timing information + ## v7.8.2 (2026-11-30) - Fixes `get_next_page` (claims, events, insurances, pickups, refunds, scan forms, shipments and trackers) dropping the `start_datetime` and `end_datetime` filters of the original `all` call diff --git a/VERSION b/VERSION index 194172b2..bb9f54cc 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -7.8.2 +7.8.3 diff --git a/lib/easypost/util.rb b/lib/easypost/util.rb index 2b255525..db128891 100644 --- a/lib/easypost/util.rb +++ b/lib/easypost/util.rb @@ -167,10 +167,22 @@ def self.validate_webhook(event_body, headers, webhook_secret) expected_signature = OpenSSL::HMAC.hexdigest('sha256', encoded_webhook_secret, event_body) digest = "hmac-sha256-hex=#{expected_signature}" - unless digest == easypost_hmac_signature + unless secure_compare(digest, easypost_hmac_signature) raise EasyPost::Errors::SignatureVerificationError.new(EasyPost::Constants::WEBHOOK_SIGNATURE_MISMATCH) end JSON.parse(event_body) end + + # Compare two strings in constant time so signature checks don't leak timing information. + def self.secure_compare(expected, actual) + return OpenSSL.secure_compare(expected, actual) if OpenSSL.respond_to?(:secure_compare) + + # TODO: This fallback is for Ruby 2.7 backwards compatibility (its bundled openssl lacks `secure_compare`), + # remove it once we only support Ruby 3.0+. + return false unless expected.bytesize == actual.bytesize + + expected.bytes.zip(actual.bytes).reduce(0) { |acc, (x, y)| acc | (x ^ y) }.zero? + end + private_class_method :secure_compare end diff --git a/spec/webhook_spec.rb b/spec/webhook_spec.rb index 3cfef98e..c7d117d8 100644 --- a/spec/webhook_spec.rb +++ b/spec/webhook_spec.rb @@ -109,6 +109,23 @@ ) end + # TODO: Remove this test along with the Ruby 2.7 `secure_compare` fallback once we only support Ruby 3.0+. + it 'validate a webhook with a same-length invalid signature using the Ruby 2.7 fallback' do + allow(OpenSSL).to receive(:respond_to?).and_call_original + allow(OpenSSL).to receive(:respond_to?).with(:secure_compare).and_return(false) + signature = Fixture.webhook_hmac_signature + headers = { + 'X-Hmac-Signature' => signature[0...-1] + (signature[-1] == '0' ? '1' : '0'), + } + + expect { + EasyPost::Util.validate_webhook(Fixture.event_bytes, headers, Fixture.webhook_secret) + }.to raise_error( + EasyPost::Errors::SignatureVerificationError, + EasyPost::Constants::WEBHOOK_SIGNATURE_MISMATCH, + ) + end + it 'validate a webhook with missing secret' do webhook_secret = '123' headers = {