Skip to content

Commit

Permalink
Merge pull request #4 from middlewares/fix/proxy-ip-detect
Browse files Browse the repository at this point in the history
Return local IP when proxy IP detection fails
  • Loading branch information
oscarotero authored Jul 13, 2017
2 parents 931ef43 + 013777f commit 907852d
Showing 1 changed file with 58 additions and 13 deletions.
71 changes: 58 additions & 13 deletions src/ClientIp.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,32 +107,77 @@ public function process(ServerRequestInterface $request, DelegateInterface $dele
*/
private function getIp(ServerRequestInterface $request)
{
if ($this->remote) {
$ip = file_get_contents('http://ipecho.net/plain');
$remoteIp = $this->getRemoteIp();

if (self::isValid($ip)) {
return $ip;
}
if (!empty($remoteIp)) {
// Found IP address via remote service.
return $remoteIp;
}

$ip = null;
$server = $request->getServerParams();
$localIp = $this->getLocalIp($request);

if (!empty($server['REMOTE_ADDR']) && self::isValid($server['REMOTE_ADDR'])) {
$ip = $server['REMOTE_ADDR'];
if ($this->proxyIps && !in_array($localIp, $this->proxyIps)) {
// Local IP address does not point at a known proxy, do not attempt
// to read proxied IP address.
return $localIp;
}

if (empty($this->proxyHeaders) || (!empty($this->proxyIps) && !in_array($ip, $this->proxyIps))) {
return $ip;
$proxiedIp = $this->getProxiedIp($request);

if (!empty($proxiedIp)) {
// Found IP address via proxy-defined headers.
return $proxiedIp;
}

foreach ($this->proxyHeaders as $name) {
if ($request->hasHeader($name) && ($ip = self::getHeaderIp($request->getHeaderLine($name))) !== null) {
return $localIp;
}

/**
* Returns the IP address from remote service.
*
* @return string|null
*/
private function getRemoteIp()
{
if ($this->remote) {
$ip = file_get_contents('http://ipecho.net/plain');
if (self::isValid($ip)) {
return $ip;
}
}
}

/**
* Returns the first valid proxied IP found.
*
* @return string|null
*/
private function getProxiedIp(ServerRequestInterface $request)
{
foreach ($this->proxyHeaders as $name) {
if ($request->hasHeader($name)) {
$ip = self::getHeaderIp($request->getHeaderLine($name));
if (self::isValid($ip)) {
return $ip;
}
}
}
}

/**
* Returns the remote address of the request, if valid.
*
* @return string|null
*/
private function getLocalIp(ServerRequestInterface $request)
{
$server = $request->getServerParams();

if (!empty($server['REMOTE_ADDR']) && self::isValid($server['REMOTE_ADDR'])) {
return $server['REMOTE_ADDR'];
}
}

/**
* Returns the first valid ip found in the header.
*
Expand Down

0 comments on commit 907852d

Please sign in to comment.