
Fail2Ban là gì?
Fail2Ban là framework chống xâm nhập mã nguồn mở, theo dõi log file hệ thống và tự động chặn (ban) các IP có dấu hiệu tấn công. Hoạt động bằng cách phát hiện mẫu (regex) trong log, sau đó gọi iptables/nftables để thêm rule DROP hoặc REJECT IP đó trong khoảng thời gian configurable.
Fail2Ban bảo vệ server khỏi brute force SSH, dictionary attack web login, Scanner port, và nhiều loại tấn công tự động khác. Đây là tool bắt buộc cho mọi Linux server exposed ra internet.
Cài đặt Fail2Ban trên Debian/Ubuntu
sudo apt update && sudo apt install fail2ban -y
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
Cấu hình chính: /etc/fail2ban/jail.local (không sửa file jail.conf gốc). Cấu hình tối thiểu:
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
backend = systemd
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3

Cấu hình jail chi tiết
SSH protection
Jail mặc định bảo vệ port SSH. Cấu hình maxretry (số lần đăng nhập sai cho phép), bantime (thời gian cấm – 3600s = 1h), findtime (cửa sổ phát hiện – nếu có 3 lần fail trong 10 phút sẽ ban). Đối với server public, đặt bantime = 86400 (24h) cho lần vi phạm đầu tiên.
Web application protection
Fail2Ban hỗ trợ filter cho: Apache/Nginx bad bots, WordPress login brute force (apache-nohome, wordpress-hardener), HTTP error scan (apache-badbots), và Django/Laravel custom log. Tạo filter riêng cho ứng dụng custom.
[nginx-http-auth]
enabled = true
filter = nginx-http-auth
port = http,https
logpath = /var/log/nginx/error.log
Custom filter
Tạo filter trong /etc/fail2ban/filter.d/myapp.conf:
[Definition]
failregex = ^.*Authentication failure for .* from .*$
ignoreregex =
Test filter: fail2ban-regex /var/log/myapp.log /etc/fail2ban/filter.d/myapp.conf
Quản lý whitelist và email alert
Thêm IP tin cậy vào whitelist (không bao giờ ban):
[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 203.0.113.5 198.51.100.0/24
Cấu hình email thông báo khi IP bị ban:
[DEFAULT]
action = %(action_)s
%(action_mwl)s
Email sẽ chứa: IP bị ban, timestamp, log lines gây ban, WHOIS info, reverse DNS.

Unban và quản lý runtime
Các command hữu ích:
fail2ban-client status– xem tất cả jail đang chạyfail2ban-client status sshd– xem IP bị ban trong jail sshdfail2ban-client set sshd unbanip 203.0.113.5– gỡ ban IPfail2ban-client reload– tải lại cấu hìnhfail2ban-client flush sshd– xóa tất cả ban IP trong jail
Nâng cao: Recidive và Rate Limiting
Jail recidive theo dõi IP bị ban nhiều lần Across jails. Nếu IP bị ban 3 lần trở lên, tự động cấm vĩnh viễn (permanent). Cấu hình:
[recidive]
enabled = true
filter = recidive
logpath = /var/log/fail2ban.log
banaction = iptables-allports
bantime = 172800
Kết hợp nginx-limit-req module để rate limit ở application layer trước khi Fail2Ban can thiệp. Giảm load server và giảm false ban.
Tích hợp với CloudFlare
Khi dùng CloudFlare, Fail2Ban cần ban ở CloudFlare level thay vì iptables (vì real IP bị proxy). Cấu hình action custom:
[action]
actionstart = curl -s -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/firewall/access_rules/rules" -H "Authorization: Bearer {api_key}" -H "Content-Type: application/json" -d '{"mode":"block","configuration":{"target":"ip","value":"{ip}"},"notes":"Fail2Ban"}'
actionstop = curl -s -X DELETE ...
Best practices và troubleshoot
- Test trong monitor mode đầu tiên:
fail2ban-client -tkiểm tra config,fail2ban-client start --dry-runchạy test. - Log rotation: Fail2Ban theo dõi log – nếu log bị rotate/split, dùng
backend = systemdthay vìauto. - Avoid self-ban: Luôn whitelist IP hiện tại trước khi kích hoạt jail mới.
- Monitoring: Tích hợp với Prometheus (
fail2ban-exporter) hoặc Grafana để dashboard IP ban theo thời gian. - SSH only from key: Fail2Ban bổ sung, không thay thế SSH key authentication. Tắt password login:
PasswordAuthentication no.
Tham khảo thêm: Fail2Ban Wiki | Commands Reference | Cloudflare Developers
Cơ chế hoạt động bên trong
Fail2Ban hoạt động qua 3 thành phần chính:
- Jail: Process giám sát một log file với filter và action cụ thể. Mỗi jail chạy độc lập trong process riêng.
- Filter: Biểu thức regex match log line → xác định “failure”. Fail2Ban đọc log theo streaming, match real-time.
- Action: Khi failure count vượt maxretry trong findtime → gọi action (iptables, nftables, sendmail, custom). Unban tự động sau bantime.
Internally, Fail2Ban dùng PyMySQL cho database tracking ban history, ConfigParser load config, và asyncio cho non-blocking log reading. Server chạy daemon, giao tiếp qua fail2ban-client (socket-based).
Xử lý log rotation
Log rotation (logrotate) có thể làm Fail2Ban mất track. Khi log file bị rotate (di chuyển/rename), Fail2Ban theo dõi inode cũ → không đọc file mới. Giải pháp:
- backend = systemd: Dùng journald API, không phụ thuộc file path
- backend = auto: Tự động phát hiện rotate qua inotify
- Post-rotation reload: Thêm
postrotatetrong logrotate config:fail2ban-client reload
Filter tùy chỉnh nâng cao
Ngoài filter có sẵn, tạo filter riêng cho ứng dụng custom. Ví dụ filter cho Laravel login:
[Definition]
failregex = ^.*Login failure.*from .*$
^.*Authentication failure.*ip=.*$
ignoreregex = ^.*Login success.*from .*$
Test regex trước khi enable: fail2ban-regex /var/log/laravel.log /etc/fail2ban/filter.d/laravel.conf. Tùy chọn maxretry và findtime khác nhau cho từng app.
Monitoring Fail2Ban
Dashboard monitoring giúp phát hiện attack pattern và false ban:
- fail2ban-exporter: Expose Prometheus metrics (banned IPs, total bans, jail status)
- Grafana: Visualize ban rate, top attacked IPs, time series
- Fail2Ban log:
/var/log/fail2ban.logchứa đầy đủ thông tin ban/unban - Email digest: Tổng hợp hourly qua
maileraction
