[Linux] Port change to prevent ssh hacking


Writing time : 2016-03-01 01:53:10

Port change to prevent ssh hacking

Usually, ssh uses port 22, but since it is a well-known port, there are cases of random attack.

You can see if a hacker is intruding and how much attack you are by looking at the ssh access log.

For details on access log, click the link below~
Checking the ssh access log

By changing the port, you can somehow defend against random attacks.

The command used for reference was written based on CentOS 7.0.

iptables fix


First, change the iptables configuration before changing the port and open the port to be changed.
If you do not open the port in advance, you may not be able to connect after changing the SSH port.

To keep the port to be changed open, modify iptables with the vi command and change the port to be connected with ssh.

#vi /etc/sysconfig/iptables  

If you use port 2211, modify to allow connection to port 2211 as follows.

-A INPUT -p tcp -m state --state NEW -m tcp --dport 2211 -j ACCEPT  

Restart the iptables service.

#systemctl restart iptables  

Save the iptables configuration.

#service iptables save  

Modify sshd_config


Now modify sshd_config with vi command to change the port to be used for ssh connection.

#vi /etc/ssh/sshd_config  

The default setting is that Port 22 is commented out with #. Leave it as it is and add only the port to be changed.

Sshd_config before port change

# If you want to change the port on a SELinux system, you have to tell  
# SELinux about this change.  
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER  
#  
#Port 22  
#AddressFamily any  

Sshd_config after port change

# If you want to change the port on a SELinux system, you have to tell  
# SELinux about this change.  
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER  
#  
#Port 22  
Port 2211  
#AddressFamily any  

Restart the sshd service.

systemctl restart sshd  

If selinux is used when the systemctl restart sshd command is executed, the following error may occur.

Job for ssh.service failed because the control process exited with error code. See "systemctl status ssh.service" and "journalctl -xe" for details.  

If the above error occurs, use the semanage command as shown below to add a port to the SELinux security policy.

#semanage port -a -t ssh_port_t -p tcp 1202  

If semanage: command not found error occurs when running semanage, install it using yum as shown below.

#yum -y install policycoreutils-python  

If the connection fails when connected to port 22, it is normal.

Connecting to 1.234.xxx.xxx:22...  
Could not connect to 'xxxx.co.kr' (port 22): Connection failed.  
Previous post

Other posts in the category