[Security] Secure SSH
Posted in:
Uncategorized
Option 1: Disable password-based authentication and use SSH keys
- Generate a new SSH key pair on your local machine using the
ssh-keygencommand. This will create a public and a private key in your~/.sshdirectory. - Copy the public key to your server using the
ssh-copy-idcommand. For example,ssh-copy-id user@server-ip. - Log in to your server using the key-based authentication by running
ssh user@server-ip. - Open the SSH configuration file
/etc/ssh/sshd_configusing a text editor such asnanoorvim. - Find the line that says
#PasswordAuthentication yesand change it toPasswordAuthentication no. - Uncomment the line that says
#PubkeyAuthentication yesand make sure it’s set toPubkeyAuthentication yes. - Save and close the file.
- Restart the SSH service by running
sudo systemctl restart sshdorsudo service sshd restart.
Option 2: Change default SSH port
- Log in to your server as root or a user with sudo privileges.
- Open the SSH configuration file
/etc/ssh/sshd_configusing a text editor such asnanoorvim. - Find the line that says
#Port 22and change it to any other port number of your choice, such asPort 2222. - Save and close the file.
- Restart the SSH service by running
sudo systemctl restart sshdorsudo service sshd restart. - Update your firewall rules to allow the new SSH port.
Option 3: Use fail2ban to protect against brute force attacks
- Install fail2ban on your server by running
sudo apt-get install fail2banorsudo yum install fail2ban. - Copy the default configuration file by running
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local. - Open the configuration file
/etc/fail2ban/jail.localusing a text editor such asnanoorvim. - Find the
[sshd]section and changeenabled = falsetoenabled = true. - Configure the maximum number of failed login attempts and the ban duration as per your requirements.
- Save and close the file.
- Restart the fail2ban service by running
sudo systemctl restart fail2banorsudo service fail2ban restart.
Option 4: Use Two-Factor Authentication (2FA)
- Install Google Authenticator on your Unix server by running
sudo apt-get install libpam-google-authenticatororsudo yum install google-authenticator. - Run
google-authenticatorcommand to configure 2FA for your user account. - Follow the prompts to generate a QR code or a secret key.
- Install a compatible 2FA app on your mobile device such as Google Authenticator or Authy.
- Scan the QR code or manually enter the secret key in the app.
- Edit the SSH configuration file
/etc/pam.d/sshdusing a text editor such asnanoorvim. - Add the following line to the end of the file:
auth required pam_google_authenticator.so. - Save and close the file.
- Restart the SSH service by running
sudo systemctl restart sshdorsudo service sshd restart. - Log in to your server using your username, password, and the 2FA code generated by your app.