Linux勉強中の方が公開鍵認証を理解する方法 (仮想マシン間で公開鍵認証)

Linux勉強中の方が公開鍵認証を理解する方法 (仮想マシン間で公開鍵認証)

>>この記事はこんな人におすすめ!

公開鍵認証の設定方法について知りたい

仮想マシンで公開鍵認証の勉強をする場合、どのような設定が必要か知りたい

1から公開鍵認証の設定をやってみたい

>>記事の概要

公開鍵認証をするためにどのような設定をするのか、公開鍵認証はどのような動作をするのか知るために、

Linuxで仮想マシンを2つ使用して、公開鍵を作成し、その公開鍵を仮想マシンに登録、SSHで公開鍵を使用して

ログインするということを行いました。

仮想マシンは作成したばかりのものを使用したため、1から公開鍵認証の設定を行う方法が分かります。

OpenSSH7.0を使用して公開鍵を作成していますが、このバージョンでは「dsa」のタイプの公開鍵はサポートされていないようです。そのため、「RSA」を使用して公開鍵を作成しています。

>>公開鍵認証について

ホストからホストへ(あるサーバーから別のサーバーへ)ログインする際に使用する認証には、
パスワードを使用して認証する以外に、公開鍵認証という方法があります。

公開鍵認証では、通信を行うホスト間で、一対である公開鍵と秘密鍵のペアを使用して認証を行います。

そのため、公開鍵認証を行うためには、事前に公開鍵を使用してログインする側(クライアント側)のユーザーの
公開鍵を、ログインされる側(サーバー側)に登録する必要があります。

公開鍵認証の仕組み概要図

>>公開鍵認証の検証内容

今回の検証では、仮想マシン2台を使用して、1から設定を行います。
やはり、1から設定を行うことで、公開鍵認証に必要な設定も理解することが出来、非常に勉強になります。

公開鍵認証について理解するには、公開鍵、秘密鍵を作成するだけでは不十分だと感じました。

公開鍵で認証するためには、いくつか設定ファイルを編集したり、使用する公開鍵を送ったりと
様々な作業が発生します。
これらの作業を身をもって体験するには、やはり、仮想マシンで実際に自分で作業を行う必要があると感じています。

<使用するもの>

・VMware 仮想マシンA Centosバージョン7

・VMware 仮想マシンB Debian 11x

※上記の仮想マシンA、Bはデフォルトの設定状態で使用。(仮想マシン出来立てほやほや)

※WindowsのPC(メモリ8G)で上記の2種類の仮想マシンを動作させました。

そのため、メモリの使用率が高かったです。

今回の検証で行う作業

1.仮想マシンAと仮想マシンBで「/etc/ssh/sshd_config」ファイルの設定内容を変更。
2.仮想マシンAと仮想マシンBでsshdサービスを再起動。
3.仮想マシンBで「authorized_keys」というファイルを作成。
4.仮想マシンAでRSA鍵を作成。
5.仮想マシンAからSCPコマンドを使用して、仮想マシンBに公開鍵を転送。
6.仮想マシンAから仮想マシンBにSSH接続し、SCPで転送したファイルを「authorized_keys」に上書き。
7.仮想マシンAから仮想マシンBに公開鍵認証でSSH接続。

>>「/etc/ssh/sshd_config」ファイルの設定内容を変更

まず、sshでの接続方法などの設定が記述されている、「/etc/ssh/sshd_config」ファイルの設定内容を変更します。

この設定変更を行わないと、公開鍵での認証が出来なかったりします。この設定変更は仮想マシンAと仮想マシンBの

両方で、「/etc/ssh/sshd_config」ファイルの設定内容を変更していきます。

※「/etc/ssh/sshd_config」ファイルの設定内容の詳細は↓のサイトでご確認いただければ幸いです。

sshd_configの設定項目の理解を目指す | Unskilled?

仮想マシンAの「/etc/ssh/sshd_config」ファイルを変更する

変更する部分は以下の2つです。

・「#PubkeyAuthentication yes」⇒「PubkeyAuthentication yes」

※「#」を抜くことでアンコメントアウトし、公開鍵認証を有効にしています。

・「UsePAM yes」⇒「UsePAM no」

変更する方法は、/etc/ssh/sshd_configファイルの、上記2項目を書き換えて保存するだけで大丈夫です。

変更後の仮想マシンAの「/etc/ssh/sshd_config」ファイルの中身は↓のような感じです。

[root@centosvm ~]# cat /etc/ssh/sshd_config
# $OpenBSD: sshd_config,v 1.100 2016/08/15 12:32:04 naddy Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/bin:/usr/bin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

# 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 ::

HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
SyslogFacility AUTHPRIV
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile .ssh/authorized_keys

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
PasswordAuthentication yes

# Change to no to disable s/key passwords
#ChallengeResponseAuthentication yes
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
#KerberosUseKuserok yes

# GSSAPI options
GSSAPIAuthentication yes
GSSAPICleanupCredentials no
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
#GSSAPIEnablek5users no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
# WARNING: 'UsePAM no' is not supported in Red Hat Enterprise Linux and may cause several
# problems.
UsePAM no

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation sandbox
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#ShowPatchLevel no
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

# override default of no subsystems
Subsystem sftp /usr/libexec/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# PermitTTY no
# ForceCommand cvs server
[root@centosvm ~]#

仮想マシンBで「/etc/ssh/sshd_config」ファイルを変更する

仮想マシンBでも同様にファイルの中身を変更します。

基本的に仮想マシンAと同じ内容にしてもらえれば大丈夫です。

仮想マシンBで変更した項目

・「#HostKey /etc/ssh/ssh_host_rsa_ke」⇒「HostKey /etc/ssh/ssh_host_rsa_key」

・「#HostKey /etc/ssh/ssh_host_ecdsa_key」⇒「HostKey /etc/ssh/ssh_host_ecdsa_key」

・「#HostKey /etc/ssh/ssh_host_ed25519_key」⇒「HostKey /etc/ssh/ssh_host_ed25519_key」

・「#PubkeyAuthentication yes」⇒「PubkeyAuthentication yes」

・「UsePAM yes」⇒「UsePAM no」

・「#AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2」⇒「AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2」

設定変更後の仮想マシンBの「/etc/ssh/sshd_config」ファイルの中身です。

※仮想マシンAはcentos、仮想マシンBはdebianということで、デフォルトの設定内容が異なり、

仮想マシンBは変更する項目が多かったです。

@debianvm:~$ cat /etc/ssh/sshd_config
#	$OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Include /etc/ssh/sshd_config.d/*.conf

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin prohibit-password
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
AuthorizedKeysFile	.ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
PasswordAuthentication yes 
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM no 

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem	sftp	/usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#	X11Forwarding no
#	AllowTcpForwarding no
#	PermitTTY no
#	ForceCommand cvs server
@debianvm:~$ 

>>仮想マシンAと仮想マシンBでsshdサービスを再起動

「/etc/ssh/sshd_config」ファイルの設定内容を変更したので、設定内容を読み込んでサービスを起動してもらうために、

仮想マシンAと仮想マシンBで、sshdを再起動させます。

1.仮想マシンAでsshdを再起動

コマンド:systemctl restart sshd.service
[root@centosvm ~]# systemctl restart sshd.service
[root@centosvm ~]#

2.仮想マシンBでsshdを再起動

コマンド:systemctl restart sshd.service
[root@debianvm ~]# systemctl restart sshd.service
[root@debianvm ~]#

>>仮想マシンBで「authorized_keys」ファイルを作成

注意:すでにこちらのファイルが作成されている場合は、別途作成する必要はありません。

仮想マシンBでの公開鍵認証を設定(/etc/ssh/sshd_config ファイル)では、「~/.ssh/authorized_keys」という

ファイルに記載されている、公開鍵を使用して認証を行うように設定されています。

そのため、公開鍵を使用して認証(仮想マシンBにアクセスしてくるクライアントを公開鍵を使用して認証)するには

仮想マシンBにアクセスしてくるサーバーの公開鍵をこちらのファイルに登録する必要があります。

コマンド:touch ~/.ssh/authorized_keys
[root@debianvm ~]# touch ~/.ssh/authorized_keys
[root@debianvm ~]#

>>仮想マシンAでRSA鍵を作成

仮想マシンA(仮想マシンBにアクセスする側)で公開鍵認証で使用する公開鍵(RSA)を作成します。

コマンド:ssh-keygen -t rsa
[root@centosvm ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Yx0rQdxzccD0YkwunrWCDHtoLRyofwOD63bt1BcCT/k root@centosvm.goritarou.com
The key's randomart image is:
+---[RSA 2048]----+
|       ... o=o.  |
|     . ...o+oo   |
|    . + + oo* .  |
|   o . @ * B o   |
|  o o * S E .    |
|   o + = + o     |
|  . ..+ . .      |
| .. .o.. .       |
| ... ..          |
+----[SHA256]-----+
[root@centosvm ~]#

<補足>

SSHの鍵を作成したときに入力する項目の内容を↓に記載します。

Enter file in which to save the key (/root/.ssh/id_rsa):デフォルトのままエンター

Enter passphrase (empty for no passphrase):設定するパスワードを入力

Enter same passphrase again:設定するパスワードを入力

Your identification has been saved in /root/.ssh/id_rsa:秘密鍵の保管場所

Your public key has been saved in /root/.ssh/id_rsa.pub:公開鍵の保管場所

>>仮想マシンAからSCPコマンドを使用して、仮想マシンBに公開鍵を転送

仮想マシンAで作成した、公開鍵を仮想マシンBに、ファイル名「publickey」として転送します。

コマンド:scp /root/.ssh/id_rsa.pub username@debianvm.goritarou.com:publickey
[root@centosvm ~]# scp /root/.ssh/id_rsa.pub username@debianvm.goritarou.com:publickey
username@debianvm.goritarou.com's password:
id_rsa.pub                                                            100%  409   234.9KB/s   00:00    
[root@centosvm ~]# 

※上記のコマンドを使用して名前解決が出来ないというエラーが出たときは、

/etc/hostsファイルを編集するなどして名前解決の設定をしてください。

名前解決の設定方法は↓の記事を確認してみてください。

>>仮想マシンAから仮想マシンBにSSH接続し、SCPで転送したファイルを「authorized_keys」に上書き

・仮想マシンAから仮想マシンBにSSH接続

コマンド:ssh username@debianvm.goritarou.com
[root@centosvm ~]# ssh username@debianvm.goritarou.com
wakisakakotaro@debianvm.goritarou.com's password:
Last login: Thu Aug 11 06:29:02 2022 from 192.168.74.140
wakisakakotaro@debianvm:~$

・仮想マシンBで「publickey」を「authorized_keys」に上書き

コマンド:cat publickey > ~/.ssh/authorized_keys
username@debianvm:~$ ls
1  publickey  ダウンロード  テンプレート  デスクトップ  ドキュメント  ビデオ  音楽  画像  公開
username  @debianvm:~$
username  @debianvm:~$
username  @debianvm:~$ cat publickey > ~/.ssh/authorized_keys

・「authorized_keys」ファイルを所有者のみ読み書きできるように変更する

コマンド:chmod 600 ~/.ssh/authorized_keys
username  @debianvm:~$ chmod 600 ~/.ssh/authorized_keys
username  @debianvm:~$

>>仮想マシンAから仮想マシンBに公開鍵認証でSSH接続

仮想マシンAから仮想マシンBにSSH接続する。

コマンド:ssh usename@debianvm.goritarou.com
[root@centosvm ~]# ssh usename@debianvm.goritarou.com
Enter passphrase for key '/root/.ssh/id_rsa':
Last login: Thu Aug 11 06:31:24 2022 from 192.168.74.140

>>公開鍵認証に失敗したときの対処方法

公開鍵にかかわらず、認証に失敗したときはログを確認しましょう。

認証に失敗したときに確認するログは↓に格納されています。

格納場所:/var/log/auth.log

コマンド:cat /var/log/auth.log
root@debianvm:/home/username# cat /var/log/auth.log
Aug 11 06:31:06 debian sshd[4385]: Disconnected from user username 192.168.74.140 port 37102
Aug 11 06:31:20 debian sshd[4413]: userauth_pubkey: key type ssh-dss not in PubkeyAcceptedKeyTypes [preauth]
Aug 11 06:31:20 debian sshd[4413]: userauth_pubkey: key type ssh-dss not in PubkeyAcceptedKeyTypes [preauth]
Aug 11 06:31:24 debian sshd[4413]: Accepted password for  username   from 192.168.74.140 port 37104 ssh2
Aug 11 06:32:36 debian sshd[4415]: Received disconnect from 192.168.74.140 port 37104:11: disconnected by user
Aug 11 06:32:36 debian sshd[4415]: Disconnected from user  username   192.168.74.140 port 37104

上記のログはdsaのタイプの鍵は使用できないという旨のログです。

OpenSSH7.0以降のバージョンでは、dsaは使用できないようです。

■参考資料:

OpenSSH 7.0 以降は DSA 鍵が利用できない (cles.jp)

sshキー(秘密鍵・公開鍵)の作成と認証 流れ – Qiita

sshd_configの設定項目の理解を目指す | Unskilled?

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA