1
0
mirror of https://github.com/flarum/core.git synced 2025-07-24 18:21:33 +02:00

Fixes wrong IP address when using a reverse proxy (#2236)

Added reverse proxy support to preserve forwarded IPs
This commit is contained in:
Jake Esser
2020-07-22 14:55:44 +02:00
committed by GitHub
parent 89a2a9786e
commit a6cb962f97
7 changed files with 128 additions and 2 deletions

View File

@@ -0,0 +1,21 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Http\Exception;
use Exception;
use Flarum\Foundation\KnownError;
class ProxyNotAllowedException extends Exception implements KnownError
{
public function getType(): string
{
return 'reverse_proxy_not_allowed';
}
}

View File

@@ -0,0 +1,72 @@
<?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
namespace Flarum\Http\Middleware;
use Flarum\Http\Exception\ProxyNotAllowedException;
use Illuminate\Support\Arr;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface as Middleware;
use Psr\Http\Server\RequestHandlerInterface;
class ProxyAddress implements Middleware
{
/**
* @var bool
*/
protected $enabled;
/**
* @var array
*/
protected $allowedAddresses;
/**
* @param bool $enabled
* @param array $allowedAddresses
*/
public function __construct($enabled, $allowedAddresses)
{
$this->enabled = $enabled;
$this->allowedAddresses = $allowedAddresses;
}
private function wildcardMatch(string $ipAddress): bool
{
foreach ($this->allowedAddresses as $allowedAddress) {
if (fnmatch($allowedAddress, $ipAddress)) {
return true;
}
}
return false;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$serverParams = $request->getServerParams();
$ipAddress = Arr::get($serverParams, 'REMOTE_ADDR', '127.0.0.1');
if ($this->enabled) {
if ($this->wildcardMatch($ipAddress)) {
// standard header for proxies, see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
$ipAddress = Arr::get($serverParams, 'X_FORWARDED_FOR', $ipAddress);
$ipAddress = Arr::get($serverParams, 'HTTP_CLIENT_IP', $ipAddress);
$ipAddress = Arr::get($serverParams, 'X_PROXYUSER_IP', $ipAddress);
} else {
throw new ProxyNotAllowedException();
}
}
$request = $request->withAttribute('ipAddress', $ipAddress);
return $handler->handle($request);
}
}