setTrustedProxies() public static méthode

You should only list the reverse proxies that you manage directly.
public static setTrustedProxies ( array $proxies )
$proxies array A list of trusted proxies
Exemple #1
0
 public function boot()
 {
     if ($trustedProxies = $this->container->getParameter('kernel.trusted_proxies')) {
         Request::setTrustedProxies($trustedProxies);
     } elseif ($this->container->getParameter('kernel.trust_proxy_headers')) {
         Request::trustProxyData(); // @deprecated, to be removed in 2.3
     }
 }
 public function setProxyConf()
 {
     if (!$this->configuration->isSetup()) {
         return;
     }
     $proxies = isset($this->configuration['trusted-proxies']) ? $this->configuration['trusted-proxies'] : [];
     Request::setTrustedProxies($proxies);
 }
Exemple #3
0
 public function boot()
 {
     if ($trustedProxies = $this->container->getParameter('kernel.trusted_proxies')) {
         Request::setTrustedProxies($trustedProxies);
     }
     if ($this->container->getParameter('kernel.http_method_override')) {
         Request::enableHttpMethodParameterOverride();
     }
 }
 /**
  */
 public static function init()
 {
     if (!static::$request) {
         Request::setTrustedProxies(Constants::$trusted_proxies);
         // Create request object from global page request otherwise.
         static::$request = Request::createFromGlobals();
     }
     // Otherwise, the request will be pre-injected.
 }
Exemple #5
0
 public function boot()
 {
     ErrorHandler::register(null, false)->throwAt($this->container->getParameter('debug.error_handler.throw_at'), true);
     if ($trustedProxies = $this->container->getParameter('kernel.trusted_proxies')) {
         Request::setTrustedProxies($trustedProxies);
     }
     if ($this->container->getParameter('kernel.http_method_override')) {
         Request::enableHttpMethodParameterOverride();
     }
     if ($trustedHosts = $this->container->getParameter('kernel.trusted_hosts')) {
         Request::setTrustedHosts($trustedHosts);
     }
 }
 /**
  * @expectedException Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException
  */
 public function testListenerThrowsWhenMasterRequestHasInconsistentClientIps()
 {
     $dispatcher = new EventDispatcher();
     $kernel = $this->getMock('Symfony\\Component\\HttpKernel\\HttpKernelInterface');
     $request = new Request();
     $request->setTrustedProxies(array('1.1.1.1'));
     $request->server->set('REMOTE_ADDR', '1.1.1.1');
     $request->headers->set('FORWARDED', '2.2.2.2');
     $request->headers->set('X_FORWARDED_FOR', '3.3.3.3');
     $dispatcher->addListener(KernelEvents::REQUEST, array(new ValidateRequestListener(), 'onKernelRequest'));
     $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
     $dispatcher->dispatch(KernelEvents::REQUEST, $event);
 }
 public function testUseRequestClientIp()
 {
     Request::setTrustedProxies(array('192.168.0.1'));
     list($event, $server) = $this->createRequestEvent(array('X_FORWARDED_FOR' => '192.168.0.2'));
     $processor = new WebProcessor();
     $processor->onKernelRequest($event);
     $record = $processor($this->getRecord());
     $this->assertCount(5, $record['extra']);
     $this->assertEquals($server['REQUEST_URI'], $record['extra']['url']);
     $this->assertEquals($server['X_FORWARDED_FOR'], $record['extra']['ip']);
     $this->assertEquals($server['REQUEST_METHOD'], $record['extra']['http_method']);
     $this->assertEquals($server['SERVER_NAME'], $record['extra']['server']);
     $this->assertEquals($server['HTTP_REFERER'], $record['extra']['referrer']);
 }
 /**
  * The signup action processes a signup request and creates new accounts
  *
  * @return ViewSpec
  */
 public function signup()
 {
     Request::setTrustedProxies(Constants::$trusted_proxies);
     $request = Request::createFromGlobals();
     $signupRequest = $this->buildSignupRequest($request);
     try {
         $this->validateSignupRequest($signupRequest);
         // guard method
         $viewSpec = $this->doWork($signupRequest);
     } catch (\RuntimeException $e) {
         $viewSpec = $this->renderException($e, $signupRequest);
     }
     return $viewSpec;
 }
Exemple #9
0
 protected function initServiceProviders()
 {
     $app = $this;
     if ($this['config']['trusted_proxies']) {
         \Symfony\Component\HttpFoundation\Request::setTrustedProxies($this['config']['trusted_proxies']);
     }
     $app['app_base_path'] = $this->basePath;
     $app->register(new \Silex\Provider\TwigServiceProvider(), array('twig.options' => array('cache' => $this->basePath . '/cache/twig', 'auto_reload' => $this['debug'], 'strict_variables' => true), 'twig.path' => array($this->basePath . '/src/views')));
     $app->register(new \Silex\Provider\SwiftmailerServiceProvider());
     $app->register(new \Devture\SilexProvider\DoctrineMongoDB\ServicesProvider('mongodb', array()));
     $app['mongodb.database'] = $app->share(function ($app) {
         return $app['mongodb.connection']->selectDatabase($app['config']['mongo']['db_name']);
     });
     $app->register(new \Devture\Bundle\FrameworkBundle\ServicesProvider($this['config']['FrameworkBundle']));
     $app->register(new \Devture\Bundle\LocalizationBundle\ServicesProvider($app['config']['LocalizationBundle']));
     $app->register(new \Devture\Bundle\UserBundle\ServicesProvider($app['config']['UserBundle']));
     $app->register(new \Devture\Bundle\NagiosBundle\ServicesProvider($app['config']['NagiosBundle']));
 }
 /**
  * Perform all the login functionality for the login page as requested.
  */
 public static function perform_login_if_requested($username_requested, $pass)
 {
     Request::setTrustedProxies(Constants::$trusted_proxies);
     $request = Request::createFromGlobals();
     $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
     $login_attempt_info = ['username' => $username_requested, 'user_agent' => $user_agent, 'ip' => $request->getClientIp(), 'successful' => 0, 'additional_info' => $_SERVER];
     $logged_in = login_user($username_requested, $pass);
     $is_logged_in = $logged_in['success'];
     if (!$is_logged_in) {
         // Login was attempted, but failed, so display an error.
         self::store_auth_attempt($login_attempt_info);
         $login_error_message = $logged_in['login_error'];
         return $login_error_message;
     } else {
         // log a successful login attempt
         $login_attempt_info['successful'] = 1;
         self::store_auth_attempt($login_attempt_info);
         return '';
     }
 }
Exemple #11
0
 /**
  * @param string $configFile path to main configuration file
  */
 public function loadConfig($configFile)
 {
     $yaml = new Parser();
     try {
         $config = $yaml->parse(file_get_contents($configFile));
     } catch (ParseException $e) {
         $this->logger->critical('Unable to parse the YAML string: ' . $e->getMessage() . ' in ' . $e->getParsedFile());
         return;
     }
     if (!is_array($config)) {
         $this->logger->critical('Parsed config file is not an array');
         return;
     }
     $config = $this->configurator->resolveMainConfig($config);
     //trusted proxies
     if (array_key_exists('trustedProxies', $config)) {
         $arrayOfProxies = is_string($config['trustedProxies']) ? array($config['trustedProxies']) : $config['trustedProxies'];
         Request::setTrustedProxies($arrayOfProxies);
     }
     //global hook options
     if (array_key_exists('options', $config)) {
         $this->options = $this->configurator->resolveOptions($config['options']);
     }
     // global hook commands
     if (array_key_exists('commands', $config)) {
         $this->addCommand($config['commands']);
     }
     // global path
     if (array_key_exists('path', $config)) {
         $this->path = $config['path'];
     }
     // configure global repositories
     if (array_key_exists('repositories', $config)) {
         $this->handleRepositoryConfig($config);
     }
     // configure repositoriesDir
     if (array_key_exists('repositoriesDir', $config)) {
         $this->loadRepos($config['repositoriesDir']);
     }
 }
Exemple #12
0
/**
 * Update the information of a viewing observer, or player.
 */
function update_activity_info()
{
    // ******************** Usage Information of the browser *********************
    Request::setTrustedProxies(Constants::$trusted_proxies);
    $request = Request::createFromGlobals();
    $remoteAddress = '' . $request->getClientIp();
    $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? substr($_SERVER['HTTP_USER_AGENT'], 0, 250) : NULL;
    // Truncated at 250 char.
    $referer = isset($_SERVER['HTTP_REFERER']) ? substr($_SERVER['HTTP_REFERER'], 0, 250) : '';
    // Truncated at 250 char.
    // ************** Setting anonymous and player usage information
    DatabaseConnection::getInstance();
    $session = SessionFactory::getSession();
    if (!$session->has('online')) {
        // *** Completely new session, update latest activity log. ***
        if ($remoteAddress) {
            // *** Delete prior to trying to re-insert into the people online. ***
            $statement = DatabaseConnection::$pdo->prepare('DELETE FROM ppl_online WHERE ip_address = :ip OR session_id = :sessionID');
            $statement->bindValue(':ip', $remoteAddress);
            $statement->bindValue(':sessionID', $session->getId());
            $statement->execute();
        }
        // *** Update viewer data. ***
        $statement = DatabaseConnection::$pdo->prepare('INSERT INTO ppl_online (session_id, activity, ip_address, refurl, user_agent) VALUES (:sessionID, now(), :ip, :referer, :userAgent)');
        $statement->bindValue(':sessionID', $session->getId());
        $statement->bindValue(':ip', $remoteAddress);
        $statement->bindValue(':referer', $referer);
        $statement->bindValue(':userAgent', $userAgent);
        $statement->execute();
        $session->set('online', true);
    } else {
        // *** An already existing session. ***
        $statement = DatabaseConnection::$pdo->prepare('UPDATE ppl_online SET activity = now(), member = :member WHERE session_id = :sessionID');
        $statement->bindValue(':sessionID', $session->getId());
        $statement->bindValue(':member', is_logged_in(), PDO::PARAM_BOOL);
        $statement->execute();
    }
}
Exemple #13
0
 public function initMountpoints()
 {
     if ($proxies = $this['config']->get('general/trustProxies')) {
         Request::setTrustedProxies($proxies);
     }
     // Mount the 'backend' on the branding:path setting. Defaults to '/bolt'.
     $backendPrefix = $this['config']->get('general/branding/path');
     $this->mount($backendPrefix, new Controllers\Login());
     $this->mount($backendPrefix, new Controllers\Backend());
     // Mount the 'async' controllers on /async. Not configurable.
     $this->mount('/async', new Controllers\Async());
     // Mount the 'thumbnail' provider on /thumbs.
     $this->mount('/thumbs', new Thumbs\ThumbnailProvider());
     // Mount the 'upload' controller on /upload.
     $this->mount('/upload', new Controllers\Upload());
     // Mount the 'extend' controller on /branding/extend.
     $this->mount($backendPrefix . '/extend', $this['extend']);
     if ($this['config']->get('general/enforce_ssl')) {
         foreach ($this['routes'] as $route) {
             /** @var \Silex\Route $route */
             $route->requireHttps();
         }
     }
     // Mount the 'frontend' controllers, as defined in our Routing.yml
     $this->mount('', new Controllers\Routing());
 }
use Symfony\Component\HttpFoundation\Request;
/**
 * @var Composer\Autoload\ClassLoader
 */
$loader = (require __DIR__ . '/../app/autoload.php');
include_once __DIR__ . '/../app/bootstrap.php.cache';
if (extension_loaded('apc') && ini_get('apc.enabled')) {
    $apcLoader = new Symfony\Component\ClassLoader\ApcClassLoader(sha1(__FILE__), $loader);
    $loader->unregister();
    $apcLoader->register(true);
}
if (getenv('APP_ENV') === 'dev') {
    umask(00);
    Debug::enable();
    $kernel = new AppKernel('dev', true);
} else {
    $kernel = new AppKernel('prod', false);
}
$kernel->loadClassCache();
if (getenv('APP_ENV') !== 'dev') {
    if (!isset($_SERVER['HTTP_SURROGATE_CAPABILITY']) || false === strpos($_SERVER['HTTP_SURROGATE_CAPABILITY'], 'ESI/1.0')) {
        require_once __DIR__ . '/../app/AppCache.php';
        $kernel = new AppCache($kernel);
    }
}
Request::enableHttpMethodParameterOverride();
Request::setTrustedProxies(array('127.0.0.1'));
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
    $loader = new ApcClassLoader($prefix ?: "ezpublish", $loader);
    $loader->register(true);
}
require_once __DIR__ . '/../ezpublish/EzPublishKernel.php';
if ($useDebugging) {
    Debug::enable();
}
$kernel = new EzPublishKernel($environment, $useDebugging);
// we don't want to use the classes cache if we are in a debug session
if (!$useDebugging) {
    $kernel->loadClassCache();
}
// Depending on the USE_HTTP_CACHE environment variable, tells whether the internal HTTP Cache mechanism is to be used.
// If not set it is activated if not in "dev" environment.
if (($useHttpCache = getenv("USE_HTTP_CACHE")) === false) {
    $useHttpCache = $environment !== "dev";
}
// Load HTTP Cache ...
if ($useHttpCache) {
    require_once __DIR__ . '/../ezpublish/EzPublishCache.php';
    $kernel = new EzPublishCache($kernel);
}
$request = Request::createFromGlobals();
// If you are behind one or more trusted reverse proxies, you might want to set them in TRUSTED_PROXIES environment
// variable in order to get correct client IP
if (($trustedProxies = getenv("TRUSTED_PROXIES")) !== false) {
    Request::setTrustedProxies(explode(",", $trustedProxies));
}
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Exemple #16
0
<?php

use Keboola\Syrup\Debug\Debug;
use Symfony\Component\HttpFoundation\Request;
umask(02);
define('ROOT_PATH', __DIR__ . '/../');
$loader = (require_once __DIR__ . '/../app/bootstrap.php.cache');
// Use APC for autoloading to improve performance.
// Change 'sf2' to a unique prefix in order to prevent cache key conflicts
// with other applications also using APC.
/*
$loader = new ApcClassLoader('sf2', $loader);
$loader->register(true);
*/
Debug::enable('prod');
require_once __DIR__ . '/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';
$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
// Because of ELB we need to trust to all incoming requests
Request::setTrustedProxies(array($request->server->get('REMOTE_ADDR')));
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
 /**
  * @expectedException Symfony\Component\HttpKernel\Exception\BadRequestHttpException
  */
 public function testInconsistentClientIpsOnMasterRequests()
 {
     $dispatcher = new EventDispatcher();
     $dispatcher->addListener(KernelEvents::REQUEST, function ($event) {
         $event->getRequest()->getClientIp();
     });
     $kernel = new HttpKernel($dispatcher, $this->getResolver());
     $request = new Request();
     $request->setTrustedProxies(array('1.1.1.1'));
     $request->server->set('REMOTE_ADDR', '1.1.1.1');
     $request->headers->set('FORWARDED', '2.2.2.2');
     $request->headers->set('X_FORWARDED_FOR', '3.3.3.3');
     $kernel->handle($request, $kernel::MASTER_REQUEST, false);
 }
Exemple #18
0
use Symfony\Component\HttpFoundation\Request;
use LoginCidadao\CoreBundle\Security\Compatibility\RamseyUuidFeatureSet;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
$loader = (require_once __DIR__ . '/../app/bootstrap.php.cache');
Debug::enable();
require_once __DIR__ . '/../app/AppKernel.php';
$kernel = new AppKernel('dev', true);
$uuidFactory = new \Ramsey\Uuid\UuidFactory(new RamseyUuidFeatureSet());
\Ramsey\Uuid\Uuid::setFactory($uuidFactory);
$generator = new \Qandidate\Stack\UuidRequestIdGenerator();
$stack = new \Qandidate\Stack\RequestId($kernel, $generator);
$kernel->loadClassCache();
try {
    $path = implode(DIRECTORY_SEPARATOR, array($kernel->getRootDir(), 'config', 'parameters.yml'));
    $params = Yaml::parse(file_get_contents($path));
    Request::setTrustedProxies($params['parameters']['trusted_proxies']);
} catch (Exception $ex) {
    http_response_code(500);
    exit('Invalid configuration');
}
$request = Request::createFromGlobals();
$allowed = $params['parameters']['dev_allowed'];
if (!IpUtils::checkIp($request->getClientIp(), $allowed)) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file.');
}
$response = $stack->handle($request);
$response->send();
$kernel->terminate($request, $response);
<?php

if (!defined('APPLICATION_PATH')) {
    define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/..'));
}
require_once __DIR__ . '/../vendor/autoload.php';
$service = new AnyContent\Repository\Service();
$service['debug'] = true;
$client = new \AnyContent\Client\Client();
$configuration = new \AnyContent\Connection\Configuration\RestLikeConfiguration();
$configuration->setUri('http://acrs.hahnair.dev/1/test');
$connection = $configuration->createReadWriteConnection();
$configuration->addContentTypes();
$repository = new \AnyContent\Client\Repository('test', $connection);
$client->addRepository($repository);
$service->setClient($client);
$service->register(new Silex\Provider\HttpCacheServiceProvider(), array('http_cache.cache_dir' => APPLICATION_PATH . '/http_cache/'));
\Symfony\Component\HttpFoundation\Request::setTrustedProxies(array('127.0.0.1'));
$service['http_cache']->run();
//$service->run();
Exemple #20
0
}
$kernel = new AppKernel($environment, $useDebugging);
// we don't want to use the classes cache if we are in a debug session
if (!$useDebugging) {
    $kernel->loadClassCache();
}
// Depending on the SYMFONY_HTTP_CACHE environment variable, tells whether the internal HTTP Cache mechanism is to be used.
// If not set it is activated if not in "dev" environment.
if (($useHttpCache = getenv('SYMFONY_HTTP_CACHE')) === false) {
    $useHttpCache = $environment !== 'dev';
}
// Load HTTP Cache ...
if ($useHttpCache) {
    // The standard HttpCache implementation can be overridden by setting the SYMFONY_HTTP_CACHE_CLASS environment variable.
    // Make sure to setup composer config so it is *autoloadable*, or fallback to use "SYMFONY_CLASSLOADER_FILE"
    if (($httpCacheClass = getenv('SYMFONY_HTTP_CACHE_CLASS')) !== false) {
        $kernel = new $httpCacheClass($kernel);
    } else {
        require_once __DIR__ . '/../app/AppCache.php';
        $kernel = new AppCache($kernel);
    }
}
$request = Request::createFromGlobals();
// If you are behind one or more trusted reverse proxies, you might want to set them in SYMFONY_TRUSTED_PROXIES environment
// variable in order to get correct client IP
if (($trustedProxies = getenv('SYMFONY_TRUSTED_PROXIES')) !== false) {
    Request::setTrustedProxies(explode(',', $trustedProxies));
}
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Exemple #21
0
/**
 * Update activity for a logged in player.
 *
 * @return void
 */
function update_activity_log($p_playerID)
{
    // (See update_activity_info in lib_header for the function that updates all the detailed info.)
    DatabaseConnection::getInstance();
    Request::setTrustedProxies(Constants::$trusted_proxies);
    $request = Request::createFromGlobals();
    $user_ip = $request->getClientIp();
    query("UPDATE players SET days = 0 WHERE player_id = :player", [':player' => $p_playerID]);
    query("Update accounts set last_ip = :ip, last_login = now() where account_id = (select _account_id from account_players join players on _player_id = player_id where player_id = :pid)", array(':ip' => $user_ip, ':pid' => $p_playerID));
}
 public function testHandleAuthenticateWithTrustedProxy()
 {
     Request::setTrustedProxies(array('10.11.12.13'));
     $hash = '123abc';
     $request = new Request();
     $request->headers->add(array('X-HTTP-Override' => 'AUTHENTICATE', 'Accept' => Kernel::USER_HASH_ACCEPT_HEADER));
     $request->server->set('REMOTE_ADDR', '10.11.12.13');
     /** @var \PHPUnit_Framework_MockObject_MockObject|Kernel $kernel */
     $kernel = $this->getMockBuilder('eZ\\Bundle\\EzPublishCoreBundle\\Kernel')->disableOriginalConstructor()->setMethods(array('generateUserHash'))->getMockForAbstractClass();
     $kernel->expects($this->once())->method('generateUserHash')->with($request)->will($this->returnValue($hash));
     $response = $kernel->handle($request);
     $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Response', $response);
     $this->assertSame(200, $response->getStatusCode());
     $this->assertSame($hash, $response->headers->get('X-User-Hash'));
 }
 public function preExecute(Request $request)
 {
     parent::preExecute($request);
     Request::setTrustedProxies(array($request->server->get('REMOTE_ADDR')));
 }
Exemple #24
0
<?php

/*
 * This file is part of the Jirro package.
 *
 * (c) Rendy Eko Prastiyo <*****@*****.**>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
use Symfony\Component\HttpFoundation\Request;
use Jirro\Component\Kernel\ApplicationFactory;
require_once __DIR__ . '/../bootstrap.php';
$application = $applicationFactory->createApplication(ApplicationFactory::TYPE_HTTP, $config);
$request = Request::createFromGlobals();
Request::setTrustedProxies(['127.0.0.1']);
Stack\run($application, $request);
Exemple #25
0
 /**
  * Forwards the Request to the backend and returns the Response.
  *
  * @param Request  $request A Request instance
  * @param bool     $catch   Whether to catch exceptions or not
  * @param Response $entry   A Response instance (the stale entry if present, null otherwise)
  *
  * @return Response A Response instance
  */
 protected function forward(Request $request, $catch = false, Response $entry = null)
 {
     if ($this->surrogate) {
         $this->surrogate->addSurrogateCapability($request);
     }
     // modify the X-Forwarded-For header if needed
     $forwardedFor = $request->headers->get('X-Forwarded-For');
     if ($forwardedFor) {
         $request->headers->set('X-Forwarded-For', $forwardedFor . ', ' . $request->server->get('REMOTE_ADDR'));
     } else {
         $request->headers->set('X-Forwarded-For', $request->server->get('REMOTE_ADDR'));
     }
     // fix the client IP address by setting it to 127.0.0.1 as HttpCache
     // is always called from the same process as the backend.
     $request->server->set('REMOTE_ADDR', '127.0.0.1');
     // make sure HttpCache is a trusted proxy
     if (!in_array('127.0.0.1', $trustedProxies = Request::getTrustedProxies())) {
         $trustedProxies[] = '127.0.0.1';
         Request::setTrustedProxies($trustedProxies);
     }
     // always a "master" request (as the real master request can be in cache)
     $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch);
     // FIXME: we probably need to also catch exceptions if raw === true
     // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC
     if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) {
         if (null === ($age = $entry->headers->getCacheControlDirective('stale-if-error'))) {
             $age = $this->options['stale_if_error'];
         }
         if (abs($entry->getTtl()) < $age) {
             $this->record($request, 'stale-if-error');
             return $entry;
         }
     }
     $this->processResponseBody($request, $response);
     if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) {
         $response->setPrivate(true);
     } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) {
         $response->setTtl($this->options['default_ttl']);
     }
     return $response;
 }
 public function __construct($environment, $debug)
 {
     Request::setTrustedProxies(['0.0.0.0/0']);
     parent::__construct($environment, $debug);
 }
 public function testTrustedProxies()
 {
     $request = Request::create('http://example.com/');
     $request->server->set('REMOTE_ADDR', '3.3.3.3');
     $request->headers->set('X_FORWARDED_FOR', '1.1.1.1, 2.2.2.2');
     $request->headers->set('X_FORWARDED_HOST', 'foo.example.com, real.example.com:8080');
     $request->headers->set('X_FORWARDED_PROTO', 'https');
     $request->headers->set('X_FORWARDED_PORT', 443);
     $request->headers->set('X_MY_FOR', '3.3.3.3, 4.4.4.4');
     $request->headers->set('X_MY_HOST', 'my.example.com');
     $request->headers->set('X_MY_PROTO', 'http');
     $request->headers->set('X_MY_PORT', 81);
     // no trusted proxies
     $this->assertEquals('3.3.3.3', $request->getClientIp());
     $this->assertEquals('example.com', $request->getHost());
     $this->assertEquals(80, $request->getPort());
     $this->assertFalse($request->isSecure());
     // disabling proxy trusting
     Request::setTrustedProxies(array());
     $this->assertEquals('3.3.3.3', $request->getClientIp());
     $this->assertEquals('example.com', $request->getHost());
     $this->assertEquals(80, $request->getPort());
     $this->assertFalse($request->isSecure());
     // trusted proxy via setTrustedProxies()
     Request::setTrustedProxies(array('3.3.3.3', '2.2.2.2'));
     $this->assertEquals('1.1.1.1', $request->getClientIp());
     $this->assertEquals('real.example.com', $request->getHost());
     $this->assertEquals(443, $request->getPort());
     $this->assertTrue($request->isSecure());
     // trusted proxy via setTrustedProxies()
     Request::setTrustedProxies(array('3.3.3.4', '2.2.2.2'));
     $this->assertEquals('3.3.3.3', $request->getClientIp());
     $this->assertEquals('example.com', $request->getHost());
     $this->assertEquals(80, $request->getPort());
     $this->assertFalse($request->isSecure());
     // check various X_FORWARDED_PROTO header values
     Request::setTrustedProxies(array('3.3.3.3', '2.2.2.2'));
     $request->headers->set('X_FORWARDED_PROTO', 'ssl');
     $this->assertTrue($request->isSecure());
     $request->headers->set('X_FORWARDED_PROTO', 'https, http');
     $this->assertTrue($request->isSecure());
     // custom header names
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, 'X_MY_FOR');
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_HOST, 'X_MY_HOST');
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'X_MY_PORT');
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'X_MY_PROTO');
     $this->assertEquals('4.4.4.4', $request->getClientIp());
     $this->assertEquals('my.example.com', $request->getHost());
     $this->assertEquals(81, $request->getPort());
     $this->assertFalse($request->isSecure());
     // disabling via empty header names
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, null);
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_HOST, null);
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, null);
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, null);
     $this->assertEquals('3.3.3.3', $request->getClientIp());
     $this->assertEquals('example.com', $request->getHost());
     $this->assertEquals(80, $request->getPort());
     $this->assertFalse($request->isSecure());
     // reset
     Request::setTrustedProxies(array());
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, 'X_FORWARDED_FOR');
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_HOST, 'X_FORWARDED_HOST');
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'X_FORWARDED_PORT');
     Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'X_FORWARDED_PROTO');
 }
Exemple #28
0
<?php

require __DIR__ . '/../vendor/autoload.php';
use Symfony\Component\HttpFoundation\Request;
$configPath = __DIR__ . '/../config/config.php';
if (file_exists($configPath) && is_readable($configPath)) {
    $config = (require $configPath);
    Request::setTrustedProxies($config['trustedProxies']);
}
function getClientIp()
{
    $request = Request::createFromGlobals();
    return $request->getClientIp();
}
 /**
  * @dataProvider getTrustedProxyData
  */
 public function testHttpCacheIsSetAsATrustedProxy(array $existing, array $expected)
 {
     Request::setTrustedProxies($existing);
     $this->setNextResponse();
     $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));
     $this->assertEquals($expected, Request::getTrustedProxies());
 }
 public function boot(Application $app)
 {
     if ($proxies = $app['config']->get('general/trustProxies')) {
         Request::setTrustedProxies($proxies);
     }
 }