Skip to content

Instantly share code, notes, and snippets.

@ointeractive-depot
Forked from ishukshin/AntiDos.php
Created May 22, 2018 08:45
Show Gist options
  • Save ointeractive-depot/cdf6d56e3cebe074885c0550f5d3baa2 to your computer and use it in GitHub Desktop.
Save ointeractive-depot/cdf6d56e3cebe074885c0550f5d3baa2 to your computer and use it in GitHub Desktop.
Simple laravel app filtering of bad clients using middleware

Feed fail2ban with the log file to ban it

/etc/fail2ban/jail.local file with

[simple-empty]

enabled = true filter = simple-empty #action = iptables-multiport[name=ReqLimit, port="http,https", protocol=tcp] action = cloudflare logpath = /path/to/laravel.app/storage/app/fail2ban.txt findtime = 3600 bantime = 3600 maxretry = 1

/etc/fail2ban/action.d/cloudflare.conf with

actionban=... actionunban=...

<?php
// app/Http/Middleware/AntiDos.php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Closure;
use File;
class AntiDos
{
/**
*
* @param Request $request
* @return boolean
*/
private function _badName(Request $request)
{
return ($request->input('name') === 'A' and $request->input('surname') === 'A');
}
/**
*
* @param Request $request
* @return boolean
*/
private function _badPasswd(Request $request)
{
return !$request->input('password');
}
/**
*
* @param string $ip
*/
private function _logFail($ip)
{
File::append(storage_path('app/fail2ban.txt'), date('Y M d H:i:s ') . $ip . "\n");
}
public function handle(Request $request, Closure $next)
{
# if bad name and passwd, log it, sleep it and deny it
if ($this->_badName($request) and $this->_badPasswd($request)) {
$this->_logFail($request->ip());
sleep(5);
abort(403);
}
return $next($request);
}
}
<?php
// app/Http/Kernel.php
...
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\AntiDos::class,
\App\Http\Middleware\EncryptCookies::class,
...
/etc/fail2ban/filter.d/simple-empty.conf
[Definition]
failregex = .* <HOST>
ignoreregex =
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment