Skip to content

Commit

Permalink
Merge pull request #458 from calcinai/webhook-timing-fix
Browse files Browse the repository at this point in the history
Use hash_equals() or polyfill for signature validation
  • Loading branch information
calcinai authored Jan 4, 2019
2 parents 855f3a9 + 050fd2c commit 06738bb
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
43 changes: 43 additions & 0 deletions src/XeroPHP/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -208,4 +208,47 @@ public static function escape($string)
{
return rawurlencode($string);
}

/**
* @param $knownString string
* @param $userInput string
* @return bool
* @see https://github.com/symfony/polyfill-php56
*/
public static function hashEquals($knownString, $userInput)
{
if (PHP_VERSION_ID >= 50600) {
return hash_equals($knownString, $userInput);
}

if (! is_string($knownString)) {
trigger_error('Expected known_string to be a string, '.gettype($knownString).' given', E_USER_WARNING);
return false;
}

if (! is_string($userInput)) {
trigger_error('Expected user_input to be a string, '.gettype($userInput).' given', E_USER_WARNING);
return false;
}

if (extension_loaded('mbstring')) {
$knownLen = mb_strlen($knownString, '8bit');
$userLen = mb_strlen($userInput, '8bit');
} else {
$knownLen = strlen($knownString);
$userLen = strlen($userInput);
}

if ($knownLen !== $userLen) {
return false;
}

$result = 0;

for ($i = 0; $i < $knownLen; ++$i) {
$result |= ord($knownString[$i]) ^ ord($userInput[$i]);
}

return $result === 0;
}
}
4 changes: 3 additions & 1 deletion src/XeroPHP/Webhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace XeroPHP;

use XeroPHP\Helpers;

class Webhook
{
/**
Expand Down Expand Up @@ -78,7 +80,7 @@ public function getSignature()
*/
public function validate($signature)
{
return $this->getSignature() === $signature;
return Helpers::hashEquals($this->getSignature(), $signature);
}

/**
Expand Down

0 comments on commit 06738bb

Please sign in to comment.