Exemple #1
0
 /**
  * @expectedException \RuntimeException
  * @requires extension sockets
  */
 public function testAnIpv6WithOptionDisabledIpv6()
 {
     if (defined('AF_INET6')) {
         $this->markTestSkipped('Only works when PHP is compiled with the option "disable-ipv6".');
     }
     IpUtils::checkIp('2a01:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65');
 }
 /**
  * @Route("/", name = "index")
  * @Template()
  */
 public function indexAction()
 {
     try {
         // Redirect admin and local users to secure area
         // TODO: Make the local network rule configurable (turned off by default)
         if (true === $this->get('security.context')->isGranted('ROLE_ADMIN') || true === IpUtils::checkIp($this->getRequest()->getClientIp(), '192.168.0.0/16') || $this->getRequest()->getClientIp() === '127.0.0.1') {
             return $this->redirect($this->generateUrl('admin_index'));
         }
     } catch (\Exception $e) {
     }
     return array();
 }
 protected function validateRequest(Request $request)
 {
     // is the Request safe?
     if (!$request->isMethodSafe()) {
         throw new AccessDeniedHttpException();
     }
     // does the Request come from a trusted IP?
     $trustedIps = array_merge($this->getLocalIpAddresses(), $request->getTrustedProxies());
     $remoteAddress = $request->server->get('REMOTE_ADDR');
     if (IpUtils::checkIp($remoteAddress, $trustedIps)) {
         return;
     }
     // is the Request signed?
     // we cannot use $request->getUri() here as we want to work with the original URI (no query string reordering)
     if ($this->signer->check($request->getSchemeAndHttpHost() . $request->getBaseUrl() . $request->getPathInfo() . (null !== ($qs = $request->server->get('QUERY_STRING')) ? '?' . $qs : ''))) {
         return;
     }
     throw new AccessDeniedHttpException();
 }
 /**
  * @Route("/_api/post-receive")
  * @param Request $request
  * @return JsonResponse
  * @Method("POST")
  */
 public function postReceiveAction(Request $request)
 {
     $this->path = $this->getParameter('amp_deploy.log_path');
     if (!file_exists($this->path)) {
         mkdir($this->path);
     }
     $this->logPath = $this->path . 'amp_deploy.log';
     $now = new \DateTime();
     $this->log('Push received at: ' . $now->format('d.m.Y H:i:s'));
     // get expected ip range from github
     $http = new Client();
     $resp = $http->get('https://api.github.com/meta');
     $data = json_decode($resp->getBody());
     // is IP in range?
     if (!IpUtils::checkIp($request->getClientIp(), $data->hooks)) {
         $this->log('ERROR: Invalid source IP: ' . $request->getClientIp());
         return new JsonResponse(['error' => 'Invalid source IP: ' . $request->getClientIp()], 403);
     }
     // check sha1 secret
     $sig = 'sha1=' . hash_hmac('sha1', $request->getContent(), $this->getParameter('amp_deploy.github_secret'));
     if ($sig != $request->headers->get('X-Hub-Signature')) {
         $this->log('Invalid hash: ' . $sig . PHP_EOL);
         return new JsonResponse(['error' => 'Invalid hash: ' . $sig], 403);
     }
     try {
         // Decode the payload json string
         $payload = json_decode($request->get('payload'));
     } catch (\Exception $e) {
         $this->log('ERROR: ' . $e->__toString());
         return new JsonResponse(['error' => 'Malformed json'], 400);
     }
     // Pushed to master?
     $log = ['Author' => $payload->head_commit->author, 'Commit_message' => $payload->head_commit->message, 'Timestamp' => $payload->head_commit->timestamp];
     if ($payload->ref === 'refs/heads/master') {
         $log['status'] = 'Master push detected, deploying';
         // Run the deploy script
         shell_exec($this->getParameter('amp_deploy.deploy_script') . ' > ' . $this->logPath . ' 2>&1 &');
     } else {
         $log['status'] = 'Not master branch push';
     }
     $this->log($log);
     return new JsonResponse($log, 200);
 }
Exemple #5
0
 private function isFromTrustedProxy()
 {
     return self::$trustedProxies && IpUtils::checkIp($this->server->get('REMOTE_ADDR'), self::$trustedProxies);
 }
 /**
  * Returns the client IP addresses.
  *
  * In the returned array the most trusted IP address is first, and the
  * least trusted one last. The "real" client IP address is the last one,
  * but this is also the least trusted one. Trusted proxies are stripped.
  *
  * Use this method carefully; you should use getClientIp() instead.
  *
  * @return array The client IP addresses
  *
  * @see getClientIp()
  */
 public function getClientIps()
 {
     $ip = $this->server->get('REMOTE_ADDR');
     if (!self::$trustedProxies) {
         return array($ip);
     }
     if (!self::$trustedHeaders[self::HEADER_CLIENT_IP] || !$this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) {
         return array($ip);
     }
     $clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
     $clientIps[] = $ip;
     // Complete the IP chain with the IP the request actually came from
     $ip = $clientIps[0];
     // Fallback to this when the client IP falls into the range of trusted proxies
     // Eliminate all IPs from the forwarded IP chain which are trusted proxies
     foreach ($clientIps as $key => $clientIp) {
         // Remove port on IPv4 address (unfortunately, it does happen)
         if (preg_match('{((?:\\d+\\.){3}\\d+)\\:\\d+}', $clientIp, $match)) {
             $clientIps[$key] = $clientIp = $match[1];
         }
         if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
             unset($clientIps[$key]);
         }
     }
     // Now the IP chain contains only untrusted proxies and the client IP
     return $clientIps ? array_reverse($clientIps) : array($ip);
 }
Exemple #7
0
 private function normalizeAndFilterClientIps(array $clientIps, $ip)
 {
     $clientIps[] = $ip;
     // Complete the IP chain with the IP the request actually came from
     $firstTrustedIp = null;
     foreach ($clientIps as $key => $clientIp) {
         // Remove port (unfortunately, it does happen)
         if (preg_match('{((?:\\d+\\.){3}\\d+)\\:\\d+}', $clientIp, $match)) {
             $clientIps[$key] = $clientIp = $match[1];
         }
         if (!filter_var($clientIp, FILTER_VALIDATE_IP)) {
             unset($clientIps[$key]);
             continue;
         }
         if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
             unset($clientIps[$key]);
             // Fallback to this when the client IP falls into the range of trusted proxies
             if (null === $firstTrustedIp) {
                 $firstTrustedIp = $clientIp;
             }
         }
     }
     // Now the IP chain contains only untrusted proxies and the client IP
     return $clientIps ? array_reverse($clientIps) : array($firstTrustedIp);
 }
 /**
  * Returns the client IP addresses.
  *
  * In the returned array the most trusted IP address is first, and the
  * least trusted one last. The "real" client IP address is the last one,
  * but this is also the least trusted one. Trusted proxies are stripped.
  *
  * Use this method carefully; you should use getClientIp() instead.
  *
  * @return array The client IP addresses
  *
  * @see getClientIp()
  */
 public function getClientIps()
 {
     $ip = $this->server->get('REMOTE_ADDR');
     if (!self::$trustedProxies) {
         return array($ip);
     }
     if (!self::$trustedHeaders[self::HEADER_CLIENT_IP] || !$this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) {
         return array($ip);
     }
     $clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
     $clientIps[] = $ip;
     // Complete the IP chain with the IP the request actually came from
     $trustedProxies = !self::$trustedProxies ? array($ip) : self::$trustedProxies;
     $ip = $clientIps[0];
     // Fallback to this when the client IP falls into the range of trusted proxies
     // Eliminate all IPs from the forwarded IP chain which are trusted proxies
     foreach ($clientIps as $key => $clientIp) {
         if (IpUtils::checkIp($clientIp, $trustedProxies)) {
             unset($clientIps[$key]);
         }
     }
     // Now the IP chain contains only untrusted proxies and the client IP
     return $clientIps ? array_reverse($clientIps) : array($ip);
 }
Exemple #9
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

use Symfony\Component\HttpFoundation\IpUtils;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
/**
 * @var Composer\Autoload\ClassLoader $loader
 */
$loader = (require __DIR__ . '/../app/autoload.php');
// 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#checking-symfony-application-configuration-and-setup
// for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !(IpUtils::checkIp(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1', '192.168.0.0/16')) || php_sapi_name() === 'cli-server')) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check ' . basename(__FILE__) . ' for more information.');
}
Debug::enable();
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
Exemple #11
0
 /**
  * Returns the client IP addresses.
  *
  * The most trusted IP address is first, and the less trusted one last.
  * The "real" client IP address is the last one, but this is also the
  * less trusted one.
  *
  * Use this method carefully; you should use getClientIp() instead.
  *
  * @return array The client IP addresses
  *
  * @see getClientIp()
  */
 public function getClientIps()
 {
     $ip = $this->server->get('REMOTE_ADDR');
     if (!self::$trustedProxies) {
         return array($ip);
     }
     if (!self::$trustedHeaders[self::HEADER_CLIENT_IP] || !$this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) {
         return array($ip);
     }
     $clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
     $clientIps[] = $ip;
     $trustedProxies = !self::$trustedProxies ? array($ip) : self::$trustedProxies;
     $ip = $clientIps[0];
     foreach ($clientIps as $key => $clientIp) {
         if (IpUtils::checkIp($clientIp, $trustedProxies)) {
             unset($clientIps[$key]);
             continue;
         }
     }
     return $clientIps ? array_reverse($clientIps) : array($ip);
 }
 /**
  * Checks if the requested ip is valid.
  *
  * @param string       $requestedIp
  * @param string|array $ips
  * @return boolean
  */
 protected function checkIps($requestedIp, $ips)
 {
     $ips = (array) $ips;
     $valid = false;
     $i = 0;
     while ($i < count($ips) && !$valid) {
         $valid = IpUtils::checkIp($requestedIp, $ips[$i]);
         $i++;
     }
     return $valid;
 }
 /**
  * @param string $clientIp
  *
  * @throws InvalidClientIpException
  */
 public function authenticateClientIp($clientIp)
 {
     if (false === IpUtils::checkIp($clientIp, self::$xsollaSubnets)) {
         throw new InvalidClientIpException(sprintf('Xsolla trusted subnets (%s) doesn\'t contain client IP address (%s). If you use reverse proxy, you should set correct client IPv4 to WebhookRequest. If you are in development environment, you can set $authenticateClientIp = false in $webhookServer->start();', implode(', ', self::$xsollaSubnets), $clientIp));
     }
 }
 private function isWithinIPRange($ip, $ipRange)
 {
     if (strpos($ipRange, '-') !== false || strpos($ipRange, '*') !== false) {
         return WDLIpUtils::IPInRange($ip, $ipRange);
     }
     if (strpos($ipRange, '/') !== false) {
         return SfIpUtils::checkIp($ip, $ipRange);
     }
     return false;
 }
 /**
  * @param string $clientIp
  *
  * @throws InvalidClientIpException
  */
 public function authenticateClientIp($clientIp)
 {
     if (false === IpUtils::checkIp($clientIp, self::$xsollaSubnets)) {
         throw new InvalidClientIpException(sprintf('Client IP address (%s) not found in allowed IP addresses whitelist (%s). Please check troubleshooting section in README.md https://github.com/xsolla/xsolla-sdk-php#troubleshooting', $clientIp, implode(', ', self::$xsollaSubnets)));
     }
 }
 /**
  * Returns the client IP addresses.
  *
  * In the returned array the most trusted IP address is first, and the
  * least trusted one last. The "real" client IP address is the last one,
  * but this is also the least trusted one. Trusted proxies are stripped.
  *
  * Use this method carefully; you should use getClientIp() instead.
  *
  * @return array The client IP addresses
  *
  * @see getClientIp()
  */
 public function getClientIps()
 {
     $clientIps = array();
     $ip = $this->server->get('REMOTE_ADDR');
     if (!self::$trustedProxies) {
         return array($ip);
     }
     if (self::$trustedHeaders[self::HEADER_FORWARDED] && $this->headers->has(self::$trustedHeaders[self::HEADER_FORWARDED])) {
         $forwardedHeader = $this->headers->get(self::$trustedHeaders[self::HEADER_FORWARDED]);
         preg_match_all('{(for)=("?\\[?)([a-z0-9\\.:_\\-/]*)}', $forwardedHeader, $matches);
         $clientIps = $matches[3];
     } elseif (self::$trustedHeaders[self::HEADER_CLIENT_IP] && $this->headers->has(self::$trustedHeaders[self::HEADER_CLIENT_IP])) {
         $clientIps = array_map('trim', explode(',', $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_IP])));
     }
     $clientIps[] = $ip;
     // Complete the IP chain with the IP the request actually came from
     $ip = $clientIps[0];
     // Fallback to this when the client IP falls into the range of trusted proxies
     foreach ($clientIps as $key => $clientIp) {
         // Remove port (unfortunately, it does happen)
         if (preg_match('{((?:\\d+\\.){3}\\d+)\\:\\d+}', $clientIp, $match)) {
             $clientIps[$key] = $clientIp = $match[1];
         }
         if (IpUtils::checkIp($clientIp, self::$trustedProxies)) {
             unset($clientIps[$key]);
         }
     }
     // Now the IP chain contains only untrusted proxies and the client IP
     return $clientIps ? array_reverse($clientIps) : array($ip);
 }