From 7c119f840ed716ac593a75fdaabfe456e3b55e4a Mon Sep 17 00:00:00 2001 From: Snir Sofer <2491403+SnirSofer@users.noreply.github.com> Date: Wed, 10 Feb 2021 02:17:41 +0200 Subject: [PATCH] Update AntiCSRF.php Add support for UserAgent --- src/AntiCSRF.php | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/AntiCSRF.php b/src/AntiCSRF.php index 58b9fe1..cf47a82 100644 --- a/src/AntiCSRF.php +++ b/src/AntiCSRF.php @@ -84,6 +84,11 @@ class AntiCSRF */ protected $hmac_ip = true; + /** + * @var bool + */ + protected $hmac_ua = true; + /** * @var bool */ @@ -269,14 +274,12 @@ public function getTokenArray(string $lockTo = ''): array list($index, $token) = $this->generateToken($lockTo); - if ($this->hmac_ip !== false) { + if ($this->hmac_ip !== false || $this->hmac_ua !== false) { // Use HMAC to only allow this particular IP to send this request $token = Base64UrlSafe::encode( \hash_hmac( $this->hashAlgo, - isset($this->server['REMOTE_ADDR']) - ? (string) $this->server['REMOTE_ADDR'] - : '127.0.0.1', + (($this->hmac_ip !== false && $this->hmac_ua !== false) ? (isset($this->server['REMOTE_ADDR']) ? (string) $this->server['REMOTE_ADDR'] : '127.0.0.1').(isset($this->server['HTTP_USER_AGENT']) ? (string) $this->server['HTTP_USER_AGENT'] : 'Mozilla') : (($this->hmac_ip !== true && $this->hmac_ua !== false) ? (isset($this->server['HTTP_USER_AGENT']) ? (string) $this->server['HTTP_USER_AGENT'] : 'Mozilla') : (isset($this->server['REMOTE_ADDR']) ? (string) $this->server['REMOTE_ADDR'] : '127.0.0.1'))), (string) Base64UrlSafe::decode($token), true ) @@ -365,7 +368,7 @@ public function validateRequest(): bool } // This is the expected token value - if ($this->hmac_ip === false) { + if ($this->hmac_ip === false && $this -> hmac_ua === false) { // We just stored it wholesale /** @var string $expected */ $expected = $stored['token']; @@ -375,9 +378,7 @@ public function validateRequest(): bool $expected = Base64UrlSafe::encode( \hash_hmac( $this->hashAlgo, - isset($this->server['REMOTE_ADDR']) - ? (string) $this->server['REMOTE_ADDR'] - : '127.0.0.1', + (($this->hmac_ip !== false && $this->hmac_ua !== false) ? (isset($this->server['REMOTE_ADDR']) ? (string) $this->server['REMOTE_ADDR'] : '127.0.0.1').(isset($this->server['HTTP_USER_AGENT']) ? (string) $this->server['HTTP_USER_AGENT'] : 'Mozilla') : (($this->hmac_ip !== true && $this->hmac_ua !== false) ? (isset($this->server['HTTP_USER_AGENT']) ? (string) $this->server['HTTP_USER_AGENT'] : 'Mozilla') : (isset($this->server['REMOTE_ADDR']) ? (string) $this->server['REMOTE_ADDR'] : '127.0.0.1'))), (string) Base64UrlSafe::decode((string) $stored['token']), true ) @@ -403,8 +404,9 @@ public function reconfigure(array $options = []): self case 'formToken': case 'sessionIndex': case 'useNativeSession': - case 'recycle_after': + case 'recycle_after': case 'hmac_ip': + case 'hmac_ua': case 'expire_old': /** @psalm-suppress MixedAssignment */ $this->$opt = $val;