「OpenSSH」の版間の差分

提供: ArchWiki
ナビゲーションに移動 検索に移動
(意味がわからない文を原文に戻した)
291行目: 291行目:
 
Both local and remote forwarding can be used to provide a secure "gateway," allowing other computers to take advantage of an SSH tunnel, without actually running SSH or the SSH daemon by providing a bind-address for the start of the tunnel as part of the forwarding specification, e.g. {{Ic|<tunnel address>:<tunnel port>:<destination address>:<destination port>}}. The {{Ic|<tunnel address>}} can be any address on the machine at the start of the tunnel, {{Ic|localhost}}, {{Ic|*}} (or blank), which, respectively, allow connections via the given address, via the loopback interface, or via any interface. By default, forwarding is limited to connections from the machine at the "beginning" of the tunnel, i.e. the {{Ic|<tunnel address>}} is set to {{Ic|localhost}}. Local forwarding requires no additional configuration, however remote forwarding is limited by the remote server's SSH daemon configuration. See the {{Ic|GatewayPorts}} option in {{Ic|sshd_config(5)}} for more information.
 
Both local and remote forwarding can be used to provide a secure "gateway," allowing other computers to take advantage of an SSH tunnel, without actually running SSH or the SSH daemon by providing a bind-address for the start of the tunnel as part of the forwarding specification, e.g. {{Ic|<tunnel address>:<tunnel port>:<destination address>:<destination port>}}. The {{Ic|<tunnel address>}} can be any address on the machine at the start of the tunnel, {{Ic|localhost}}, {{Ic|*}} (or blank), which, respectively, allow connections via the given address, via the loopback interface, or via any interface. By default, forwarding is limited to connections from the machine at the "beginning" of the tunnel, i.e. the {{Ic|<tunnel address>}} is set to {{Ic|localhost}}. Local forwarding requires no additional configuration, however remote forwarding is limited by the remote server's SSH daemon configuration. See the {{Ic|GatewayPorts}} option in {{Ic|sshd_config(5)}} for more information.
   
  +
--[[利用者:Aosho235|Aosho235]] ([[利用者・トーク:Aosho235|トーク]]) 2015年12月27日 (日) 12:27 (JST)=== マルチプレクス ===
=== マルチプレクス ===
 
   
  +
SSH デーモンは通常はポート 22 番をリッスンします。しかし、公共のインターネット・ホットスポットでは HTTP/HTTPS のポート(80 と 443)以外のトラフィックをブロックしていることが一般的です。そのため SSH 接続がブロックされてしまいます。すぐできる解決策として、許可されているポートで sshd を起動するという方法があります:
The SSH daemon usually listens on port 22. However, it is common practice for many public internet hotspots to block all traffic that is not on the regular HTTP/S ports (80 and 443, respectively), thus effectively blocking SSH connections. The immediate solution for this is to have {{ic|sshd}} listen additionally on one of the whitelisted ports:
 
   
 
{{hc|/etc/ssh/sshd_config|
 
{{hc|/etc/ssh/sshd_config|
300行目: 300行目:
 
}}
 
}}
   
  +
しかしポート 443 番は HTTPS を提供する Web サーバにすでに使われていることが多いです。その場合は {{Pkg|sslh}} のようなマルチプレクサを使います。これは指定ポートをリッスンし、そこに来るパケットを複数のサービスに賢く振り分けることができます。
However, it is likely that port 443 is already in use by a web server serving HTTPS content, in which case it is possible to use a multiplexer, such as {{Pkg|sslh}}, which listens on the multiplexed port and can intelligently forward packets to many services.
 
   
 
=== SSH の高速化 ===
 
=== SSH の高速化 ===

2015年12月27日 (日) 12:27時点における版

関連記事

Secure Shell (SSH) は暗号技術を利用して、安全にリモートコンピュータと通信するためのネットワークプロトコルです。暗号によってデータの機密性と完全性が保証されます。SSH は公開鍵暗号を使ってリモートコンピュータを認証し、リモートコンピュータは必要に応じてユーザーを認証します。

基本的に SSH はリモートマシンにログインしてコマンドを実行するために使われますが、トンネリングや TCP ポートや X11 接続の任意のフォワーディングをサポートしており、SFTP や SCP プロトコルを使うことでファイル転送をすることも可能です。

デフォルトでは、SSH サーバーは標準の TCP 22番ポートを使います。通常は SSH クライアントプロトコルを使って sshd デーモンの接続を確立してリモート接続を承認します。Mac OS X, GNU/Linux, Solaris, OpenVMS など近代的なオペレーティングシステムのほとんどでサーバーとクライアントの両方が備わってします。複雑なもの・完全なものまで様々なレベルのバージョンがプロプライエタリ・フリーウェア・オープンソースを問わずに存在します。

(ソース: Wikipedia:ja:Secure Shell)

目次

OpenSSH

OpenSSH (OpenBSD Secure Shell) は ssh プロトコルを使ってコンピューターネットワークを介して暗号化通信セッションを提供するコンピュータープログラムのセットです。SSH Communications Security によるプロプライエタリの Secure Shell ソフトウェアスイートに代わるオープンのプログラムとして作成されました。OpenSSH は Theo de Raadt に率いられている OpenBSD プロジェクトの一環として開発されています。

同じような名前の OpenSSL と OpenSSH が混同されることがときどきありますが、プロジェクトの目的・開発チームは異なります。

OpenSSH のインストール

公式リポジトリから opensshインストールしてください。

SSH の設定

クライアント

SSH クライアントの設定ファイルは /etc/ssh/ssh_config もしくは ~/.ssh/config です。

Protocol 2 を明示的に設定する必要はありません。デフォルトの設定ファイルではコメントアウトされています。つまり明示的に有効にされない限り Protocol 1 は使われません。 (ソース: http://www.openssh.org/txt/release-5.4)

デーモン

SSH デーモンの設定ファイルは /etc/ssh/sshd_config です。

特定のユーザーにだけアクセスを許可するには次の行を追加してください:

AllowUsers    user1 user2

特定のグループにだけアクセスを許可するには:

AllowGroups   group1 group2

SSH による root ログインを無効にするには、PermitRootLogin 行を次のように変更してください:

PermitRootLogin no
ノート: バージョン 7.0p1 からは PermitRootLogin prohibit-password がデフォルトになっています。man sshd_config を参照。

ウェルカムメッセージを追加するには /etc/issue ファイルを編集して Banner 行を次のように変更してください:

Banner /etc/issue

ホスト鍵は sshd の systemd サービスによって自動的に生成されます。sshd に特定の鍵を使用させたい場合、手動で設定します:

HostKey /etc/ssh/ssh_host_rsa_key

サーバーに WAN からアクセスできる場合、デフォルトのポートである 22 から別のランダムなポートに変更することが推奨されています:

Port 39901
ノート: OpenSSH では設定ファイルに Port x 行を複数記述することで複数のポートを使うことができます。

パスワードによるログインを使わないようにすればセキュリティは大幅に向上します。詳しくは SSH 鍵#パスワードログインの無効化 を見て下さい。

sshd デーモンの管理

次のコマンドで sshd デーモンを起動することができます:

# systemctl start sshd.service

次のコマンドで sshd デーモンを起動時に有効にすることができます:

# systemctl enable sshd.service

詳しくは systemd#ユニットを使う を見て下さい。

警告: Systemd は非同期にプロセスを実行します。SSH デーモンを特定の IP アドレス ListenAddress 192.168.1.100 に結びつけている場合、デフォルトの sshd.service ユニットファイルはネットワークインターフェイスが有効にされることに依存していないため、ブート中にロードが失敗する可能性があります。IP アドレスをバインドする時は、カスタムした sshd.service ユニットファイルに After=network.target を追加してください。systemd#ユニットファイルの編集 を参照。

また SSH デーモンソケットを有効にすることで初めて接続があったときにデーモンが起動するようにすることもできます:

# systemctl start sshd.socket
# systemctl enable sshd.socket

デフォルトの22番以外のポートを使う場合、ユニットファイルを編集する必要があります:

# systemctl edit sshd.socket
[Socket]
ListenStream=
ListenStream=12345
警告: sshd.socket を使用すると ListenAddress の設定が打ち消されて、どのアドレスからでも接続できるようになってしまいます。ListenAddress の設定を適用するには、ListenStream でポートと IP を指定する必要があります (例: ListenStream=192.168.1.100:22)。また、[Socket] の下に FreeBind=true を追加するようにしてください。そうしないと IP アドレスの設定が ListenAddress の設定と同じように無効になってしまいます: ネットワークが立ち上がっていない場合にソケットの起動が失敗します。
ヒント: ソケットアクティベーションを使う場合、sshd.socket でもデーモンの標準の sshd.service でもログの接続試行を監視することはできません。ただし # journalctl /usr/bin/sshd を実行することで監視できます。

サーバーに接続する

サーバーに接続するには、次を実行してください:

$ ssh -p port user@server-address

SSH の保護

管理業務のために SSH によるリモートログインを許可することは良いことですが、サーバーのセキュリティに脅威を及ぼすことにもなりえます。総当り攻撃の標的になりやすいので、SSH のアクセスは制限して、第三者がサーバーにアクセスできないようにする必要があります。

  • わかりにくいアカウント名やパスワードを使う
  • 信頼できる国からの SSH 接続だけを許可する
  • fail2bansshguard をつかってブルートフォース攻撃を監視し、総当りを起こっている IP を閉め出す

ブルートフォースアタックからの保護

ブルートフォースは単純な攻撃方法です: ランダムなユーザー名とパスワードの組み合わせをとにかく沢山作ってウェブページや SSH などのサーバーログインプロンプトにログインを絶えず試行します。ブルートフォース攻撃からは fail2bansshguard などの自動スクリプトを使うことで攻撃者をブロックすることで身を守ることができます。

もしくは、公開鍵認証を使うことでブルートフォース攻撃を出来なくすることもできます。sshd_config に次の設定を追加:

PasswordAuthentication no

上の設定を適用する前に、SSH アクセスが必要な全てのアカウントで authorized_keys ファイルに公開鍵認証の設定をするようにしてください。詳しくは SSH 鍵#リモートサーバーに公開鍵をコピー を参照。

2段階認証

SSH 鍵のペアによる認証を使用していてパスワードによろうログインを無効化している場合に、2段階認証を使いたいときは Google AuthenticatorSSH 鍵#2段階認証と公開鍵 を見て下さい。

root ログインを制限する

一般的に、SSH で無制限に root ログインを許可することは推奨されません。セキュリティの向上のために、SSH での root ログインを制限する方法は2つ存在します。

root ログインを拒否する

Sudo を使うことで、root アカウントの認証を行うことなく、必要に応じて root 権限を選択的に付与することができます。このため SSH による root ログインを拒否して、攻撃者にパスワードに加えて (root でない) ユーザー名も推測させる必要を生じさせることで、ブルートフォース攻撃を困難にすることが可能です。

/etc/ssh/sshd_config の "Authentication" セクションを編集することで SSH からの root ログインを拒否するように設定できます。#PermitRootLogin yesno に変更して行をアンコメントしてください:

/etc/ssh/sshd_config
PermitRootLogin no
...

そして、SSH デーモンを再起動してください。

これで、SSH を使って root でログインすることはできなくなります。ただし、通常ユーザーでログインしてから susudo を使ってシステム管理を行うことは依然として可能です。

root ログインを限定する

自動的な作業の中にも、リモートによるフルシステムバックアップなど、root 権限を必要とするものがあります。セキュアな方法で root を許可したい場合、SSH による root ログインを無効化する代わりに、特定のコマンドだけ root ログインを許可することができます。~root/.ssh/authorized_keys を編集して、以下のように特定のキーの前にコマンドを記述します:

command="/usr/lib/rsync/rrsync -ro /" ssh-rsa …

This will allow any login with this specific key only to execute the command specified between the quotes.

The increased attack surface created by exposing the root user name at login can be compensated by adding the following to sshd_config:

PermitRootLogin forced-commands-only

This setting will not only restrict the commands which root may execute via SSH, but it will also disable the use of passwords, forcing use of public key authentication for the root account.

A slightly less restrictive alternative will allow any command for root, but makes brute force attacks infeasible by enforcing public key authentication. For this option, set:

PermitRootLogin without-password

他の SSH クライアントとサーバー

OpenSSH の他にも、多数の SSH クライアントサーバーが存在します。

Dropbear

Dropbear は SSH-2 クライアント・サーバーです。dropbear公式リポジトリから利用可能です。

コマンドラインの ssh クライアントは dbclient という名前が付けられています。

Mosh: Mobile Shell

Mosh の ウェブサイト より:

ローミングが可能で、断続的な接続もサポートしているリモート端末アプリケーションです。ユーザーのキーストロークのローカルエコーと行編集を提供します。Mosh は SSH の代替です。SSH よりも強固でレスポンスが早く、特に Wi-Fi や携帯端末からの接続、長距離通信など通信速度が遅い場合に役に立ちます。

公式リポジトリから moshインストールするか AUR にある最新版 mosh-gitAUR を使って下さい。

Mosh にはドキュメントに記載されていないコマンドラインオプション --predict=experimental が存在し、よりアグレッシブにローカルのキーストロークのエコーを生成します。キーボード入力が遅延なく確認できるのに興味があるのであればこの prediction モードを使ってみて下さい。

Tips and tricks

暗号化 SOCKS トンネル

This is highly useful for laptop users connected to various unsafe wireless connections. The only thing you need is an SSH server running at a somewhat secure location, like your home or at work. It might be useful to use a dynamic DNS service like DynDNS so you do not have to remember your IP-address.

手順 1: 接続の開始

You only have to execute this single command to start the connection:

$ ssh -TND 4711 user@host

where user is your username at the SSH server running at the host. It will ask for your password, and then you are connected! The N flag disables the interactive prompt, and the D flag specifies the local port on which to listen on (you can choose any port number if you want). The T flag disables pseudo-tty allocation.

It is nice to add the verbose (-v) flag, because then you can verify that it is actually connected from that output.

手順 2: ブラウザ (やその他のプログラム) の設定

The above step is completely useless if you do not configure your web browser (or other programs) to use this newly created socks tunnel. Since the current version of SSH supports both SOCKS4 and SOCKS5, you can use either of them.

  • For Firefox: Edit → Preferences → Advanced → Network → Connection → Setting:
Check the Manual proxy configuration radio button, and enter localhost in the SOCKS host text field, and then enter your port number in the next text field (4711 in the example above).

Firefox does not automatically make DNS requests through the socks tunnel. This potential privacy concern can be mitigated by the following steps:

  1. Type about:config into the Firefox location bar.
  2. Search for network.proxy.socks_remote_dns
  3. Set the value to true.
  4. Restart the browser.
  • For Chromium: You can set the SOCKS settings as environment variables or as command line options. I recommend to add one of the following functions to your .bashrc:
function secure_chromium {
    port=4711
    export SOCKS_SERVER=localhost:$port
    export SOCKS_VERSION=5
    chromium &
    exit
}

OR

function secure_chromium {
    port=4711
    chromium --proxy-server="socks://localhost:$port" &
    exit
}

Now open a terminal and just do:

$ secure_chromium

Enjoy your secure tunnel!

X11 フォワーディング

X11 フォワーディングはリモートシステムで X11 プログラムを動作させて、グラフィカルインターフェイスをローカルのクライアントマシンで表示させるメカニズムです。X11 フォワーディングではリモートホストに X11 システムを完全にインストールさせる必要はなく、xauth をインストールするだけで十分です。xauth は、、X11 セッションの認証を行うために必要なサーバーとクライアントによって使用される Xauthority の設定を管理するユーティリティです (ソース)。

警告: X11 forwarding has important security implications which should be at least acknowledged by reading relevant sections of ssh, sshd_config and ssh_config manual pages. See also a short writeup

セットアップ

リモート側:

  • 公式リポジトリから xorg-xauthxorg-xhostインストール
  • /etc/ssh/sshd_config 内:
    • AllowTcpForwardingX11UseLocalhost オプションを yes に設定し、X11DisplayOffset10 に設定 (何も変更を加えてなければこの値がデフォルトになっています、man sshd_config を参照)
    • X11Forwardingyes に設定
  • sshd デーモン再起動
  • リモートシステムでも X サーバーを動作させる必要があります。

クライアント側では、接続するたびにコマンドラインで -X スイッチを指定して ForwardX11 オプションを有効にするか、openSSH クライアントの設定ファイルForwardX11yes に設定してください。

ヒント: You can enable the ForwardX11Trusted option (-Y switch on the command line) if GUI is drawing badly or you receive errors; this will prevent X11 forwardings from being subjected to the X11 SECURITY extension controls. Be sure you have read the warning at the beginning of this section if you do so.

使用方法

通常通りリモートマシンにログインします、クライアント側の設定ファイルで ForwardX11 を有効にしていない場合は -X スイッチを指定します:

$ ssh -X user@host

グラフィカルなアプリケーションを実行しようとするとエラーが表示される場合、代わりに ForwardX11Trusted を試してみて下さい:

$ ssh -Y user@host

リモートサーバーで X プログラムが起動できるようになったら、出力がローカルセッションに転送されます:

$ xclock

"Cannot open display" エラーが表示される場合、root 以外のユーザーで以下のコマンドを実行してみてください:

$ xhost +

The above command will allow anybody to forward X11 applications. To restrict forwarding to a particular host type:

$ xhost +hostname

where hostname is the name of the particular host you want to forward to. See man xhost for more details.

Be careful with some applications as they check for a running instance on the local machine. Firefox is an example: either close the running Firefox instance or use the following start parameter to start a remote instance on the local machine:

$ firefox -no-remote

If you get "X11 forwarding request failed on channel 0" when you connect (and the server /var/log/errors.log shows "Failed to allocate internet-domain X11 display socket"), make sure package xorg-xauth is installed. If its installation is not working, try to either:

  • enable the AddressFamily any option in sshd_config on the server, or
  • set the AddressFamily option in sshd_config on the server to inet.

Setting it to inet may fix problems with Ubuntu clients on IPv4.

For running X applications as other user on the SSH server you need to xauth add the authentication line taken from xauth list of the SSH logged in user.

他のポートのフォワーディング

In addition to SSH's built-in support for X11, it can also be used to securely tunnel any TCP connection, by use of local forwarding or remote forwarding.

Local forwarding opens a port on the local machine, connections to which will be forwarded to the remote host and from there on to a given destination. Very often, the forwarding destination will be the same as the remote host, thus providing a secure shell and, e.g. a secure VNC connection, to the same machine. Local forwarding is accomplished by means of the -L switch and it's accompanying forwarding specification in the form of <tunnel port>:<destination address>:<destination port>.

Thus:

$ ssh -L 1000:mail.google.com:25 192.168.0.100

will use SSH to login to and open a shell on 192.168.0.100, and will also create a tunnel from the local machine's TCP port 1000 to mail.google.com on port 25. Once established, connections to localhost:1000 will connect to the Gmail SMTP port. To Google, it will appear that any such connection (though not necessarily the data conveyed over the connection) originated from 192.168.0.100, and such data will be secure as between the local machine and 192.168.0.100, but not between 192.168.0.100, unless other measures are taken.

Similarly:

$ ssh -L 2000:192.168.0.100:6001 192.168.0.100

will allow connections to localhost:2000 which will be transparently sent to the remote host on port 6001. The preceding example is useful for VNC connections using the vncserver utility--part of the tightvnc package--which, though very useful, is explicit about its lack of security.

Remote forwarding allows the remote host to connect to an arbitrary host via the SSH tunnel and the local machine, providing a functional reversal of local forwarding, and is useful for situations where, e.g., the remote host has limited connectivity due to firewalling. It is enabled with the -R switch and a forwarding specification in the form of <tunnel port>:<destination address>:<destination port>.

Thus:

$ ssh -R 3000:irc.freenode.net:6667 192.168.0.200

will bring up a shell on 192.168.0.200, and connections from 192.168.0.200 to itself on port 3000 (remotely speaking, localhost:3000) will be sent over the tunnel to the local machine and then on to irc.freenode.net on port 6667, thus, in this example, allowing the use of IRC programs on the remote host to be used, even if port 6667 would normally be blocked to it.

Both local and remote forwarding can be used to provide a secure "gateway," allowing other computers to take advantage of an SSH tunnel, without actually running SSH or the SSH daemon by providing a bind-address for the start of the tunnel as part of the forwarding specification, e.g. <tunnel address>:<tunnel port>:<destination address>:<destination port>. The <tunnel address> can be any address on the machine at the start of the tunnel, localhost, * (or blank), which, respectively, allow connections via the given address, via the loopback interface, or via any interface. By default, forwarding is limited to connections from the machine at the "beginning" of the tunnel, i.e. the <tunnel address> is set to localhost. Local forwarding requires no additional configuration, however remote forwarding is limited by the remote server's SSH daemon configuration. See the GatewayPorts option in sshd_config(5) for more information.

--Aosho235 (トーク) 2015年12月27日 (日) 12:27 (JST)=== マルチプレクス ===

SSH デーモンは通常はポート 22 番をリッスンします。しかし、公共のインターネット・ホットスポットでは HTTP/HTTPS のポート(80 と 443)以外のトラフィックをブロックしていることが一般的です。そのため SSH 接続がブロックされてしまいます。すぐできる解決策として、許可されているポートで sshd を起動するという方法があります:

/etc/ssh/sshd_config
Port 22
Port 443

しかしポート 443 番は HTTPS を提供する Web サーバにすでに使われていることが多いです。その場合は sslh のようなマルチプレクサを使います。これは指定ポートをリッスンし、そこに来るパケットを複数のサービスに賢く振り分けることができます。

SSH の高速化

同一のホストのセッションは全て単一の接続を使うようにすることで、後のログインを劇的に高速化することができます。/etc/ssh/ssh_config$HOME/.ssh/config の適当なホストの下に以下の行を追加してください:

Host examplehost.com
  ControlMaster auto
  ControlPersist yes
  ControlPath ~/.ssh/socket-%r@%h:%p

上記のオプションの詳しい説明は ssh_config(5) マニュアルページを見て下さい。

速度を向上させる別のオプションとして圧縮を有効化する -C フラグがあります。/etc/ssh/ssh_config の適切なホストの下に次の行を追加することで永続的に設定することができます:

Compression yes
警告: man ssh states that "Compression is desirable on modem lines and other slow connections, but will only slow down things on fast networks". This tip might be counterproductive depending on your network configuration.

Login time can be shortened by using the -4 flag, which bypasses IPv6 lookup. This can be made permanent by adding this line under the proper host in /etc/ssh/ssh_config:

AddressFamily inet

Changing the ciphers used by SSH to less cpu-demanding ones can improve speed. In this respect, the best choices are arcfour and blowfish-cbc.

警告: Please do not do this unless you know what you are doing; arcfour has a number of known weaknesses.

To use alternative ciphers, run SSH with the -c flag:

$ ssh -c arcfour,blowfish-cbc user@server-address

To use them permanently, add this line under the proper host in /etc/ssh/ssh_config:

Ciphers arcfour,blowfish-cbc

SSHFS でリモートファイルシステムをマウントする

sshfs を使って (SSH でアクセスした) リモートのファイルシステムをローカルフォルダにマウントする方法は Sshfs の記事を参照してください。マウントしたファイルは様々なツールであらゆる操作することができます (コピー、名前の変更、vim で編集など)。基本的に shfs よりも sshfs を使用することを推奨します。sshfs は shfs の新しいバージョンであり、元の shfs は2004年から更新されていません。

Keep alive

一定時間操作がないと ssh セッションは自動的にログアウトします。接続を維持するには以下をクライアントの ~/.ssh/config/etc/ssh/ssh_config に追加してください:

ServerAliveInterval 120

これで120秒ごとに "keep alive" シグナルがサーバーに送信されます。

反対に、外部からの接続を維持するには、次をサーバーの /etc/ssh/sshd_config に設定します (数字は0より大きく):

ClientAliveInterval 120

ssh の設定に接続データを保存する

Whenever you want to connect to a ssh server, you usually have to type at least its address and the username. To save that typing work for servers you regularly connect to, you can use the personal ~/.ssh/config or the global /etc/ssh/ssh_config files as shown in the following example:

~/.ssh/config
Host myserver
    HostName 123.123.123.123
    Port 12345
    User bob
    IdentityFile ~/.ssh/some_key_file
Host other_server
    HostName test.something.org
    User alice
    CheckHostIP no
    Cipher blowfish

Now you can simply connect to the server by using the name you specified:

$ ssh myserver

To see a complete list of the possible options, check out ssh_config's manpage on your system or the ssh_config documentation on the official website.

systemd で SSH トンネルを自動的に再起動

systemd を使ってブート時/ログイン時に SSH 接続を自動的に開始して、接続が失敗した時に再起動させることができます。SSH トンネルの管理に役立つツールとなります。

以下のサービスでは、ssh の設定に保存された接続設定を使って、ログイン時に SSH トンネルを開始します。接続が何らかの理由で閉じられた場合、10秒待機してから再起動します:

~/.config/systemd/user/tunnel.service
[Unit]
Description=SSH tunnel to myserver

[Service]
Type=simple
Restart=always
RestartSec=10
ExecStart=/usr/bin/ssh -F %h/.ssh/config -N myserver

上記のユーザーサービスを有効化して起動してください。トンネルがタイムアウトするのを防ぐ方法は #Keep alive を見て下さい。起動時にトンネルを開始したい場合、ユニットをシステムサービスとして書きなおして下さい。

Autossh - SSH セッションとトンネルの自動再起動

ネットワークの状態が悪かったりしてクライアントが切断してしまい、セッションやトンネルの接続を維持できない場合、Autossh を使って自動的にセッションとトンネルを再起動できます。Autossh は公式リポジトリからインストールできます。

使用例:

$ autossh -M 0 -o "ServerAliveInterval 45" -o "ServerAliveCountMax 2" username@example.com

sshfs を組み合わせる:

$ sshfs -o reconnect,compression=yes,transform_symlinks,ServerAliveInterval=45,ServerAliveCountMax=2,ssh_command='autossh -M 0' username@example.com: /mnt/example 

プロキシ設定で設定した SOCKS プロクシを使って接続:

$ autossh -M 0 -o "ServerAliveInterval 45" -o "ServerAliveCountMax 2" -NCD 8080 username@example.com 

With the -f option autossh can be made to run as a background process. Running it this way however means the passprase cannot be entered interactively.

The session will end once you type exit in the session, or the autossh process receives a SIGTERM, SIGINT of SIGKILL signal.

systemd を使ってブート時に自動的に Autossh を起動する

If you want to automatically start autossh, it is now easy to get systemd to manage this for you. For example, you could create a systemd unit file like this:

[Unit]
Description=AutoSSH service for port 2222
After=network.target

[Service]
Environment="AUTOSSH_GATETIME=0"
ExecStart=/usr/bin/autossh -M 0 -NL 2222:localhost:2222 -o TCPKeepAlive=yes foo@bar.com

[Install]
WantedBy=multi-user.target

Here AUTOSSH_GATETIME=0 is an environment variable specifying how long ssh must be up before autossh considers it a successful connection, setting it to 0 autossh also ignores the first run failure of ssh. This may be useful when running autossh at boot. Other environment variables are available on the manpage. Of course, you can make this unit more complex if necessary (see the systemd documentation for details), and obviously you can use your own options for autossh, but note that the -f implying AUTOSSH_GATETIME=0 does not work with systemd.

Then place this in, for example, /etc/systemd/system/autossh.service. Afterwards, you can then enable your autossh tunnels with, e.g.:

$ systemctl start autossh

(or whatever you called the service file)

If this works OK for you, you can make this permanent by running

$ systemctl enable autossh

That way autossh will start automatically at boot.

It is also easy to maintain several autossh processes, to keep several tunnels alive. Just create multiple .service files with different names.

ソケットアクティベーションで SSH ポート番号を変更する (sshd.socket)

次の内容で /etc/systemd/system/sshd.socket.d/port.conf ファイルを作成:

[Socket]
# Disable default port
ListenStream=
# Set new port
ListenStream=12345

リロードすれば systemd は自動的に新しいポートを開きます:

systemctl daemon-reload

トラブルシューティング

チェックリスト

以下は最初に行うべきトラブルシューティングのチェックリストです。何かする前に以下の問題をチェックすることを推奨します。

SSH の設定を確認

1. クライアントとサーバーの ~/.ssh フォルダにユーザーがアクセスできるようにする:

$ chmod 700 /home/USER/.ssh
$ chmod 600 /home/USER/.ssh/*

2. ライアントとサーバーの ~/.ssh フォルダにある全てのファイルの所有者がユーザーになっていることを確認:

$ chown -R USER: /home/USER/.ssh

3. クライアントの公開鍵を確認。サーバーの authorized_keys やユーザーの ~/.ssh/ ファイルにある id_rsa.pub ファイルなど。

4. /etc/ssh/sshd_configAllowUsers or AllowGroups オプションで SSH のアクセスが制限されていないか確認。

5. ユーザーにパスワードが設定されていることを確認。新しいユーザーを追加したあとパスワードが設定されていなかったり一度もログインされてなかったりすることがあります。

SSH を再起動 + ユーザーの再ログイン

6. sshd (サーバー) を再起動

7. クライアントとホスト、両方でユーザー (シェル) の再ログイン。

期限切れのキーを削除 (任意)

8. Delete old/invalid key rows in server's ~/.ssh/authorized_keys file.

9. Delete old/invalid private and public keys within the clients ~/.ssh folder.

推奨事項

10. Keep as few keys as possible in user's ~/.ssh/authorized_keys file on the server.

11. Secure server's /home/USER/.ssh/authorized_keys file against manipulation:

$ chmod 400 /home/USER/.ssh/authorized_keys

電源オフ/再起動した後も SSH 接続が残ってしまう

systemd が sshd の前に network を停止してしまうと電源を切った後も SSH 接続が繋がったままになります。この問題を修正するには、After ステートメントを修正してください:

/usr/lib/systemd/system/systemd-user-sessions.service
#After=remote-fs.target
After=network.target

接続が拒否されるまたはタイムアウトする

ルーターがポートフォワーディングをしていないか?

SKIP THIS STEP IF YOU ARE NOT BEHIND A NAT MODEM/ROUTER (eg, a VPS or otherwise publicly addressed host). Most home and small businesses will have a NAT modem/router.

The first thing is to make sure that your router knows to forward any incoming ssh connection to your machine. Your external IP is given to you by your ISP, and it is associated with any requests coming out of your router. So your router needs to know that any incoming ssh connection to your external IP needs to be forwarded to your machine running sshd.

Find your internal network address.

ip a

Find your interface device and look for the inet field. Then access your router's configuration web interface, using your router's IP (find this on the web). Tell your router to forward it to your inet IP. Go to [1] for more instructions on how to do so for your particular router.

SSH が動作しているか?

$ ss -tnlp

上記のコマンドで SSH ポートが開いていると表示されない場合、SSH は動作していません。/var/log/messages にエラーがないか確認してください。

接続をブロックするようなファイアウォールのルールが存在しないか?

iptables によってポート 22 の接続がブロックされている可能性があります。次のコマンドで確認してください:

# iptables -nvL

INPUT チェインのパケットを拒否するようなルールがないか見て下さい。そして、必要であれば、次のようなコマンドでポートのブロックを解除します:

# iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT

ファイアウォールの設定に関する詳細はファイアウォールを見て下さい。

Is the traffic even getting to your computer?

Start a traffic dump on the computer you're having problems with:

# tcpdump -lnn -i any port ssh and tcp-syn

This should show some basic information, then wait for any matching traffic to happen before displaying it. Try your connection now. If you do not see any output when you attempt to connect, then something outside of your computer is blocking the traffic (e. g., hardware firewall, NAT router etc.).

ISP またはサードパーティによってデフォルトのポートがブロックされてないか?

ノート: このステップは次のことを確認した後で実行してください。ファイアーウォールを何も起動していないこと。DMZ へのルータを正しく設定している、またはコンピュータへポートを転送していること。それでもまだ動かない場合。ここで診断のステップと解決法が見つかるでしょう。

ときどき ISP(インターネット・サービス・プロバイダ)が SSH のデフォルトポート(22番)をブロックしている場合があります。この場合はあなたが何をしても(ポートを開ける、スタックを強化する、フラッドアタックを防御する、など)無意味になります。これを確認するためには、全てのインターフェイス(0.0.0.0)をリッスンする sshd を立ち上げ、リモートから接続してみます。

このようなエラーメッセージが出る場合:

ssh: connect to host www.inet.hr port 22: Connection refused

これはそのポートが ISP にブロックされていないが、サーバのそのポートで SSH が起動していないことを意味します (security through obscurity を参照)。

しかし、次のようなエラーメッセージが出る場合:

ssh: connect to host 111.222.333.444 port 22: Operation timed out 

これは何かがポート 22 での TCP トラフィックを拒否(reject)していることを意味します。そのポートはあなたのサーバ上のファイアーウォールか第三者(ISP など)のどちらかによってステルスされています。自分のサーバでファイアーウォールが起動していないことが確かなら、またルータやスイッチの中でグレムリンが育っていないことが確かなら、ISP がトラフィックをブロックしています。

ダブルチェックのために、サーバ上で Wireshark を起動を起動してポート 22 でのトラフィックをリッスンしてみましょう。Wireshark はレイヤ 2 のパケット・スニファリング・ユーティリティであり、TCP/UDP はレイヤ 3 以上なので(IP Network stackを参照)、もしリモートから接続するときに何も受け取っていなければ、十中八九、第三者がブロックしています。

問題診断

tcpdump または wireshark-cli パッケージの Wireshark をインストールしてください。

tcpdump の場合:

# tcpdump -ni interface "port 22"

Wireshark の場合:

$ tshark -f "tcp port 22" -i interface

interface は WAN 接続に使っているネットワークインターフェイスに置き換えてください (確認したいときは ip a を実行)。リモートで接続を試行してもパケットが全く受け取れない場合、ISP によってポート 22 のトラフィックがブロックされている可能性があります。

解決方法

解決方法は、単に ISP がブロックしていない他のポートを使うことです。/etc/ssh/sshd_config を編集して他のポートを使うようにしましょう。例えば次を追加します:

Port 22
Port 1234

そしてこのファイル中の他の Port 設定をコメントアウトします。「Port 22」をコメントにして「Port 1234」を追加するだけでは、sshd がポート 1234 しかリッスンしなくなるので、この問題は解決しません。この 2 行どちらも使用し、sshd が両方のポートをリッスンするようにします。

あとは systemctl restart sshd.service で sshd を起動するだけです。そして ssh クライアントでも同じポートに変更します。There are numerous solutions to that problem, but let us cover two of them here.

Read from socket failed: connection reset by peer

最近の openssh のバージョンでは、楕円曲線暗号関連のバグのせいで、上記のエラーメッセージで接続が失敗することがあります。その場合 ~/.ssh/config に次の行を追加してください:

HostKeyAlgorithms ssh-rsa-cert-v01@openssh.com,ssh-dss-cert-v01@openssh.com,ssh-rsa-cert-v00@openssh.com,ssh-dss-cert-v00@openssh.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-rsa,ssh-dss

openssh 5.9 では、上記の修正方法は働きません。代わりに、~/.ssh/config に以下の行を記述してください:

Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc 
MACs hmac-md5,hmac-sha1,hmac-ripemd160

openssh バグフォーラムの 議論 も参照。

"[your shell]: No such file or directory" / ssh_exchange_identification problem

One possible cause for this is the need of certain SSH clients to find an absolute path (one returned by whereis -b [your shell], for instance) in $SHELL, even if the shell's binary is located in one of the $PATH entries.

"Terminal unknown" や "Error opening terminal" エラーメッセージ

ssh でログイン時に "Terminal unknown" のようなエラーが表示されることがあります。nano などの ncurses アプリケーションを実行すると "Error opening terminal" というメッセージが表示されます。この問題を解決する方法は2つあります。$TERM 変数を使って簡単に修正する方法と terminfo ファイルを使って根本的に解決する方法です。

$TERM 変数を設定する解決策

リモートサーバーに接続した後に以下のコマンドを使って $TERM 変数を "xterm" に設定してください:

$ TERM=xterm

この方法はあくまで次善策であり、たまにしか接続しない ssh サーバーで使うようにしてください。良くない副作用があるからです。また、接続するたびにコマンドを実行する必要があります。もしくは ~.bashrc で設定してください。

terminfo ファイルを使う解決策

A profound solution is transferring the terminfo file of the terminal on your client computer to the ssh server. In this example we cover how to setup the terminfo file for the "rxvt-unicode-256color" terminal. Create the directory containing the terminfo files on the ssh server, while you are logged in to the server issue this command:

$ mkdir -p ~/.terminfo/r/

Now copy the terminfo file of your terminal to the new directory. Replace rxvt-unicode-256color with your client's terminal in the following command and ssh-server with the relevant user and server adress.

$ scp /usr/share/terminfo/r/rxvt-unicode-256color ssh-server:~/.terminfo/r/

After logging in and out from the ssh server the problem should be fixed.

Connection closed by x.x.x.x [preauth]

sshd のログでこのエラーが確認できる場合、HostKey が正しく設定されているか確認してください:

HostKey /etc/ssh/ssh_host_rsa_key

OpenSSH 7.0 によって id_dsa が拒否される

OpenSSH 7.0 では ssh-dss が無効になっており、http://www.openssh.com/legacy.html には id_dsa 鍵が使われている場合にサーバーにアクセスする方法が書かれていません:

PubkeyAcceptedKeyTypes +ssh-dss

While this can be added a per host basis or with -o, to make sure "ProxyCommand ssh" still works, add it to ssh_config.

no matching key exchange method found by OpenSSH 7.0

OpenSSH 7.0 also deprecated the key algorithm diffie-hellman-group1-sha1, as we could see in http://www.openssh.com/legacy.html.

If the client and server are unable to agree on a mutual set of parameters then the connection will fail. OpenSSH (7.0 and greater) will produce an error message like this:

 Unable to negotiate with 127.0.0.1: no matching key exchange method found.
 Their offer: diffie-hellman-group1-sha1

In this case, the client and server were unable to agree on the key exchange algorithm. The server offered only a single method diffie-hellman-group1-sha1. OpenSSH supports this method, but does not enable it by default because is weak and within theoretical range of the so-called Logjam attack.

The best resolution for these failures is to upgrade the software at the other end. OpenSSH only disables algorithms that we actively recommend against using because they are known to be weak. In some cases, this might not be immediately possible so you may need to temporarily re-enable the weak algorithms to retain access.

For the case of the above error message, OpenSSH can be configured to enable the diffie-hellman-group1-sha1 key exchange algorithm (or any other that is disabled by default) using the KexAlgorithm option - either on the command-line:

 ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 user@127.0.0.1

or in the ~/.ssh/config file:

 Host somehost.example.org
 	KexAlgorithms +diffie-hellman-group1-sha1

参照