A lightweight, real-time security automation tool written in Python designed to protect Linux servers against SSH brute-force attacks. The tool monitors authentication logs (/var/log/auth.log), extracts attacker IP addresses using Regular Expressions, tracks attack thresholds with whitelisting, and automatically blocks malicious hosts via iptables.
- Real-Time Log Streaming: Leverages tailing mechanisms (
readline()andseek()) to analyze incoming authentication logs on the fly with zero high CPU overhead. - Regex Pattern Matching: Accurate extraction of IPv4 addresses associated with failed login attempts using precise capture groups.
- Threshold-Based Detection: Utilizes state-tracking with Python dictionaries to prevent false positives by enforcing configurable attempt limits (
MAX_ATTEMPTS). - Whitelisting: Built-in safeguards (
127.0.0.1,::1) to prevent self-lockout or loopback banning during administrative access. - Automated Firewall Banning: Direct kernel-level IP blocking using Linux
iptablesrules via Python'ssubprocessexecution. - Modular Design: Clear separation of concerns between pattern extraction (
utils.py), firewall execution (firewall.py), and event handling (detector.py).
[ /var/log/auth.log ] ---> [ detector.py ] ---> (Extract IP via utils.py)
|
+---> Check Whitelist
+---> Increment Attempt Counter
|
(Count >= Threshold?)
|
v
[ Trigger firewall.py ] ---> [ iptables -A INPUT -s IP -j DROP ]
ssh-brute-force-detector/
│── utils.py # Contains RegEx extraction logic for IP addresses
│── firewall.py # Executes system-level iptables blocking commands
│── detector.py # Main event loop, log listener, and threshold logic
│── .gitignore # Ignores Python bytecode and environment artifacts
└── README.md # Project documentation
- Operating System: Linux (Debian/Ubuntu, Kali Linux, CentOS)
- Python Version: Python 3.x
- System Utilities: iptables and root (
sudo) privileges
git clone https://github.com/aymendja/ssh-brute-force-detector.git
cd ssh-brute-force-detector-
Verify SSH Service: Ensure your SSH service is running and logging to
/var/log/auth.log:sudo systemctl status ssh
-
Execute Detector: Run the main script with root privileges (required for accessing system logs and managing
iptablesrules):sudo python3 detector.py
-
Simulate an Attack: Try initiating failed SSH logins from a remote host:
ssh invalid_user@<your-server-ip>
You can adjust the behavior in detector.py:
# Maximum allowed failed attempts before banning
MAX_ATTEMPTS = 3
# Trusted IP addresses that will never be banned
WHITELIST = ["127.0.0.1", "::1"]This tool is designed for educational and defensive security management purposes.