さくらVPSでssh設定
さくらVPSのセキュリティ対策のために、sshでサーバにログインする際に
パスワード認証ではなく公開鍵認証を使うようにする。
公開鍵認証についてはこことかにわかりやすく書いてるから参考にするといい(かも)。
まず、VPSに接続する手元のPC上で公開鍵と秘密鍵のペアを生成する。
$ mkdir -m 700 ~/.ssh $ ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/Users/hogehoge/.ssh/id_rsa): .ssh/id_rsa Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in .ssh/id_rsa. Your public key has been saved in .ssh/id_rsa.pub. The key fingerprint is: 12:34:56:78:90:ab:cd:ef:12:34:56:78:90:ab:cd:ef hogehoge@hogehoge.local The key's randomart image is: +--[ RSA 2048]----+ | . . ++| | + + =| | . = ==| | + . .E+| | S . * *| | . + | | .| | | | | +-----------------+
とすると、.ssh/に公開鍵のid_rsa.pubと秘密鍵のid_rsaが生成される。
次に、生成した公開鍵をVPSに送信する。【xxx.xxx.xxx.xxx】はサーバのIPアドレスを入力する。
$ sftp root@xxx.xxx.xxx.xxx Are you sure you want to continue connecting (yes/no)? yes password: sftp> put .ssh/id_rsa.pub Uploading .ssh/id_rsa.pub to /root/id_rsa.pub .ssh/id_rsa.pub 100% 418 0.4KB/s 00:00 quit
次に、サーバ側の設定を行う。
$ ssh root@xxx.xxx.xxx.xxx
% mkdir .ssh
% chmod 700 .ssh
% mv id_rsa.pub .ssh/authorized_keys
この状態で手元のPCから
$ ssh -i ~/.ssh/id_rsa root@xxx.xxx.xxx.xxx
としてログインできたら成功。
また、サーバ側で
をしておく。
VPSにログインして
% sudo emacs /etc/ssh/sshd_config
としてから、
Port 22 PermitRootLogin yes #PasswordAuthentication yes
を、
Port 12345 # ←ここは任意のポート番号に変更 PermitRootLogin no PasswordAuthentication no
に変更する。
rootでパスワード認証はできないが公開鍵認証はしたい場合は、
PermitRootLogin without-password
に変更する。
次に、/etc/serviceのsshポート番号を変更する。
% sudo emacs /etc/services
としてから、
ssh 22/tcp ssh 22/udp
を、
ssh 12345/tcp ssh 12345/udp
に変更する。
最後に、sshd_configの設定を確認する。
% sudo sshd -t
と入力して、何も出力されなければ成功。
$ ssh -i ~/.ssh/id_rsa hoge@xxx.xxx.xxx.xxx -p 12345
とすると接続できる。
でも毎回入力するのは面倒なので、configにhost登録を行う。
$ emacs ~/.ssh/config
Host sakura
User hoge
HostName xxx.xxx.xxx.xxx
IdentityFile ~/.ssh/id_rsa
Port 12345
これでターミナルに
$ ssh sakura
と入力するだけでログインできるようになる。