Fail2ban sous Debian12

Tags: #<Tag:0x00007fc9df5bbc50> #<Tag:0x00007fc9df5bbb10>

Bonjour à tous

Je viens d’installer debian 12 pour la premiere fois puis derriere un petit fail2ban, donc rien d’exotique.
Par contre fail2ban part en vrille dés le depart:

root@Brine:~# apt install fail2ban
Lecture des listes de paquets... Fait
Construction de l'arbre des dépendances... Fait
Lecture des informations d'état... Fait
Les paquets supplémentaires suivants seront installés :
  python3-pyinotify python3-systemd whois
Paquets suggérés :
  mailx system-log-daemon monit sqlite3 python-pyinotify-doc
Les NOUVEAUX paquets suivants seront installés :
  fail2ban python3-pyinotify python3-systemd whois
0 mis à jour, 4 nouvellement installés, 0 à enlever et 0 non mis à jour.
Il est nécessaire de prendre 589 ko dans les archives.
Après cette opération, 2 901 ko d'espace disque supplémentaires seront utilisés.
Souhaitez-vous continuer ? [O/n] o
Réception de :1 http://deb.debian.org/debian bookworm/main amd64 fail2ban all 1.                                                                                                                        0.2-2 [451 kB]
Réception de :2 http://deb.debian.org/debian bookworm/main amd64 python3-pyinoti                                                                                                                        fy all 0.9.6-2 [27,4 kB]
Réception de :3 http://deb.debian.org/debian bookworm/main amd64 python3-systemd                                                                                                                         amd64 235-1+b2 [39,3 kB]
Réception de :4 http://deb.debian.org/debian bookworm/main amd64 whois amd64 5.5                                                                                                                        .17 [70,8 kB]
589 ko réceptionnés en 0s (1 640 ko/s)
Sélection du paquet fail2ban précédemment désélectionné.
(Lecture de la base de données... 153932 fichiers et répertoires déjà installés.                                                                                                                        )
Préparation du dépaquetage de .../fail2ban_1.0.2-2_all.deb ...
Dépaquetage de fail2ban (1.0.2-2) ...
Sélection du paquet python3-pyinotify précédemment désélectionné.
Préparation du dépaquetage de .../python3-pyinotify_0.9.6-2_all.deb ...
Dépaquetage de python3-pyinotify (0.9.6-2) ...
Sélection du paquet python3-systemd précédemment désélectionné.
Préparation du dépaquetage de .../python3-systemd_235-1+b2_amd64.deb ...
Dépaquetage de python3-systemd (235-1+b2) ...
Sélection du paquet whois précédemment désélectionné.
Préparation du dépaquetage de .../whois_5.5.17_amd64.deb ...
Dépaquetage de whois (5.5.17) ...
Paramétrage de whois (5.5.17) ...
Paramétrage de fail2ban (1.0.2-2) ...
Created symlink /etc/systemd/system/multi-user.target.wants/fail2ban.service → /                                                                                                                        lib/systemd/system/fail2ban.service.
Paramétrage de python3-pyinotify (0.9.6-2) ...
Paramétrage de python3-systemd (235-1+b2) ...
Traitement des actions différées (« triggers ») pour man-db (2.11.2-2) ...
root@Brine:~# systemctl enable fail2ban
Synchronizing state of fail2ban.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable fail2ban
root@Brine:~# systemctl status fail2ban
× fail2ban.service - Fail2Ban Service
     Loaded: loaded (/lib/systemd/system/fail2ban.service; enabled; preset: enabled)
     Active: failed (Result: exit-code) since Thu 2023-07-27 15:05:32 CEST; 20s ago
   Duration: 239ms
       Docs: man:fail2ban(1)
   Main PID: 1759 (code=exited, status=255/EXCEPTION)
        CPU: 127ms
juil. 27 15:05:32 Brine systemd[1]: Started fail2ban.service - Fail2Ban Service.
juil. 27 15:05:32 Brine fail2ban-server[1759]: 2023-07-27 15:05:32,638 fail2ban.configreader   [1759]: WARNING 'allowipv6' not defined in 'Definition'. Using def>
juil. 27 15:05:32 Brine fail2ban-server[1759]: 2023-07-27 15:05:32,647 fail2ban                [1759]: ERROR   Failed during configuration: Have not found any lo>
juil. 27 15:05:32 Brine fail2ban-server[1759]: 2023-07-27 15:05:32,653 fail2ban                [1759]: ERROR   Async configuration of server failed
juil. 27 15:05:32 Brine systemd[1]: fail2ban.service: Main process exited, code=exited, status=255/EXCEPTION
juil. 27 15:05:32 Brine systemd[1]: fail2ban.service: Failed with result 'exit-code'.

Donc une petite correction dans fail2ban.conf pour passer
#allowipv6 = auto
par
allowipv6 = no

mais par contre rien a faire pour l’erreur concernant la partie ssh malgré que j’ai modifié la section comme suit en créant bien sur avant le repertoire /var/log/fail2ban:

enabled = true
port    = ssh
#logpath = %(sshd_log)s
logpath = /var/log/fail2ban
backend = %(sshd_backend)s

J’ai toujours Active: failed (Result: exit-code) sur la commande status:

root@Brine:/etc/fail2ban# systemctl status fail2ban
× fail2ban.service - Fail2Ban Service
     Loaded: loaded (/lib/systemd/system/fail2ban.service; enabled; preset: enabled)
     Active: failed (Result: exit-code) since Thu 2023-07-27 15:32:57 CEST; 1s ago
   Duration: 439ms
       Docs: man:fail2ban(1)
    Process: 1995 ExecStart=/usr/bin/fail2ban-server -xf start (code=exited, status=255/EXCEPTION)
   Main PID: 1995 (code=exited, status=255/EXCEPTION)
        CPU: 168ms

juil. 27 15:32:57 Brine systemd[1]: Started fail2ban.service - Fail2Ban Service.
juil. 27 15:32:57 Brine fail2ban-server[1995]: Server ready
juil. 27 15:32:57 Brine systemd[1]: fail2ban.service: Main process exited, code=exited, status=255/EXCEPTION
juil. 27 15:32:57 Brine systemd[1]: fail2ban.service: Failed with result 'exit-code'.

Voici une grande partie mon fichier jail.local

#
# WARNING: heavily refactored in 0.9.0 release.  Please review and
#          customize settings for your setup.
#
# Changes:  in most of the cases you should not modify this
#           file, but provide customizations in jail.local file,
#           or separate .conf files under jail.d/ directory, e.g.:
#
# HOW TO ACTIVATE JAILS:
#
# YOU SHOULD NOT MODIFY THIS FILE.
#
# It will probably be overwritten or improved in a distribution update.
#
# Provide customizations in a jail.local file or a jail.d/customisation.local.
# For example to change the default bantime for all jails and to enable the
# ssh-iptables jail the following (uncommented) would appear in the .local file.
# See man 5 jail.conf for details.
#
# [DEFAULT]
# bantime = 1h
#
# [sshd]
# enabled = true
#
# See jail.conf(5) man page for more information



# Comments: use '#' for comment lines and ';' (following a space) for inline comments


[INCLUDES]

#before = paths-distro.conf
before = paths-debian.conf

# The DEFAULT allows a global definition of the options. They can be overridden
# in each jail afterwards.

[DEFAULT]

#
# MISCELLANEOUS OPTIONS
#

# "bantime.increment" allows to use database for searching of previously banned ip's to increase a
# default ban time using special formula, default it is banTime * 1, 2, 4, 8, 16, 32...
#bantime.increment = true

# "bantime.rndtime" is the max number of seconds using for mixing with random time
# to prevent "clever" botnets calculate exact time IP can be unbanned again:
#bantime.rndtime =

# "bantime.maxtime" is the max number of seconds using the ban time can reach (doesn't grow further)
#bantime.maxtime =

# "bantime.factor" is a coefficient to calculate exponent growing of the formula or common multiplier,
# default value of factor is 1 and with default value of formula, the ban time
# grows by 1, 2, 4, 8, 16 ...
#bantime.factor = 1

# "bantime.formula" used by default to calculate next value of ban time, default value below,
# the same ban time growing will be reached by multipliers 1, 2, 4, 8, 16, 32...
#bantime.formula = ban.Time * (1<<(ban.Count if ban.Count<20 else 20)) * banFactor
#
# more aggressive example of formula has the same values only for factor "2.0 / 2.885385" :
#bantime.formula = ban.Time * math.exp(float(ban.Count+1)*banFactor)/math.exp(1*banFactor)

# "bantime.multipliers" used to calculate next value of ban time instead of formula, corresponding
# previously ban count and given "bantime.factor" (for multipliers default is 1);
# following example grows ban time by 1, 2, 4, 8, 16 ... and if last ban count greater as multipliers count,
# always used last multiplier (64 in example), for factor '1' and original ban time 600 - 10.6 hours
#bantime.multipliers = 1 2 4 8 16 32 64
# following example can be used for small initial ban time (bantime=60) - it grows more aggressive at begin,
# for bantime=60 the multipliers are minutes and equal: 1 min, 5 min, 30 min, 1 hour, 5 hour, 12 hour, 1 day, 2 day
#bantime.multipliers = 1 5 30 60 300 720 1440 2880

# "bantime.overalljails" (if true) specifies the search of IP in the database will be executed
# cross over all jails, if false (default), only current jail of the ban IP will be searched
#bantime.overalljails = false

# --------------------

# "ignoreself" specifies whether the local resp. own IP addresses should be ignored
# (default is true). Fail2ban will not ban a host which matches such addresses.
#ignoreself = true

# "ignoreip" can be a list of IP addresses, CIDR masks or DNS hosts. Fail2ban
# will not ban a host which matches an address in this list. Several addresses
# can be defined using space (and/or comma) separator.
ignoreip = 127.0.0.1/8 172.16.0.0/24 10.1.0.0/24 192.168.115.0/24 192.168.120.0/24 172.16.10.0/24

# External command that will take an tagged arguments to ignore, e.g. <ip>,
# and return true if the IP is to be ignored. False otherwise.
#
# ignorecommand = /path/to/command <ip>
ignorecommand =

# "bantime" is the number of seconds that a host is banned.
bantime  = 86400

# A host is banned if it has generated "maxretry" during the last "findtime"
# seconds.
findtime  = 1200

# "maxretry" is the number of failures before a host get banned.
maxretry = 3

# "maxmatches" is the number of matches stored in ticket (resolvable via tag <matches> in actions).
maxmatches = %(maxretry)s

# "backend" specifies the backend used to get files modification.
# Available options are "pyinotify", "gamin", "polling", "systemd" and "auto".
# This option can be overridden in each jail as well.
#
# pyinotify: requires pyinotify (a file alteration monitor) to be installed.
#              If pyinotify is not installed, Fail2ban will use auto.
# gamin:     requires Gamin (a file alteration monitor) to be installed.
#              If Gamin is not installed, Fail2ban will use auto.
# polling:   uses a polling algorithm which does not require external libraries.
# systemd:   uses systemd python library to access the systemd journal.
#              Specifying "logpath" is not valid for this backend.
#              See "journalmatch" in the jails associated filter config
# auto:      will try to use the following backends, in order:
#              pyinotify, gamin, polling.
#
# Note: if systemd backend is chosen as the default but you enable a jail
#       for which logs are present only in its own log files, specify some other
#       backend for that jail (e.g. polling) and provide empty value for
#       journalmatch. See https://github.com/fail2ban/fail2ban/issues/959#issuecomment-74901200
backend = auto

# "usedns" specifies if jails should trust hostnames in logs,
#   warn when DNS lookups are performed, or ignore all hostnames in logs
#
# yes:   if a hostname is encountered, a DNS lookup will be performed.
# warn:  if a hostname is encountered, a DNS lookup will be performed,
#        but it will be logged as a warning.
# no:    if a hostname is encountered, will not be used for banning,
#        but it will be logged as info.
# raw:   use raw value (no hostname), allow use it for no-host filters/actions (example user)
usedns = warn

# "logencoding" specifies the encoding of the log files handled by the jail
#   This is used to decode the lines from the log file.
#   Typical examples:  "ascii", "utf-8"
#
#   auto:   will use the system locale setting
logencoding = auto

# "enabled" enables the jails.
#  By default all jails are disabled, and it should stay this way.
#  Enable only relevant to your setup jails in your .local or jail.d/*.conf
#
# true:  jail will be enabled and log files will get monitored for changes
# false: jail is not enabled
enabled = false


# "mode" defines the mode of the filter (see corresponding filter implementation for more info).
mode = normal

# "filter" defines the filter to use by the jail.
#  By default jails have names matching their filter name
#
filter = %(__name__)s[mode=%(mode)s]


#
# ACTIONS
#

# Some options used for actions

# Destination email address used solely for the interpolations in
# jail.{conf,local,d/*} configuration files.
destemail = xxx@domain.com

# Sender email address used solely for some actions
sender = Fail2ban_Brine_server@domain.com

# E-mail action. Since 0.8.1 Fail2Ban uses sendmail MTA for the
# mailing. Change mta configuration parameter to mail if you want to
# revert to conventional 'mail'.
mta = sendmail

# Default protocol
protocol = tcp

# Specify chain where jumps would need to be added in ban-actions expecting parameter chain
chain = <known/chain>

# Ports to be banned
# Usually should be overridden in a particular jail
port = 0:65535

# Format of user-agent https://tools.ietf.org/html/rfc7231#section-5.5.3
fail2ban_agent = Fail2Ban/%(fail2ban_version)s

#
# Action shortcuts. To be used to define action parameter

# Default banning action (e.g. iptables, iptables-new,
# iptables-multiport, shorewall, etc) It is used to define
# action_* variables. Can be overridden globally or per
# section within jail.local file
banaction = iptables-multiport
banaction_allports = iptables-allports

# The simplest action to take: ban only
action_ = %(banaction)s[port="%(port)s", protocol="%(protocol)s", chain="%(chain)s"]

# ban & send an e-mail with whois report to the destemail.
action_mw = %(action_)s
            %(mta)s-whois[sender="%(sender)s", dest="%(destemail)s", protocol="%(protocol)s", chain="%(chain)s"]

# ban & send an e-mail with whois report and relevant log lines
# to the destemail.
action_mwl = %(action_)s
             %(mta)s-whois-lines[sender="%(sender)s", dest="%(destemail)s", logpath="%(logpath)s", chain="%(chain)s"]

# See the IMPORTANT note in action.d/xarf-login-attack for when to use this action
#
# ban & send a xarf e-mail to abuse contact of IP address and include relevant log lines
# to the destemail.
action_xarf = %(action_)s
             xarf-login-attack[service=%(__name__)s, sender="%(sender)s", logpath="%(logpath)s", port="%(port)s"]

# ban & send a notification to one or more of the 50+ services supported by Apprise.
# See https://github.com/caronc/apprise/wiki for details on what is supported.
#
# You may optionally over-ride the default configuration line (containing the Apprise URLs)
# by using 'apprise[config="/alternate/path/to/apprise.cfg"]' otherwise
# /etc/fail2ban/apprise.conf is sourced for your supported notification configuration.
# action = %(action_)s
#          apprise

# ban IP on CloudFlare & send an e-mail with whois report and relevant log lines
# to the destemail.
action_cf_mwl = cloudflare[cfuser="%(cfemail)s", cftoken="%(cfapikey)s"]
                %(mta)s-whois-lines[sender="%(sender)s", dest="%(destemail)s", logpath="%(logpath)s", chain="%(chain)s"]

# Report block via blocklist.de fail2ban reporting service API
#
# See the IMPORTANT note in action.d/blocklist_de.conf for when to use this action.
# Specify expected parameters in file action.d/blocklist_de.local or if the interpolation
# `action_blocklist_de` used for the action, set value of `blocklist_de_apikey`
# in your `jail.local` globally (section [DEFAULT]) or per specific jail section (resp. in
# corresponding jail.d/my-jail.local file).
#
action_blocklist_de  = blocklist_de[email="%(sender)s", service="%(__name__)s", apikey="%(blocklist_de_apikey)s", agent="%(fail2ban_agent)s"]

# Report ban via abuseipdb.com.
#
# See action.d/abuseipdb.conf for usage example and details.
#
action_abuseipdb = abuseipdb

# Choose default action.  To change, just override value of 'action' with the
# interpolation to the chosen action shortcut (e.g.  action_mw, action_mwl, etc) in jail.local
# globally (section [DEFAULT]) or per specific section
action = %(action_)s


#
# JAILS
#

#
# SSH servers
#

[sshd]

# To use more aggressive sshd modes set filter parameter "mode" in jail.local:
# normal (default), ddos, extra or aggressive (combines all).
# See "tests/files/logs/sshd" or "filter.d/sshd.conf" for usage example and details.
#mode   = normal

#[sshd]
enabled = true
port    = ssh
#logpath = %(sshd_log)s
logpath = /var/log/fail2ban
backend = %(sshd_backend)s


[dropbear]

port     = ssh
logpath  = %(dropbear_log)s
backend  = %(dropbear_backend)s


[selinux-ssh]

port     = ssh
logpath  = %(auditd_log)s

Je ne vois pas du tout ou j’aurais éventuellement fait une erreur ou oublié quelquechose pour que fail2ban ne démarre pas.

Par avance merci pour votre aide.

resolu en mettant
logpath = /var/log/fail2ban/sshd_fail2ban.log

alors pourquoi la directive d’origine logpath = %(sshd_log)s ne fonctionne pas?

Attention, dans la configuration de fail2ban, logpath ne sert pas à indiquer à fail2ban où il doit écrire des logs, mais le chemin des fichiers à analyser pour détecter d’éventuelles tentatives d’intrusion.

man 5 jail.conf:

       logpath
              filename(s) of the log files to be monitored, separated by new lines.
              Globs -- paths containing * and ? or [0-9] -- can be used however only the files that exist at start up matching this glob pattern will be considered.

              Optional space separated option 'tail' can be added to the end of the path to cause the log file to be read from the end, else default 'head' option reads file from the beginning

              Ensure syslog or the program that generates the log file isn't configured to compress repeated log messages to "*last message repeated 5 time*s" otherwise it will  fail  to  detect.  This  is
              called RepeatedMsgReduction in rsyslog and should be Off.

C’est la vraie question. Avec le paramètre d’origine, après un redémarrage de fail2ban, s’il tombe en erreur regarde dans journalctl -u fail2ban, il y aura peut-être plus d’indications.

Par défaut dans fail2ban fraîchement installé, seul le jail ssh est activé, et son logpath est donc le fichier de log utilisé par ssh (/var/log/auth.log)

Bonjour
et merci pour ta réponse

Bon ben de retour de vacances, avec ton intervention, je viens de me rendre compte que le fichier /var/log/auth.log n’existe pas dans une installation toute fraiche de debian 12 …étrange.

j’ai donc fait un touch pour créer ce fichier et remis le paramétrage d’origine dans fail2ban ( logpath = %(sshd_log)s) et cette fois fail2ban démarre sans problème.

Merci :wink:

Bonjour,

J’avis le même problème avec Fail2ban sur Débian 12.

J’ai la même chose que vous, ce qui réglé le problème avec Fail2ban.

Mais le fichier /var/log/auth.log ne s’alimente pas, il est toujours vide.

Avez vous le même problème ?

Essayez de réinstaller rsyslog

(et vérifiez que le service soit démarré)

La question que je me pose c’est de savoir ce que les devs de D12 avaient fumé pour avoir ce bug.

Bonjour,

J’ai installé rsyslog et maintenant tout fonctionne correctement.

rsyslog ne fait plus parti de la distribution Débian 12 qui utilise maintenant systemd-journald.

Mais il semble que Fail2ban ne soit pas encore capable de travailler avec systemd-journal .

A suivre.

Merci a vous tous de vos réponse

Fail2ban est capable de le gérer. Ça fonctionne bien pour sshd, en changeant le backend. Il faut préciser systemd dans votre fichier de configuration de la jail sshd

[sshd]
enabled = true
backend = systemd

Puis un petit systemctl restart fail2ban

3 J'aime

Eux rien. Mais toi sûrement en lisant les notes de publications de Debian Bookworm. Extrait très bref :

Depuis Bookworm, rsyslog n’est plus installé par défaut.

Cela dit fail2ban sait aussi utiliser systemd-journald. Donc je doute qu’il soit nécessaire d’installer rsyslog.

1 J'aime

Pour info: ayant ce problème ce matin lors de l’installation de F2B sur D12 je n’ai eu qu’à installer rsyslog et exécuter un reboot de la machine.
Je n’ai pas eu à modifier le chemin des logs

[sshd]
enable = true
mode   = aggressive
port    = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s

Je précise que c’est la premiere fois que F2B m’a donné du soucis

edit:

avant le reboot:

× fail2ban.service - Fail2Ban Service
     Loaded: loaded (/lib/systemd/system/fail2ban.service; enabled; preset: enabled)
     Active: failed (Result: exit-code) since Sun 2023-11-19 07:51:40 CET; 7s ago
   Duration: 184ms
       Docs: man:fail2ban(1)
    Process: 999 ExecStart=/usr/bin/fail2ban-server -xf start (code=exited, status=255/EXCEPTION)
   Main PID: 999 (code=exited, status=255/EXCEPTION)
        CPU: 171ms

nov. 19 07:51:39 debian-docker systemd[1]: Started fail2ban.service - Fail2Ban Service.
nov. 19 07:51:40 debian-docker fail2ban-server[999]: 2023-11-19 07:51:40,090 fail2ban.configreader   [>
nov. 19 07:51:40 debian-docker fail2ban-server[999]: 2023-11-19 07:51:40,105 fail2ban                [>
nov. 19 07:51:40 debian-docker fail2ban-server[999]: 2023-11-19 07:51:40,110 fail2ban                [>
nov. 19 07:51:40 debian-docker systemd[1]: fail2ban.service: Main process exited, code=exited, status=>
nov. 19 07:51:40 debian-docker systemd[1]: fail2ban.service: Failed with result 'exit-code'.

Après le reboot:

● fail2ban.service - Fail2Ban Service
     Loaded: loaded (/lib/systemd/system/fail2ban.service; enabled; preset: enabled)
     Active: active (running) since Sun 2023-11-19 07:53:04 CET; 45s ago
       Docs: man:fail2ban(1)
   Main PID: 517 (fail2ban-server)
      Tasks: 5 (limit: 1060)
     Memory: 26.9M
        CPU: 408ms
     CGroup: /system.slice/fail2ban.service
             └─517 /usr/bin/python3 /usr/bin/fail2ban-server -xf start

Warning: some journal files were not opened due to insufficient permissions.

Et pour checker:

Status
|- Number of jail:      1
`- Jail list:   sshd

:~# fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     0
|  `- File list:        /var/log/auth.log
`- Actions
   |- Currently banned: 0
   |- Total banned:     0
   `- Banned IP list:

L’alternative, à mon avis la plus clean c’est d’utiliser la directive :

backend = systemd

dans jail.conf ou le fichier local

Merci, cette réponse m’a beaucoup aidé.
En plus de fail2ban, j’utilise quelques bonnes pratiques pour éviter de subir des tentatives de brute force ssh comme le changement du port d’écoute ssh, la restriction d’adresse ip source ou même maintenir une liste d’utilisateurs autorisés à se connecter en ssh.
J’ai utilisé cet article : https://www.jjworld.fr/vps-securiser-son-serveur-prive-virtuel/