Browse Source

HTTP_X_FORWARDED_FOR can be spoofed, proxies append to the list, so use last ip

Marc Ypes 8 years ago
parent
commit
42c2d489df
2 changed files with 4 additions and 3 deletions
  1. 2 1
      src/Http/ServerRequest.php
  2. 2 2
      tests/TestCase/Http/ServerRequestTest.php

+ 2 - 1
src/Http/ServerRequest.php

@@ -550,7 +550,8 @@ class ServerRequest implements ArrayAccess, ServerRequestInterface
     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 {

+ 2 - 2
tests/TestCase/Http/ServerRequestTest.php

@@ -688,13 +688,13 @@ class ServerRequestTest extends TestCase
     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());