Concise and useful commands to secure your server
Secure your SSH server with simple effective steps
# 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# /etc/ssh/sshd_config
PermitRootLogin no# /etc/ssh/sshd_config
Port 2222# /etc/ssh/sshd_config
PasswordAuthentication no
ChallengeResponseAuthentication no
PubkeyAuthentication yessudo systemctl restart sshd
# or
sudo service ssh restartManage users and permissions
sudo adduser ayoub# Ubuntu/Debian
sudo usermod -aG sudo ayoub
# CentOS/RHEL
sudo usermod -aG wheel ayoubsudo 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/.sshsudo deluser ayoub
# Remove home dir too
sudo deluser --remove-home ayoubManage ports through firewall
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcpsudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --reloadsudo ss -tulpn
# or
sudo netstat -tulpnnc -zv ayoub.pw 80
nmap ayoub.pw -p 80
curl -v http://ayoub.pw:80Essential commands for firewall management
# 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 numberedEnhance server security
sudo apt install fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo systemctl enable fail2ban
sudo systemctl start fail2ban# /etc/fail2ban/jail.d/sshd.conf
[sshd]
enabled = true
maxretry = 3
bantime = 3600sudo apt install libpam-google-authenticator
google-authenticator
# Add to /etc/pam.d/sshd:
# auth required pam_google_authenticator.so# /etc/ssh/sshd_config
AllowUsers ayoub adminsudo last -10
# Failed attempts
sudo lastb -10
# Live SSH log
sudo journalctl -u sshd -f