Change SSH Default Port and Disable SSH Root Login

Date Posted:12-04-2017

By default linux machine SSH port is 22 and root login would be enabled. We will explain on how to change SSH default port and Disable SSH Root login. We need to make sure to add new user which has privilege to become root.

Implementation:

Change Default SSH Port

Login to server as a root user.

Open the file /etc/ssh/sshd_config and change the line Port to random port. In our example, we will change the port number to 2222

vi /etc/ssh/sshd_config

from

Port 22

To

Port 2222

Restart sshd service

/etc/init.d/sshd restart

Open a new terminal on your local machine and new way to login to the server is to use new port

ssh username@IPaddress -p2222

Disable Direct Root login:

Lets create a new user on the host.

useradd altroot

Assign the password for the user

passwd altroot

Now, its time to add the user to sudoers file to run all the commands. Execute the command visudo and add the content

visudo

altroot ALL=(ALL) ALL

Save the file.

Try login from new terminal on your local machine using the new login. If you followed this post from beginning then SSH port is also different.

ssh altroot@IPaddress -p2222

After login enter the password the command su – to become root

su -

Incase if you want to become root with entering root password, try adding below lines on visudo file.

visudo

altroot ALL=(ALL) NOPASSWD:ALL

Now, login from your local machine using new login. If you followed this post from beginning then SSH port is also different.

ssh altroot@IPaddress -p2222

Now to become root, we just need to enter below command because we added NOPASSWD on sudoers file

sudo su -

Now, we are going to disable root login since we confirmed that we can become root using an alternate user.

Open the file /etc/ssh/sshd_config

vi /etc/ssh/sshd_config

Change the lines from

#PermitRootLogin yes

To,

PermitRootLogin no

Restart SSHD service

/etc/init.d/sshd restart

Thats it 🙂 We will no longer be able to login as root because we disabled root login. Still, we can become root as we have alternate user.

 

Leave a Reply