中堅プログラマーの備忘録

忘れっぽくなってきたので備忘録として・・・

【raspberry PI 3B +】CentOS7のSSHのポート番号を変更する

1.概要

SSHのポート番号はデフォルトで22が割り当てられていますが
不正アクセス等の対策しないとセキュリティー上よくないので
今回は任意のポートに変更してみます。

2.現状確認

まずは現在のfirewallの状態を確認します。

[root@localhost ~]# firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: eth0
  sources:
  services: ssh dhcpv6-client
  ports: 22/tcp
  protocols:
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

SSHの22番ポートが開放されています。
これを適当なポート番号、56789番に設定してみようと思います。

3.【sshd_config】ファイルの編集

SSHの設定ファイルは【/etc/ssh/sshd_config】に存在します。

[root@localhost ~]# vi /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 ::


今回、編集する箇所は下記のとおりです。

#Port 22

Port 56789

これでポートの編集は完了しました。

設定を反映させるためにsshdの再起動を行います。

[root@localhost ~]# :q

4.firewallのポート番号変更

firewallのポート番号変更は【ssh.xml】から行います。
このファイルは【/usr/lib/firewalld/services/ssh.xml】に存在するのですが
これはシステムデフォルトの設定ファイルが置かれている場所なので
直接編集することは禁止となっています。

ではどうするのかというと
【/usr/lib/firewalld/services/ssh.xml】を【/etc/firewalld/services/ssh.xml】にコピーして
これを編集することになります。
【/usr/lib/firewalld/】はシステムデフォルトのパスになりますが
【/etc/firewalld/】にファイルがある場合はこちらが上書きされるようになってるようです。

では【ssh.xml】をコピーします。

[root@localhost ~]# cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/ssh.xml


コピーした【ssh.xml】を編集します。

[root@localhost ~]# vi /etc/firewalld/services/ssh.xml

ファイルの中身は下記のとおりです。


  SSH
  Secure Shell (SSH) is a protocol for logging into and executing commands on remote machines. It provides secure encrypted communications. If you plan on accessing your machine remotely via SSH over a firewalled interface, enable this option. You need the openssh-server package installed for this option to be useful.
  


編集する箇所は下記のとおりです。





firewallを再起動します。

[root@localhost ~]# systemctl restart firewalld.service


再起動が完了したら一度SSH接続を切断し
56789番ポートで再度接続します。


問題なく接続出来たらSSHのポートが変更出来たことになります。

5.22番ポートの確認

22番ポートからSSH接続してみます。

f:id:tsu--kun:20190604132812p:plain

接続が拒否されたら変更が完了したことになります。