2014年8月7日木曜日

Cygwin で SSHd をインストールする

Windows 7 + Cygwin 1.7.31 + openssh 6.6.1p1-3 の環境で、SSHd サービスを設定する。

ホスト名 SSH_SERVER (192.168.100.10) に SSHd をインストールし、ホスト名 SSH_CLIENT から接続する。
鍵ペアは SSH2 の ECDSA と ED25519 の2種類でログイン出来るようにする。

SSHサーバー側の設定


必要なパッケージをインストールする。

$ apt-cyg install cygrunsrv openssh

管理者権限で起動した Cygwin ターミナルから ssh-host-config を実行する。
ちなみに、この「ssh-host-config」スクリプト内で実行される「csih_*」は、「/usr/share/csih/cygwin-service-installation-helper.sh」内に記述されている。エラーが出たら、この辺を含めて読んでいくと良さそう。
また、-d オプションを付けて実行するとデバッグモードで動作する。

Cygwinターミナルを「管理者として実行」して起動する。
sshd サービスは、特権アカウント cyg_server で実行するように設定される。

$ ssh-host-config

ssh-keygen: generating new host keys: RSA1 RSA DSA ECDSA ED25519
*** Info: Creating default /etc/ssh_config file
*** Info: Creating default /etc/sshd_config file
*** Info: Privilege separation is set to yes by default since OpenSSH 3.3.
*** Info: However, this requires a non-privileged account called 'sshd'.
*** Info: For more info on privilege separation read /usr/share/doc/openssh/README.privsep.
*** Query: Should privilege separation be used? (yes/no)  yes              #← 「privilege separation」を使用する
*** Info: Note that creating a new user requires that the current account have
*** Info: Administrator privileges.  Should this script attempt to create a
*** Query: new local account 'sshd'? (yes/no) yes                          #← non-privileged のsshdという新しいローカルアカウントを作成する
*** Info: Updating /etc/sshd_config file

*** Query: Do you want to install sshd as a service?
*** Query: (Say "no" if it is already installed as a service) (yes/no) yes #← サービスとしてsshdをインストールする
*** Query: Enter the value of CYGWIN for the daemon: []                    #← 詳細不明。昔使っていた binmode ntsec tty は今は Obsolete されている
*** Info: On Windows Server 2003, Windows Vista, and above, the
*** Info: SYSTEM account cannot setuid to other users -- a capability
*** Info: sshd requires.  You need to have or to create a privileged
*** Info: account.  This script will help you do so.

*** Info: You appear to be running Windows XP 64bit, Windows 2003 Server,
*** Info: or later.  On these systems, it's not possible to use the LocalSystem
*** Info: account for services that can change the user id without an
*** Info: explicit password (such as passwordless logins [e.g. public key
*** Info: authentication] via sshd).

*** Info: If you want to enable that functionality, it's required to create
*** Info: a new account with special privileges (unless a similar account
*** Info: already exists). This account is then used to run these special
*** Info: servers.

*** Info: Note that creating a new user requires that the current account
*** Info: have Administrator privileges itself.

*** Info: No privileged account could be found.

*** Info: This script plans to use 'cyg_server'.
*** Info: 'cyg_server' will only be used by registered services.
*** Query: Do you want to use a different name? (yes/no) no                #← SYSTEM アカウントは他のユーザへ setuid できないので(また、その他の理由で)、特権アカウントを作る必要がある。
*** Query: Create new privileged user account 'cyg_server'? (yes/no) yes   #← 新しい特権ユーザ'cyg_server'を作成する
*** Info: Please enter a password for new user cyg_server.  Please be sure
*** Info: that this password matches the password rules given on your system.
*** Info: Entering no password will exit the configuration.
*** Query: Please enter the password: ********                             #← cyg_server のパスワードを設定
*** Query: Reenter: ********                                               #← cyg_server のパスワードを再入力

*** Info: User 'cyg_server' has been created with password '********'.
*** Info: If you change the password, please remember also to change the
*** Info: password for the installed services which use (or will soon use)
*** Info: the 'cyg_server' account.

*** Info: Also keep in mind that the user 'cyg_server' needs read permissions
*** Info: on all users' relevant files for the services running as 'cyg_server'.
*** Info: In particular, for the sshd server all users' .ssh/authorized_keys
*** Info: files must have appropriate permissions to allow public key
*** Info: authentication. (Re-)running ssh-user-config for each user will set
*** Info: these permissions correctly. [Similar restrictions apply, for
*** Info: instance, for .rhosts files if the rshd server is running, etc].

*** Info: The sshd service has been installed under the 'cyg_server'
*** Info: account.  To start the service now, call `net start sshd' or
*** Info: `cygrunsrv -S sshd'.  Otherwise, it will start automatically
*** Info: after the next reboot.

*** Info: Host configuration finished. Have fun!

ちなみに、Cygwinターミナルを「管理者として実行」しないと以下の警告を受ける

$ ssh-host-config

*** Warning: Running this script typically requires administrator privileges!
*** Warning: However, it seems your account does not have these privileges.
*** Warning: Here's the list of groups in your user token:

    None
    Users

*** Warning: This usually means you're running this script from a non-admin
*** Warning: desktop session, or in a non-elevated shell under UAC control.

*** Warning: Make sure you have the appropriate privileges right now,
*** Warning: otherwise parts of this script will probably fail!

*** Query: Are you sure you want to continue?  (Say "no" if you're not sure
*** Query: you have the required privileges) (yes/no) no    #← 実行しない

*** Info: Ok.  Exiting.  Make sure to switch to an administrative account
*** Info: or to start this script from an elevated shell.
スクリプトで作成されたユーザを確認する。
「sshd」「cyg_server」が作られている。

C:\>net user

\\SSH_SERVER のユーザー アカウント

-------------------------------------------------------------------------
Administrator            cyg_server               Guest
hogeuser                      sshd
コマンドは正常に終了しました。
sshd サービスの登録状態を確認する。

$ cygrunsrv --verbose -Q sshd
Service             : sshd
Display name        : CYGWIN sshd
Current State       : Stopped
Command             : /usr/sbin/sshd -D
stdin path          : /dev/null
stdout path         : /var/log/sshd.log
stderr path         : /var/log/sshd.log
Process Type        : Own Process
Startup             : Automatic
Dependencies        : tcpip
Account             : .\cyg_server

sshdの設定ファイル (/etc/sshd_config) を編集

$ ls -l /etc/sshd_config
-rw-r--r-- 1 cyg_server root 3.6K 8月   7 09:21 /etc/sshd_config

$ grep -v "^#" /etc/sshd_config | grep -v "^$"
Port 22
Protocol 2                                      # SSH1 は使用せず、SSH2に固定
HostKey /etc/ssh_host_ecdsa_key                 # ECDSA と
HostKey /etc/ssh_host_ed25519_key               # ED25519 のみ受け付ける
PermitRootLogin no                              # rootのログインを許可しない
StrictModes no
AuthorizedKeysFile      .ssh/authorized_keys2   # SSH2 用
PasswordAuthentication no                       # パスワード認証を使わない
ChallengeResponseAuthentication no
UsePrivilegeSeparation sandbox                  # Default for new installations.
Subsystem       sftp    /usr/sbin/sftp-server
AllowUsers  hogeuser                            # 許可するユーザー
DenyUsers   Administrator cyg_server Guest sshd # 許可しないユーザー

sshd サービスを起動する

C:\> net start sshd
    または
$ cygrunsrv -S sshd
    または
「サービス」から「起動」
    または
Windows起動時に自動起動

管理者権限で起動したコマンドプロンプトからサービスを起動/停止してみる

C:\> net start "CYGWIN sshd"
CYGWIN sshd サービスを開始します.
CYGWIN sshd サービスは正常に開始されました。

C:\> net stop "CYGWIN sshd"
CYGWIN sshd サービスを停止中です.
CYGWIN sshd サービスは正常に停止されました。


SSHクライアント側の設定


必要なパッケージをインストールする。

$ apt-cyg install openssh

クライアントの鍵ペアを作成する (一般ユーザのCygwin ターミナルで)

ssh-user-config スクリプトで作成してみる

$ ssh-user-config
*** Query: Shall I create a SSH2 RSA identity file for you? (yes/no) no  #← SSH2 RSA鍵を作らない
*** Query: Shall I create a SSH2 DSA identity file for you? (yes/no) yes #← SSH2 DSA鍵を作る
*** Info: Generating /home/hogeuser/.ssh/id_dsa
Enter passphrase (empty for no passphrase): ********                     #← SSH2 DSA鍵のパスフレーズを設定
Enter same passphrase again: ********                                    #← SSH2 DSA鍵のパスフレーズを再入力
*** Query: Do you want to use this identity to login to this machine? (yes/no) no    #← 手動で登録するので authorized_keys に登録しなかった
*** Query: Shall I create a SSH2 ECDSA identity file for you? (yes/no) yes           #← SSH2 ECDSA鍵を作る
*** Info: Generating /home/hogeuser/.ssh/id_ecdsa
Enter passphrase (empty for no passphrase): ********                     #← SSH2 ECDSA鍵パスフレーズを設定
Enter same passphrase again: ********                                    #← SSH2 ECDSA鍵パスフレーズを再入力
*** Query: Do you want to use this identity to login to this machine? (yes/no) no    #← 手動で登録するので authorized_keys に登録しなかった
*** Query: Shall I create a (deprecated) SSH1 RSA identity file for you? (yes/no) no #← SSH1 RSA鍵を作らない

*** Info: Configuration finished. Have fun!

ssh-keygen コマンドで作成してみる (ssh-user-config スクリプトを使わずに)

# SSH2 ED25519鍵を作る
#     -t : 作成する鍵のタイプ (RSA1 RSA DSA ECDSA ED25519 など)
#     -C : コメント
$ ssh-keygen -t ED25519 -C hogeuser@ssh_server-20140807
Generating public/private ED25519 key pair.
Enter file in which to save the key (/home/hogeuser/.ssh/id_ed25519)   #← エンター
Enter passphrase (empty for no passphrase): ********              #← パスフレーズ設定
Enter same passphrase again: ********                             #← パスフレーズ再入力
Your identification has been saved in /home/hogeuser/.ssh/id_ed25519.
Your public key has been saved in /home/hogeuser/.ssh/id_ed25519.pub.
The key fingerprint is:
XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX hogeuser@ssh_server-20140807
The key's randomart image is:
+--[ED25519  256--+
|   .   .E     o  |
|+   .  .+   .  . |
|    + o  . oo =  |
|     + o+ . .  o |
|    ..S   . o .  |
|   .     ==      |
|.       +        |
|                 |
|                 |
+-----------------+

$ cat ~/.ssh/id_ed25519
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jYmMAAAAGYmNyeXB0AAAAGAAAABDtGYMLK/
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
jri73Gp8d3ZH88rA==
-----END OPENSSH PRIVATE KEY-----

$ cat ~/.ssh/id_ed25519.pub
ssh-ed25519 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX9cV67GyM hogeuser@ssh_server-20140807

作成されたファイルを確認する。

$ ls -l ~/.ssh
-rw------- 1 hogeuser None 751 8月   7 09:50 id_dsa -rw-r--r-- 1 hogeuser None 599 8月   7 09:50 id_dsa.pub -rw------- 1 hogeuser None 314 8月   7 09:51 id_ecdsa -rw-r--r-- 1 hogeuser None 171 8月   7 09:51 id_ecdsa.pub -rw------- 1 hogeuser None 464 8月   7 10:02 id_ed25519 -rw-r--r-- 1 hogeuser None 105 8月   7 10:02 id_ed25519.pub

鍵ペアのパーミッション設定(確認)

$ chmod 744 ~/.ssh
$ chmod 600 ~/.ssh/id_*
$ chmod 644 ~/.ssh/id_*.pub

クライアント側の公開鍵を、サーバー側に登録する


クライアント側の id_ecdsa.pub と id_ed25519.pub を安全な方法でサーバー側へコピーする。(せっかく作ったけど、今回は SSH2 DSA 鍵は使わないことにした)
公開鍵を ~/.ssh/authorized_keys2 に追加する

$ cd ~/tmp                   # ←ここに公開鍵をコピーしたとする
$ cat id_ecdsa.pub id_ed25519.pub >> ~/.ssh/authorized_keys2
$ rm id_ecdsa.pub id_ed25519.pub

鍵ペアのパーミッション設定(確認)

$ chmod 744 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys2

クライアント側から接続してみる


#    -2 : SSH2 で
#    -4 : IPv4 で
#    -i ~/.ssh/id_ed25519 : 秘密鍵を指定
#    hogeuser@192.168.100.100 : ユーザ名とホスト名
hogeuser@SSH_CLIENT ~
$ ssh -2 -4 -i ~/.ssh/id_ed25519 hogeuser@192.168.100.100
The authenticity of host '192.168.100.100 (192.168.100.100)' can't be established.
ECDSA key fingerprint is a5:cc:00:0f:32:7e:3d:3a:4f:b4:8c:c5:55:73:75:c5.
Are you sure you want to continue connecting (yes/no)? yes      #← fingerprint が正しければ yes
Warning: Permanently added '192.168.100.100' (ECDSA) to the list of known hosts.
Enter passphrase for key '/home/hogeuser/.ssh/id_ed25519': ********  #← パスフレーズを入力
Last login: Thu Aug  7 10:35:18 2014 from ssh_client

hogeuser@SSH_SERVER ~
$                      #←ログインできた

勝手に使える鍵を選択してくれるから、(ユーザ名と)ホスト名だけ指定してもok

hogeuser@SSH_CLIENT ~
$ ssh hogeuser@192.168.100.100
Enter passphrase for key '/home/hogeuser/.ssh/id_ecdsa':
Last login: Thu Aug  7 10:37:26 2014 from ssh_client

hogeuser@SSH_SERVER ~
$                      #←ログインできた

接続できない場合は、「-v」「-vv」「-vvv」オプション (3段階) を付けて ssh を起動してみる
以下は「~/.ssh/authorized_keys2」が存在しなかった場合の実行例。

$ ssh -v -2 -4 -i ~/.ssh/id_ed25519 hogeuser@192.168.100.100
OpenSSH_6.6.1, OpenSSL 1.0.1h 5 Jun 2014
debug1: Reading configuration data /etc/ssh_config
debug1: Connecting to 192.168.100.100 [192.168.100.100] port 22.
debug1: Connection established.
debug1: identity file /home/hogeuser/.ssh/id_rsa type -1
debug1: identity file /home/hogeuser/.ssh/id_rsa-cert type -1
debug1: identity file /home/hogeuser/.ssh/id_dsa type -1
debug1: identity file /home/hogeuser/.ssh/id_dsa-cert type -1
debug1: identity file /home/hogeuser/.ssh/id_ecdsa type 3
debug1: identity file /home/hogeuser/.ssh/id_ecdsa-cert type -1
debug1: identity file /home/hogeuser/.ssh/id_ed25519 type 4
debug1: identity file /home/hogeuser/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.6.1
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1
debug1: match: OpenSSH_6.6.1 pat OpenSSH_6.6.1* compat 0x04000000
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5-etm@openssh.com none
debug1: kex: client->server aes128-ctr hmac-md5-etm@openssh.com none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ECDSA a5:cc:00:0f:32:7e:3d:3a:4f:b4:8c:c5:55:73:75:c5
debug1: Host '192.168.100.100' is known and matches the ECDSA host key.
debug1: Found key in /home/hogeuser/.ssh/known_hosts:1
debug1: ssh_ecdsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /home/hogeuser/.ssh/id_rsa
debug1: Trying private key: /home/hogeuser/.ssh/id_dsa
debug1: Offering ECDSA public key: /home/hogeuser/.ssh/id_ecdsa
debug1: Authentications that can continue: publickey
debug1: Offering ED25519 public key: /home/hogeuser/.ssh/id_ed25519
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
Permission denied (publickey).

sshd をデバッグモードで起動する


管理者権限で起動したcygwinターミナルから sshd をデバッグモードで起動してみようとしたら、以下のようなエラーが出て起動できなかった。
これは、cyg_server アカウント以外のユーザで起動したためだと思う。

$ /usr/sbin/sshd -d
debug1: sshd version OpenSSH_6.6.1, OpenSSL 1.0.1e 11 Feb 2013
debug1: key_parse_private2: missing begin marker
debug1: read PEM private key done: type RSA
debug1: private host key: #0 type 1 RSA
debug1: key_parse_private2: missing begin marker
debug1: read PEM private key done: type DSA
debug1: private host key: #1 type 2 DSA
debug1: key_parse_private2: missing begin marker
debug1: read PEM private key done: type ECDSA
debug1: private host key: #2 type 3 ECDSA
debug1: private host key: #3 type 4 ED25519
/var/empty must be owned by root and not group or world-writable.

# パーミッションは特に問題ない(と思う)
$ ls -ld /var/empty
drwxr-xr-x+ 1 cyg_server root 0 8月   4 11:34 /var/empty/

sshd をデバッグモードで起動するには、サービスに登録してしまった方がいいと思う

# デバッグモードのSSHDをサービスに登録する
# サーバ側で cygwin ターミナルを管理者権限で起動
# 1度 SSH で接続→切断すると、毎回サービスが停止する
#   --args の d はデバッグレベル。1~3個まで指定できる
#   デバッグログは /var/log/sshd_debug に出力される
#   sshd サービスは自動起動しない(手動)
$ cygrunsrv --install sshd_debug_mode \
            --disp "CYGWIN sshd DEBUG MODE" \
            --path /usr/sbin/sshd \
            --args "-Dddd -E /var/log/sshd_debug" \
            --type manual \
            --user cyg_server
            -y tcpip
Enter password of user `SSH_SERVER\cyg_server': ******** #← cyg_server ユーザのパスワードを入力
Reenter, please: ********                           #← cyg_server ユーザのパスワードを再入力

# デバッグモードの sshd を起動する
$ cygrunsrv -S sshd_debug_mode

以下のエラーでSSHDサービスの起動に失敗した場合は、cygserverのパスワードを再設定すると良いらしい。
(参考: Cygwin - マルチメディア実験室 - Redmine for School of Education)

$ cygrunsrv -S sshd_debug_mode
cygrunsrv: Error starting a service: StartService:  Win32 error 1069:
OI?クsオスス゚AT[rX・
               Jn?ォワケ・オスB
(SJIS: ログオンに失敗したため、サービスを開始できませんでした。)

------------------------

C:\>net start sshd_debug_mode
システム エラー 1069 が発生しました。

ログオンに失敗したため、サービスを開始できませんでした。

cyg_server ユーザのパスワードを再設定する。

#   パスワードは 5 から 8 文字のようだ(もっと長いパスワードを指定してた)
$ passwd cyg_server
Enter the new password (minimum of 5, maximum of 8 characters).
Please use a combination of upper and lower case letters and numbers.
New password: ********
Re-enter new password: ********
Password changed.

# デバッグモードの sshd サービスを起動
$ cygrunsrv -S sshd_debug_mode

必要がなくなったら、デバッグモードの sshd サービスを削除しておく
$ cygrunsrv -R sshd_debug_mode


0 件のコメント:

コメントを投稿