@Version : 4.5.0
@Build : f114df512
By using this site, you acknowledge that you have read and understand the Cookie Policy, Privacy Policy, and the Terms. Close

Securing your SSH server.

Posted Friday, November 15th, 2019

ShellLinux
Securing your SSH server.

Warning

This can potentially cause damage if you make mistakes. You can lose access to remove servers so Behave and Check before executing or saving.

Changing Default Port

Plain point: You dont want those bad guys who run scripts on IP ranges trying out SSH logins on Port 22. Let it find common guys.
The first thing you should do when you fire up a remote server that is to accessed via SSH is to change the default port 22 to any custom port like 2229.

Firewall consideration (optional)

In case you server is configure with UFW or FirewallD on Centos, you first need to allow the port to be accessible to the outside world.

For UFW (Ubuntu)

sudo ufw allow 2229

For Centos with SELinux and FirewallD

Allow port on FirewallD

sudo firewall-cmd --add-port 2229/tcp --permanent

Adding port to SELinux

sudo semanage port -a -t ssh_port_t -p tcp 2229

Now you are ready to change the port.

Open ssh config file

 sudo nano /etc/ssh/sshd_config

Add a new Port. Dont replace port as if something goes wrong

..........
# What ports, IPs and protocols we listen for
Port 22
Port 2229
.........

Reload ssh server

sudo syetemctl reload sshd

Test the new port using

ssh [email protected]_IP -p 2229

If you can login, then you can now safely remove port 22 from the bind list.

Open ssh config file

 sudo nano /etc/ssh/sshd_config

Remove port 22

..........
# What ports, IPs and protocols we listen for
Port 2229
.........

And reload the server

sudo syetemctl reload sshd

Using SSH Key for login(Only if you still use password logins).

Next thing you wanna do is to disable password login on your server and only use public key based login. This also goes hand in hand with disabling remote logins for root user.

Copy public key to server.

ssh-copy-id [email protected]_IP -p 2229

You get prompts, just follow through and put your password.

Now try to login to the server. You should not get a password prompt. If so, then you are ready to disable password logins.

Open ssh config file

 sudo nano /etc/ssh/sshd_config

Find ChallengeResponseAuthentication and set to no:

........
ChallengeResponseAuthentication=no
........

Find PasswordAuthentication set to no:

.......
PasswordAuthentication=no
.......

Find UsePAM and set to no:

......
UsePAM=no
......

Find PermitRootLogin and set to no:

.......
PermitRootLogin no
.......

And if you are no Centos, find PubkeyAuthentication and set to yes:

.........
PubkeyAuthentication yes
........

Now you can reboot the server and try login with password. You can try any user that has no key added.

Cheers!