Block many wrong requests via PHP



  • I have an API that requires a security token to run. Is it possible to use Fail2Ban or ModEvasive to block access from IPs that often try to access the API with an incorrect token?

    I use PHP to receive these requests, is it possible with it to inform Fail2Ban or ModEvasive that the user's IP should be blocked (temporarily), for example, after 10 failed attempts?



  • If such an abusive token usage is logged in log-file or journal from your application (API) you can use fail2ban to ban them. Here is an example for log-file:

    [my-php-app]
    ports = http,https
    backend = auto
    logpath = /var/log/path-to-my.log
    datepattern = ^{DATE}
    failregex = ^\s*<ADDR>\s+\S+\s+Incorrect token used\.
    maxretry = 10
    findtime = 30m
    bantime = 1h
    

    For systemd journal you have to set backend to systemd (and proper value for journalmatch, see the man pages or fail2ban's default filters for example).

    This would match messages illustrated by following test and ban for 1 hour all intruders doing that after 10 attempts occurred in 30 minutes.

    $ msg="$(date +%FT%T) 192.0.2.1 - Incorrect token used. (more info here ...)"
    $ fail2ban-client -d '^{DATE}' "$msg" '^\s*<ADDR>\s+\S+\s+Incorrect token used\.'
    
    Running tests
    =============
    
    Use      datepattern : ^{DATE} : Default Detectors
    Use   failregex line : ^\s*<ADDR>\s+\S+\s+Incorrect token used\.
    Use      single line : 2021-06-11T17:00:03 192.0.2.1 - Incorrect token us...
    
    
    Results
    =======
    
    Failregex: 1 total
    |-  #) [# of hits] regular expression
    |   1) [1] ^\s*<ADDR>\s+\S+\s+Incorrect token used\.
    `-
    
    Ignoreregex: 0 total
    
    Date template hits:
    |- [# of hits] date format
    |  [1] ^ExYear(?P<_sep>[-/.])Month(?P=_sep)Day(?:T|  ?)24hour:Minute:Second(?:[.,]Microseconds)?(?:\s*Zone offset)?
    `-
    
    Lines: 1 lines, 0 ignored, 1 matched, 0 missed
    [processed in 0.00 sec]
    

    If you has different logging format you must adjust failregex (and possibly datepattern).


    Newer version of fail2ban allows direct notification from application using fail2ban-API (via client or direct via pickle protocol to unix-socket), see GH/fail2ban/fail2ban#2559 (comment). Prerequirements for this - your php-fpm user is able to write to /run/fail2ban/fail2ban.sock.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2