From 7acdd018a1555c9bc5dcc1702074a10f862bb170 Mon Sep 17 00:00:00 2001 From: Lukas Reschke Date: Tue, 26 Aug 2014 23:58:13 +0200 Subject: Add support for getting the real client IP behind proxies Fixes https://github.com/owncloud/core/issues/10624 Fix copy paste fail Add unittest for comma separated headers Revert 3rdparty --- lib/private/request.php | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'lib/private/request.php') diff --git a/lib/private/request.php b/lib/private/request.php index 5fd5b3a7197..b063c1f5967 100755 --- a/lib/private/request.php +++ b/lib/private/request.php @@ -15,6 +15,34 @@ class OC_Request { const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost)(:[0-9]+|)$/'; + /** + * Returns the remote address, if the connection came from a trusted proxy and `forwarded_for_headers` has been configured + * then the IP address specified in this header will be returned instead. + * Do always use this instead of $_SERVER['REMOTE_ADDR'] + * @return string IP address + */ + public static function getRemoteAddress() { + $remoteAddress = $_SERVER['REMOTE_ADDR']; + $trustedProxies = \OC::$server->getConfig()->getSystemValue('trusted_proxies', array()); + + if(is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) { + $forwardedForHeaders = \OC::$server->getConfig()->getSystemValue('forwarded_for_headers', array()); + + foreach($forwardedForHeaders as $header) { + if (array_key_exists($header, $_SERVER) === true) { + foreach (explode(',', $_SERVER[$header]) as $IP) { + $IP = trim($IP); + if (filter_var($IP, FILTER_VALIDATE_IP) !== false) { + return $IP; + } + } + } + } + } + + return $remoteAddress; + } + /** * Check overwrite condition * @param string $type -- cgit v1.2.3