Преглед на файлове

merged branch pulzarraider/proxy_ip_fix (PR #2695)

Commits
-------

11b6156 updated unittest
a931e21 get correct client IP from X-forwarded-for header

Discussion
----------

[HttpFoundation] Get correct client IP when using trusted proxy (Varnish)

Bug fix: yes
Feature addition: no
Backwards compatibility break: no
Symfony2 tests pass: yes
Fixes the following tickets: -
Todo: -
Note: This is reopened PR #2686 for 2.0 branch.

If using trusted proxy (Varnish, ...) the client IP must be identified from X-Forwarded-For header. The header has de-facto standard format:

X-Forwarded-For : client1, proxy1, proxy2,

where the value is a comma+space separated list of IP addresses, the left-most being the farthest downstream client, and each successive proxy that passed the request adding the IP address where it received the request from. See: http://en.wikipedia.org/wiki/X-Forwarded-For

Function getClientIp should return only one client IP, not a list of all nonimportant IPs as it's now. Similar example can be seen in Cake framework: http://api.cakephp.org/view_source/request-handler-component/#line-477

There are many ways how to chose the first IP from X-Forwarded-For header. Any other faster and more reliable way is welcome.
Fabien Potencier преди 13 години
родител
ревизия
286ce0ea40
променени са 2 файла, в които са добавени 4 реда и са изтрити 1 реда
  1. 2 1
      src/Symfony/Component/HttpFoundation/Request.php
  2. 2 0
      tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php

+ 2 - 1
src/Symfony/Component/HttpFoundation/Request.php

@@ -453,7 +453,8 @@ class Request
             if ($this->server->has('HTTP_CLIENT_IP')) {
                 return $this->server->get('HTTP_CLIENT_IP');
             } elseif (self::$trustProxy && $this->server->has('HTTP_X_FORWARDED_FOR')) {
-                return $this->server->get('HTTP_X_FORWARDED_FOR');
+                $clientIp = explode(',', $this->server->get('HTTP_X_FORWARDED_FOR'), 2);
+                return isset($clientIp[0]) ? trim($clientIp[0]) : '';
             }
         }
 

+ 2 - 0
tests/Symfony/Tests/Component/HttpFoundation/RequestTest.php

@@ -525,6 +525,8 @@ class RequestTest extends \PHPUnit_Framework_TestCase
             array('88.88.88.88', true, '127.0.0.1', null, '88.88.88.88'),
             array('::1', false, '::1', null, null),
             array('2620:0:1cfe:face:b00c::3', true, '::1', '2620:0:1cfe:face:b00c::3', null),
+            array('2620:0:1cfe:face:b00c::3', true, '::1', null, '2620:0:1cfe:face:b00c::3, ::1'),
+            array('88.88.88.88', true, '123.45.67.89', null, '88.88.88.88, 87.65.43.21, 127.0.0.1'),
         );
     }