From 5c170ef4d1943c88c66f58bc2225128438cbeece Mon Sep 17 00:00:00 2001 From: Paul van der Knaap Date: Thu, 26 May 2022 10:55:14 +0200 Subject: [PATCH] Add HMAC/IP support for different remote IP's through proxies & CloudFlare --- src/AntiCSRF.php | 38 ++++++++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 6 deletions(-) diff --git a/src/AntiCSRF.php b/src/AntiCSRF.php index 526b8bf..3a1da6b 100644 --- a/src/AntiCSRF.php +++ b/src/AntiCSRF.php @@ -280,9 +280,7 @@ public function getTokenArray(string $lockTo = ''): array $token = Base64UrlSafe::encode( \hash_hmac( $this->hashAlgo, - isset($this->server['REMOTE_ADDR']) - ? (string) $this->server['REMOTE_ADDR'] - : '127.0.0.1', + $this->getRemoteIP(), (string) Base64UrlSafe::decode($token), true ) @@ -407,9 +405,7 @@ public function validateRequestOrThrow() $expected = Base64UrlSafe::encode( \hash_hmac( $this->hashAlgo, - isset($this->server['REMOTE_ADDR']) - ? (string) $this->server['REMOTE_ADDR'] - : '127.0.0.1', + $this->getRemoteIP(), (string) Base64UrlSafe::decode((string) $stored['token']), true ) @@ -548,4 +544,34 @@ protected static function noHTML(string $untrusted): string { return \htmlentities($untrusted, ENT_QUOTES, 'UTF-8'); } + + /** + * Wrapper to support different sources of remote IP addresses. + * + * @return string + */ + protected function getRemoteIP(): string + { + if (isset($this->server["HTTP_CF_CONNECTING_IP"]) && filter_var($this->server["HTTP_CF_CONNECTING_IP"], FILTER_VALIDATE_IP)) + { + return $this->server["HTTP_CF_CONNECTING_IP"]; + } + + if (isset($this->server["HTTP_X_FORWARDED_FOR"]) && filter_var($this->server["HTTP_X_FORWARDED_FOR"], FILTER_VALIDATE_IP)) + { + return $this->server["HTTP_X_FORWARDED_FOR"]; + } + + if (isset($this->server["HTTP_CLIENT_IP"]) && filter_var($this->server["HTTP_CLIENT_IP"], FILTER_VALIDATE_IP)) + { + return $this->server["HTTP_CLIENT_IP"]; + } + + if (isset($this->server['REMOTE_ADDR'])) + { + return $this->server['REMOTE_ADDR']; + } + + return '127.0.0.1'; + } }