commit 55140d50e36939852d3c44d7630c7497749b3a23 Author: Xavier Date: Wed Aug 24 07:57:22 2022 +0200 first commit diff --git a/README.md b/README.md new file mode 100755 index 0000000..61f6db8 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ + Linux Secu Version 1.0 +============================ + + +Linux Sécu est un outils regroupant
+Fail2ban, rkhunter et debsums
+ +## Version en production 1.0 + +## 1.0 + + +## Menu + +1 -> Run checkrootkit debsums
+2 -> Run check Rkhunter All
+3 -> Run check Rkhunter juste alerte importante
+4 -> Run Update Rkhunter
+5 -> Run Fix Rkhunter
+10 -> Run Update ClamAv
+11 -> Run Scan ClamAv
+20 -> Gestion service
+23 -> Fin du programme + + + +## Gestion service +1 -> Restart fail2ban
+2 -> Check client fail2ban
+3 -> Restart clamav
+10 -> Status fail2ban
+11 -> Status clamav
+23 -> Retour + + + + +73 +Xavier + + + diff --git a/inc/checkrootkit b/inc/checkrootkit new file mode 100755 index 0000000..7e839a7 --- /dev/null +++ b/inc/checkrootkit @@ -0,0 +1,2 @@ +#!/bin/sh +debsums -a -s diff --git a/inc/clamavupdate b/inc/clamavupdate new file mode 100755 index 0000000..d27aa18 --- /dev/null +++ b/inc/clamavupdate @@ -0,0 +1,5 @@ +#!/bin/sh +systemctl stop clamav-freshclam +/usr/bin/freshclam ‐v >> /var/log/resul_freshclam.txt +systemctl start clamav-freshclam + diff --git a/inc/clamscan b/inc/clamscan new file mode 100755 index 0000000..6ba55dd --- /dev/null +++ b/inc/clamscan @@ -0,0 +1,10 @@ +#!/bin/sh +if test -z "$1" + then echo "la commande est clamscan et le chemin a scanner" + else echo "le paramètre entré est \"${1}\" " +fi + +sudo clamscan --infected --recursive --remove --log=/var/log/resul_clamscan_partage.txt $1 +sleep 5 +exit 0 + diff --git a/inc/fail2ban/action.d/abuseipdb.conf b/inc/fail2ban/action.d/abuseipdb.conf new file mode 100755 index 0000000..15e41fb --- /dev/null +++ b/inc/fail2ban/action.d/abuseipdb.conf @@ -0,0 +1,105 @@ +# Fail2ban configuration file +# +# Action to report IP address to abuseipdb.com +# You must sign up to obtain an API key from abuseipdb.com. +# +# NOTE: These reports may include sensitive Info. +# If you want cleaner reports that ensure no user data see the helper script at the below website. +# +# IMPORTANT: +# +# Reporting an IP of abuse is a serious complaint. Make sure that it is +# serious. Fail2ban developers and network owners recommend you only use this +# action for: +# * The recidive where the IP has been banned multiple times +# * Where maxretry has been set quite high, beyond the normal user typing +# password incorrectly. +# * For filters that have a low likelihood of receiving human errors +# +# This action relies on a api_key being added to the above action conf, +# and the appropriate categories set. +# +# Example, for ssh bruteforce (in section [sshd] of `jail.local`): +# action = %(known/action)s +# %(action_abuseipdb)s[abuseipdb_apikey="my-api-key", abuseipdb_category="18,22"] +# +# See below for catagories. +# +# Original Ref: https://wiki.shaunc.com/wikka.php?wakka=ReportingToAbuseIPDBWithFail2Ban +# Added to fail2ban by Andrew James Collett (ajcollett) + +## abuseIPDB Catagories, `the abuseipdb_category` MUST be set in the jail.conf action call. +# Example, for ssh bruteforce: action = %(action_abuseipdb)s[abuseipdb_category="18,22"] +# ID Title Description +# 3 Fraud Orders +# 4 DDoS Attack +# 9 Open Proxy +# 10 Web Spam +# 11 Email Spam +# 14 Port Scan +# 18 Brute-Force +# 19 Bad Web Bot +# 20 Exploited Host +# 21 Web App Attack +# 22 SSH Secure Shell (SSH) abuse. Use this category in combination with more specific categories. +# 23 IoT Targeted +# See https://abuseipdb.com/categories for more descriptions + +[Definition] + +# Option: actionstart +# Notes.: command executed once at the start of Fail2Ban. +# Values: CMD +# +actionstart = + +# Option: actionstop +# Notes.: command executed once at the end of Fail2Ban +# Values: CMD +# +actionstop = + +# Option: actioncheck +# Notes.: command executed once before each actionban command +# Values: CMD +# +actioncheck = + +# Option: actionban +# Notes.: command executed when banning an IP. Take care that the +# command is executed with Fail2Ban user rights. +# +# ** IMPORTANT! ** +# +# By default, this posts directly to AbuseIPDB's API, unfortunately +# this results in a lot of backslashes/escapes appearing in the +# reports. This also may include info like your hostname. +# If you have your own web server with PHP available, you can +# use my (Shaun's) helper PHP script by commenting out the first #actionban +# line below, uncommenting the second one, and pointing the URL at +# wherever you install the helper script. For the PHP helper script, see +# +# +# --ciphers ecdhe_ecdsa_aes_256_sha is used to workaround a +# "NSS error -12286" from curl as it attempts to connect using +# SSLv3. See https://www.centos.org/forums/viewtopic.php?t=52732 +# Tags: See jail.conf(5) man page +# Values: CMD +# +actionban = curl --fail --ciphers ecdhe_ecdsa_aes_256_sha --data 'key=' --data-urlencode 'comment=' --data 'ip=' --data 'category=' "https://www.abuseipdb.com/report/json" + +# Option: actionunban +# Notes.: command executed when unbanning an IP. Take care that the +# command is executed with Fail2Ban user rights. +# Tags: See jail.conf(5) man page +# Values: CMD +# +actionunban = + +[Init] +# Option: abuseipdb_apikey +# Notes Your API key from abuseipdb.com +# Values: STRING Default: None +# Register for abuseipdb [https://www.abuseipdb.com], get api key and set below. +# You will need to set the catagory in the action call. +abuseipdb_apikey = diff --git a/inc/fail2ban/action.d/apf.conf b/inc/fail2ban/action.d/apf.conf new file mode 100755 index 0000000..5c4a261 --- /dev/null +++ b/inc/fail2ban/action.d/apf.conf @@ -0,0 +1,25 @@ +# Fail2Ban configuration file +# https://www.rfxn.com/projects/advanced-policy-firewall/ +# +# Note: APF doesn't play nicely with other actions. It has been observed to +# remove bans created by other iptables based actions. If you are going to use +# this action, use it for all of your jails. +# +# DON'T MIX APF and other IPTABLES based actions +[Definition] + +actionstart = +actionstop = +actioncheck = +actionban = apf --deny "banned by Fail2Ban " +actionunban = apf --remove + +[Init] + +# Name used in APF configuration +# +name = default + +# DEV NOTES: +# +# Author: Mark McKinstry diff --git a/inc/fail2ban/action.d/badips.conf b/inc/fail2ban/action.d/badips.conf new file mode 100755 index 0000000..6f9513f --- /dev/null +++ b/inc/fail2ban/action.d/badips.conf @@ -0,0 +1,19 @@ +# Fail2ban reporting to badips.com +# +# Note: This reports an IP only and does not actually ban traffic. Use +# another action in the same jail if you want bans to occur. +# +# Set the category to the appropriate value before use. +# +# To get see register and optional key to get personalised graphs see: +# http://www.badips.com/blog/personalized-statistics-track-the-attackers-of-all-your-servers-with-one-key + +[Definition] + +actionban = curl --fail --user-agent "" http://www.badips.com/add// + +[Init] + +# Option: category +# Notes.: Values are from the list here: http://www.badips.com/get/categories +category = diff --git a/inc/fail2ban/action.d/badips.py b/inc/fail2ban/action.d/badips.py new file mode 100755 index 0000000..805120e --- /dev/null +++ b/inc/fail2ban/action.d/badips.py @@ -0,0 +1,391 @@ +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*- +# vi: set ft=python sts=4 ts=4 sw=4 noet : + +# This file is part of Fail2Ban. +# +# Fail2Ban is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# Fail2Ban is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Fail2Ban; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +import sys +if sys.version_info < (2, 7): # pragma: no cover + raise ImportError("badips.py action requires Python >= 2.7") +import json +import threading +import logging +if sys.version_info >= (3, ): # pragma: 2.x no cover + from urllib.request import Request, urlopen + from urllib.parse import urlencode + from urllib.error import HTTPError +else: # pragma: 3.x no cover + from urllib2 import Request, urlopen, HTTPError + from urllib import urlencode + +from fail2ban.server.actions import Actions, ActionBase, BanTicket +from fail2ban.helpers import splitwords, str2LogLevel + + + +class BadIPsAction(ActionBase): # pragma: no cover - may be unavailable + """Fail2Ban action which reports bans to badips.com, and also + blacklist bad IPs listed on badips.com by using another action's + ban method. + + Parameters + ---------- + jail : Jail + The jail which the action belongs to. + name : str + Name assigned to the action. + category : str + Valid badips.com category for reporting failures. + score : int, optional + Minimum score for bad IPs. Default 3. + age : str, optional + Age of last report for bad IPs, per badips.com syntax. + Default "24h" (24 hours) + banaction : str, optional + Name of banaction to use for blacklisting bad IPs. If `None`, + no blacklist of IPs will take place. + Default `None`. + bancategory : str, optional + Name of category to use for blacklisting, which can differ + from category used for reporting. e.g. may want to report + "postfix", but want to use whole "mail" category for blacklist. + Default `category`. + bankey : str, optional + Key issued by badips.com to retrieve personal list + of blacklist IPs. + updateperiod : int, optional + Time in seconds between updating bad IPs blacklist. + Default 900 (15 minutes) + loglevel : int/str, optional + Log level of the message when an IP is (un)banned. + Default `DEBUG`. + Can be also supplied as two-value list (comma- or space separated) to + provide level of the summary message when a group of IPs is (un)banned. + Example `DEBUG,INFO`. + agent : str, optional + User agent transmitted to server. + Default `Fail2Ban/ver.` + + Raises + ------ + ValueError + If invalid `category`, `score`, `banaction` or `updateperiod`. + """ + + TIMEOUT = 10 + _badips = "https://www.badips.com" + def _Request(self, url, **argv): + return Request(url, headers={'User-Agent': self.agent}, **argv) + + def __init__(self, jail, name, category, score=3, age="24h", + banaction=None, bancategory=None, bankey=None, updateperiod=900, + loglevel='DEBUG', agent="Fail2Ban", timeout=TIMEOUT): + super(BadIPsAction, self).__init__(jail, name) + + self.timeout = timeout + self.agent = agent + self.category = category + self.score = score + self.age = age + self.banaction = banaction + self.bancategory = bancategory or category + self.bankey = bankey + loglevel = splitwords(loglevel) + self.sumloglevel = str2LogLevel(loglevel[-1]) + self.loglevel = str2LogLevel(loglevel[0]) + self.updateperiod = updateperiod + + self._bannedips = set() + # Used later for threading.Timer for updating badips + self._timer = None + + @staticmethod + def isAvailable(timeout=1): + try: + response = urlopen(Request("/".join([BadIPsAction._badips]), + headers={'User-Agent': "Fail2Ban"}), timeout=timeout) + return True, '' + except Exception as e: # pragma: no cover + return False, e + + def logError(self, response, what=''): # pragma: no cover - sporadical (502: Bad Gateway, etc) + messages = {} + try: + messages = json.loads(response.read().decode('utf-8')) + except: + pass + self._logSys.error( + "%s. badips.com response: '%s'", what, + messages.get('err', 'Unknown')) + + def getCategories(self, incParents=False): + """Get badips.com categories. + + Returns + ------- + set + Set of categories. + + Raises + ------ + HTTPError + Any issues with badips.com request. + ValueError + If badips.com response didn't contain necessary information + """ + try: + response = urlopen( + self._Request("/".join([self._badips, "get", "categories"])), timeout=self.timeout) + except HTTPError as response: # pragma: no cover + self.logError(response, "Failed to fetch categories") + raise + else: + response_json = json.loads(response.read().decode('utf-8')) + if not 'categories' in response_json: + err = "badips.com response lacked categories specification. Response was: %s" \ + % (response_json,) + self._logSys.error(err) + raise ValueError(err) + categories = response_json['categories'] + categories_names = set( + value['Name'] for value in categories) + if incParents: + categories_names.update(set( + value['Parent'] for value in categories + if "Parent" in value)) + return categories_names + + def getList(self, category, score, age, key=None): + """Get badips.com list of bad IPs. + + Parameters + ---------- + category : str + Valid badips.com category. + score : int + Minimum score for bad IPs. + age : str + Age of last report for bad IPs, per badips.com syntax. + key : str, optional + Key issued by badips.com to fetch IPs reported with the + associated key. + + Returns + ------- + set + Set of bad IPs. + + Raises + ------ + HTTPError + Any issues with badips.com request. + """ + try: + url = "?".join([ + "/".join([self._badips, "get", "list", category, str(score)]), + urlencode({'age': age})]) + if key: + url = "&".join([url, urlencode({'key': key})]) + self._logSys.debug('badips.com: get list, url: %r', url) + response = urlopen(self._Request(url), timeout=self.timeout) + except HTTPError as response: # pragma: no cover + self.logError(response, "Failed to fetch bad IP list") + raise + else: + return set(response.read().decode('utf-8').split()) + + @property + def category(self): + """badips.com category for reporting IPs. + """ + return self._category + + @category.setter + def category(self, category): + if category not in self.getCategories(): + self._logSys.error("Category name '%s' not valid. " + "see badips.com for list of valid categories", + category) + raise ValueError("Invalid category: %s" % category) + self._category = category + + @property + def bancategory(self): + """badips.com bancategory for fetching IPs. + """ + return self._bancategory + + @bancategory.setter + def bancategory(self, bancategory): + if bancategory != "any" and bancategory not in self.getCategories(incParents=True): + self._logSys.error("Category name '%s' not valid. " + "see badips.com for list of valid categories", + bancategory) + raise ValueError("Invalid bancategory: %s" % bancategory) + self._bancategory = bancategory + + @property + def score(self): + """badips.com minimum score for fetching IPs. + """ + return self._score + + @score.setter + def score(self, score): + score = int(score) + if 0 <= score <= 5: + self._score = score + else: + raise ValueError("Score must be 0-5") + + @property + def banaction(self): + """Jail action to use for banning/unbanning. + """ + return self._banaction + + @banaction.setter + def banaction(self, banaction): + if banaction is not None and banaction not in self._jail.actions: + self._logSys.error("Action name '%s' not in jail '%s'", + banaction, self._jail.name) + raise ValueError("Invalid banaction") + self._banaction = banaction + + @property + def updateperiod(self): + """Period in seconds between banned bad IPs will be updated. + """ + return self._updateperiod + + @updateperiod.setter + def updateperiod(self, updateperiod): + updateperiod = int(updateperiod) + if updateperiod > 0: + self._updateperiod = updateperiod + else: + raise ValueError("Update period must be integer greater than 0") + + def _banIPs(self, ips): + for ip in ips: + try: + ai = Actions.ActionInfo(BanTicket(ip), self._jail) + self._jail.actions[self.banaction].ban(ai) + except Exception as e: + self._logSys.error( + "Error banning IP %s for jail '%s' with action '%s': %s", + ip, self._jail.name, self.banaction, e, + exc_info=self._logSys.getEffectiveLevel()<=logging.DEBUG) + else: + self._bannedips.add(ip) + self._logSys.log(self.loglevel, + "Banned IP %s for jail '%s' with action '%s'", + ip, self._jail.name, self.banaction) + + def _unbanIPs(self, ips): + for ip in ips: + try: + ai = Actions.ActionInfo(BanTicket(ip), self._jail) + self._jail.actions[self.banaction].unban(ai) + except Exception as e: + self._logSys.error( + "Error unbanning IP %s for jail '%s' with action '%s': %s", + ip, self._jail.name, self.banaction, e, + exc_info=self._logSys.getEffectiveLevel()<=logging.DEBUG) + else: + self._logSys.log(self.loglevel, + "Unbanned IP %s for jail '%s' with action '%s'", + ip, self._jail.name, self.banaction) + finally: + self._bannedips.remove(ip) + + def start(self): + """If `banaction` set, blacklists bad IPs. + """ + if self.banaction is not None: + self.update() + + def update(self): + """If `banaction` set, updates blacklisted IPs. + + Queries badips.com for list of bad IPs, removing IPs from the + blacklist if no longer present, and adds new bad IPs to the + blacklist. + """ + if self.banaction is not None: + if self._timer: + self._timer.cancel() + self._timer = None + + try: + ips = self.getList( + self.bancategory, self.score, self.age, self.bankey) + # Remove old IPs no longer listed + s = self._bannedips - ips + m = len(s) + self._unbanIPs(s) + # Add new IPs which are now listed + s = ips - self._bannedips + p = len(s) + self._banIPs(s) + if m != 0 or p != 0: + self._logSys.log(self.sumloglevel, + "Updated IPs for jail '%s' (-%d/+%d)", + self._jail.name, m, p) + self._logSys.debug( + "Next update for jail '%' in %i seconds", + self._jail.name, self.updateperiod) + finally: + self._timer = threading.Timer(self.updateperiod, self.update) + self._timer.start() + + def stop(self): + """If `banaction` set, clears blacklisted IPs. + """ + if self.banaction is not None: + if self._timer: + self._timer.cancel() + self._timer = None + self._unbanIPs(self._bannedips.copy()) + + def ban(self, aInfo): + """Reports banned IP to badips.com. + + Parameters + ---------- + aInfo : dict + Dictionary which includes information in relation to + the ban. + + Raises + ------ + HTTPError + Any issues with badips.com request. + """ + try: + url = "/".join([self._badips, "add", self.category, str(aInfo['ip'])]) + self._logSys.debug('badips.com: ban, url: %r', url) + response = urlopen(self._Request(url), timeout=self.timeout) + except HTTPError as response: # pragma: no cover + self.logError(response, "Failed to ban") + raise + else: + messages = json.loads(response.read().decode('utf-8')) + self._logSys.debug( + "Response from badips.com report: '%s'", + messages['suc']) + +Action = BadIPsAction diff --git a/inc/fail2ban/action.d/blocklist_de.conf b/inc/fail2ban/action.d/blocklist_de.conf new file mode 100755 index 0000000..2f31d8b --- /dev/null +++ b/inc/fail2ban/action.d/blocklist_de.conf @@ -0,0 +1,86 @@ +# Fail2Ban configuration file +# +# Author: Steven Hiscocks +# +# + +# Action to report IP address to blocklist.de +# Blocklist.de must be signed up to at www.blocklist.de +# Once registered, one or more servers can be added. +# This action requires the server 'email address' and the associated apikey. +# +# From blocklist.de: +# www.blocklist.de is a free and voluntary service provided by a +# Fraud/Abuse-specialist, whose servers are often attacked on SSH-, +# Mail-Login-, FTP-, Webserver- and other services. +# The mission is to report all attacks to the abuse departments of the +# infected PCs/servers to ensure that the responsible provider can inform +# the customer about the infection and disable them +# +# IMPORTANT: +# +# Reporting an IP of abuse is a serious complaint. Make sure that it is +# serious. Fail2ban developers and network owners recommend you only use this +# action for: +# * The recidive where the IP has been banned multiple times +# * Where maxretry has been set quite high, beyond the normal user typing +# password incorrectly. +# * For filters that have a low likelihood of receiving human errors +# + +[Definition] + +# Option: actionstart +# Notes.: command executed once at the start of Fail2Ban. +# Values: CMD +# +actionstart = + +# Option: actionstop +# Notes.: command executed once at the end of Fail2Ban +# Values: CMD +# +actionstop = + +# Option: actioncheck +# Notes.: command executed once before each actionban command +# Values: CMD +# +actioncheck = + +# Option: actionban +# Notes.: command executed when banning an IP. Take care that the +# command is executed with Fail2Ban user rights. +# Tags: See jail.conf(5) man page +# Values: CMD +# +actionban = curl --fail --data-urlencode 'server=' --data 'apikey=' --data 'service=' --data 'ip=' --data-urlencode 'logs=' --data 'format=text' --user-agent "" "https://www.blocklist.de/en/httpreports.html" + +# Option: actionunban +# Notes.: command executed when unbanning an IP. Take care that the +# command is executed with Fail2Ban user rights. +# Tags: See jail.conf(5) man page +# Values: CMD +# +actionunban = + +[Init] + +# Option: email +# Notes server email address, as per blocklise.de account +# Values: STRING Default: None +# +#email = + +# Option: apikey +# Notes your user blocklist.de user account apikey +# Values: STRING Default: None +# +#apikey = + +# Option: service +# Notes service name you are reporting on, typically aligns with filter name +# see http://www.blocklist.de/en/httpreports.html for full list +# Values: STRING Default: None +# +#service = diff --git a/inc/fail2ban/action.d/bsd-ipfw.conf b/inc/fail2ban/action.d/bsd-ipfw.conf new file mode 100755 index 0000000..cbd6a15 --- /dev/null +++ b/inc/fail2ban/action.d/bsd-ipfw.conf @@ -0,0 +1,91 @@ +# Fail2Ban configuration file +# +# Author: Nick Munger +# Modified by: Ken Menzel +# Daniel Black (start/stop) +# Fabian Wenk (many ideas as per fail2ban users list) +# +# Ensure firewall_enable="YES" in the top of /etc/rc.conf +# + +[Definition] + +# Option: actionstart +# Notes.: command executed once at the start of Fail2Ban. +# Values: CMD +# +actionstart = ipfw show | fgrep -c -m 1 -s 'table()' > /dev/null 2>&1 || ( ipfw show | awk 'BEGIN { b = } { if ($1 < b) {} else if ($1 == b) { b = $1 + 1 } else { e = b } } END { if (e) exit e
else exit b }'; num=$?; ipfw -q add $num from table\(
\) to me ; echo $num > "" ) + + +# Option: actionstop +# Notes.: command executed once at the end of Fail2Ban +# Values: CMD +# +actionstop = [ ! -f ] || ( read num < ""
ipfw -q delete $num
rm "" ) + + +# Option: actioncheck +# Notes.: command executed once before each actionban command +# Values: CMD +# +actioncheck = + + +# Option: actionban +# Notes.: command executed when banning an IP. Take care that the +# command is executed with Fail2Ban user rights. +# Tags: See jail.conf(5) man page +# Values: CMD +# +# requires an ipfw rule like "deny ip from table(1) to me" +actionban = e=`ipfw table
add 2>&1`; x=$?; [ $x -eq 0 -o "$e" = 'ipfw: setsockopt(IP_FW_TABLE_XADD): File exists' ] || { echo "$e" 1>&2; exit $x; } + + +# Option: actionunban +# Notes.: command executed when unbanning an IP. Take care that the +# command is executed with Fail2Ban user rights. +# Tags: See jail.conf(5) man page +# Values: CMD +# +actionunban = e=`ipfw table
delete 2>&1`; x=$?; [ $x -eq 0 -o "$e" = 'ipfw: setsockopt(IP_FW_TABLE_XDEL): No such process' ] || { echo "$e" 1>&2; exit $x; } + +[Init] +# Option: table +# Notes: The ipfw table to use. If a ipfw rule using this table already exists, +# this action will not create a ipfw rule to block it and the following +# options will have no effect. +# Values: NUM +table = 1 + +# Option: port +# Notes.: Specifies port to monitor. Blank indicate block all ports. +# Values: [ NUM | STRING ] +# +port = + +# Option: startstatefile +# Notes: A file to indicate that the table rule that was added. Ensure it is unique per table. +# Values: STRING +startstatefile = /var/run/fail2ban/ipfw-started-table_
+ +# Option: block +# Notes: This is how much to block. +# Can be "ip", "tcp", "udp" or various other options. +# Values: STRING +block = ip + +# Option: blocktype +# Notes.: How to block the traffic. Use a action from man 5 ipfw +# Common values: deny, unreach port, reset +# ACTION defination at the top of man ipfw for allowed values. +# Values: STRING +# +blocktype = unreach port + +# Option: lowest_rule_num +# Notes: When fail2ban starts with action and there is no rule for the given table yet +# then fail2ban will start looking for an empty slot starting with this rule number. +# Values: NUM +lowest_rule_num = 111 + + diff --git a/inc/fail2ban/action.d/cloudflare.conf b/inc/fail2ban/action.d/cloudflare.conf new file mode 100755 index 0000000..89df5b9 --- /dev/null +++ b/inc/fail2ban/action.d/cloudflare.conf @@ -0,0 +1,78 @@ +# +# Author: Mike Rushton +# +# IMPORTANT +# +# Please set jail.local's permission to 640 because it contains your CF API key. +# +# This action depends on curl. +# Referenced from http://www.normyee.net/blog/2012/02/02/adding-cloudflare-support-to-fail2ban by NORM YEE +# +# To get your CloudFlare API Key: https://www.cloudflare.com/a/account/my-account +# +# CloudFlare API error codes: https://www.cloudflare.com/docs/host-api.html#s4.2 + +[Definition] + +# Option: actionstart +# Notes.: command executed once at the start of Fail2Ban. +# Values: CMD +# +actionstart = + +# Option: actionstop +# Notes.: command executed once at the end of Fail2Ban +# Values: CMD +# +actionstop = + +# Option: actioncheck +# Notes.: command executed once before each actionban command +# Values: CMD +# +actioncheck = + +# Option: actionban +# Notes.: command executed when banning an IP. Take care that the +# command is executed with Fail2Ban user rights. +# Tags: IP address +# number of failures +#
+_nft_get_handle_id = grep -oP '@\s+.*\s+\Khandle\s+(\d+)$' + +_nft_add_set = add set
\{ type \; \} + <_nft_for_proto--iter> + add rule
%(rule_stat)s + <_nft_for_proto--done> +_nft_del_set = { %(_nft_list)s | %(_nft_get_handle_id)s; } | while read -r hdl; do + delete rule
$hdl; done + delete set
+ +# Option: _nft_shutdown_table +# Notes.: command executed after the stop in order to delete table (it checks that no sets are available): +# Values: CMD +# +_nft_shutdown_table = { list table
| grep -qP '^\s+set\s+'; } || { + delete table
+ } + +# Option: actionstart +# Notes.: command executed on demand at the first ban (or at the start of Fail2Ban if actionstart_on_demand is set to false). +# Values: CMD +# +actionstart = add table
+ -- add chain
\{ type hook priority \; \} + %(_nft_add_set)s + +# Option: actionflush +# Notes.: command executed once to flush IPS, by shutdown (resp. by stop of the jail or this action); +# uses `nft flush set ...` and as fallback (e. g. unsupported) recreates the set (with references) +# Values: CMD +# +actionflush = { flush set
2> /dev/null; } || { + %(_nft_del_set)s + %(_nft_add_set)s + } + +# Option: actionstop +# Notes.: command executed at the stop of jail (or at the end of Fail2Ban) +# Values: CMD +# +actionstop = %(_nft_del_set)s + <_nft_shutdown_table> + +# Option: actioncheck +# Notes.: command executed once before each actionban command +# Values: CMD +# +actioncheck = list chain
| grep -q '@[ \t]' + +# Option: actionban +# Notes.: command executed when banning an IP. Take care that the +# command is executed with Fail2Ban user rights. +# Tags: See jail.conf(5) man page +# Values: CMD +# +actionban = add element
\{ \} + +# Option: actionunban +# Notes.: command executed when unbanning an IP. Take care that the +# command is executed with Fail2Ban user rights. +# Tags: See jail.conf(5) man page +# Values: CMD +# +actionunban = delete element
\{ \} + +[Init] + +# Option: table +# Notes.: main table to store chain and sets (automatically created on demand) +# Values: STRING Default: f2b-table +table = f2b-table + +# Option: table_family +# Notes.: address family to work in +# Values: [ip | ip6 | inet] Default: inet +table_family = inet + +# Option: chain +# Notes.: main chain to store rules +# Values: STRING Default: f2b-chain +chain = f2b-chain + +# Option: chain_type +# Notes.: refers to the kind of chain to be created +# Values: [filter | route | nat] Default: filter +# +chain_type = filter + +# Option: chain_hook +# Notes.: refers to the kind of chain to be created +# Values: [ prerouting | input | forward | output | postrouting ] Default: input +# +chain_hook = input + +# Option: chain_priority +# Notes.: priority in the chain. +# Values: NUMBER Default: -1 +# +chain_priority = -1 + +# Option: addr_type +# Notes.: address type to work with +# Values: [ipv4_addr | ipv6_addr] Default: ipv4_addr +# +addr_type = ipv4_addr + +# Default name of the filtering set +# +name = default + +# Option: port +# Notes.: specifies port to monitor +# Values: [ NUM | STRING ] Default: +# +port = ssh + +# Option: protocol +# Notes.: internally used by config reader for interpolations. +# Values: [ tcp | udp ] Default: tcp +# +protocol = tcp + +# Option: blocktype +# Note: This is what the action does with rules. This can be any jump target +# as per the nftables man page (section 8). Common values are drop, +# reject, reject with icmpx type host-unreachable, redirect to 2222 +# Values: STRING +blocktype = reject + +# Option: nftables +# Notes.: Actual command to be executed, including common to all calls options +# Values: STRING +nftables = nft + +# Option: addr_set +# Notes.: The name of the nft set used to store banned addresses +# Values: STRING +addr_set = addr-set- + +# Option: addr_family +# Notes.: The family of the banned addresses +# Values: [ ip | ip6 ] +addr_family = ip + +[Init?family=inet6] +addr_family = ip6 +addr_type = ipv6_addr +addr_set = addr6-set- diff --git a/inc/fail2ban/action.d/nginx-block-map.conf b/inc/fail2ban/action.d/nginx-block-map.conf new file mode 100755 index 0000000..33c15f9 --- /dev/null +++ b/inc/fail2ban/action.d/nginx-block-map.conf @@ -0,0 +1,108 @@ +# Fail2Ban configuration file for black-listing via nginx +# +# Author: Serg G. Brester (aka sebres) +# +# To use 'nginx-block-map' action you should define some special blocks in your nginx configuration, +# and use it hereafter in your locations (to notify fail2ban by failure, resp. nginx by ban). +# +# Example (argument "token_id" resp. cookie "session_id" used here as unique identifier for user): +# +# http { +# ... +# # maps to check user is blacklisted (banned in f2b): +# #map $arg_token_id $blck_lst_tok { include blacklisted-tokens.map; } +# map $cookie_session_id $blck_lst_ses { include blacklisted-sessions.map; } +# ... +# # special log-format to notify fail2ban about failures: +# log_format f2b_session_errors '$msec failure "$cookie_session_id" - $remote_addr - $remote_user ' +# ;# '"$request" $status $bytes_sent ' +# # '"$http_referer" "$http_user_agent"'; +# +# # location checking blacklisted values: +# location ... { +# # check banned sessionid: +# if ($blck_lst_ses != "") { +# try_files "" @f2b-banned; +# } +# ... +# # notify fail2ban about a failure inside nginx: +# error_page 401 = @notify-f2b; +# ... +# } +# ... +# # location for return with "403 Forbidden" if banned: +# location @f2b-banned { +# default_type text/html; +# return 403 "
+# +# You are banned!
"; +# } +# ... +# # location to notify fail2ban about a failure inside nginx: +# location @notify-f2b { +# access_log /var/log/nginx/f2b-auth-errors.log f2b_session_errors; +# } +# } +# ... +# +# Note that quote-character (and possibly other special characters) are not allowed currently as session-id. +# Thus please add any session-id validation rule in your locations (or in the corresponding backend-service), +# like in example below: +# +# location ... { +# if ($cookie_session_id !~ "^[\w\-]+$") { +# return 403 "Wrong session-id" +# } +# ... +# } +# +# The parameters for jail corresponding log-format (f2b_session_errors): +# +# [nginx-blck-lst] +# filter = +# datepattern = ^Epoch +# failregex = ^ failure "[^"]+" - +# usedns = no +# +# The same log-file can be used for IP-related jail (additionally to session-related, to ban very bad IPs): +# +# [nginx-blck-ip] +# maxretry = 100 +# filter = +# datepattern = ^Epoch +# failregex = ^ failure "[^"]+" - +# usedns = no +# + +[Definition] + +# path to configuration of nginx (used to target nginx-instance in multi-instance system, +# and as path for the blacklisted map): +srv_cfg_path = /etc/nginx/ + +# cmd-line arguments to supply to test/reload nginx: +#srv_cmd = nginx -c %(srv_cfg_path)s/nginx.conf +srv_cmd = nginx + +# first test configuration is correct, hereafter send reload signal: +blck_lst_reload = %(srv_cmd)s -qt; if [ $? -eq 0 ]; then + %(srv_cmd)s -s reload; if [ $? -ne 0 ]; then echo 'reload failed.'; fi; + fi; + +# map-file for nginx, can be redefined using `action = nginx-block-map[blck_lst_file="/path/file.map"]`: +blck_lst_file = %(srv_cfg_path)s/blacklisted-sessions.map + +# Action definition: + +actionstart_on_demand = false +actionstart = touch '%(blck_lst_file)s' + +actionflush = truncate -s 0 '%(blck_lst_file)s'; %(blck_lst_reload)s + +actionstop = %(actionflush)s + +actioncheck = + +actionban = echo "\\\\ 1;" >> '%(blck_lst_file)s'; %(blck_lst_reload)s + +actionunban = id=$(echo "" | sed -e 's/[]\/$*.^|[]/\\&/g'); sed -i "/$id 1;/d" %(blck_lst_file)s; %(blck_lst_reload)s diff --git a/inc/fail2ban/action.d/npf.conf b/inc/fail2ban/action.d/npf.conf new file mode 100755 index 0000000..8b00d17 --- /dev/null +++ b/inc/fail2ban/action.d/npf.conf @@ -0,0 +1,61 @@ +# Fail2Ban configuration file +# +# NetBSD npf ban/unban +# +# Author: Nils Ratusznik +# Based on pf.conf action file +# + +[Definition] + +# Option: actionstart +# Notes.: command executed once at the start of Fail2Ban. +# Values: CMD +# +# we don't enable NPF automatically, as it will be enabled elsewhere +actionstart = + + +# Option: actionstop +# Notes.: command executed once at the end of Fail2Ban +# Values: CMD +# +# we don't disable NPF automatically either +actionstop = + + +# Option: actioncheck +# Notes.: command executed once before each actionban command +# Values: CMD +# +actioncheck = + + +# Option: actionban +# Notes.: command executed when banning an IP. Take care that the +# command is executed with Fail2Ban user rights. +# Tags: IP address +# number of failures +#