1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ラズパイでOpenSSHを使った公開鍵認証

Last updated at Posted at 2023-01-03

やりたかったこと

Macからラズパイに公開鍵認証でSSH接続させるように設定したかった。

vi /etc/ssh/sshd_configでパスフレーズのみの認証をできなくする。

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

設定変更後は、systemctl restart sshdでプロセスを再起動させること。

ターミナルを落としたりSSH接続した状態から抜けてしまうと、再接続できなくなるリスクがある。
絶対に繋いだままにしておくこと。
ssh接続を試す場合は、別のターミナルを起動して接続を試すこと。

SSH接続に失敗する

Mac(クライアント側)で、秘密鍵(id_ecdsa)と公開鍵(id_ecdsa.pub)のキーペアを作成。
-iオプションで秘密鍵(id_ecdsa)を指定してSSH接続を試すも、下記のエラーとなる。
(-vオプションをつけるとデバッグメッセージを表示できる。)

Mac
% ssh -v username@192.168.0.254 -i id_ecdsa
〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
username@192.168.0.254: Permission denied (publickey).

原因を調査する

ラズパイ側で認証ログを調べるも、全然情報がない。

# tail /var/log/auth.log 
〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜
Jan  3 13:43:00 raspberrypi sshd[7919]: Connection closed by authenticating user username 192.168.0.10 port 54467 [preauth]
Jan  3 13:43:09 raspberrypi sshd[7928]: Connection closed by authenticating user username 192.168.0.10 port 54468 [preauth]

vi /etc/ssh/sshd_configでログレベルを変更。
おそらく標準がINFO(コメントアウトされてる)になっているので、debugに変更。

- #LogLevel INFO
+ LogLevel debug

設定変更後は、systemctl restart sshdでプロセスを再起動させること。

これで認証失敗の原因が調査できるようになった。

鍵の参照先が違う

ログを見てみると、/home/username/.ssh/authorized_keys2を参照しにいっているようである。そんな名称ではない。

# tail -20 /var/log/auth.log
〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜
Jan  3 13:51:43 raspberrypi sshd[8816]: debug1: trying public key file /home/username/.ssh/authorized_keys2
Jan  3 13:51:43 raspberrypi sshd[8816]: debug1: Could not open authorized keys '/home/username/.ssh/authorized_keys2': No such file or directory
〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜

vi /etc/ssh/sshd_configで鍵名称を変更した。

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
- #AuthorizedKeysFile     .ssh/authorized_keys .ssh/authorized_keys2
+ AuthorizedKeysFile      .ssh/id_ecdsa.pub

権限で引っかかる

# tail -20 /var/log/auth.log
〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜
Jan  3 13:53:56 raspberrypi sshd[9466]: debug1: Could not open authorized keys '/home/username/.ssh/id_ecdsa.pub': Permission denied
〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜〜

あ・・・rootでファイル作ったんだった・・・。
接続するユーザー名で作らないと当然権限がないので引っかかる。

# ls -l
合計 4
-rwx------ 1 root root 199  1月  3 13:35 id_ecdsa.pub

ということで、権限を変更する。

# chown username:username id_ecdsa.pub

接続できた

これで接続できるようになった。
もう-vオプションは要らない。

% ssh username@192.168.0.254 -i id_ecdsa
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?