Securing a Linux server’s entry point is one of the most critical tasks in defensive cybersecurity. The Secure Shell (SSH) protocol allows remote administration, making it a prime target for brute-force attacks, credential stuffing, and unauthorized access. A robust hardening strategy combines rate limiting to stop automated attackers, network restrictions to limit attack surface, and Multi-Factor Authentication (MFA) to protect against stolen credentials. This lab exercise guides IT students and junior engineers through the practical implementation of Fail2Ban, source IP restriction, and PAM-based MFA on a standard Ubuntu or Debian system.
Understanding the Hardening Architecture
Before executing commands, it is essential to understand the three-layer defense model being implemented:
1. Fail2Ban: An intrusion prevention software that scans log files for malicious activity (such as repeated failed login attempts) and automatically bans the offending IP addresses by updating firewall rules.
2. Source Restriction: Configuring the SSH daemon (sshd) to only accept connections from specific IP ranges or networks, effectively blocking all other traffic at the application layer.
3. MFA via PAM: Integrating a Multi-Factor Authentication mechanism using the Pluggable Authentication Modules (PAM) stack, ensuring that even if a password is compromised, an attacker cannot log in without the second factor (e.g., a TOTP token).
This approach aligns with industry best practices for incident response and secure configuration management. Note that while this guide uses standard Linux distributions, specific package names or command paths may vary slightly depending on the OS version (e.g., Ubuntu 22.04 vs. Debian 12). Always verify package availability in your specific environment.
Step 1: Installing and Configuring Fail2Ban
Fail2Ban acts as an automated firewall manager that reacts to brute-force attempts. The goal is to ban IPs that exceed a threshold of failed SSH login attempts within a short timeframe.
Installation and Basic Configuration
First, install Fail2Ban using your package manager. On Debian-based systems, run:
sudo apt update
sudo apt install fail2ban -y
Once installed, locate the default action file for SSH. Create or edit the jail.local configuration file to override defaults without modifying the system package files:
sudo nano /etc/fail2ban/jail.local
Inside this file, you will define a new jail specifically for SSH. The following configuration block sets a threshold of 3 failed attempts within 600 seconds (10 minutes), followed by a ban lasting 1 hour. To make the ban more effective, we use actioniptables to update the firewall directly:
[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
findtime = 600
bantime = 3600
action = actioniptables-multi
Explanation of Parameters:
* maxretry: The number of allowed failures before a ban. Setting this low (e.g., 3) significantly reduces the window for attackers to guess passwords.
* findtime: The time window in seconds during which failures are counted.
* action: Defines how the IP is banned. actioniptables-multi bans on both IPv4 and IPv6 if available.
Expected Results and Verification
After restarting Fail2Ban with sudo systemctl restart fail2ban, you can simulate an attack to verify functionality. From a different machine, attempt to SSH into the server three times incorrectly:
ssh user@server-ip
# Enter a wrong password
# Repeat 3 times
Check the Fail2Ban status:
sudo fail2ban-client status sshd
Illustrative Output:
Target = port/ssh
Address = 192.168.1.50, 2001:db8::1
Failures = 3
Ignored =
Time found = [current timestamp]
Banned IP = [Your testing IP address]
If your IP appears in the “Banned” section and you attempt to connect again, the connection will be dropped immediately by the firewall.
Step 2: Restricting Login Sources via iptables or UFW
Relying solely on password complexity is insufficient if an attacker gains access to a credential leak. The next layer of defense is restricting SSH access to known networks. This reduces the attack surface to only trusted locations.
Configuring Source Restrictions
You can use ufw (Uncomplicated Firewall) for simplicity or direct iptables. Here, we will demonstrate using ufw, which is standard on Ubuntu systems. First, ensure fail2ban and sshd are running, then restrict SSH to a specific subnet (e.g., your corporate office network):
sudo ufw allow from 10.0.0.0/8 to any port 22 proto tcp
sudo ufw deny 22
sudo ufw enable
Explanation:
* allow from: Permits traffic only from the specified CIDR block (Class A private network).
* deny 22: Blocks all other incoming traffic on port 22 from anywhere else in the world.
* Security Consideration: If you are configuring this for a public-facing server, ensure you replace the dummy IP range with your actual data center or cloud VPC CIDR blocks. Never lock yourself out; always test from multiple devices before finalizing rules.
Verification Steps
Attempt to SSH from a device outside your allowed subnet (e.g., your home internet):
ssh user@server-ip
# Expected Result: Connection timed out or "Connection refused"
Attempt from within the allowed subnet:
ssh user@server-ip
# Expected Result: Login prompt appears
Step 3: Enforcing MFA via PAM and Google Authenticator
The final and most critical layer is Multi-Factor Authentication. Passwords can be phished or leaked; tokens cannot easily be stolen remotely. We will integrate Google Authenticator using the libpam-google-authenticator package.
Implementation Steps
- Install Dependencies: Ensure the necessary PAM libraries are present.
bash
sudo apt install libpam-google-authenticator -y -
Configure for the User: Log in as the user who needs MFA (or use
sudo su - username) and run:
bash
google-authenticator
Follow the interactive prompts:- “Do you want to disallow previous authentication tokens?” -> Yes.
- “Do you want to disable root login with password?” -> Yes (optional but recommended).
- “Do you want to enable rate limit for authentication failures?” -> Yes.
-
Update PAM Configuration: The package installs the module, but you must ensure it is loaded in
/etc/pam.d/sshd. Edit the file:
bash
sudo nano /etc/pam.d/sshd
Add this line at the very top of the file (before anypasswordorauthlines that might interfere):
bash
auth required pam_google_authenticator.so
Common Errors and Fixes
- Error: “pam_google_authenticator.so: cannot open shared object file”.
- Fix: Ensure the library is installed via the package manager. On some minimal systems, you may need to install
libpam-modules.
- Fix: Ensure the library is installed via the package manager. On some minimal systems, you may need to install
- Error: “Authentication failed” immediately after setup.
- Fix: Verify that the time on your server and your client device are synchronized (NTP). MFA tokens are time-based; a clock skew of more than 30 seconds will invalidate codes. Check with
timedatectl status.
- Fix: Verify that the time on your server and your client device are synchronized (NTP). MFA tokens are time-based; a clock skew of more than 30 seconds will invalidate codes. Check with
Industry Application and Student Practice Task
For students, the exercise ends here: configure the lab VM, document the configuration files, and write a short report on how each layer contributes to defense-in-depth. For industry practitioners, this setup forms the baseline for a production server. However, real-world scenarios often involve cloud environments (AWS EC2, Azure VMs) where iptables might be managed by the security group, and PAM modules need to be installed within the guest OS image pipeline (e.g., using Ansible or Chef).
Practical Checklist for Deployment:
1. [ ] Backup current /etc/ssh/sshd_config and /etc/fail2ban/jail.local.
2. [ ] Install Fail2Ban and verify jail.local is enabled.
3. [ ] Configure firewall rules to allow only required IP ranges.
4. [ ] Install PAM MFA modules and configure for the admin user.
5. [ ] Test login with password + TOTP code.
6. [ ] Verify Fail2Ban bans a test IP after simulated failures.
7. [ ] Review log files (/var/log/auth.log) for any suspicious activity before enabling strict modes.
Conclusion and Disclaimer
Hardening a Linux SSH server is a multi-step process that requires careful planning and testing in a safe, isolated environment. By combining Fail2Ban for rate limiting, source IP restrictions for network segmentation, and PAM-based MFA for credential protection, you create a resilient defense against common attack vectors. Remember that terms, availability, eligibility, laws, and prices depend on the specific insurer, policy, and jurisdiction if this were part of an insurance audit; similarly, technology configurations must be verified against your specific OS version and security policies before production deployment. Always test these changes in a lab environment to avoid locking yourself out of critical systems.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

