From a9dcf73cc1f2ef49befb2e243013e776d74963a2 Mon Sep 17 00:00:00 2001
From: Eesaan Atluri <atlurie@uab.edu>
Date: Fri, 24 Jan 2025 19:13:38 -0500
Subject: [PATCH] feat: Add fail2ban config files as templates

Adds fail2ban filter and jail configs
---
 ansible/group_vars/all                        |  6 +++++
 .../roles/fail2ban/templates/jail.local.j2    |  7 ++++++
 .../templates/sshpiperd_filter.local.j2       | 22 +++++++++++++++++++
 .../templates/sshpiperd_jail.local.j2         |  9 ++++++++
 4 files changed, 44 insertions(+)
 create mode 100644 ansible/roles/fail2ban/templates/jail.local.j2
 create mode 100644 ansible/roles/fail2ban/templates/sshpiperd_filter.local.j2
 create mode 100644 ansible/roles/fail2ban/templates/sshpiperd_jail.local.j2

diff --git a/ansible/group_vars/all b/ansible/group_vars/all
index 7055312..357ce7b 100644
--- a/ansible/group_vars/all
+++ b/ansible/group_vars/all
@@ -75,3 +75,9 @@
 
 # account app
   account_app_port: 8000
+
+# fail2ban
+  enable_fail2ban: true
+  maxretry: 1
+  findtime: 600
+  bantime: 1200
diff --git a/ansible/roles/fail2ban/templates/jail.local.j2 b/ansible/roles/fail2ban/templates/jail.local.j2
new file mode 100644
index 0000000..af6ae66
--- /dev/null
+++ b/ansible/roles/fail2ban/templates/jail.local.j2
@@ -0,0 +1,7 @@
+[DEFAULT]
+banaction = firewalld
+bantime  = {{ bantime }}
+ignoreip = {{ fail2ban_cidr_list }}
+
+[sshd]
+enabled = true
diff --git a/ansible/roles/fail2ban/templates/sshpiperd_filter.local.j2 b/ansible/roles/fail2ban/templates/sshpiperd_filter.local.j2
new file mode 100644
index 0000000..f5a6081
--- /dev/null
+++ b/ansible/roles/fail2ban/templates/sshpiperd_filter.local.j2
@@ -0,0 +1,22 @@
+# Refer to https://github.com/fail2ban/fail2ban/wiki/Developing-Regex-in-Fail2ban for developing regex using fail2ban
+#
+[INCLUDES]
+before = common.conf
+
+[DEFAULT]
+_daemon = sshpiperd
+__iso_datetime = "\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[+-]\d{2}:\d{2}|Z)"
+__pref = time=%(__iso_datetime)s level=(?:debug|error)
+
+[Definition]
+# Define the prefix regex for the log lines
+prefregex = ^<F-MLFID>%(__prefix_line)s%(__pref)s</F-MLFID>\s+<F-CONTENT>.+</F-CONTENT>$
+
+# Failregex to match the specific failure log lines (prefregex is automatically included)
+failregex = ^msg="connection from .*failtoban: ip <HOST> too auth many failures"$
+
+ignoreregex =
+
+mode = normal
+
+maxlines = 1
diff --git a/ansible/roles/fail2ban/templates/sshpiperd_jail.local.j2 b/ansible/roles/fail2ban/templates/sshpiperd_jail.local.j2
new file mode 100644
index 0000000..681212c
--- /dev/null
+++ b/ansible/roles/fail2ban/templates/sshpiperd_jail.local.j2
@@ -0,0 +1,9 @@
+# This configuration will block the remote host after {{maxretry}} failed SSH login attempts.
+[sshpiperd]
+enabled  = true
+filter   = sshpiperd
+logpath  = /var/log/messages
+port     = 22
+maxretry = {{ maxretry }}
+backend  = auto
+findtime = {{ findtime }}
-- 
GitLab