Fail2ban: Difference between revisions

imported>Occhioverde
Document all the availabe Fail2ban module options
imported>Occhioverde
Added instructions on how to create new actions and filters; added "See also" section
Line 54: Line 54:
   };
   };
</syntaxHighlight>
</syntaxHighlight>
== Extending Fail2ban ==
Fail2ban capabilities can be freely extended by adding new jails, filters, and actions; the first ones of them are already covered in the "Basic usage" section, while the other two need dedicated config files to be created in the <source lang="nix" enclose="none">/etc/fail2ban/filter.d</source> and <source lang="nix" enclose="none">/etc/fail2ban/action.d</source> folders.
In order to do this, you'll have to add a <source lang="nix" enclose="none">environment.etc</source> section to your NixOS config file and specify there the contents of your custom actions and filters:
<syntaxHighlight lang=nix>
  environment.etc = {
    # Define an action that will trigger a Ntfy push notification upon the issue of every new ban
    "fail2ban/action.d/ntfy.local".text = pkgs.lib.mkDefault (pkgs.lib.mkAfter ''
      [Definition]
      norestored = true # Needed to avoid receiving a new notification after every restart
      actionban = curl -H "Title: <ip> has been banned" -d "<name> jail has banned <ip> from accessing $(hostname) after <failures> attempts of hacking the system." https://ntfy.sh/Fail2banNotifications
    '');
    # Defines a filter that detects URL probing by reading the Nginx access log
    "fail2ban/filter.d/nginx-url-probe.local".text = pkgs.lib.mkDefault (pkgs.lib.mkAfter ''
      [Definition]
      failregex = ^<HOST>.*(GET /(wp-|admin|boaform|phpmyadmin|\.env|\.git)|\.(dll|so|cfm|asp)|(\?|&)(=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000|=PHPE9568F36-D428-11d2-A769-00AA001ACF42|=PHPE9568F35-D428-11d2-A769-00AA001ACF42|=PHPE9568F34-D428-11d2-A769-00AA001ACF42)|\\x[0-9a-zA-Z]{2})
    '');
  };
</syntaxHighlight>
The defined filters and actions can then be used in a new jail (created as seen above):
<syntaxHighlight lang=nix>
  services.fail2ban = {
    # --- snip ---
    jails = {
      ngnix-url-probe = ''
        enabled = true
        filter = nginx-url-probe
        logpath = /var/log/nginx/access.log
        action = %(action_)s[blocktype=DROP]
                ntfy
        backend = auto # Do not forget to specify this if your jail uses a log file
        maxretry = 5
        findtime = 600
      '';
    };
  };
</syntaxHighlight>
For more details on how to develop Fail2ban filters please see [https://fail2ban.readthedocs.io/en/latest/filters.html the official documentation].
== See also ==
* Linode's tutorial on how to setup Fail2ban (not NixOS-specific): https://www.linode.com/docs/guides/using-fail2ban-to-secure-your-server-a-tutorial/
* Solène's blog post on how to extend Fail2ban on NixOS: https://dataswamp.org/~solene/2022-10-02-nixos-fail2ban.html


[[Category:Applications]]
[[Category:Applications]]