sshや公開鍵・秘密鍵の設定について

今日はsshや公開鍵・秘密鍵の設定についてまとめてみました。


クライアント側(接続する側)での公開鍵・秘密鍵の生成

公開鍵・秘密鍵を生成する時は、「ssh-keygen」コマンドを使います。

ssh-keygen -t rsa
       .
      (省略)
       .
The keys randomart image is:
+--[ RSA2048]----+
|                 |
|       .         |
|        o        |
|oo     . .       |
|*.. .   S .      |
|+E o       .     |
|=.o . .   .      |
|.+ . o ...       |
|*+.   ..+o       |
+-----------------+

実行後、パスワードを聞かれますがセキュリティーに問題がないならばEnterを2回押してパスワードなしで設定しても問題ありません。「rsa」は鍵のファイル名です。 その後、コンソールにイメージが表示され、以下のディレクトリに公開鍵と秘密鍵が生成されます。



秘密鍵は絶対に流出させないよう、気をつけましょう。流出したら、新しい鍵を再生成しサーバーに登録した公開鍵を削除、新しい公開鍵を登録し直しましょう。

ちなみに「-t」などについては以下のような意味があります。


ssh-keygenのオプション

  • -t「鍵の種類を指定」
  • -b「生成する鍵のビット数を指定」
    (RSA 鍵の場合、最小のサイズは 1024 ビットであり、デフォルトは 2048 ビット)
  • -C「コメントを追加」
  • -f「鍵を格納するファイル名を指定」
#例文
$ ssh-keygen -t rsa -b 4096 -C "Qiita@hoge.com" -f ~/.ssh/id_rsa


公開鍵を接続先サーバーに登録(authorized_key)

クライアント側で生成した公開鍵を接続先サーバーに登録します。登録先は接続先サーバーの~/.ssh/authorized_keysです。

公開鍵を「scp」コマンドで接続先サーバーに転送し、「cat」コマンドでauthorized_keysに追加します。ちなみに手動でauthorized_keysを開いて追加したりすると、余計な空白スペースなどができて、うまく認識されない可能性があるのでなるべく「cat」コマンドを使いましょう。

# 公開鍵をリモートサーバーに転送
scp ~/.ssh/id_rsa.pub ログイン先ユーザー名@ホスト名:

# リモートサーバーにログイン
ssh ログイン先ユーザー名@ホスト名  

# ログイン後、「authorized_keys」に公開鍵の内容をコピー
cat id_rsa.pub >> .ssh/authorized_keys


または以下のように一発でできる方法もあります。

ssh-copy-id -i ~/.ssh/id_rsa.pub ログイン先ユーザー名@ホスト名:

ユーザーのパスワードが要求されるので入力すると、サーバー側にログインして、~/.ssh/authorized_keysというファイルの中にpublic keyの内容が反映されていることが確認できます。公開鍵をリモートサーバーに接続するには一番楽で確実な方法と思われます。


楽に接続するためのクライアント側の設定(.ssh/configの設定)

一般的に接続先サーバーにアクセスするには以下のようにしなければなりません。

# ポート名を指定するケース
ssh ログイン先ユーザー名@ホスト名 -p ポート番号

# 公開鍵認証のケース
ssh ログイン先ユーザー名@ホスト名 -i ~/.ssh/鍵のパス

# ポート名、公開鍵認証のケース
ssh ログイン先ユーザー名@ホスト名 -i ~/.ssh/鍵のパス -p ポート番号

正直なところ、毎回これをやるのは面倒です。そこでクライアント側の.ssh/configを編集することでSSH接続時の情報を定義、sshコマンドのオプションを省略でき、コマンドオプションでは指定できない情報も設定できるようになります。

まず.ssh/configの存在を確認しましょう。そもそも.sshもconfigもない場合は次のようにしてディレクトとconfigファイルを作成します。

$ mkdir ~/.ssh

#アクセス権を「所有者は読み書き実行アクセス権を持つ」に設定
$ chmod 700 .ssh

$ touch ~/.ssh/config

その後、configには以下のように記述します(例)。

# サーバーA
Host serverA
    HostName 3.115.145.192
    User docterA
    IdentityFile ~/.ssh/id_rsa_a
    Port 20022
    TCPKeepAlive yes
    IdentitiesOnly yes

# サーバーB
Host serverB
    HostName 4.113.145.190
    User docterB
    IdentityFile ~/.ssh/id_rsa_b
    Port 22
    TCPKeepAlive yes
    IdentitiesOnly yes

# サーバーC
Host serverC
    HostName gehogeho.com
    User docterC
    IdentityFile ~/.ssh/id_rsa_c
    Port 10022
    TCPKeepAlive yes
    IdentitiesOnly yes

サーバーAにアクセスする時

$ ssh serverA

サーバーBにアクセスする時

$ ssh serverB

サーバーCにアクセスする時

$ ssh serverC

ちなみに「TCPKeepAlive」などの項目は以下のようになります。

オプション 概要
Host ホスト名(sshで接続時に指定)
HostName ホストのアドレスかIPアドレス
User 接続先でのログインユーザ名
IdentityFile ログインするための秘密鍵のパス
Port ポート番号(デフォルトは22、いくつも接続するなら重複しないように)
TCPKeepAlive 接続状態を継続したい場合:yes 継続しない場合:no
IdentitiesOnly IdentityFileが必要な場合:yes 必要ない場合:no
ServerAliveInterval 一定期間サーバからデータが送られてこないときに、タイムアウトする秒数。(例) 120

接続を制限するための接続先サーバーの設定(.ssh/sshd_configの設定)

接続される側のサーバーでルートログイン禁止などアクセス制限を設定するために使うのが、.ssh/sshd_configファイルです。 全体は以下のようになります。

#       $OpenBSD: sshd_config,v 1.80 2008/07/02 02:24:18 djm Exp $


# OpenSSH is to specify options with their default value where
# default value.

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

# activation of protocol 1
Protocol 2

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 1024

# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH

# Authentication:

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

#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKeysFile     .ssh/authorized_keys
#AuthorizedKeysCommand none
#AuthorizedKeysCommandRunAs nobody

#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and 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
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# the setting of "PermitRootLogin without-password".
# and ChallengeResponseAuthentication to 'no'.
#UsePAM no
UsePAM yes

# Accept locale-related environment variables
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#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

# no default banner path
#Banner none

# 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
#       ForceCommand cvs server

sshd_configについてはあまりにも項目が多いので、詳しくは以下のサイトをご覧ください。

unskilled.site

qiita.com

sshd_configについてよく触るのは以下の三か所です。

  • Port(ポート番号)
  • PermitRootLogin(ルートでのログインについて)
  • PasswordAuthentication(パスワード認証について)

セキュリティ対策として、以下のような設定をします。

ポート番号変更(デフォルトの22のままでは危険なため)
(変更前)
#Port 22
(変更後)
Port 50100
ルートログイン禁止
(変更前)
#PermitRootLogin yes
(変更後)
PermitRootLogin no
パスワード認証の禁止
(変更前)
PasswordAuthentication yes
(変更後)
PasswordAuthentication no

設定が終われば、サーバーを再起動し設定を反映させます。

踏み台サーバー/SSHゲートウェイ/SSHプロキシ経由での多段SSH接続

AWSなどで作業していると、あるサーバーBにアクセスするために、別サーバーAを経由しなければならないという状況はよくあるかと思います。つまり既にSSH接続しているサーバーからさらにSSH接続するというケースです。

しかし、これだと接続先サーバーで新たに公開鍵・秘密鍵を作成しなければならず、接続先サーバーに秘密鍵があることになるのでセキュリティとしても不安ですし、何よりもややこしいと思います。

[vagrant@node1 ~]$ ssh node2
Last login: Sun Feb 22 15:39:03 2015 from 192.168.33.11
[vagrant@node2 ~]$ ssh node3
Last login: Sun Feb 22 15:39:09 2015 from 192.168.33.12
[vagrant@node3 ~]$ 

こういう時には~/.ssh/configに多段SSH接続の情報を設定しておくと、踏み台サーバーに秘密鍵を置く必要もなく、コマンド一発で接続できるようになります。

/.ssh/configでの設定

Host node2

Host node3
  ProxyCommand ssh -W %h:%p node2
#直接node3にアクセスできる
[vagrant@node1 ~]$ ssh node3
Last login: Sun Feb 22 15:39:48 2015 from 192.168.33.12
[vagrant@node3 ~]$ exit

参考URL

qiita.com