Webサーバーの設定

鍵認証とは?

公開鍵と秘密鍵を対として、秘密鍵を持つユーザーのみ接続できるセキュリティ方法。

 

鍵認証での接続許可

まずは鍵認証での接続の許可をするために「sshd_config」ファイルを編集する。

$ sudo vim etc/ssh/sshd_config

 

「/」を入力し、次にPubkeyAuthenticationを入力し検索する。

#PubkeyAuthentication yes

 

「i」キー で-INSERT-モードになり編集する。
先頭の「#」を削除しyesをnoに変更する。

PubkeyAuthentication yes

 

$ sudo systemctl restart sshd.service

 

サーバー側での作業1

公開鍵の保管場所の作成

サーバーに接続して、pwdコマンドで現在のディレクトリを確認する。
/home/usernameにいることを確認する。

$ pwd
/home/username

 

公開鍵の保管場所「.ssh」ディレクトリを作成し、パーミッションを「700」に変更する。

$ mkdir ~/.ssh
$ chmod 700 ~/.ssh

※この端末(Terminal)は通信したままにしておく。
参照:端末(Terminal)とサーバーの接続がすぐに切れる問題を解決!

 

PC側での作業1

秘密鍵と公開鍵を別ターミナル(端末)の作成

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_rsa): [Enter]キー
Enter passphrase (empty for no passphrase): [Enter]キー
Enter same passphrase again: [Enter]キー
Your identification has been saved in /home/username/.ssh/id_rsa.
Your public key has been saved in /home/username/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:RAHGWTe4nadDVAcad6sfgakdfgjqrrS9AFBGA username@xxxxx
The key’s randomart image is:
+—[RSA 2048]—-+
| o..o . . |
| .+o + o |
| o+oo . . |
| ooo=oo o |
| . S*o+.B . |
|.. o. o* =E. .|
|…..+o….. . |
| ..+.+= |
| *Oo. |
+—-[SHA256]—–+

 

秘密鍵と公開鍵の確認

$ ls -la .ssh
-rw——- 1 username username 1679 12月 9 13:19 id_rsa
-rw-r–r– 1 username username 395 12月 9 13:19 id_rsa.pub
id_rsaが秘密鍵になる。
id_rsa.pubが公開鍵になる。
※.sshディレクトリは隠しファイルになっているので「ls -a」コマンドで表示できる。

 

パーミッションを600へ変更

$ chmod 600 .ssh/id_rsa.pub

 

公開鍵をサーバー側に転送しファイル名の変更

$ scp ~/.ssh/id_rsa.pub username@xxx-xxx-xxxxx:~/.ssh/authorized_keys

 

サーバー側での作業2

サーバー側での作業1で使用した接続しているターミナルで公開鍵を確認する。

$ ls -la .ssh
-rw——- 1 username username 395 12月 9 2019 authorized_keys

 

PC側での作業2

秘密鍵での接続

新しいターミナルを起動し、秘密鍵を使って接続する。

$ ssh -p 22 i ~/.ssh/id_rsa username@xxx-xxx-xxxxx
初めて接続するときには「Are you sure you want to continue connecting (yes/no)? 」と出る場合があるので「yes」で接続する。
初期設定では.sshディレクトリのid_rsaのファイルを読み込んでいる。
秘密鍵のファイルを別ディレクトリに移動した場合はその場所を指定する。

 

参照元情報

CentOS 7 構築・運用・管理パーフェクトガイド
CentOS 7 構築・運用・管理
パーフェクトガイド