arrow_upward

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to Change SSHD's Port The Right-Way In CentOS 8
#1
Before we begin, please note that changing SSHD's port isn't much about security but about reducing the size of your log files and shaving off few CPU cycles due to the inevitable automated(/random) login attempts directed towards the default SSH port (ie port 22.)

Indeed, our assumption here is that you do know better and that you've already disabled SSH password login in favour of the public-key authentication [1]; thus our problem is to get SSH daemon off its default port to not bother with those failed login attempts that are piling up in the logs and get the 'poor' fail2ban service a break (in case you did install it), which save us few CPU cycles.

1-Make SSHD Listen on 2 Ports:
What we'll do is to configure 'sshd' to listen on two ports, the default and the random one (eg 4600.) This is a good practice to avoid being locked out of the VPS if something goes wrong.
vi /etc/ssh/sshd_config
# Uncomment the line, # Port 22
Port 22
Port 4600

Next we need to check if SSHD does indeed listen on both ports, as follows:
[root@centos ~]# netstat -tulpn|grep sshd
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      836/sshd            
tcp6       0      0 :::22                   :::*                    LISTEN      836/sshd            

At our surprise, SSHD failed to listen on our selected port!!.. What might be the cause? If we check the logs, we see this:
[root@centos ~]# journalctl -u sshd -f
-- Logs begin at Wed 2020-04-08 14:54:06 +01. --
Apr 10 16:39:52 centos.xyz.xy sshd[836]: Server listening on :: port 22.
Apr 10 16:39:52 centos.xyz.xy sshd[836]: error: Bind to port 4600 on 0.0.0.0 failed: Permission denied.
Apr 10 16:39:52 centos.xyz.xy sshd[836]: error: Bind to port 4600 on :: failed: Permission denied.
Apr 10 16:39:52 centos.xyz.xy systemd[1]: Started OpenSSH server daemon.

2- Enable the Selected Port Usage by SSHD with SELinux:
So, SSHD failed with a permission denied. Of course, SSHD doesn't have the permission to listen on any port other than its own/22; says WHO?.. Well, SELinux says so, and it's in its enforcing mode.
[root@centos ~]# semanage port -l | grep ssh
ssh_port_t                     tcp      22

What we need to do is ask SELinux for permission to use port 4600 for SSHD, like so:
[root@centos ~]# semanage port -a -t ssh_port_t -p tcp 4600
# Now let's see:
[root@centos ~]# semanage port -l | grep ssh
ssh_port_t                     tcp      4600, 22

Now let's test again to see if it's working:
# First restart SSHD
[root@centos ~]# systemctl restart sshd
#check on which ports SSHD is listening on:
[root@static ~]# netstat -tulpn|grep sshd
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      2776/sshd          
tcp        0      0 0.0.0.0:4600            0.0.0.0:*               LISTEN      2776/sshd          
tcp6       0      0 :::22                   :::*                    LISTEN      2776/sshd          
tcp6       0      0 :::4600                 :::*                    LISTEN      2776/sshd          
It's all good!

3- Open the Firewall to the Selected SSHD Port:
We need to let the port 4600 through the firewall:

Before: only ssh and dhcp services are allowed to pass through
[root@centos ~]# firewall-cmd --zone=public --list-all
public (active)
 target: default
 icmp-block-inversion: no
 interfaces: ens3
 sources:
 services: dhcpv6-client ssh
 ports:
 protocols:
 masquerade: no
 forward-ports:
 source-ports:
 icmp-blocks:
 rich rules:

We now want to allow port 4600/tcp through
[root@centos ~]# firewall-cmd --zone=public --add-port=4600/tcp --permanent
success
[root@centos ~]# firewall-cmd --reload
success

Now TCP traffic through port 4600 is also allowed:
[root@centos ~]# firewall-cmd --zone=public --list-all
public (active)
 target: default
 icmp-block-inversion: no
 interfaces: ens3
 sources:
 services: dhcpv6-client ssh
 ports: 4600/tcp
 protocols:
 masquerade: no
 forward-ports:
 source-ports:
 icmp-blocks:
 rich rules:

4-Test SSHD Login with the Custom Port:
At this stage we have to completely logout and test if we can login with the new port:
If we exit our shell both as root and sudoer:
[root@centos ~]# exit
logout
[user@centos ~]$ exit
logout
Connection to 50.*.*.* closed.
[user@local ~]$ ssh -i ~/.ssh/centos-key-ecdsa 50.*.*.* -p 4600
Activate the web console with: systemctl enable --now cockpit.socket

Last login: ....
[user@centos ~]............................YOUR.IN
Our setup is working!

5-Disable SSHD Default Port:
> To Shut-off SSHD default port through the firewall
[root@centos ~]# firewall-cmd --zone=public --remove-service=ssh --permanent
success
[root@centos ~]# firewall-cmd --reload
success
[root@centos ~]# firewall-cmd --zone=public --list-all
public (active)
 target: default
 icmp-block-inversion: no
 interfaces: ens3
 sources:
 services: dhcpv6-client
 ports: 4600/tcp
 protocols:
 masquerade: no
 forward-ports:
 source-ports:
 icmp-blocks:
 rich rules:
From this moment onward, we're done with those random poking around port 22; the logs will be much cleaner and fail2ban will thank you for it.

6- Make SSHD Listen on the Selected Port Only:
> Last thing to do is to completely remove port 22 from the SSHD config and restart the SSHD daemon, and I'll leave that to you.

That's all there is to it.


Notes:
[1]- If you're unsure, please check Running Fedora inside an LXD/LXC System Container for a reminder.
VirMach's Buffalo_VPS-9 Holder (Dec. 20 - July 21)
microLXC's Container Holder (july 20 - ?)
VirMach's Phoenix_VPS-9 Holder (Apr. 20 - June 20)
NanoKVM's NAT-VPS Holder (jan. 20 - ?)
#2
A life lesson to learn: Never disconnect your old SSH session that is running on the previous port before you have the new SSH port working correctly 100%! You will regret it the moment you closed the old session and can no longer connect via the new and the old port. This will especially be frustrating in cases where you have no means of emergency access to the VPS.

I think this belongs into any guide about changing SSH configurations. You can apply this even when setting up things like public key authentication or doing other things. One wrong configuration line and you can lock yourself out, too.

Otherwise this is a perfectly working guide.
[Image: zHHqO5Q.png]
#3
(04-11-2020, 03:10 PM)Hidden Refuge Wrote: A life lesson to learn: Never disconnect your old SSH session that is running on the previous port before you have the new SSH port working correctly 100%! You will regret it the moment you closed the old session and can no longer connect via the new and the old port. This will especially be frustrating in cases where you have no means of emergency access to the VPS.

I think this belongs into any guide about changing SSH configurations. You can apply this even when setting up things like public key authentication or doing other things. One wrong configuration line and you can lock yourself out, too.

Indeed!.. The golden rule is 'Never terminate "something" before the new "thing" kicks in!' It's valid in IT as well as in LIFE in general. This is what separates prudence from recklessness.

Ok!.. I'll profit from this post to expand a bit into the WHY of this tutorial. Actually I didn't plan it at all!

> First, I'm a minimalist that subscribes to the saying: 'If it ain't broke.. don't Fix it!' Thus, I generally don't block port 22. But the thing is that the hammering was so unusually intense on the poor Phoenix VPS-9 that I decided to do it this time. Yes, I did read @deanhills remarks on this in various threads but never imagined the intensity of it!

I'm not sure if this is because the scanners are focusing more on the IP ranges of the datacenters in the hope to sneak into the unsuspecting newbies' systems (and there are so many of them around...) Because scanning the Whole 4 Billion IPv4 addresses at that rate is just insane!!

I did check on the IPv6 VPSs, there is none of that!.. I guess the gazillion IPs aren't all that attractive nor practical :-)

> Second, When I started to skim through the various topics laying around this forum -when I first started to post in here, I did notice that a fair amount of them (even in the 'VPS Protection' forum) were disasters waiting to happen when blindly implemented. Hence the "Right-Way" mention in the title.

> Third, Because I'm usually working on an SELinux-enforced system, I wanted to include the step needed to deal with that issue which is easily forgotten.

> Fianlly, even-though the title mentions specifically CentOS 8, this guide is valid for every modern RedHat system (Fedora, CentOS and RHEL.) CentOS 8 is just the system that happens to be the one I'm working on in Phoenix VPS-9.
VirMach's Buffalo_VPS-9 Holder (Dec. 20 - July 21)
microLXC's Container Holder (july 20 - ?)
VirMach's Phoenix_VPS-9 Holder (Apr. 20 - June 20)
NanoKVM's NAT-VPS Holder (jan. 20 - ?)
#4
Quote:great tutorial mate! and i know why @hidden refuge said this lesson... well someone did disconnected before double checking it works Tongue

@OldMeister - I've put your post in tags so that you won't earn any points for this post.  One-liner posts which make no contribution to the topic of discussion except to praise or thank the author is not allowed.  Ordinarily it is removed from the Forum but I'm allowing it and hope new members who joined our Forum more recently will note this too.  Please note future one-liners like these will be removed.  If you appreciate a tutorial or contents of a discussion you need to click on the "rate" button underneath @"Hidden Refuge"s first post and thank him that way.

Thank you will only be allowed if in addition to showing appreciation you have something of substance to add to the topic of the discussion or have questions about the content.  In other words, you've really studied the tutorial and wish to genuinely participate in the topic of discussion.
Thank you Post4vps and BladeNode for vps 6!!!
#5
@fChk  Yesterday when I reinstalled my VPS 9 Dallas and noticed the hammering of my Port 22, I tried to change the port number the old fashioned way.  However it didn't want to work.  @Mashirohen directed me to this thread, and that put me totally into the right direction. SELinux and Firewall.  So many steps to follow however and with each version of CentOS they're slightly different.  But at least one can still change the port number.

I am on CentOS 7 x86_64 Minimal v2 and had to do it slightly (very slightly) different, but thought I would put my steps here for the record for CentOS 7:

1. Fresh install of CentOS 7 x86_64 Minimal v2

2. Install Nano and add new 4-digit port number (of own choosing) to sshd configuration (I will use 5000 in the example):

yum install nano

nano /etc/ssh/sshd_config

Scroll with down key to #Port 22 and change it to Port 5000 (4-digit number of own choosing)
Remember to remove the comment # before Port number so it looks like: Port 5000 (replace with your number)

Ctrl X Select Y for Yes and then use Enter Key to exit out of configuration

3. Install semanage and let SELinux know of the new port number

yum install policycoreutils-python

semanage port -a -t ssh_port_t -p tcp 5000
Replace 5000 with new 4-digit port number

Test whether successful:
semanage port -l | grep ssh

Result should show Port 22 + Port 5000

4. Restart sshd and check which ports it is listening to
systemctl restart sshd

netstat -tulpn|grep sshd
The new port number should be in there

4. Add new port number to Firewall

Check whether Firewall is running:

firewall-cmd --state

firewall-cmd --zone=public --add-port=5000/tcp --permanent
(replace 5000 with new port number)

firewall-cmd --reload

Check Port
firewall-cmd --zone=public --list-all
It should show new port number

5. Test new port number by exiting SSH (both user and root) and then logging back in.

6. Disable SSHD Default Port

firewall-cmd --zone=public --remove-service=ssh --permanent

firewall-cmd --reload

Test port:
firewall-cmd --zone=public --list-all
Has to show new port number/tcp in result

And @fChk is correct.  No more hammering of Port 22. Thank you for this thread and Mashiro pointing me to it.  Otherwise I'd never have been able to change the port number.  Big Grin
Terminal
Thank you to Post4VPS and VirMach for my awesome VPS 9!  
#6
(05-10-2021, 01:51 AM)deanhills Wrote: And @fChk is correct.  No more hammering of Port 22. Thank you for this thread and Mashiro pointing me to it.  Otherwise I'd never have been able to change the port number.  Big Grin

Glad it worked!.. SELinux has a tendency to complicate things for people not well-versed in its idiosyncrasies.. That was one of the objectives of this tutorial after all.
VirMach's Buffalo_VPS-9 Holder (Dec. 20 - July 21)
microLXC's Container Holder (july 20 - ?)
VirMach's Phoenix_VPS-9 Holder (Apr. 20 - June 20)
NanoKVM's NAT-VPS Holder (jan. 20 - ?)
#7
(05-10-2021, 02:05 AM)fChk Wrote: Glad it worked!.. SELinux has a tendency to complicate things for people not well-versed in its idiosyncrasies.. That was one of the objectives of this tutorial after all.

You wouldn't believe it. I've just installed VestaCP, went through the process of installing a multiple php selector. And then created a WordPress site from the command line. Then when I went back into SSH, it wouldn't connect! Don't know what made me check, but looks like VestaCP created a Firewall rule for SSH on Port 22. I then fixed that. But I now wonder whether I would have been able to get in on Port 22. How can a Panel script be that powerful? After all of my hard work to change the port number and a script can nix it.

And then I'm wondering. If I can do without DNS, emails and FTP. Then maybe I could do without a panel too. Guess that's going to be my next project to figure out.
Terminal
Thank you to Post4VPS and VirMach for my awesome VPS 9!  
#8
(05-10-2021, 04:20 AM)deanhills Wrote: How can a Panel script be that powerful?  After all of my hard work to change the port number and a script can nix it.
If you can do it then any script run as root can do it too!.. A script is just a series of commands like the ones that you painstakingly type at the keyboard!

Like I said in the VPS Management Mode thread and I quote:
(05-09-2020, 11:37 PM)fChk Wrote: When you depend on CP, you lose your freedom! As instead of dealing with an issue in its fundamental ways, you start thinking of it from the standpoint of the CP that you're using--which is never the cleanest way to approach a problem. Hence, why it's a necessity for you to AT LEAST BE AWARE OF ALL THE ASSUMPTIONS (explicit or implicit) THAT YOUR CP HAS. Which is sad because it's a futile and time-consuming exercise and really counter-productive in the long-run!...

The most important thing when using CPs is to be 100% aware of its assumptions; failing to do that chaos is guaranteed at some point.

By the way, @deanhills, can you move the VPS Management Mode thread from the 'General' forum to the 'VPS General Discussion' forum where it naturally belongs.

(05-10-2021, 04:20 AM)deanhills Wrote: And then I'm wondering.  If I can do without DNS, emails and FTP.  Then maybe I could do without a panel too.  Guess that's going to be my next project to figure out.
There you go !.. That's the spirit!!.. :-)

Everybody will come to realize -at some point- that reliance on third-party CPs has its shortcomings that can only overcome by doing things manually or via home-grown automating scripts.
VirMach's Buffalo_VPS-9 Holder (Dec. 20 - July 21)
microLXC's Container Holder (july 20 - ?)
VirMach's Phoenix_VPS-9 Holder (Apr. 20 - June 20)
NanoKVM's NAT-VPS Holder (jan. 20 - ?)


Possibly Related Threads…
Thread
Author
Replies
Views
Last Post
5,224
04-13-2020, 06:45 AM
Last Post: Mashiro
5,539
12-16-2019, 06:52 AM
Last Post: youssefbasha

person_pin_circle Users browsing this thread: 1 Guest(s)
Sponsors: VirMach - Host4Fun - CubeData - Evolution-Host - HostDare - Hyper Expert - Shadow Hosting - Bladenode - Hostlease - RackNerd - ReadyDedis - Limitless Hosting