From 42c2d489df9b1f7cf220143fc648daf427c7a0f1 Mon Sep 17 00:00:00 2001 From: Marc Ypes Date: Fri, 25 Aug 2017 00:58:24 +0200 Subject: [PATCH] HTTP_X_FORWARDED_FOR can be spoofed, proxies append to the list, so use last ip --- src/Http/ServerRequest.php | 3 ++- tests/TestCase/Http/ServerRequestTest.php | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Http/ServerRequest.php b/src/Http/ServerRequest.php index 81877c633d1..be1be669a49 100644 --- a/src/Http/ServerRequest.php +++ b/src/Http/ServerRequest.php @@ -550,7 +550,8 @@ public function session(Session $session = null) public function clientIp() { if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_FOR')) { - $ipaddr = preg_replace('/(?:,.*)/', '', $this->getEnv('HTTP_X_FORWARDED_FOR')); + $addresses = explode(',', $this->getEnv('HTTP_X_FORWARDED_FOR')); + $ipaddr = end($addresses); } elseif ($this->trustProxy && $this->getEnv('HTTP_CLIENT_IP')) { $ipaddr = $this->getEnv('HTTP_CLIENT_IP'); } else { diff --git a/tests/TestCase/Http/ServerRequestTest.php b/tests/TestCase/Http/ServerRequestTest.php index 26492fb2502..1404a0bf7ba 100644 --- a/tests/TestCase/Http/ServerRequestTest.php +++ b/tests/TestCase/Http/ServerRequestTest.php @@ -688,13 +688,13 @@ public function testDefaultEnvValue() public function testClientIp() { $request = new ServerRequest(['environment' => [ - 'HTTP_X_FORWARDED_FOR' => '192.168.1.5, 10.0.1.1, proxy.com', + 'HTTP_X_FORWARDED_FOR' => '192.168.1.5, 10.0.1.1, proxy.com, real.ip', 'HTTP_CLIENT_IP' => '192.168.1.2', 'REMOTE_ADDR' => '192.168.1.3' ]]); $request->trustProxy = true; - $this->assertEquals('192.168.1.5', $request->clientIp()); + $this->assertEquals('real.ip', $request->clientIp()); $request->env('HTTP_X_FORWARDED_FOR', ''); $this->assertEquals('192.168.1.2', $request->clientIp());