9
votes

Yes, I know there's Voter tutorial in cookbook. But I'm looking for something slightly different. I need two different layers of blacklisting:

  1. deny certain IP to access whole site
  2. deny certain IP to log in

I wrote Voter that checks if user's IP is in database. For first scenario, I wrote a kernel listener that checks every request and throws 403 in case it encounters banned user:

if (VoterInterface::ACCESS_DENIED === $this->voter->vote($token, $this, array())) {
    throw new AccessDeniedHttpException('Blacklisted, punk!');
}

First problem lies in VoterInterface itself, which forces me to use TokenInterface $token, which I don't really need in this case. But that doesn't matter that much I guess. Next thing is that I actually had to use AccessDeniedHttpException as AccessDeniedException always tries to redirect me to login page and causes endless redirect loop in this case. I'd live with it as it works just fine in dev environment, but when I switch to prod I keep getting 503 with following in prod log:

[2011-11-21 20:54:04] security.INFO: Populated SecurityContext with an anonymous Token [] []

[2011-11-21 20:54:04] request.ERROR: Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: Blacklisted, punk! (uncaught exception) at xxx line 28 [] []

[2011-11-21 20:54:04] request.ERROR: Exception thrown when handling an exception (Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: Blacklisted, punk!) [] []

From what I've read, it might be problem with xdebug, but it happens even when I turn it off. I also tried vanilla \Exception and it does the same thing. Anyone have any idea why it happens? Or maybe some other solution for such blacklisting case.

Also, I've no idea how to solve second case as I don't know how to stop user before he gets token assigned. My current solution is dealing with InteractiveLoginEvent, checking if user is blacklisted and if so, removing his token. It doesn't seem to be a safe one and I'm not really comfortable with it. So, any idea how to solve this one? I guess I'm just missing some obvious "pre login event".

6
In the error message, do you think the exception between brackets is the exception that is handled or the exception that is thrown?greg0ire
I'd say it's the one that's being handled, but was also thinking if some kind of loop is not happening.Ondrej Slinták
Search for "Exception thrown when handling" in the code, you'll see it is the second option => there is a loopgreg0ire

6 Answers

4
votes

To deny access to the entire website, you can adapt the whitelist code used to secure the dev environment. Stick something like this in app.php:

if (in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '1.2.3.4',))) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this site.');
}
4
votes

For site-wide IP restrictions it's best to handle them at the apache level, so your app does not even get hit by the request. In case you are trying to keep out a spammer, this way you don't waste any resources on their sometimes automated requests. In your case, writing the deny rules to the .htaccess file would be appropriate. In larger setups you can also configure a firewall to block specific IPs so those requests don't even hit your server at all.

4
votes

To the first problem – there are filters in EventDispatcher, so you can throw AccessDeniedHttpException before Controller start process request.

To the second problem – if you use custom User Provider you can check for banned IP addresses in UserRepository.

namespace Acme\SecurityBundle\Entity;
//… some namespaces
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * UserRepository
 */
class UserRepository extends … implements …
{

    public function loadUserByUsername($username)
    {
        if ( $this->isBanned() ) {
            throw new AccessDeniedHttpException("You're banned!");
        }
        //… load user from DB
    }

    //… some other methods

    private function isBanned()
    {
        $q = $this->getEntityManager()->createQuery('SELECT b FROM AcmeSecurityBundle:BlackList b WHERE b.ip = :ip')
            ->setParameter('ip', @$_SERVER['REMOTE_ADDR'])
            ->setMaxResults(1)
        ;
        $blackList = $q->getOneOrNullResult();

        //… check if is banned
    }

}
1
votes

you also can use a firewall on the server, for example: http://www.shorewall.net/blacklisting_support.htm which blocks the given ips completly of the server.

to autogenerate such a blacklist file, look at the following example: http://www.justin.my/2010/08/generate-shorewall-blacklist-from-spamhaus-and-dshield/

1
votes

You can easily block IP and range of IP using my bundle => https://github.com/Spomky-Labs/SpomkyIpFilterBundle

0
votes

It's not a best practice. Insight (analyse by Sensio) returns : "Using PHP response functions (like header() here) is discouraged, as it bypasses the Symfony event system. Use the HttpFoundationResponse class instead." and "$_SERVER super global should not be used."

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';

require_once __DIR__.'/../app/AppKernel.php';


$request = Request::createFromGlobals();

$client_ip = $request->getClientIp();
$authorized_hosts = ['127.0.0.1', 'fe80::1', '::1', 'localhost', 'yourIpAddress'];

// Securisation
if (!in_array($client_ip, $authorized_hosts)) {
    $response = new Response(
        "Forbidden",
        Response::HTTP_FORBIDDEN,
        array('content-type' => 'text/html')
    );
    $response->send();
    exit();
}

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

It's ok for SensioInsight