Skip to main content
Version: v1.4.0

PHP Bouncer Library

CrowdSec

💠 Hub💬 Discourse

Introduction#

Description#

This library allows you to create CrowdSec bouncers for PHP applications or frameworks like e-commerce, blog or other exposed applications. It can also be used in a standalone mode using auto-prepend directive.

Prerequisites#

To be able to use this bouncer, the first step is to install CrowdSec v1. CrowdSec is only in charge of the "detection", and won't block anything on its own. You need to deploy a bouncer to "apply" decisions.

Please note that first and foremost a CrowdSec agent must be installed on a server that is accessible by this library.

Features#

  • CrowdSec Local API Support
    • Handle IP, IP ranges and Country scoped decisions
    • Clear, prune and refresh the Local API cache
    • Live mode or Stream mode
    • Api-Key and TLS connection
  • Large PHP matrix compatibility: 7.2.x, 7.3.x, 7.4.x, 8.0.x and 8.1.x
  • Built-in support for the most known cache systems like Redis, Memcached, PhpFiles
  • Events logged using monolog
  • Cap remediation level (ex: for sensitives websites: ban will be capped to captcha)

Usage#

When a user is suspected by CrowdSec to be malevolent, a bouncer will either send him/her a captcha to resolve or simply a page notifying that access is denied. If the user is considered as a clean user, he will access the page as normal.

By default, the ban wall is displayed as below:

Ban wall

By default, the captcha wall is displayed as below:

Ban wall

Please note that it is possible to customize all the colors of these pages so that they integrate best with your design.

On the other hand, all texts are also fully customizable. This will allow you, for example, to present translated pages in your users' language.

Create your own bouncer#

You can use this library to develop your own PHP application bouncer. Any custom bouncer should extend the AbstractBounce class.

Quick start#

In your PHP project, just add these lines to verify an IP:


<?phpuse CrowdSecBouncer\Bouncer;
// Init bouncer$bouncer = new Bouncer();$bouncer->configure(['api_key' => 'YOUR_BOUNCER_API_KEY', 'api_url' => 'http://localhost:8080']);
// Ask remediation to API$remediation = $bouncer->getRemediationForIp($requestedIp);echo "\nResult: $remediation\n\n"; // "ban", "captcha" or "bypass"

Test your bouncer#

To test your bouncer, you could add decision to ban your own IP for 5 minutes for example:

cscli decisions add --ip <YOUR_IP> --duration 5m --type ban

You can also test a captcha:

cscli decisions delete --all # be careful with this command!cscli decisions add --ip <YOUR_IP> --duration 15m --type captcha

Configurations#

You can pass an array of configurations in the $bouncer->configure($configs) method.

Here is the list of available settings:

Local API Connection#
  • auth_type: Select from api_key and tls. Choose if you want to use an API-KEY or a TLS (pki) authentification. TLS authentication is only available if you use CrowdSec agent with a version superior to 1.4.0.
  • api_key: Key generated by the cscli (CrowdSec cli) command like cscli bouncers add bouncer-php-library. Only required if you choose api_key as auth_type.
  • tls_cert_path: absolute path to the bouncer certificate (e.g. pem file). Only required if you choose tls as auth_type.
  • tls_key_path: Absolute path to the bouncer key (e.g. pem file). Only required if you choose tls as auth_type.
  • tls_verify_peer: This option determines whether request handler verifies the authenticity of the peer's certificate. Only required if you choose tls as auth_type. When negotiating a TLS or SSL connection, the server sends a certificate indicating its identity. If tls_verify_peer is set to true, request handler verifies whether the certificate is authentic. This trust is based on a chain of digital signatures, rooted in certification authority (CA) certificates you supply using the tls_ca_cert_path setting below.
  • tls_ca_cert_path: Absolute path to the CA used to process peer verification. Only required if you choose tls as auth_type and tls_verify_peer is set to true.
  • api_url: Define the URL to your Local API server, default to http://localhost:8080.
  • api_timeout: In seconds. The timeout when calling Local API. Must be greater or equal than 1. Default to 1 sec.
  • use_curl: By default, this lib call the REST Local API using file_get_contents method (allow_url_fopen is required). You can set use_curl to true in order to use cURL request instead (curl is in then required)
Debug#
  • debug_mode: true to enable verbose debug log. Default to false.
  • disable_prod_log: true to disable prod log. Default to false.
  • log_directory_path: Absolute path to store log files. Important note: be sur this path won't be publicly accessible.
  • display_errors: true to stop the process and display errors on browser if any.
  • forced_test_ip: Only for test or debug purpose. Default to empty. If not empty, it will be used instead of the real remote ip.
  • forced_test_forwarded_ip: Only for test or debug purpose. Default to empty. If not empty, it will be used instead of the real forwarded ip. If set to no_forward, the x-forwarded-for mechanism will not be used at all.
Bouncer behavior#
  • bouncing_level: Select from bouncing_disabled, normal_bouncing or flex_bouncing. Choose if you want to apply CrowdSec directives (Normal bouncing) or be more permissive (Flex bouncing). With the Flex mode, it is impossible to accidentally block access to your site to people who don’t deserve it. This mode makes it possible to never ban an IP but only to offer a Captcha, in the worst-case scenario.
  • fallback_remediation: Select from bypass (minimum remediation), captcha or ban (maximum remediation). Default to 'captcha'. Handle unknown remediations as.
  • max_remediation_level: Select from bypass,captcha or ban. Default to 'ban'. Cap the remediation to the selected one.
  • trust_ip_forward_array: If you use a CDN, a reverse proxy or a load balancer, set an array of IPs. For other IPs, the bouncer will not trust the X-Forwarded-For header.
  • excluded_uris: array of URIs that will not be bounced.
Cache#
  • cache_system: Select from phpfs (File system cache), redis or memcached.
  • fs_cache_path: Will be used only if you choose File system as cache_system. Important note: be sur this path won't be publicly accessible.
  • redis_dsn: Will be used only if you choose Redis cache as cache_system.
  • memcached_dsn: Will be used only if you choose Memcached as cache_system.
  • clean_ip_cache_duration: Set the duration we keep in cache the fact that an IP is clean. In seconds. Defaults to 5.
  • bad_ip_cache_duration: Set the duration we keep in cache the fact that an IP is bad. In seconds. Defaults to 20.
  • captcha_cache_duration: Set the duration we keep in cache the captcha flow variables for an IP. In seconds. Defaults to 86400.. In seconds. Defaults to 20.
  • geolocation_cache_duration: Set the duration we keep in cache a geolocation result for an IP . In seconds. Defaults to 86400. Depends on the below geolocation[save_result] configuration.
  • stream_mode: true to enable stream mode, false to enable the live mode. Default to false. By default, the live mode is enabled. The first time a stranger connects to your website, this mode means that the IP will be checked directly by the CrowdSec API. The rest of your user’s browsing will be even more transparent thanks to the fully customizable cache system. But you can also activate the stream mode. This mode allows you to constantly feed the bouncer with the malicious IP list via a background task (CRON), making it to be even faster when checking the IP of your visitors. Besides, if your site has a lot of unique visitors at the same time, this will not influence the traffic to the API of your CrowdSec instance.
Geolocation#
  • geolocation: Settings for geolocation remediation (i.e. country based remediation).

  • geolocation[enabled]: true to enable remediation based on country. Default to false.

  • geolocation[type]: Geolocation system. Only 'maxmind' is available for the moment. Default to maxmind.

  • geolocation[save_result]: true to store the geolocalized country in cache. Default to true. Setting true will avoid multiple call to the geolocalized system (e.g. maxmind database).

  • geolocation[maxmind]: MaxMind settings.

  • geolocation[maxmind][database_type]: Select from country or city. Default to country. These are the two available MaxMind database types.

  • geolocation[maxmind][database_path]: Absolute path to the MaxMind database (e.g. mmdb file)

Captcha and ban wall settings#
  • hide_mentions: true to hide CrowdSec mentions on ban and captcha walls.

  • Wording and css settings:

    theme_color_text_primary

    theme_color_text_secondary

    theme_color_text_button

    theme_color_text_error_message

    theme_color_background_page

    theme_color_background_container

    theme_color_background_button

    theme_color_background_button_hover

    theme_custom_css

    theme_text_captcha_wall_tab_title

    theme_text_captcha_wall_title

    theme_text_captcha_wall_subtitle

    theme_text_captcha_wall_refresh_image_link

    theme_text_captcha_wall_captcha_placeholder

    theme_text_captcha_wall_send_button

    theme_text_captcha_wall_error_message

    theme_text_captcha_wall_footer

    theme_text_ban_wall_tab_title

    theme_text_ban_wall_title

    theme_text_ban_wall_subtitle

    theme_text_ban_wall_footer

The Standalone example#

This library includes the StandaloneBounce class. You can see that class as a good example for creating your own bouncer. This class extends AbstractBounce. All bouncers should do the same. In order to add the bounce logic, you should first instantiate your bouncer:

use \CrowdSecBouncer\StandaloneBounce$bounce = new StandaloneBounce();

And then, you should initialize the bouncer by passing all the configuration array in a init method:

$configs = [...] // @See below for configuration details$bouncer = $bounce->init($configs)

Finally, you can bounce by calling:

$bouncer->run();

If you have implemented a safelyBounce method (like in StandaloneBounce class), you can just do:

use \CrowdSecBouncer\StandaloneBounce$bounce = new StandaloneBounce();$configs = [...] // Retrieve configs from somewhere (database, static file, etc)$bounce->safelyBounce($configs);

To go further and learn how to include this library in your project, you should follow the DEVELOPER GUIDE.

Ready to use PHP bouncers#

To have a more concrete idea on how to develop a bouncer, you may look at the following bouncers for Magento 2 and WordPress :

Installation#

Requirements#

  • PHP >= 7.2
  • required php extensions: ext-json, ext-gd
  • suggested php extension: ext-curl

Library installation#

Use Composer by simply adding crowdsec/bouncer as a dependency:

composer require crowdsec/bouncer

Standalone mode installation#

This library can also be used on its own so that every browser access to a php script will be bounced.

In order to use the standalone mode, you will have to :

  • give the correct permission for the folder that contains the lib

  • copy the scripts/auto-prepend/settings.example.php to a scripts/auto-prepend/settings.php file

  • set an auto_prepend_file directive in your PHP setup.

Files permission#

The owner of the /path/to/the/crowdsec-lib should be your webserver owner (e.g. www-data).

You can achieve it by running command like:

sudo chown www-data /path/to/the/crowdsec-lib

Settings file#

Please copy the scripts/auto-prepend/settings.example.php to a scripts/auto-prepend/settings.php and fill the necessary settings in it.

auto_prepend_file directive#

We will now describe how to set an auto_prepend_file directive in order to call the scripts/auto-prepend/bounce.php for each php script access.

Adding an auto_prepend_file directive can be done in different ways:

.ini file#

You should add this line to a .ini file :

auto_prepend_file = /absolute/path/to/scripts/auto-prepend/bounce.php
Nginx#

If you are using Nginx, you should modify your nginx configuration file by adding a fastcgi_param directive. The php block should look like below:

location ~ \.php$ {    ...    ...    ...    fastcgi_param PHP_VALUE "/absolute/path/to/scripts/auto-prepend/bounce.php";}
Apache#

If you are using Apache, you should add this line to your .htaccess file:

php_value auto_prepend_file "/absolute/path/to/scripts/auto-prepend/bounce.php"

Technical notes#

See Technical notes

Developer guide#

See Developer guide