LAYOUB.SEC

SSH SECURITY GUIDE

Concise and useful commands to secure your server

01

SSH HARDENING

Secure your SSH server with simple effective steps

Generate SSH key
# Local machine
ssh-keygen -t ed25519 -C "ayoub@ayoub.pw"
ssh-copy-id ayoub@ayoub.pw
# Or copy public key manually:
cat ~/.ssh/id_ed25519.pub
# Add to server authorized_keys
Disable root login
# /etc/ssh/sshd_config
PermitRootLogin no
Change default port
# /etc/ssh/sshd_config
Port 2222
Keys only no password
# /etc/ssh/sshd_config
PasswordAuthentication no
ChallengeResponseAuthentication no
PubkeyAuthentication yes
Restart SSH
sudo systemctl restart sshd
# or
sudo service ssh restart
02

ADD USER

Manage users and permissions

Create new user
sudo adduser ayoub
Add to sudo group
# Ubuntu/Debian
sudo usermod -aG sudo ayoub
# CentOS/RHEL
sudo usermod -aG wheel ayoub
Setup SSH keys for user
sudo mkdir -p /home/ayoub/.ssh
sudo chmod 700 /home/ayoub/.ssh
sudo touch /home/ayoub/.ssh/authorized_keys
sudo chmod 600 /home/ayoub/.ssh/authorized_keys
sudo chown -R ayoub:ayoub /home/ayoub/.ssh
Delete user
sudo deluser ayoub
# Remove home dir too
sudo deluser --remove-home ayoub
03

OPEN PORTS

Manage ports through firewall

Open port via UFW
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
Open port via firewalld
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --reload
Check open ports
sudo ss -tulpn
# or
sudo netstat -tulpn
Test port externally
nc -zv ayoub.pw 80
nmap ayoub.pw -p 80
curl -v http://ayoub.pw:80
04

UFW FIREWALL

Essential commands for firewall management

All UFW commands
# Enable firewall
sudo ufw enable
# Default policies
sudo ufw default deny incoming
sudo ufw default allow outgoing
# Allow ports
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 2222/tcp
# Allow from specific IP
sudo ufw allow from 192.168.1.100 to any port 22
# Deny / Delete
sudo ufw deny 23
sudo ufw delete allow 23
# Status
sudo ufw status verbose
sudo ufw status numbered
05

EXTRA SECURITY

Enhance server security

Install fail2ban
sudo apt install fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
Rate limiting SSH
# /etc/fail2ban/jail.d/sshd.conf
[sshd]
enabled = true
maxretry = 3
bantime = 3600
Two-factor auth
sudo apt install libpam-google-authenticator
google-authenticator
# Add to /etc/pam.d/sshd:
# auth required pam_google_authenticator.so
Limit SSH users
# /etc/ssh/sshd_config
AllowUsers ayoub admin
Monitor logins
sudo last -10
# Failed attempts
sudo lastb -10
# Live SSH log
sudo journalctl -u sshd -f