環境
# サーバー
CentOS Linux release 7.8.2003 (Core)
# OpenSSH バージョン
OpenSSH_7.4p1, OpenSSL 1.0.2k-fips 26 Jan 2017
クライアント
クライアントでキーを作成する。
コマンド
$ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/.ssh/id_rsa): ※ ファイル名(省略可)
Enter passphrase (empty for no passphrase): ※ パスワード入力
Enter same passphrase again: ※ 再度パスワード入力
Your identification has been saved in id_rsa.
Your public key has been saved in id_rsa.pub.
The key fingerprint is:
SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX your_email@example.com
+---[RSA 4096]----+
| |
+----[SHA256]-----+
作成した公開鍵をサーバーへ転送します。
コマンド
$ ssh-copy-id -i ~/.ssh/id_rsa.pub [リモートユーザー]@[リモートサーバーのホスト名]
サーバー
サーバー側の設定を行う。
コマンド
# 初めてキーを設定する場合
$ mv ./id_rsa.pub ~/.ssh/authorized_keys
# キーを追加する場合
$ cat ./id_rsa.pub >> ~/.ssh/authorized_keys
パーミッションを設定する。
コマンド
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys
SSH設定を変更する。
コマンド
# vi /etc/ssh/sshd_config
sshd_config
# Rootログイン
-PermitRootLogin yes
+PermitRootLogin no
# 公開鍵認証
-#PubkeyAuthentication yes
+PubkeyAuthentication yes
# パスワード認証
-PasswordAuthentication yes
+PasswordAuthentication no
SSHサービス再起動する。
コマンド
# systemctl restart sshd
SSHポート変更
sshd_configのポート指定を変更します。
コマンド
# vi /etc/ssh/sshd_config
sshd_config
-#Port 22
+Port 20022
sshd_configのポート設定について記述あります。
ポートを変更した場合は、SELinuxも変更する必要があります。
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
SELinux設定
SELinux状態確認
# getenforce
Enforcing
コマンド
# yum install policycoreutils-python
# semanage port --list
# semanage port --list | grep ssh
ssh_port_t tcp 22
# semanage port -a -t ssh_port_t -p tcp 20022
# semanage port --list | grep ssh
ssh_port_t tcp 20022, 22
ファイアウォール (firewalld) の設定
コマンド
# systemctl status firewalld
# firewall-cmd --list-services --zone=public --permanent
dhcpv6-client ssh
CentOS 7 の firewalld では、システム初期値保存場所とユーザー設定保存場所が分かれています。
ユーザーが設定を変更する場合は、ファイルをコピーして設定します。
- /usr/lib/firewalld/ はシステム初期設定の保存場所
- /etc/firewalld/ はユーザーが変更した設定の保存場所
コマンド
# cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/
# vi /etc/firewalld/services/ssh.xml
ssh.xml
<?xml version="1.0" encoding="utf-8"?>
<service>
<short>SSH</short>
<description>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.</description>
- <port protocol="tcp" port="22"/>
+ <port protocol="tcp" port="20022"/>
</service>
コマンド
# firewall-cmd --reload