配置Fail2Ban
配置环境
useradd fail2ban
visudo#添加
fail2ban ALL=(ALL) ALL
配置conda源
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/conda create --prefix=/app/env/fail2ban python=3.10
conda activate /app/env/fail2banpip install pyinotify -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install python-systemd -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install dnspython -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pyasyncore -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pyasynchat -i https://pypi.tuna.tsinghua.edu.cn/simple
下载fail2ban
https://github.com/fail2ban/fail2ban
su - fail2ban
cd fail2ban-1.1.0
sudo python setup.py install
查看配置文件路径下是否包含文件
cd /etc/fail2ban
编辑fail2ban配置文件
vi /etc/fail2ban/jail.local
ignoreip = 127.0.0.1/8 ::1[sshd]
enabled = true
port = 22
filter = sshd
logpath = /var/log/secure
maxretry = 5
bantime = 10
findtime = 600[pgsql]
enabled = true
port = 5432
filter = pgsql
logpath = /app/postgresql/log/postgresql-*.log
maxretry = 3
bantime = 10
findtime = 600[vault]
enabled = true
port = 8200
filter = vault
logpath = /app/vault/logs/vault_audit.log
maxretry = 3
bantime = 60
findtime = 600
参数解释
enabled: 启用此监控规则。
port: 监控的端口号,通常是5432。
filter: 使用我们刚刚定义的过滤器pgsql。
logpath: 指定PGSQL日志的路径。你提到日志是按照年月日分割的,所以使用postgresql-*.log来匹配所有日志文件。
maxretry: 允许的最大失败次数(3次)。
bantime: 封禁时间(1小时)。
findtime: 规定时间内达到最大失败次数即触发封禁(10分钟内3次失败)。
vi /etc/fail2ban/filter.d/pgsql.conf
[INCLUDES]
before = common.conf[Definition]
_daemon = postgres(ql)?(-\d+(\.\d+)?)?
failregex = ^.*client=<HOST>.*FATAL:\s+password authentication failed for user ".*".*$
^.*client=<HOST>.*FATAL:\s+no pg_hba.conf entry for host .*, user .*, database .*$ignoreregex =
vi /etc/fail2ban/filter.d/vault.conf
[INCLUDES]
before = common.conf[Definition]
failregex = ^.*"error":".*(invalid token|invalid_credentials|permission denied|missing client token|token expired).*".*\"remote_address\":\"<HOST>\".*"type\":\"request\".*
ignoreregex =
重启Fail2Ban以应用配置
-
复制fail2ban.service脚本
首先,将fail2ban.service脚本复制到/etc/systemd/system/目录,并重命名为fail2ban:
sudo cp /usr/MyWorkSpace/fail2ban-1.1.0/build/fail2ban.service /etc/systemd/system/fail2ban.service
-
重新加载 systemd 配置
sudo systemctl daemon-reload sudo systemctl start fail2ban sudo systemctl stop fail2ban sudo systemctl enable fail2ban sudo systemctl restart fail2ban
-
最后,检查Fail2Ban服务是否正常运行:
sudo systemctl status fail2ban
验证配置
sudo fail2ban-client statussudo fail2ban-client status sshdsudo fail2ban-client status pgsqlsudo fail2ban-client status vault