SSH

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page SSH and the translation is 92% complete.
Outdated translations are marked like this.

SSH (Secure SHell) は、リモートマシンに安全にログインし、作業を行うためのユビキタスなツールです。すべての機密情報は強固に暗号化され、リモートシェルとしての機能だけでなく、ファイル転送と、任意のプロトコルに対するポートフォワーディングにも対応しており、リモートサービスへの安全なアクセスを可能にします。昔ながらの telnetrlogin、その他同様の安全でないツールを置き換えますが、SSH はただのリモートシェルではなく、リモートシステムで作業を行うための機能が完備されている環境でもあります。

メインの ssh コマンドに加えて、SSH プログラムスイートには scp (Secure Copy Program)、sftp (Secure File Transfer Protocol)、または鍵の管理に役立つ ssh-agent といったツールも含まれます。標準的な SSH ポートは、ポート 22 です。

SSH には複数のバージョンが存在してきました。現在最も広く使われている SSH の実装で、デファクトスタンダードとなっているのは、OpenBSDOpenSSH です。これは Gentoo でもプリインストールされていてBSD ("と、よりフリーな") ライセンスの下で公開されています。

SSH はマルチプラットフォームで、とても広く利用されています: OpenSSH はほとんどの Unix ライク OS、Windows 10、MacOS にデフォルトでインストールされていて、Android や "脱獄" した iOS にもインストールできます (SSH クライアントを利用できます)。そのため、SSH は異種システム間の作業のための素晴らしいツールとなっています。

インストール

インストールの確認

net-misc/opensshsystem 集合に含まれているので、Gentoo Linux が配置された環境には、OpenSSH が既にインストールされているはずです。正しく機能する OpenSSH が存在しているかどうかは、ssh コマンドを実行すれば確認できます。使い方の文章が出力されるはずです:

user $ssh
usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]
           [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
           [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]
           [-i identity_file] [-J [user@]host[:port]] [-L address]
           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
           [-Q query_option] [-R address] [-S ctl_path] [-W host:port]
           [-w local_tun[:remote_tun]] destination [command]

使い方が出力されない場合、OpenSSH が壊れているか、またはインストールされていないのかもしれません。emerge のセクションに従って、USE フラグを変更した後の再ビルドと同じようにして、再インストールしてみてください。もし OpenSSH がインストールされていなかった場合は、これで再インストールされるはずです。そして、system 集合の一部として、インストールされたまま残り続けるはずです。

もしこれでも OpenSSH がインストールされないのであれば、パッケージがマスクされているか、package.provided に含まれているかもしれませんが、通常はそのようなことはないでしょう。

USE フラグ

USE flags for net-misc/openssh Port of OpenBSD's free SSH release

X Add support for X11
audit Enable support for Linux audit subsystem using sys-process/audit
debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
kerberos Add kerberos support
ldns Use LDNS for DNSSEC/SSHFP validation.
libedit Use the libedit library (replacement for readline)
livecd Enable root password logins for live-cd environment.
pam Add support for PAM (Pluggable Authentication Modules) - DANGEROUS to arbitrarily flip
pie Build programs as Position Independent Executables (a security hardening technique)
security-key Include builtin U2F/FIDO support
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
ssl Enable additional crypto algorithms via OpenSSL
static !!do not set this during bootstrap!! Causes binaries to be statically linked instead of dynamically
test Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently)
verify-sig Verify upstream signatures on distfiles
xmss Enable XMSS post-quantum authentication algorithm

Emerge

OpenSSH パッケージのみに対する USE フラグを変更したら、新しいフラグが適用されるように OpenSSH を再ビルドしてください。OpenSSH は system 集合に含まれているので、world ファイルに追加しないように、--oneshot を使用するべきです:

root #emerge --ask --changed-use --oneshot net-misc/openssh

make.conf 内で OpenSSH に影響するグローバルな USE フラグを変更した後は、新しい USE フラグにアップデートするように world を emerge してください:

root #emerge --ask --verbose --update --deep --newuse @world

設定

鍵の作成

安全なシェルを提供するために、暗号鍵が SSH の提供する暗号化、復号化、ハッシュといった機能の管理に使われています。

システム鍵がすべて生成されていない場合、sshd init スクリプトがその初回実行時に生成するでしょう。通常は (システムが不正アクセスを受けていない限り) 再生成する必要はありませんが、そのような必要性が発生した場合は、ssh-keygen コマンドを使ってこれを手動で行うことができます (rsa、ecdsa および Ed25519 アルゴリズム):

root #ssh-keygen -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key -N ""
root #ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_ecdsa_key -N ""
root #ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N ""

サーバーの設定

SSH サーバーは設定ファイルの位置変更も含め OpenRC の /etc/conf.d/sshd で設定することもできますが、通常は /etc/ssh/sshd_config ファイルで設定されます。サーバーを設定する方法についての詳細は sshd_config(5) の man ページを参照してください。

SSH サーバはテストモードを使って構成ファイルの妥当性を検証する方法を提供します:

root #/usr/sbin/sshd -t
重要
リモートログインが利用できる状態を維持するために、サーバを再起動する前に構成ファイルの変更の妥当性を必ず検証してください。

クライアントの設定

ssh クライアントや関連プログラム(scpsftp など)は以下のファイルを使って設定できます:

  • ~/.ssh/config
  • /etc/ssh/ssh_config

詳細については ssh_config(5)man ページを読んでください。

侵入の防止

SSH はよく攻撃されるサービスです。sshguardfail2ban といったツールはログを監視し、繰り返しログインを試行し失敗しているリモートユーザーをブラックリストに追加してくれます。頻繁に攻撃されるシステムを安全に保つには、これらを必要に応じて活用しましょう。

サービス

SSH サーバを実行するためのコマンドは、有効な init システムによって異なります。

OpenRC

OpenSSH デーモンを default ランレベルに追加する:

root #rc-update add sshd default

sshd デーモンを開始するには:

root #rc-service sshd start

OpenSSH サーバーは他の OpenRC で管理されているサービスと同様にしてコントロールできます:

root #rc-service sshd start
root #rc-service sshd stop
root #rc-service sshd restart
メモ
サーバーへのアクティブな SSH 接続は、rc-service sshd restart が実行されても影響を受けず維持されます。

systemd

システム起動時に OpenSSH デーモンを起動するには:

root #systemctl enable sshd.service
Created symlink from /etc/systemd/system/multi-user.target.wants/sshd.service to /usr/lib64/systemd/system/sshd.service.

OpenSSH デーモンをすぐに開始するには:

root #systemctl start sshd.service

サービスが開始されているか確認するには:

root #systemctl status sshd.service

使い方

コマンド

OpenSSH は複数のコマンドを提供します。使い方については、各コマンドの man ページを確認してください:

  • scp(1) - 安全なファイルコピー
  • sftp(1) - 安全なファイル転送
  • ssh-add(1) - 認証エージェントに秘密鍵を追加する
  • ssh-agent(1) - 認証エージェント
  • ssh-copy-id(1) - ローカルで利用可能な鍵を使って、リモートマシンへのログインを認可されるようにする
  • ssh-keygen(1) - 認証鍵ユーティリティ
  • ssh-keyscan(1) - サーバから SSH 公開鍵を集める
  • sshd(8) - OpenSSH デーモン

エスケープシーケンス

アクティブな SSH セッションの間にチルダ(~)キーを押すと、エスケープシーケンスが開始されます。オプションの一覧を見るには以下を入力してください:

ssh>~?

このエスケープは改行の直後しか認識されないことに注意してください。エスケープは、fish などの一部のシェルではうまく動作しないことがあります。

リモート SSH サーバへのパスワードレス認証

git サーバーを管理するのに便利です。

関連
さらなる詳細については Security Handbook も確認してください。
警告
Leaving the passphrase empty implies the private key file will not be encrypted. An attacker having access to the local filesystem will be able to read the private key.

クライアント

クライアントでは、もしまだ行っていなければ、鍵ペアを作成します。以下のコマンドを実行することで、鍵ペアを作成してください (もちろん、パスワードは入力しないでください):

user $ssh-keygen -t ed25519
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/larry/.ssh/id_ed25519): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/larry/.ssh/id_ed25519
Your public key has been saved in /home/larry/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256:riDdFuPhN7alEsAvm717gM1IZBP3DYXGo5apQG7OUM1 larry@client
The key's randomart image is:
+--[ED25519 256]--+
| .+   ..+o.      |
| o +   Ao+.o     |
|. o A Oo  . .    |
| =   + .o +      |
|  o   . S= + .   |
|     . *. B + .  |
|      o.=  * o   |
|     ...+ = .    |
|      .. .+=     |
+----[SHA256]-----+

The default file names of the keys must not be changed, or the server may persist in asking for a password even after running ssh-copy-id as explained below. The file name will be one of:

  • id_rsa
  • id_ecdsa
  • id_ed25519

depending on the key algorithm used.

サーバ

ユーザー用のアカウントがサーバー上に存在することを確認し、クライアントの id_ed25519.pub ファイルをサーバーのユーザーのホームディレクトリーにある ~/.ssh/authorized_keys ファイルの中に配置してください。これは以下のコマンドをクライアントコンピューター上で実行することで行えます(ここではサーバー上のユーザーのパスワードを入力する必要があります):

user $ssh-copy-id <server>
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/larry/.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
/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
larry@<server>'s password: 
 
Number of key(s) added: 1
 
Now try logging into the machine, with:   "ssh '<server>'"
and check to make sure that only the key(s) you wanted were added.

これ以降は以下を実行することでパスワードなしでログインできるはずです:

user $ssh <server>
larry@<server>

そしてサーバー側では、/etc/ssh/sshd_configPasswordAuthentication no を設定するべきです。

単一マシンでのテスト

上の手順はローカルでテストすることもできます:

user $ssh-keygen -t ed25519
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/larry/.ssh/id_ed25519): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again:
...
user $mv ~/.ssh/id_ed25519.pub ~/.ssh/authorized_keys
user $ssh localhost

ssh 越しのリモートサービス

SSH は、暗号化された「トンネル」を介して、HTTP、HTTPS、ファイル共有などのリモートサービスにアクセスするために使用することができます。リモートサービスアクセスの詳細は、SSH tunnelingSSH jump host の記事にあります。

リモートホストへファイルをコピーする

SSH の一部である SFTP コマンドは、SSH ファイル転送プロトコルを使用して、リモートホストへファイルをコピーします。この目的では rsync も代替となりえます。

メモ
2019 年の OpenSSH 8.0 リリースノートでは、「scp プロトコルは時代遅れで、柔軟性に欠け、積極的に修正されていない。ファイル転送には、sftp や rsync などのより現代的なプロトコルを代わりに使用することを推奨する。」とされています。2021 年の OpenSSH 8.8 リリースノートでは、「近い将来の OpenSSH のリリースで、scp(1) はデフォルトで、レガシーな scp/rcp プロトコルに代わって SFTP を使用するように切り替える予定である。」とされています。

ssh-agent

OpenSSH には、キャッシュにより頻繁なパスワード入力を防止する ssh-agent デーモンが同梱されています。これを起動すると、ssh-agent の通信ソケットを指すために SSH_AUTH_SOCK 環境変数が使用されます。ssh-agent をセットアップする通常の方法は、ユーザのセッションの最上位プロセスで実行することです。そうしないと、環境変数がセッション中で確認することができません。

グラフィカルユーザセッションを起動するように構成されている場合、ssh-agent を起動するための適切な方法を見つけるのは複雑になることがあります。例えば、lightdm ディスプレイマネージャを使用している場合は、 /etc/lightdm/Xsession を編集して:

user $exec $command

の部分を、以下のようにしてください:

user $exec ssh-agent $command

ssh-agent にセッションを通して一度だけパスワードを入力させるようにするには、ssh-add を手動で実行するか、AddKeysToAgent オプションを利用してください。

最近の Xfcessh-agent (と gpg-agent) を自動的に起動します。これらが両方ともインストールされている場合は、両方が自動起動され、特にスマートカードが絡む場合にアイデンティティ管理が複雑になります。少なくとも SSH のエージェントか、あるいは両方の XFCE による自動起動を停止して、シェル、X セッションまたはそれに類するものを使用してください。

user $xfconf-query -c xfce4-session -p /startup/ssh-agent/enabled -n -t bool -s false
user $xfconf-query -c xfce4-session -p /startup/gpg-agent/enabled -n -t bool -s false

ヒント

セッションを維持するためのターミナルマルチプレクサ

接続が切れた後でセッションを再開するために、ターミナルマルチプレクサを使用することができます。TmuxScreen は、接続が切れたときにコマンドが実行中だったとしてもセッションに再接続できる、2 つの人気のあるマルチプレクサです。

不安定な接続の上での SSH

インターネット接続が不安定な場合や、ネットワーク間をローミングしている (wifi ネットワーク間を移動しているなどの) 場合は、SSH セッションが切断されないようにするために mosh を利用することができます。

Kitty 端末でセッションのために新しいタブを開く

Kitty 端末エミュレータでは SSH kitten を使用することで、現在の SSH セッションで、再ログインすることなく、新しい「タブ」またはウィンドウを開くことができます。

Kitty はその他にも実用的な SSH 機能を提供しています。

Benchmark the optimal rounds for an ed25519 key

ヒント
It is highly advisable to conduct benchmarking for the ed25519 key generation process, particularly considering the default value of 16 rounds and the potential performance improvements achievable with higher round values.
ファイル ssh-benchmark.shSSH 暗号をベンチマークする
#!/bin/sh

rounds="16 32 64 100 150"
num_runs=20

for r in $rounds; do
    printf "Benchmarking 'ssh-keygen -t ed25519 -a %s' on average:\n" "$r"
    total_time=0
    i=1
    while [ $i -le $num_runs ]; do
        start_time=$(date +%s.%N)
        ssh-keygen -t ed25519 -a "$r" -f test -N test >/dev/null 2>&1
        end_time=$(date +%s.%N)
        runtime=$(echo "$end_time - $start_time" | bc)
        total_time=$(echo "$total_time + $runtime" | bc)
        rm test{,.pub} >/dev/null 2>&1
        printf "Run %s: %s seconds\n" "$i" "$runtime"
        i=$((i + 1))
    done
    average_time=$(echo "scale=3; $total_time / $num_runs"| bc)
    printf "Average execution time: %s seconds\n\n" "$average_time"
done
メモ
It is highly recommended to perform benchmarking for ed25519 key generation, considering both security and performance aspects. While the highest recommended round may offer superior security, it's essential to find the optimal balance based on individual requirements and time constraints. By conducting benchmark tests, one can evaluate the trade-off between security and performance, ensuring the selection of an appropriate round value for ed25519 keys.

Benchmarking is a crucial process to measure the performance and efficiency of a system or a specific component, such as cryptographic algorithms. In the context of SSH (Secure Shell) ciphers, it is important to determine the optimal number of rounds for generating ed25519 keys.

The provided script, ssh-benchmark.sh, conducts benchmarking on the ssh-keygen command with different round values for ed25519 keys. The script executes the ssh-keygen command multiple times with varying round values and measures the execution time for each run. It then calculates the average execution time for each round value.

By benchmarking different round values, system administrators and security professionals can identify the optimal round value that strikes a balance between security and performance. Higher round values generally provide stronger security but can result in increased computational overhead. Finding the right balance ensures that ed25519 keys are generated efficiently without compromising security.

Benchmarking helps identify potential bottlenecks, vulnerabilities, or areas that require improvement in security systems. It assists in selecting the most suitable algorithms and configurations for a particular use case, ensuring that security measures are robust and effective.

トラブルシューティング

問題への対処に役立つかもしれない、3つの異なるデバッグモードレベルがあります。-v オプションを使うと、SSH は自身の進捗についてデバッグメッセージを出力します。これは接続、認証、そして設定の問題をデバッグする際に有用です。複数の -v オプションを付けるとより詳細な情報が出力されます。最も詳細なのは3番目のレベルです。

user $ssh example.org -v
user $ssh example.org -vv
user $ssh example.org -vvv

パーミッションが広すぎる

ssh 接続は、~/.ssh ディレクトリとその内容のファイルパーミッションが正しい場合にだけ、動作するでしょう。

  • ~/.ssh ディレクトリパーミッションは 700 (drwx------) であるべきです。所有者が完全なアクセス権を持ち、他はだれもアクセスできません。
  • ~/.ssh 以下について:
    • 公開鍵ファイルのパーミッションは 644 (-rw-r--r--) であるべきです。誰でもファイルを読むことができ、所有者だけが書き込むことができます。
    • 他のすべてのファイルのパーミッションは 600 (-rw-------) であるべきです。所有者だけがファイルを読み書きできます。

これらのパーミッションは、クライアントとサーバの両側で正しく設定されている必要があります。

長時間続いている接続が切断される

インターネットに接続するデバイスの多くはネットワークアドレス変換 (Network Address Translation、NAT) を使っています。これは、家庭やビジネスでよく使われているプライベートネットワーク上のデバイスから、ネットワークで1つの IP アドレスしか持っていないにもかかわらず、外部ネットワークにアクセスするための仕組みです。残念なことに、すべての NAT デバイスが同じに作られているわけではなく、またそのうちいくつかは SSH で使われているような長時間持続し時折使われる TCP 接続を不正に閉じてしまいます。これは一般的に、ssh クライアントプログラムが終了していないにも関わらず突然サーバーと対話できなくなるという形で識別できます。

この問題を解決するために、OpenSSH クライアントとサーバーでは 'keep alive'、すなわちリンクの持続状況を維持・確認するための不可視なメッセージを送信するよう設定できます:

  • ローカルサーバーに接続しているすべてのクライアントに対して keep alive を有効にするには、ClientAliveInterval 30 (またはその他の秒単位の値)を /etc/ssh/sshd_config ファイルで設定します。
  • ローカルクライアントから接続するすべてのサーバーに対して keep alive を有効にするには、ServerAliveInterval 30 (またはその他の秒単位の値)を /etc/ssh/ssh_config または ~/.ssh/config ファイルで設定します。
  • 切断を減らすように、TCPKeepAlive no を設定します。

例えば、サーバの設定を変更するには、次のファイルを追加してください:

ファイル /etc/ssh/sshd_config/01_ClientAlive.conf切断の発生を抑える (サーバ)
# 以下の ClientAlive の値は、活動の無いセッションを 30 分間開き続けます
ClientAliveCountMax 60
ClientAliveInterval 30
#
# TCPKeepAlive を無効化します
TCPKeepAlive no

クライアントの設定を変更するには、次のファイルを追加してください:

ファイル /etc/ssh/ssh_config/01_ServerAlive.conf切断の発生を抑える (クライアント)
# 以下の ServerAlive の値は、活動の無いセッションを 2 時間開き続けます
ServerAliveInterval 60
ServerAliveCountMax 120

新しい鍵が使用されない

このシナリオは、リモートシステムにアクセスするための鍵が作成され、リモートシステムに公開鍵がインストールされたが、リモートシステムが (なぜか) ssh 経由でアクセスできないケースを取り扱います。これは鍵ファイルの名前が ssh から見えない場合に起こることがあります。

トラブルシューティングの節の先頭で説明した出力詳細度オプションを付けて ssh を実行することで、ssh がどの鍵ファイルを試しているのか確認してください。詳細な出力には、試行中の鍵ファイルと、実際に使用される鍵ファイル (もしあれば) の名前が含まれるでしょう。

システムのデフォルトの鍵ファイルは /etc/ssh/ssh_config に列挙されています。コメントアウトされている、IdentityFile ディレクティブを含む行を参照してください。

デフォルト以外の名前を持つ鍵を使用する方法がいくつかあります。

鍵の名前を毎回コマンドライン上で指定することができます:

user $ssh -i ~/.ssh/my_keyfile user@remotesys

または、そのリモートシステムへの ssh 接続のための特別なケースを追加するように、以下の ssh 設定ファイルを追加してください:

ファイル /etc/ssh/ssh_config/02_remotesys.confホスト remotesys のために使用する鍵ファイルを定義する
Host remotesys
    IdentityFile ~/.ssh/id_rsa
    IdentityFile ~/.ssh/my_keyfile

If any are specified, it appears to be necessary to specify all the desired keys on a remote host. Read up on the ssh IdentityFile.

X11 フォワーディングでフォワーディングまたはトンネリングされない

問題点: X11 フォワーディングを許可するように設定ファイルを変更した後も X アプリケーションがサーバー上で実行され、クライアントにフォワーディングされない。

解決策: おそらく、リモートサーバーやホストへの SSH ログインの間に DISPLAY 変数が unset されたか、または SSH セッションがそれをセットした後にセットされています。

この状況をテストするには、リモートログインの後に以下を実行します:

user $echo $DISPLAY
localhost:10.0

出力は localhost:10.0 か、あるいはサーバー側で X11UseLocalhost no の設定をしている場合は localhost2.local:10.0 といったものになるはずです。通常の :0.0 が表示されない場合、~/.bash_profile 中の DISPLAY 変数が unset または再初期化されていないことを確認してください。もしそうなっていたら、SSH ログインの途中で ~/.bash_profile 内のそのコードが実行されないようにするため、DISPLAY 変数のカスタムした初期化をすべて削除またはコメントアウトしてください:

user $ssh -t larry@localhost2 bash --noprofile

上のコマンドの larry は適切なユーザー名に必ず置き換えてください。

この作業を完了させるために使える方法として、ユーザーの ~/.bashrc ファイルでエイリアスを定義するというものがあります。

関連項目

  • Autossh — a command that detects when SSH connections drop and automatically reconnects them.
  • dropbear — a lightweight SSH server. It runs on a variety of POSIX-based platforms.
  • Keychain — この文書では SSH 共有鍵をキーチェーンプログラムとともに使用する方法を記述します。
  • Mosh — a SSH client server that is aware of connectivity problems of the original SSH implementation.
  • SCP — an interactive file transfer program, similar to the copy command, that copies files over an encrypted SSH transport.
  • SFTP — an interactive file transfer program, similar to FTP, which performs all operations over an encrypted SSH transport.
  • SSHFS — a secure shell client used to mount remote filesystems to local machines.
  • SSH tunneling — a method of connecting to machines on the other side of a gateway machine.
  • SSH jump host — employed as an alternative to SSH tunneling to access internal machines through a gateway.
  • rsync — a powerful file sync program capable of efficient file transfers and directory synchronization.
  • Securing the SSH service (Security Handbook)
  • SSH デーモンの開始 — Gentoo ハンドブック — インストール

外部資料