0

Brief

Allow the following TCP port numbers on SSH server

  • 22
  • 2222

Premises

  1. The machine uses an Amazon Linux AMI distribution
  2. The SSH installation is based on an SELinux system

Details

By default, SSH uses TCP port 22. Is it possible to allow the SSH server to accept inbound traffic from TCP port 2222? If so... How?

I looked at the SSH's config file...

/etc/ssh/sshd_config

...
# 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
#ListenAddress 0.0.0.0
#ListenAddress ::
...

It tells that I should use semanage to configure this section instead of overwriting the said file.

How to use semanage to allow the SSH server to accept inbound traffic from 2 TCP port numbers mentioned above? Also both at the same time.

2 Answers2

4

This comment means that you must do both.

You must specify all of the desired Ports in sshd_config, and you must also run semanage as shown if you wish to add any ports other than 22.

For example:

Port 22
Port 2222

Then you would run semanage:

semanage port -a -t ssh_port_t -p tcp 2222

After doing both of these, it is safe to restart OpenSSH.

systemctl restart sshd
Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
  • I am a little reluctant of forcefully editing the configuration file. You mentioned I should do both, does that mean I really need to uncomment the line that says `#Port 22` and make it `Port 22`, then add another line `Port 2222`. -- before I do `semanage` stuffs and so on -- Will the semanage not enough? **Thanks** – Abel Melquiades Callejo Aug 05 '18 at 20:42
  • 1
    @AbelMelquiadesCallejo Yes, you must edit the file, uncomment `Port 22` and add in another line `Port 2222`. Running `semanage` only tells SELinux to _allow_ sshd to bind to the port. It does not actually configure sshd to do so. Editing `sshd_config` does that. – Michael Hampton Aug 05 '18 at 20:43
  • I tried this answer and the weird thing is that at first it told of using `semanage` but when I issued `which semanage`, it turns out it was not installed after all. Also for **Amazon Linux AMI**s, the right way to restart SSH is `/etc/init.d/sshd restart` **Thanks again** – Abel Melquiades Callejo Aug 05 '18 at 21:07
  • Ah, you are using old Amazon Linux, and not Amazon Linux 2. – Michael Hampton Aug 05 '18 at 21:08
0

Is it possible to allow the SSH server to accept inbound traffic from TCP port 2222? If so... How?

It is as simple as adding (additional to the default implied 22) Port directives in your sshd_config file

Port 22
Port 2222

With regards to the SELinux related command, that is usually only relevant on Red Hat related distributions such as RHEL, Fedora and CentOS

And

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

Will add 2222 as a valid port for ssh to the ssh policy on the server running sshd

HBruijn
  • 77,029
  • 24
  • 135
  • 201