Skip to content

Commit

Permalink
Fix handling of proxy addresses
Browse files Browse the repository at this point in the history
- Never use Client-IP header; untrustworthy
- When multiple addresses are present in X-Forwaded-For header, use the
  rightmost, not leftmost. See:

    http://en.wikipedia.org/wiki/X-Forwarded-For#Format
  • Loading branch information
weierophinney committed Nov 29, 2012
1 parent c00c516 commit c3819ab
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
10 changes: 3 additions & 7 deletions library/Zend/Session/Validator/RemoteAddr.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,11 @@ protected function getIpAddress()
{
if (static::$useProxy) {
// proxy IP address
if (isset($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP']) {
$ips = explode(',', $_SERVER['HTTP_CLIENT_IP']);
return trim($ips[0]);
}

// proxy IP address
// Only ever look at X-Forwarded-For header; Client-IP is unreliable
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
$ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
return trim($ips[0]);
$ip = array_pop($ips);
return trim($ip);
}
}

Expand Down
17 changes: 15 additions & 2 deletions tests/ZendTest/Session/Validator/RemoteAddrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,15 +102,28 @@ public function testHttpClientIp()
$this->restore();
}

public function testMultipleHttpXForwardedFor()
public function testUsesRightMostAddressWhenMultipleHttpXForwardedForAddressesPresent()
{
$this->backup();
$_SERVER['REMOTE_ADDR'] = '0.1.2.3';
$_SERVER['HTTP_X_FORWARDED_FOR'] = '2.1.2.3, 1.1.2.3';
RemoteAddr::setUseProxy(true);
$validator = new RemoteAddr();
RemoteAddr::setUseProxy(false);
$this->assertEquals('2.1.2.3', $validator->getData());
$this->assertEquals('1.1.2.3', $validator->getData());
$this->restore();
}

public function testShouldNotUseClientIpHeaderToTestProxyCapabilities()
{
$this->backup();
$_SERVER['REMOTE_ADDR'] = '0.1.2.3';
$_SERVER['HTTP_X_FORWARDED_FOR'] = '2.1.2.3, 1.1.2.3';
$_SERVER['HTTP_CLIENT_IP'] = '0.1.2.4';
RemoteAddr::setUseProxy(true);
$validator = new RemoteAddr();
RemoteAddr::setUseProxy(false);
$this->assertEquals('1.1.2.3', $validator->getData());
$this->restore();
}
}

0 comments on commit c3819ab

Please sign in to comment.