Giter Club home page Giter Club logo

firewall's Introduction

Firewall 2.2

Latest Stable Version License Downloads Code Quality Build Coverage StyleCI

Purpose

This a "soft-firewall" package. Its purpose is to help people prevent unauthorized access to routes by IP address. It is able to keep track of IPs, countries and hosts (dynamic ip), and redirect non-authorized users to, for instance, a "Coming Soon" page, while letting whitelisted IPs to have access to the entire site. It is now also able to detect and block attacks (too many requests) from single IPs or whole countries.

This package can prevent some headaches and help you block some access to your apps, but cannot replace firewalls and appliances, for attacks at the network level, you'll still need a real firewall.

Features

  • Control access to routes and groups via black and white lists.
  • Detect and block attacks to your application, from IP addresses or countries.
  • Send Slack notifications in attack events.
  • Allow whitelisted to access the whole site and send everyone else to a "coming soon page".
  • Redirect blacklisted users to some other page.
  • Use database or arrays to store IP lists.
  • Whitelist your development machine using a dynamic DNS host name.
  • Done using middleware, so you can protect/unprotect groups of routes.
  • All features are available for hosts, IP addresses, ranges of IP addresses and whole countries.
  • Super fast, less than 10ms increase in each request.
  • Highly configurable.

Concepts

Blacklist

All IP addresses in those lists will no be able to access routes filtered by the blacklist filter.

Whitelist

Those IP addresses, ranges or countries can

  • Access blacklisted routes even if they are in a range of blacklisted IP addresses.
  • Access 'allow whitelisted' filtered routes.
  • If a route is filtered by the 'allow whitelisted' filter and the IP is not whitelisted, the request will be redirected to an alternative url or route name.

Attack Detection

attack

Firewall is able to detect simple attacks to your page, by counting requests from the same IP or country. Just enable it on your config/firewall.php and, to receive notifications, configure the Slack service in config/services.php:

'slack' => [
    'webhook_url' => env('SLACK_WEBHOOK_URL'),
],

and add the route notification method to your user model:

/**
 * Route notifications for the Slack channel.
 *
 * @return string
 */
public function routeNotificationForSlack()
{
    return config('services.slack.webhook_url');
}

IPs lists

IPs (white and black) lists can be stored in array, files and database. Initially database access to lists is disabled, so, to test your Firewall configuration you can publish the config file and edit the blacklist or whitelist arrays:

'blacklist' => array(
    '127.0.0.1',
    '192.168.17.0/24'
    '127.0.0.1/255.255.255.255'
    '10.0.0.1-10.0.0.255'
    '172.17.*.*'
    'country:br'
    '/usr/bin/firewall/blacklisted.txt',
),

The file (for instance /usr/bin/firewall/blacklisted.txt) must contain one IP, range or file name per line, and, yes, it will search for files recursively, so you can have a file of files if you need:

127.0.0.2
10.0.0.0-10.0.0.100
/tmp/blacklist.txt

Redirecting non-whitelisted IP addresses

Non-whitelisted IP addresses can be blocked or redirected. To configure redirection you'll have to publish the config.php file and configure:

'redirect_non_whitelisted_to' => 'coming/soon',

Artisan Commands

You have access to the following commands:

Global

  firewall:cache:clear  Clear the firewall cache.
  firewall:list         List all IP address, white and blacklisted.
  firewall:updategeoip  Update the GeoIP database.

When database is enabled

  firewall:blacklist          Add an IP address to blacklist.
  firewall:clear              Remove all ip addresses from white and black lists.
  firewall:remove             Remove an IP address from white or black list.
  firewall:whitelist          Add an IP address to whitelist.

Those are results from firewall:list:

+--------------+-----------+-----------+
| IP Address   | Whitelist | Blacklist |
+--------------+-----------+-----------+
| 10.17.12.7   |           |     X     |
| 10.17.12.100 |     X     |           |
| 10.17.12.101 |     X     |           |
| 10.17.12.102 |     X     |           |
| 10.17.12.200 |           |     X     |
+--------------+-----------+-----------+
+-----------------------+-----------+-----------+
| IP Address            | Whitelist | Blacklist |
+-----------------------+-----------+-----------+
| 172.0.0.0-172.0.0.255 |           |     X     |
| country:br            |           |     X     |
| host:mypc.myname.com  |     X     |           |
+-----------------------+-----------+-----------+

Facade

You can also use the Firewall Facade to manage the lists:

$whitelisted = Firewall::isWhitelisted('10.17.12.1');
$blacklisted = Firewall::isBlacklisted('10.0.0.3');

Firewall::whitelist('192.168.1.1');
Firewall::blacklist('10.17.12.1', true); /// true = force in case IP is whitelisted
Firewall::blacklist('127.0.0.0-127.0.0.255');
Firewall::blacklist('200.212.331.0/28');
Firewall::blacklist('country:br');

if (Firewall::whichList($ip) !== false)  // returns false, 'whitelist' or 'blacklist'
{
    Firewall::remove($ip);
}

Return a blocking access response:

return Firewall::blockAccess();

Suspicious events will be (if you wish) logged, so tail it:

php artisan tail

Blocking Whole Countries

You can block a country by, instead of an ip address, pass country:<2-letter ISO code>. So, to block all Brazil's IP addresses, you do:

php artisan firewall:blacklist country:br

You will have to add this requirement to your composer.json file:

"geoip/geoip": "~1.14"

or

"geoip2/geoip2": "~2.0"

You need to enable country search on your firewall.php config file:

'enable_country_search' => true,

And you can schedule this command to update your cities GeoIp database regularly:

php artisan firewall:updategeoip

You can find those codes here: isocodes

Session Blocking

You can block users from accessing some pages only for the current session, by using those methods:

Firewall::whitelistOnSession($ip);
Firewall::blacklistOnSession($ip);
Firewall::removeFromSession($ip);

Playground & Bootstrap App

Click here to see it working and in case you need a help figuring out things, try this repository.

playground

Installation

Compatible with

  • Laravel 4+ (version 1.*)
  • Laravel 5.0, 5.1, 5.2 and 5.3 (version 1.*)
  • Laravel 5.4, 5.5, 5.6 and 5.7 (version 2.*)

Installing

Require the Firewall package using Composer:

composer require pragmarx/firewall
  • Laravel 5.5 and up

    You don't have to do anything else, this package uses Package Auto-Discovery's feature, and should be available as soon as you install it via Composer.

  • Laravel 5.4 and below

    Add the Service Provider and the Facade to your app/config/app.php:

PragmaRX\Firewall\Vendor\Laravel\ServiceProvider::class,
'Firewall' => PragmaRX\Firewall\Vendor\Laravel\Facade::class,

Add middlewares to your app/Http/Kernel.php

protected $routeMiddleware = [
    ...
    'fw-only-whitelisted' => \PragmaRX\Firewall\Middleware\FirewallWhitelist::class,
    'fw-block-blacklisted' => \PragmaRX\Firewall\Middleware\FirewallBlacklist::class,
    'fw-block-attacks' => \PragmaRX\Firewall\Middleware\BlockAttacks::class,
];

or

protected $middlewareGroups = [
    'web' => [
        ...
    ],

    'api' => [
        ...
    ],
    
    'firewall' => [
        \PragmaRX\Firewall\Middleware\FirewallBlacklist::class,
        \PragmaRX\Firewall\Middleware\BlockAttacks::class,
    ],
];

Then you can use them in your routes:

Route::group(['middleware' => 'fw-block-blacklisted'], function () 
{
    Route::get('/', 'HomeController@index');
});

Or you could use both. In the following example the allow group will give free access to the 'coming soon' page and block or just redirect non-whitelisted IP addresses to another, while still blocking access to the blacklisted ones.

Route::group(['middleware' => 'fw-block-blacklisted'], function () 
{
    Route::get('coming/soon', function()
    {
        return "We are about to launch, please come back in a few days.";
    });

    Route::group(['middleware' => 'fw-only-whitelisted'], function () 
    {
        Route::get('/', 'HomeController@index');
    });
});

Note: You can add other middleware you have already created to the new groups by simply adding it to the fw-allow-wl or fw-block-bl middleware group.

Migrate your database

php artisan migrate

Warning: If you already have a Firewall package installed and migrated, you need to update your migration name, in the migrations table, to 2014_02_01_311070_create_firewall_table, otherwise the migrate command will fail tell you the table already exists.

To publish the configuration file you'll have to:

Laravel 4

php artisan config:publish pragmarx/firewall

Laravel 5

php artisan vendor:publish --provider="PragmaRX\Firewall\Vendor\Laravel\ServiceProvider"

TODO

  • Tests, tests, tests.

Author

Antonio Carlos Ribeiro

License

Firewall is licensed under the BSD 3-Clause License - see the LICENSE file for details

Contributing

Pull requests and issues are more than welcome.

firewall's People

Contributors

alariva avatar antonioribeiro avatar bryant1410 avatar ecointest avatar exfriend avatar hornet-wing avatar jamesggordon avatar justplayingames avatar liepumartins avatar lloricode avatar mmeklin15 avatar phroggyy avatar robertboes avatar ryan-eurecab avatar stylecibot avatar swilla avatar zek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firewall's Issues

Error: The helper "table" not defined

When run php artisan firewall:list I got this error

[Symfony\Component\Console\Exception\InvalidArgumentException]
  The helper "table" is not defined.

Laravel 5.2

Update of city mmdb

Thanks for this amazing firewall!!

Is it possible to implement an updater of the geolite2 mmdb?
I write a class for this:

<?php

namespace App\Common;


class GeoIPUpdater
{
   /**
     *
     * Update GEOLITE2 MMDB DATABASE file from maxmind.com
     * http://dev.maxmind.com/geoip/geoip2/geolite2/
     * GeoLite2 databases are updated on the first Tuesday of each month.
     * Work with Laravel Schedule in App\Console\Kernel
     *      $schedule->call(function(){
     *           try {
     *               $geoIpResult = GeoIPUpdater::updateGeoIpFiles();
     *           } catch (\Exception $e) {
     *               $geoIpResult = false;
     *           }
     *           if(!Storage::disk('logs')->exists('geoIpUpdate.log')){
     *           Storage::disk('logs')->append('geoIpUpdate.log' , 'DATE;RESULT;');
     *           }
     *           Storage::disk('logs')
     *                 ->append('geoIpUpdate.log' , Carbon::now()->toDateTimeString() . ';' . $geoIpResult);
     *      })->monthlyOn(7,'3:57');
     *
     * Do mkdir /resources/geoip
     *
     * @return bool
     */
    public static function updateGeoIpFiles() {
        //http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz
        $geodblink = config('geoip.uri.mmdb');

        //http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.md5
        $geodbmd5link = config('geoip.uri.md5');

        //GET DB & MD5 FILES
        $database_gz_filePath = self::getHTTPFile($geodblink, resource_path() . '/geoip/');
        $md5_filePath = self::getHTTPFile($geodbmd5link, resource_path() . '/geoip/');

        //UNZIP, TEST MD5 & COPY TO VENDOR\pragmarx\support\GeoIp;
        if($database_gz_filePath && $md5_filePath){
            $database_filePath= self::dezipGzFile(resource_path() . '/geoip/' . basename(config('geoip.uri.mmdb')));
            if($database_filePath){
                $calc_md5 = md5_file($database_filePath);
                $original_md5 = file_get_contents($md5_filePath);
                if($calc_md5==$original_md5){
                    $final_success = copy($database_filePath, base_path('vendor/pragmarx/support/src/GeoIp/'.basename($database_filePath)));
                    return $final_success;
                }
                return false;
            }
            return false;
        }
        return false;
    }

    private static function getHTTPFile($uri, $destinationPath) {
        set_time_limit(360);

        $fileWriteName = $destinationPath . basename($uri);

        $fileRead = @fopen($uri,"rb");
        $fileWrite = @fopen($fileWriteName, 'wb');
        if ($fileRead===false || $fileWrite===false) {
            // error reading or opening file
            return false;
        }

        while(!feof($fileRead))
        {
            $content = @fread($fileRead, 1024*8);
            $success = fwrite($fileWrite, $content);
            if($success===false){
                return false;
            }
        }
        fclose($fileWrite);
        fclose($fileRead);

        return $fileWriteName;
    }

    private static function dezipGzFile($filePath) {
        $buffer_size = 4096; // read 4kb at a time
        $out_file_name = str_replace('.gz', '', $filePath);

        $fileRead = gzopen($filePath, 'rb');
        $fileWrite = fopen($out_file_name, 'wb');

        if ($fileRead===false || $fileWrite===false) {
            // error reading or opening file
            return false;
        }

        while(!gzeof($fileRead)) {
            // Read buffer-size bytes
            // Both fwrite and gzread and binary-safe
            $success = fwrite($fileWrite, gzread($fileRead, $buffer_size));
            if($success===false){
                return $success;
            }
        }

        // Files are done, close files
        fclose($fileWrite);
        gzclose($fileRead);
        return $out_file_name;
    }

}

config option redirect_non_whitelisted_to seems not working

Hi I have mentioned route for redirect_non_whitelisted_to like

redirect_non_whitelisted_to => 'coming/soon' and created same route as well, but filter does not redirect it to desired route, rather it returns with values mentioned in following option

'block_response_code' => 403,

'block_response_message' => 'You are not authorized',

By Filter files came to know that only Whitelist.php filter uses redirect_non_whitelisted_to and not Blacklist.php am i right or Am I doing something wrong?

Usage of Facades in Migration stub

I would recommend to not use the Firewall facade in migrations because it is not guaranteed to be available. For instance:

  • Dev 1 installed Firewall package
  • A few days pass, Dev 1 decides to remove Firewall package.
  • Dev 2 comes back from holiday, pulls down the latest changes in master and attempts to migrate:
 [Symfony\Component\Debug\Exception\FatalErrorException]
Class 'PragmaRX\Firewall\Vendor\Laravel\Facade' not found

The state of migrations should ideally be allowed to run regardless of what packages are/are not installed (with the "sane" exception of DB::). What are you thoughts?

https://github.com/antonioribeiro/firewall/blob/master/src/stubs/create_firewall_tables.stub

Cannot set ranges (they are supposedly invalid IP addresses)

When trying to add a range of IP addresses it fails, saying the range is not a valid IP address.
For example I tried:
Firewall::whiteList(10.0.0.1-10.0.0.255)
or
php artisan firewall:whitelist 10.0.0.1-10.0.0.255

Using the range that was provided in the readme. Also '127.0.0.1/255.255.255.255' is not working, whereas '192.168.17.0/24' is working (all examples from the readme).

I have enabled ranges. Looking at the code, it seems to me, that PragmaRX\Support\IpAddress::ipV4Valid() is only checking, if the given IP address is either already an IP address or a CIDR, but not if its a range. But this seems not to be the reason for '127.0.0.1/255.255.255.255' not working.

Am I doing something wrong or is this a bug?

Thank you for your time and help!

Block Countries

Please add the ability to block countries ! not just single IP's ....

Migrations fails with mongodb

If you launch migrations with mongo db they fails:

PHP Fatal error:  Call to a member function beginTransaction() on a non-object in /var/www/html/paperapp-api/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 487
PHP Stack trace:
PHP   1. {main}() /var/www/html/paperapp-api/artisan:0
PHP   2. Symfony\Component\Console\Application->run() /var/www/html/paperapp-api/artisan:59
PHP   3. Symfony\Component\Console\Application->doRun() /var/www/html/paperapp-api/workbench/mazzmedia/webapp-core-library-conversion/vendor/symfony/console/Symfony/Component/Console/Application.php:126
PHP   4. Symfony\Component\Console\Application->doRunCommand() /var/www/html/paperapp-api/workbench/mazzmedia/webapp-core-library-conversion/vendor/symfony/console/Symfony/Component/Console/Application.php:195
PHP   5. Illuminate\Console\Command->run() /var/www/html/paperapp-api/workbench/mazzmedia/webapp-core-library-conversion/vendor/symfony/console/Symfony/Component/Console/Application.php:874
PHP   6. Symfony\Component\Console\Command\Command->run() /var/www/html/paperapp-api/vendor/laravel/framework/src/Illuminate/Console/Command.php:100
PHP   7. Illuminate\Console\Command->execute() /var/www/html/paperapp-api/workbench/mazzmedia/webapp-core-library-conversion/vendor/symfony/console/Symfony/Component/Console/Command/Command.php:253
PHP   8. Illuminate\Database\Console\Migrations\MigrateCommand->fire() /var/www/html/paperapp-api/vendor/laravel/framework/src/Illuminate/Console/Command.php:112
PHP   9. Illuminate\Database\Migrations\Migrator->run() /var/www/html/paperapp-api/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:70
PHP  10. Illuminate\Database\Migrations\Migrator->runMigrationList() /var/www/html/paperapp-api/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:82
PHP  11. Illuminate\Database\Migrations\Migrator->runUp() /var/www/html/paperapp-api/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:111
PHP  12. CreateFirewallTables->up() /var/www/html/paperapp-api/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:135
PHP  13. PragmaRX\Support\Migration->up() /var/www/html/paperapp-api/app/database/migrations/2015_01_23_092957_create_firewall_tables.php:16
PHP  14. PragmaRX\Support\Migration->executeInTransaction() /var/www/html/paperapp-api/vendor/pragmarx/support/src/Migration.php:72
PHP  15. Illuminate\Database\Connection->beginTransaction() /var/www/html/paperapp-api/vendor/pragmarx/support/src/Migration.php:109
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Call to a member function beginTransaction() on a non-object","file":"\/var\/www\/html\/paperapp-api\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Connection.php","line":487}}

Broken artisan optimize in Laravel 5.1

Hey guys,

i was having problems with the php artisan optimize command building bad compiled.php file.

Error when using laravel with the compiled.php generated is:
PHP Fatal error: Cannot declare interface Illuminate\Contracts\Container\Container, because the name is already in use in /Users/fgreinus/Web/paladalo/bootstrap/cache/compiled.php on line 4

Do you got any suggestions on how to fix this?

Additionally:
This also happens on a clean laravel 5.1 installation with only firewall installed.

ReflectionException: "Class firewall.config does not exist" after upgrading antonioribeiro/support to v0.3.3

I encountered this error trying to run an artisan migrate. It seems unable to find the Firewall facade in Firewall::getMigrator()->up(). Downgrading to antonioribeiro/support v0.3.2 allowed the migration to run fine. Note: I'm running Laravel 4.1.

Here is the exception trace:

() at /vendor/laravel/framework/src/Illuminate/Container/Container.php:501
ReflectionClass->__construct() at /vendor/laravel/framework/src/Illuminate/Container/Container.php:501
Illuminate\Container\Container->build() at /vendor/laravel/framework/src/Illuminate/Container/Container.php:425
Illuminate\Container\Container->make() at /vendor/laravel/framework/src/Illuminate/Foundation/Application.php:463
Illuminate\Foundation\Application->make() at /vendor/laravel/framework/src/Illuminate/Container/Container.php:809
Illuminate\Container\Container->offsetGet() at /vendor/pragmarx/firewall/src/Vendor/Laravel/ServiceProvider.php:153
PragmaRX\Firewall\Vendor\Laravel\ServiceProvider->PragmaRX\Firewall\Vendor\Laravel\{closure}() at /vendor/laravel/framework/src/Illuminate/Container/Container.php:207
Illuminate\Container\Container->Illuminate\Container\{closure}() at /vendor/laravel/framework/src/Illuminate/Container/Container.php:498
Illuminate\Container\Container->build() at /vendor/laravel/framework/src/Illuminate/Container/Container.php:425
Illuminate\Container\Container->make() at /vendor/laravel/framework/src/Illuminate/Foundation/Application.php:463
Illuminate\Foundation\Application->make() at /vendor/laravel/framework/src/Illuminate/Container/Container.php:809
Illuminate\Container\Container->offsetGet() at /vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:146
Illuminate\Support\Facades\Facade::resolveFacadeInstance() at /vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:116
Illuminate\Support\Facades\Facade::getFacadeRoot() at /vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:200
Illuminate\Support\Facades\Facade::__callStatic() at /app/database/migrations/2014_11_13_013053_create_firewall_tables.php:16
PragmaRX\Firewall\Vendor\Laravel\Facade::getMigrator() at /app/database/migrations/2014_11_13_013053_create_firewall_tables.php:16
CreateFirewallTables->up() at /vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:133
Illuminate\Database\Migrations\Migrator->runUp() at /vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:109
Illuminate\Database\Migrations\Migrator->runMigrationList() at /vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:80
Illuminate\Database\Migrations\Migrator->run() at /vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:65
Illuminate\Database\Console\Migrations\MigrateCommand->fire() at /vendor/laravel/framework/src/Illuminate/Console/Command.php:108
Illuminate\Console\Command->execute() at /vendor/symfony/console/Symfony/Component/Console/Command/Command.php:241
Symfony\Component\Console\Command\Command->run() at /vendor/laravel/framework/src/Illuminate/Console/Command.php:96
Illuminate\Console\Command->run() at /vendor/symfony/console/Symfony/Component/Console/Application.php:887
Symfony\Component\Console\Application->doRunCommand() at /vendor/symfony/console/Symfony/Component/Console/Application.php:191
Symfony\Component\Console\Application->doRun() at /vendor/symfony/console/Symfony/Component/Console/Application.php:121
Symfony\Component\Console\Application->run() at /artisan:59

Unexpected Class for GeoIP - Laravel 4.2

After i update your codes... and when i re-run the php artisan migrate i have this new line or error again.

{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'","file":"\/home\/sitename\/vendor\/pragmarx\/support\/src\/geoip\/GeoIp.php","line":38}}

Again, everything are in placed... it looks like, the codes was referring to Laravel 5.2? or it is flexible to 4.2?

Note: Also i tried to use the old GeoIP.php file and seems to work fine, though the problem here is, It never redirect to certain page if the IP or country was blocked...

Routes was served like this:

    Route::group(array('before' => 'fw-block-bl'), function() {
        Route::get('blockd', function(){
            return View::make('_home.blockd');
        });

        Route::group(array('before' => 'fw-allow-wl'), function() {
            Route::get('/', 'PagesController@homeLatest');
        }); 
    });

But if i am visiting the page, it always went to blank page... which is weird in my understanding.

ReflectionException when trying to use this library

Whoops, looks like something went wrong.
1/1 ReflectionException in Container.php line 741: Class fw-allow-wl does not exist

in Container.php line 741
at ReflectionClass->__construct('fw-allow-wl') in Container.php line 741
at Container->build('fw-allow-wl', array()) in Container.php line 631
at Container->make('fw-allow-wl', array()) in Application.php line 674
at Application->make('fw-allow-wl') in Pipeline.php line 123
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 710
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 675
at Router->dispatchToRoute(object(Request)) in Router.php line 635
at Router->dispatch(object(Request)) in Kernel.php line 236
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in PrerenderMiddleware.php line 105
at PrerenderMiddleware->handle(object(Request), object(Closure))
at call_user_func_array(array(object(PrerenderMiddleware), 'handle'), array(object(Request), 

can't use artisan commands in latest version

Using the latest 1.0.3 and Laravel 5.2.45. Following all your installation instructions.

Firewall is working for blocking single IPs

Only artisan commands available are "tables" and "list". Cannot use clear, whitelist or blacklist.

Have added countries to block manually to the firewall.php config file. I've added a large list of countries on individual line. Even if I uncomment the country I am testing access from, it always blocks me. No caches are enabled. It always blocks me if I have country search enabled.

Any chance for an update?

isLaravel5 funciton is not visible

There is an error.

I think it's because the call of isLaravel5 is placed before it's declaration:

declaration on 1086 line

if ( ! function_exists( 'isLaravel5' ))
{
	_function isLaravel5()_
	{
		return Laravel::VERSION >= '5.0.0';
	}
   ...

and call on 927

if ( ! function_exists( 'csrf_token' ) && ! isLaravel5())

An error

$ php artisan optimaze                                                                                                                                                                              
                                                                                                                                                                                                    
Fatal error: Call to undefined function isLaravel5() in C:\OpenServer\domains\shaman-admin-api\vendor\pragmarx\support\src\helpers.php on line 927                                                  
                                                                                                                                                                                                    
Call Stack:                                                                                                                                                                                         
    0.0002     128976   1. {main}() C:\OpenServer\domains\shaman-admin-api\artisan:0                                                                                                                
    0.0004     131064   2. require('C:\OpenServer\domains\shaman-admin-api\bootstrap\autoload.php') C:\OpenServer\domains\shaman-admin-api\artisan:16                                               
    0.0006     132496   3. require('C:\OpenServer\domains\shaman-admin-api\vendor\autoload.php') C:\OpenServer\domains\shaman-admin-api\bootstrap\autoload.php:17                                   
    0.0008     145080   4. ComposerAutoloaderInit5e6695309826f98ddf2a06b49a4e09ac::getLoader() C:\OpenServer\domains\shaman-admin-api\vendor\autoload.php:7                                         
    0.0161    1593912   5. composerRequire5e6695309826f98ddf2a06b49a4e09ac() C:\OpenServer\domains\shaman-admin-api\vendor\composer\autoload_real.php:56                                            
    0.0174    1741464   6. require('C:\OpenServer\domains\shaman-admin-api\vendor\pragmarx\support\src\helpers.php') C:\OpenServer\domains\shaman-admin-api\vendor\composer\autoload_real.php:66    
                                                                                                                                                                                                    
Dump $_SERVER                                                                                                                                                                                       
   $_SERVER['REMOTE_ADDR'] is undefined                                                                                                                                                             
   $_SERVER['REQUEST_METHOD'] is undefined                                                                                                                                                          
Dump $_SESSION                                                                                                                                                                                      
   $_SESSION['*'] is undefined                                                                                                                                                                      
Dump $_REQUEST              

Error on Migrate:Refresh --Seed

When using firewall if I run:

php artisan migrate:refresh --seed

I get a Symfony error. My guess is because firewall doesn't keep its migration file inside laravels migration folder, but instead inside its own vendor folder.

$ php artisan migrate:refresh --seed
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Call to undefined method PragmaRX\\Firewall\\Vendor\\Laravel\\Facade::down()","file":"\/Users\/Alex\/Sandbox\/01_projects\/lla\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Migrations\/Migrator.php","line":197}}

Any idea how I can get this to work?

Compatibility with 5.4 - method share was removed

Command php artisan optimize returns following errors

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Call to undefined method Illuminate\Foundation\Application::share()


Script php artisan optimize handling the post-update-cmd event returned with error code 255

There is an explanation https://laracasts.com/discuss/channels/laravel/undefined-method-illuminatefoundationapplicationshare-when-upgrading-to-laravel-54

Method share has been removed and should be replaced with the singleton.

Requirements could not be resolved to an installable set of packages

Attemping $composer require pragmarx/firewall in a Laravel 4.2 installation causes the following error:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for pragmarx/firewall 0.3.* -> satisfiable by pragmarx/firewall[v0.3.0].
    - Conclusion: remove laravel/framework v4.2.16
    - pragmarx/firewall v0.3.0 requires illuminate/filesystem ~5 -> satisfiable by illuminate/filesystem[v5.0.0, v5.0.4].
    - don't install illuminate/filesystem v5.0.0|don't install laravel/framework v4.2.16
    - don't install illuminate/filesystem v5.0.4|don't install laravel/framework v4.2.16
    - Installation request for laravel/framework == 4.2.16.0 -> satisfiable by laravel/framework[v4.2.16].

It looks like the requirement for illuminate/filesystem ~5 can't be satisfied without Laravel 5?

Duplicate queries in isBlacklisted

Currently, the isBlacklisted($ip) function queries the database four times, two of those are just duplicates of the first. This is due to the structure of the function:

public function isBlacklisted($ip  = null)
{
    return ! $this->isWhitelisted($ip) &&
            $this->whichList($ip) == 'blacklist';
}

The isWhitelisted($ip) function uses the whichList function, hence doing two calls to whichList. I might fork this and fix it.

GeoIP is not found

Hello,

Whenever i tried to configure the code, it was ended to this portion:

{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Class 'PragmaRX\Support\GeoIp' not found","file":"\/home\/sitename\/vendor\/pragmarx\/firewall\/src\/Vendor\/Laravel\/ServiceProvider.php","line":151}}

Any idea sir?

IP Addresses not being cached

I'm running 0.2.0 on Laravel 4.1. I have set 'cache_expire_time' => 60 in my config, but I am still seeing a firewall DB hit on every single request. I'm using the Laravel memcached cache driver, which is working fine for in the rest of my application. Not sure if this is a bug or if I could have missed something.

Referring issue to #37 - Unexpected Class from GeoIp

Hi Antonio... After giving it a try again, here's the output of the new installation from Laravel 4.2/Bluehost VPS.

And, just wanted to clarify if i should also need to install the tracker?
And, whenever i try to block a certain country, it is not working... It ends on blank screen instead of /warning page. I did follow correctly but still no luck.

Btw, i have a page that i would like to redirect it to /warning page instead of / or coming/soon...

Route::group(array('before' => 'fw-block-bl'), function() {
    Route::get('warning', 'PagesController@blockedIP');

    Route::group(array('before' => 'fw-allow-wl'), function()  {
        Route::get('/', 'PagesController@homeLatest');
    });
});

And always end up to blank page. No Whoops message, just plain white page.

screenshot 2015-11-30 10 01 55

Migrations problem

Hi,
I have a problem with migrations command:

php artisan firewall:tables

[InvalidArgumentException]
There are no commands defined in the "firewall" namespace.

How can I solve?

Thanks

License Question

Hi @antonioribeiro!

It's a bit confusing how firewall is licensed -- the bottom of the readme says it's MIT, but the license image at the top and the LICENSE are both BSD 3_Clause. Could you clarify? I want to make sure you get correct attribution. :-)

Thanks for making this!
M

compatibility with laravel 5.2.5?

I recently upgraded my application to 5.2.5 and soon saw a few errors from the package. I am pasting the stack below here:

[2015-12-29 09:23:20] local.ERROR: exception 'BadMethodCallException' with message 'Method filter does not exist.' in /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php:81
Stack trace:
#0 /home/vagrant/Code/archive/vendor/pragmarx/firewall/src/Vendor/Laravel/ServiceProvider.php(163): Illuminate\Routing\Router->__call('filter', Array)
#1 /home/vagrant/Code/archive/vendor/pragmarx/firewall/src/Vendor/Laravel/ServiceProvider.php(163): Illuminate\Routing\Router->filter('fw-block-bl', '\\PragmaRX\\Firew...')
#2 /home/vagrant/Code/archive/vendor/pragmarx/firewall/src/Vendor/Laravel/ServiceProvider.php(67): PragmaRX\Firewall\Vendor\Laravel\ServiceProvider->registerFilters()
#3 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(531): PragmaRX\Firewall\Vendor\Laravel\ServiceProvider->register()
#4 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php(74): Illuminate\Foundation\Application->register(Object(PragmaRX\Firewall\Vendor\Laravel\ServiceProvider))
#5 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(507): Illuminate\Foundation\ProviderRepository->load(Array)
#6 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Bootstrap/RegisterProviders.php(17): Illuminate\Foundation\Application->registerConfiguredProviders()
#7 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Application.php(203): Illuminate\Foundation\Bootstrap\RegisterProviders->bootstrap(Object(Illuminate\Foundation\Application))
#8 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(208): Illuminate\Foundation\Application->bootstrapWith(Array)
#9 /home/vagrant/Code/archive/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(105): Illuminate\Foundation\Console\Kernel->bootstrap()
#10 /home/vagrant/Code/archive/artisan(36): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#11 {main}

I also posted a question at SO here

Now the package is really great, no doubt, but I am guessing it is not compatible with 5.2.5. How do I work around this?

Support for CIDR would be really helpful

It would be really nice to have if you would add support of CIDR and wildcard such as (192.168.0.*). This would make this module really powerful. I would like to raise this as a feature request.

Thank you

Firewall Facade not found

Currently using Laravel 5.1.

Can't use any of the static methods in the Firewall Facade, generally because it seems that the facade can't be seen.

And the service provider and aliases have been properly configured.

image

image

I tried to rule out the possibility that it only conflicts with some of my packages so I tried it on a fresh install of laravel 5.1

image

And so, as of writing, I realize that it might be because it doesn't support 5.1 yet?

composer.json PHP 5.4+

This package is not compatible with PHP 5.3 as it uses PHPs array shorthand syntax. 5.4 is also needed for using $this in anonymous functions.

Please update composer.json to reflect the needed version of PHP.

firewall:blacklist country:ca

Running the above command after doing the relevant migrations and adding the service provider I've run into the error:

country:ca is not a valid IP address

Error in Laravel 4.0.*

After installation I get the following error when trying to open one of my views.

Error in exception handler: The "C:\xampp\htdocs\project\vendor\pragmarx\firewall\src\Vendor\Laravel/../../views" directory does not exist. in C:\xampp\htdocs\project\vendor\twig\twig\lib\Twig\Loader\Filesystem.php:93

My composer.json dependencies:

    "require": {
        "laravel/framework": "4.0.*",
        "atrauzzi/laravel-doctrine": "dev-master",
        "rcrowe/twigbridge": "0.5.*",
        "barryvdh/laravel-ide-helper": "1.*",
        "robmorgan/phinx": "0.3.8",
        "squizlabs/php_codesniffer": "1.*",
        "phprtflite/phprtflite": "master",
        "lucadegasperi/oauth2-server-laravel": "1.0.x",
        "zircote/swagger-php": "*",
        "pragmarx/firewall": "0.5.*@dev"
    },

can't get IPs from a file

it seems that we can't use this feature :

'blacklist' => array(
    '/path/to/dir/blacklisted.txt',
)

laravel 5.1 not working

why it is not working with laravel 5.1, my settings:

protected $routeMiddleware = [
    'fw-block-bl' => \PragmaRX\Firewall\Middleware\FirewallBlacklist::class,
    'fw-allow-wl' => \PragmaRX\Firewall\Middleware\FirewallWhitelist::class,
];

'blacklist' => [
    '192.168.10.111',
    '*.*.*.*',
    '127.0.0.1',
    '::1',
],

'whitelist' => [
     '127.0.0.2',
 ],

Route::group(['before' => 'fw-block-bl'], function ()
{
    Route::get('/h2', 'HomeController@index');
});

OR

Route::group(['middleware' => 'fw-block-bl'], function ()
{
    Route::get('/h2', 'HomeController@index');
});

nothing blocked, I think the middleware not working? any idea?

thanks in advance.

Installation error with PHP7.1 (Composer 1.3)

"pragmarx/firewall": "0.5.*@dev",
Updates: pragmarx/firewall:dev-master 04e61fa

  - Updating pragmarx/firewall dev-master (0d19bc3 => 04e61fa)    The package has modified files:
    M .gitignore
    M .travis.yml
    M LICENSE
    M changelog.md
    M composer.json
    M phpunit.xml
    M readme.md
    M src/Database/Migrator.php
    M src/Exceptions/ConfigurationOptionNotAvailable.php
    M src/Filters/Blacklist.php

                                   
  [ErrorException]                 
  A non-numeric value encountered  
                                   

Exception trace:
 () at phar:///usr/local/bin/composer/src/Composer/Downloader/GitDownloader.php:254
 Composer\Util\ErrorHandler::handle() at phar:///usr/local/bin/composer/src/Composer/Downloader/GitDownloader.php:254
 Composer\Downloader\GitDownloader->cleanChanges() at phar:///usr/local/bin/composer/src/Composer/Downloader/VcsDownloader.php:135
 Composer\Downloader\VcsDownloader->update() at phar:///usr/local/bin/composer/src/Composer/Downloader/DownloadManager.php:268
 Composer\Downloader\DownloadManager->update() at phar:///usr/local/bin/composer/src/Composer/Installer/LibraryInstaller.php:207
 Composer\Installer\LibraryInstaller->updateCode() at phar:///usr/local/bin/composer/src/Composer/Installer/LibraryInstaller.php:109
 Composer\Installer\LibraryInstaller->update() at phar:///usr/local/bin/composer/src/Composer/Installer/InstallationManager.php:193
 Composer\Installer\InstallationManager->update() at phar:///usr/local/bin/composer/src/Composer/Installer/InstallationManager.php:160
 Composer\Installer\InstallationManager->execute() at phar:///usr/local/bin/composer/src/Composer/Installer.php:584
 Composer\Installer->doInstall() at phar:///usr/local/bin/composer/src/Composer/Installer.php:223
 Composer\Installer->run() at phar:///usr/local/bin/composer/src/Composer/Command/UpdateCommand.php:158
 Composer\Command\UpdateCommand->execute() at phar:///usr/local/bin/composer/vendor/symfony/console/Command/Command.php:257
 Symfony\Component\Console\Command\Command->run() at phar:///usr/local/bin/composer/vendor/symfony/console/Application.php:849
 Symfony\Component\Console\Application->doRunCommand() at phar:///usr/local/bin/composer/vendor/symfony/console/Application.php:193
 Symfony\Component\Console\Application->doRun() at phar:///usr/local/bin/composer/src/Composer/Console/Application.php:227
 Composer\Console\Application->doRun() at phar:///usr/local/bin/composer/vendor/symfony/console/Application.php:124
 Symfony\Component\Console\Application->run() at phar:///usr/local/bin/composer/src/Composer/Console/Application.php:100
 Composer\Console\Application->run() at phar:///usr/local/bin/composer/bin/composer:52
 require() at /usr/local/bin/composer:24

Setting ip_list_cache_expire_time breaks firewall:list command

If you set the ip_list_cache_expire_time variable in the configuration file to something other than zero, php artisan firewall:list no longer works.

The reason is because firewall:list uses the the all() method in the Firewall class and the first thing the all() method does is this:

public function all()
{
    $cacheTime = $this->config->get('ip_list_cache_expire_time');

    if ($cacheTime && $this->cache->has(static::IP_ADDRESS_LIST_CACHE_NAME))
    {
        return $this->cache->get(static::IP_ADDRESS_LIST_CACHE_NAME);
    }
...

I'm not sure what this has to do with returning the list of currently blacklisted/whitelisted IP addresses. I would lodge a PR except this code looks so deliberate that I'm sure I'm missing something and I don't want to break some other behaviour that was intended.

I discovered this issue when I accidentally set ip_list_cache_expire_time instead of cache_expire_time. Once I set ip_list_cache_expire_time back to zero, the firewall:list function worked again.

php artisan firewall:tables not working

Hi

Upon execution of php artisan firewall:tables, I get the following error "Invalid Argument Exception", there are no commands defined in the "firewall" namespace. Tried uninstalling and reinstalling a few times, nothing has changed. Any tips on this would be appreciated.

Behind load balancer / proxy

If the app is behind a load balancer or proxy then getClientIp() will return the IP address of the load balancer or proxy, not the IP address of the actual client. Is there a way to use x-forwarded-for or to setTrustedProxies() on the request used by the firewall? Maybe this should be a config option which is set on the request in the service provider. Any help would be appreciated.

Handling for use of both whitelist and blacklist in evaluation?

I glanced through the code and tried to figure out if there was anything in there for this, but didn't see it right off the bat. What happens if you get more complex with your needs and want to apply both the whitelist and blacklist to a route? From what I can tell right now, it's a "last in wins" kind of scenario - is this valid?

I could see someone wanting to, say, allow everyone from a specific subnet inside an organization to be able to view some data (maybe /user/view/1) but prevent others from viewing it. With the current setup it looks like that might just have to be some kind of nested route handling, but that seems like a bit of overkill.

Breaks in production with Laravel 5.3.30

Steps to reproduce:

composer create-project laravel/laravel l53test 5.3.30
edit .env set to production and debug = false
composer require pragmarx/firewall
php artisan // boom

PHP Fatal error: Cannot declare interface Illuminate\Contracts\Container\Container, because the name is already in use in {dir}/bootstrap/cache/compiled.php on line 4

Does not break if Laravel 5.3.16 is installed this way, so there's a conflict/regression somewhere.

Call to undefined method PragmaRX\Firewall\Firewall::blockAccess()

Have just installed into my Laravel 4.1 project and get the following error:

Call to undefined method PragmaRX\Firewall\Firewall::blockAccess()

Your service provider returns an instance of Firewall for the firewall service and that class doesn't have a blockAccess method, but the service provider does.

All very odd...

IP blacklisting broken (commit 0c901ed)

Hello,

in our environment the IP blacklisting is not working.
We think we spotted the error, it's in the Firewall::isBlacklisted() method:

    /**
     * Check if IP is blacklisted.
     *
     * @param null $ip
     * @return bool
     */
    public function isBlacklisted($ip = null) {
        $list = $this->whichList($ip);
        return !$list == 'whitelist' &&
        $list == 'blacklist';
    }

The boolean expression at the end returns FALSE for IP's which are blacklisted
but not whitelisted.

The problem is caused by missing parentheses around the first comparison.
Correct would be:

return !($list == 'whitelist') &&
       $list == 'blacklist';

Best regards,
Anke

Matching non-database IP always matches country code

It looks like the following code is always matching the first results in the array listing of IP address and countries using the config file (not database), even though it shouldn't.

https://github.com/antonioribeiro/firewall/blob/master/src/Repositories/Firewall/Firewall.php

private function ipArraySearch($ip, $ips)
    {
        foreach($ips as $key => $value)
        {
            if (
                (isset($value['ip_address']) && $value['ip_address'] == $ip) ||
                ($key == $ip) ||
                ($value == $ip)
            )
            {
                return $value;
            }
        }
        return false;
    }

Changing:

($key == $ip) ||

To:

(strval($key) == $ip) ||

Will fix it and only return the appropriate result.

Laravel 5.1 anyone get it working?

I'm wondering if anyone has gotten this working with 5.1. I've wrapped all my routes with Route::group(['before' => 'fw-block-bl'], function () { and added ips to blacklist but it is still allowing me to access all routes.

Thanks!

php artisan firewall:tables -> 'ErrorException' with message 'file_put_contents(...

I am trying out this package, and during the install process, the php artisan firewall:tables command runs into an Exception. It seems that it is trying to put the migration file ona path that is L4 specific:

exception 'ErrorException' with message 'file_put_contents(/home/vagrant/[APP_ROOT]/app/database/migrations/2015_02_18_185309_create_firewall_tables.php): failed to open stream: No such file or directory' in /home/vagrant/[APP_ROOT]/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:74

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.