← back

Securing SSH

Securing SSH Like a Pro πŸ›‘οΈ

SSH (Secure Shell) is the lifeline of remote server management, but if not secured properly, it’s an open invitation to attackers. Let’s harden SSH to keep the bad guys out. πŸ”’


1. Change the Default Port πŸ“Œ

Everyone knows SSH runs on port 22. Let’s not make it easy for attackers. Change it to something uncommon.

Edit /etc/ssh/sshd_config

sudo nano /etc/ssh/sshd_config

Find #Port 22, uncomment it, and change the number:

Port 1337  # πŸ΄β€β˜ οΈ

Restart SSH:

sudo systemctl restart ssh

2. Disable Root Login 🚫

Direct root login is a security risk. Disable it in /etc/ssh/sshd_config:

PermitRootLogin no

Restart SSH:

sudo systemctl restart ssh

Now, always login with a non-root user and sudo when needed.


3. Use SSH Keys πŸ”‘

Passwords are weak. Use key-based authentication instead.

Generate an SSH Key (if you don’t have one):

ssh-keygen -t ed25519 -C "hello@hisalman.in"  # replace with your email

Copy the Key to the Server:

ssh-copy-id user@your-server

Now, disable password authentication in /etc/ssh/sshd_config:

PasswordAuthentication no

Restart SSH:

sudo systemctl restart ssh

4. Enable Fail2Ban πŸ›‘

Brute-force attacks are common. Fail2Ban blocks repeated failed attempts.

Install Fail2Ban:

sudo apt install fail2ban -y

Enable SSH protection:

sudo nano /etc/fail2ban/jail.local

Add:

[sshd]
enabled = true
port = 1337  # your custom SSH port
maxretry = 5
bantime = 3600  # 1 hour

Restart Fail2Ban:

sudo systemctl restart fail2ban

5. Allow Only Specific Users πŸ‘₯

Limit SSH access to specific users by adding this to /etc/ssh/sshd_config:

AllowUsers youruser

Restart SSH:

sudo systemctl restart ssh

6. Bonus: Enable 2FA for SSH πŸ”

Want extra security? Use Two-Factor Authentication (2FA).

Install Google Authenticator:

sudo apt install libpam-google-authenticator -y

Run the setup:

google-authenticator

Answer the prompts, then add this line to /etc/pam.d/sshd:

auth required pam_google_authenticator.so

Enable it in /etc/ssh/sshd_config:

ChallengeResponseAuthentication yes

Restart SSH:

sudo systemctl restart ssh

Stay safe & happy hacking!