以前、 authorized_keys の配置ミスで SSH 接続できずにいたときに頂いた情報をもとに、 ssh-copy-id を試してみた。
原因判明。
authorized_keys ファイルの配置場所が誤っていた。
本来、 ~/.ssh/ に配置すべきところを、誤って、 ~/public_html/.ssh/ に配置してしまっていたという…。
「一体、お前は何年 ssh を触っているんだ。お前は何回同様の設定を繰り返してきたんだ。」と新年早々自己嫌悪_| ̄|○— 不断 (@fudan10u) January 2, 2021
ssh-copy-id 使おう?w
— 近藤 和宏 (@kondoujp) January 2, 2021
今回の実験で使用したリモートサーバーはロリポップ!のレンタルサーバー。
ロリポップ!の SSH に関するマニュアルは <https://lolipop.jp/manual/user/ssh/> にあります。
f7u@peach ~ % ssh-copy-id -h Usage: /usr/bin/ssh-copy-id [-h|-?|-f|-n] [-i [identity_file]] [-p port] [[-o <ssh -o options>] ...] [user@]hostname -f: force mode -- copy keys without trying to check if they are already installed -n: dry run -- no keys are actually copied -h|-?: print this help
以下の ACCOUNT 部分は各自のアカウントに読み替えてください。
f7u@peach ~ % ssh-copy-id -i ~/.ssh/id_ed25519.pub -p 2222 ACCOUNT@ssh.lolipop.jp /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/f7u/.ssh/id_ed25519.pub" /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed Enter passphrase for key '/Users/f7u/.ssh/id_ed25519': /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys Enter passphrase for key '/Users/f7u/.ssh/id_ed25519': ACCOUNT@ssh.lolipop.jp's password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh -p '2222' 'ACCOUNT@ssh.lolipop.jp'" and check to make sure that only the key(s) you wanted were added.
簡単!!
…だったのだが、「何故、同じ SSH 鍵のパスフレーズが2回も要求されるのだろうか?」という疑問が。
ssh-copy-id のソースを眺めたところ…
1回目は、追加しようとしている公開鍵に対応する秘密鍵を使って、リモートサーバーに SSH 接続可能かを確認するためのもの。接続が可能であれば、追加しようとしている公開鍵は既にリモートサーバーの ~/.ssh/authorized_keys に追加されていることになるため、処理が中断される。
2回目は、追加しようとしている公開鍵を実際に追加するためにリモートサーバーへログインするためのもの。1回目のログイン試行で使用された鍵から順に(?) ~/.ssh 以下に存在する全ての鍵でログインが試行される。いずれかの鍵でログインに成功すれば、そこで追加しようとしている公開鍵が追加される。いずれの鍵も未登録の場合は、リモートサーバーで許可されている認証方式の順にフォールバックされる。ロリポップ!の場合は publickey,gssapi-keyex,gssapi-with-mic,password の設定になっている模様。
…といった感じなのだろう、と推測。今回のケースでは、指定した鍵以外が存在しなかったため、同じ鍵でログイン試行が行われた後、パスワード認証にフォールバックされたということなのだろう。
推測を確認すべく、テスト用の鍵を追加作成して試したところ、
f7u@peach ~ % ssh-copy-id -i ~/.ssh/id_rsa.pub -p 2222 ACCOUNT@ssh.lolipop.jp /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/f7u/.ssh/id_rsa.pub" /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed Enter passphrase for key '/Users/f7u/.ssh/id_rsa': /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys Enter passphrase for key '/Users/f7u/.ssh/id_rsa': Enter passphrase for key '/Users/f7u/.ssh/id_ed25519': Number of key(s) added: 1 Now try logging into the machine, with: "ssh -p '2222' 'ACCOUNT@ssh.lolipop.jp'" and check to make sure that only the key(s) you wanted were added.
のようになり、最初のようにパスワード認証までフォールバックすることはなかった。このことから、先の推測が正確かどうかはさておき、大きくは外れていないだろうと考えて、納得することにした。