summaryrefslogtreecommitdiffstats
path: root/configs/fail2ban.nix
blob: 8bffe7042a48941b6d2f754e6c4d3512f7c3e5f4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
{
  environment.etc."fail2ban/filter.d/sshd-normal.local".text = ''
    [Definition]
    failregex   = ^.*: Failed password for .* from <HOST> port \d+.*$
                  ^.*: pam_unix\(sshd:auth\): authentication failure;.* rhost=<HOST>\b.*$
    ignoreregex = ^.*: Failed password for root from <HOST> port \d+.*$
                  ^.*: pam_unix\(sshd:auth\): authentication failure;.* rhost=<HOST>\b.* user=root\b.*$
  '';

  # The pam_unix lines look like:
  #   pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=10.243.13.42  user=root
  environment.etc."fail2ban/filter.d/sshd-instaban.local".text = ''
    [Definition]
    failregex   = ^.*: (?:Failed password for invalid user|Invalid user|Failed password for root)\b.* from <HOST> port \d+.*$
                  ^.*: pam_unix\(sshd:auth\): authentication failure;.* rhost=<HOST>\b.* user=root\b.*$
  '';

  services.fail2ban = {
    enable = true;

    ignoreIP = [
      "10.0.0.0/8"
      "172.16.0.0/12"
      "192.168.0.0/16"
      "42::/16"
    ];

    bantime-increment = {
      enable = true;
      multipliers = "1 2 4 8 16 32 64";
      maxtime = "168h";
      overalljails = true;
    };

    jails = {
      # Disable NixOS' default sshd jail.
      sshd.enabled = false;

      sshd-instaban.settings = {
        filter = "sshd-instaban";
        port = "ssh";
        findtime = 600;
        maxretry = 1;
        bantime = "24h";
        # nft verdicts are lowercase (iptables' would be DROP).
        action = "%(action_)s[blocktype=drop]";

        journalmatch = ''
          SYSLOG_IDENTIFIER=sshd-session
        '';
      };
      sshd-normal.settings = {
        filter = "sshd-normal";
        port = "ssh";

        journalmatch = ''
          SYSLOG_IDENTIFIER=sshd-session
        '';

        findtime = 600; # 10 minutes
        maxretry = 5;
        bantime = "24h";
      };
    };
  };

  # services.fail2ban sets this to "VERBOSE".
  services.openssh.settings.LogLevel = "INFO";
}