Difference between revisions of "Secure Shell (简体中文)"

From ArchWiki
Jump to: navigation, search
(设置SSH)
(管理SSHD守护进程)
(19 intermediate revisions by 6 users not shown)
Line 1: Line 1:
[[Category:Daemons and system services (简体中文)]]
+
[[Category:Secure Shell (简体中文)]]
[[Category:简体中文]]
+
[[en:Secure Shell]]
{{i18n|SSH}}
+
[[es:Secure Shell]]
 +
[[fr:ssh]]
 +
[[it:Secure Shell]]
 +
[[ko:Secure Shell]]
 +
[[pl:Secure Shell]]
 +
[[pt:Secure Shell]]
 +
[[ru:Secure Shell]]
 +
[[sr:Secure Shell]]
 +
'''Secure Shell'''('''SSH''')是一个允许两台电脑之间通过安全的连接进行数据交换的网络协议。加密技术保证了数据的保密性和完整性。如果有必要的话,SSH采用公匙加密技术来验证远程主机,以及必要时允许远程主机验证用户。
  
= 介绍 =
+
SSH 通常用于远程访问和执行命令,但是它也支持隧道,转发任意 TCP 端口以及 X11 连接;它还能够用 SFTP 或 SCP 协议来传递文件。
Secure Shell或者SSH是一个允许两台电脑之间通过安全的连接进行数据交换的网络协议。加密技术保证了数据的保密性和完整性。如果有必要的话,SSH采用公匙加密技术来验证远程主机和允许远程主机验证用户?(SSH uses public-key cryptography to authenticate the remote computer and allow the remote computer to authenticate the user, if necessary.)
+
  
= SSH =
+
一个 SSH 服务器,默认地,在 TCP 端口 22 进行监听。一个 SSH 客户端程序通常被用来建立一个接受远程连接的 '''sshd''' 守护进程。这两者都以专利的,自由软件的以及开源版本的形式和不同的复杂性和完整性,被广泛地应用在现代的操作系统中,包括 Mac OS X,GNU/Linux,Solaris 和 OpenVMS 等。
SSH通常用于远程访问和执行命令,但是它也支持tunneling,forwarding arbitrary TCP ports and X11 connections; 它还能够用SFTP或SCP协议来传递文件。
+
  
一个SSH服务器,默认地,在TCP端口22进行监听。一个SSH客户端程序通常被用来建立一个接受远程连接的sshd守护进程。这两者都以专利的,自由软件的以及开源版本的形式和不同的复杂性和完整性,被广泛地应用在现代的操作系统中,包括Mac OS X,Linux,Solaris和OpenVMS等。
+
== OpenSSH ==
 
+
= OpenSSH =
+
  
 
OpenSSH (OpenBSD Secure Shell) 是一套用ssh协议,通过电脑网络,提供加密通讯会话的电脑程序。它相对于SSH Communications Security公司拥有专利的Secure Shell软件套装,被创建为开源。OpenSSH是由Theo de Raadt领导的OpenBSD项目的一部分。  
 
OpenSSH (OpenBSD Secure Shell) 是一套用ssh协议,通过电脑网络,提供加密通讯会话的电脑程序。它相对于SSH Communications Security公司拥有专利的Secure Shell软件套装,被创建为开源。OpenSSH是由Theo de Raadt领导的OpenBSD项目的一部分。  
Line 17: Line 21:
 
人们常把OpenSSH与相似的OpenSSL搞混,但是,这两个项目是由不同的团队开发出来的,有不同的用途,相似的名字只是由于相似的目标。
 
人们常把OpenSSH与相似的OpenSSL搞混,但是,这两个项目是由不同的团队开发出来的,有不同的用途,相似的名字只是由于相似的目标。
  
== 安装OpenSSH ==
+
=== 安装OpenSSH ===
 
  pacman -S openssh
 
  pacman -S openssh
  
== 配置SSH ==
+
=== 配置SSH ===
===客户端===
+
====客户端====
SSH客户端的配置文件是{{Filename|/etc/ssh/ssh_config}}。
+
SSH客户端的配置文件是{{ic|/etc/ssh/ssh_config}}。
  
 
以下是一个范例::
 
以下是一个范例::
  
{{File|name=/etc/ssh/ssh_config|content=
+
{{hc|/etc/ssh/ssh_config|
 
# $OpenBSD: ssh_config,v 1.26 2010/01/11 01:39:46 dtucker Exp $
 
# $OpenBSD: ssh_config,v 1.26 2010/01/11 01:39:46 dtucker Exp $
  
Line 81: Line 85:
 
这表示只有协议2将被用到,因为协议1 被认为不太安全。
 
这表示只有协议2将被用到,因为协议1 被认为不太安全。
  
===守护进程===
+
====守护进程====
SSH客户端的配置文件是{{Filename|/etc/ssh/ssh'''d'''_config}}。
+
SSH客户端的配置文件是{{ic|/etc/ssh/ssh'''d'''_config}}。
  
 
以下是一个范例::
 
以下是一个范例::
  
{{File|name=/etc/ssh/sshd_config|content=
+
{{hc|/etc/ssh/sshd_config|2=
 
# $OpenBSD: sshd_config,v 1.82 2010/09/06 17:10:19 naddy Exp $
 
# $OpenBSD: sshd_config,v 1.82 2010/09/06 17:10:19 naddy Exp $
  
Line 213: Line 217:
 
  PermitRootLogin no
 
  PermitRootLogin no
  
你也可以取消BANNER选项的注释,然后编辑{{Filename|/etc/issue}}加入友好的欢迎信息内容。
+
你也可以取消BANNER选项的注释,然后编辑{{ic|/etc/issue}}加入友好的欢迎信息内容。
  
 
{{Tip| 你可能想要把默认的端口从22改成其它更高的端口(参考 [http://en.wikipedia.org/wiki/Security_through_obscurity security through obscurity]).}}  
 
{{Tip| 你可能想要把默认的端口从22改成其它更高的端口(参考 [http://en.wikipedia.org/wiki/Security_through_obscurity security through obscurity]).}}  
Line 219: Line 223:
 
尽管ssh的运行端口可以被像nmap这样的端口扫描器侦测到,但改变它可以减少由于自动验证的尝试造成登录次数。
 
尽管ssh的运行端口可以被像nmap这样的端口扫描器侦测到,但改变它可以减少由于自动验证的尝试造成登录次数。
  
{{Tip| 完全取消密码登录方式也可以增强安全性,因为每个访问服务器的用户都需要创建ssh密钥。(参考 [http://wiki.archlinux.org/index.php/Using_SSH_Keys Using SSH Keys]).}}
+
{{Tip| 完全取消密码登录方式也可以增强安全性,因为每个访问服务器的用户都需要创建ssh密钥。(参考 [https://wiki.archlinux.org/index.php/Using_SSH_Keys Using SSH Keys]).}}
  
{{File|name=/etc/ssh/sshd_config|content=
+
{{hc|/etc/ssh/sshd_config|
 
PasswordAuthentication no
 
PasswordAuthentication no
 
ChallengeResponseAuthentication no}}
 
ChallengeResponseAuthentication no}}
  
===允许其它主机进入===
+
=== 管理sshd守护进程 ===
{{Box Note | 你必须要更改你的文件,因为默认的情况下这个文件是空的。}}
+
你可以使用下面的命令开机启动sshd:
 +
# systemctl enable sshd.service
  
为了让其他人通过ssh登录到你的机器上,你必须要设置“/etc/hosts.allow”这个文件,加入类似下面的文字:
+
{{Warning|Systemd is an asynchronous starting process. If you bind the SSH daemon to a specific IP address {{ic|ListenAddress 192.168.1.100}} it may fail to load during boot since the default sshd.service unit file has no dependency on network interfaces being enabled. When binding to an IP address, you will need to add {{ic|After=network.target}} to a custom sshd.service unit file. See [[Systemd#Replacing provided unit files]].}}
  
<pre>
+
或者你可以启用SSH Daemon socket,这样当第一次传入连接时启动守护进程:
# 让每个人都能连接到你
+
# systemctl enable sshd.socket
sshd: ALL
+
如果你使用非默认端口22,你必须在文件(/lib/systemd/system/sshd.socket)中设置"ListenStream"为相应的端口。
  
# 或者限制只能特定的ip能够
+
===连接到服务器===
sshd: 192.168.0.1
+
 
+
# 或者限制ip段
+
sshd: 10.0.0.0/255.255.255.0
+
 
+
# 或者限制为IP匹配
+
sshd: 192.168.1.
+
</pre>
+
 
+
现在检查你的“/etc/hosts.deny”文件,找到并确保有类似下面一行的内容:
+
ALL: ALL
+
 
+
你能SSH出去别人也应该能够SSH进来:)。
+
 
+
开始使用新的配置之前,要先重启守护进程(以root身份):
+
# rc.d restart sshd
+
 
+
== 管理SSHD守护进程 ==
+
只要把sshd加到/etc/[[rc.conf]]中的"DAEMONS" section部分:
+
DAEMONS=(... ... '''sshd''' ... ...)
+
 
+
开始/重启/停止这个daemon:
+
# /etc/rc.d/sshd {start|stop|restart}
+
 
+
==连接到服务器==
+
  
 
运行下面的命令:
 
运行下面的命令:
 
  $ ssh -p port user@server-address
 
  $ ssh -p port user@server-address
  
= 小细节和小戏法 =
+
== 小细节和小戏法 ==
  
== 加密Socks通道 ==
+
=== 加密Socks通道 ===
 
对于连接到各种不安全的无线网络上的笔记本电脑用户来说,这个是特别有用的!唯一所需要的就是一个一定程度上处于安全的地点的SSH服务器,比如在家里或办公室。用动态的DNS服务[http://www.dyndns.org/ DynDNS]也可能是很有用的,这样你就不必记住你的IP了。
 
对于连接到各种不安全的无线网络上的笔记本电脑用户来说,这个是特别有用的!唯一所需要的就是一个一定程度上处于安全的地点的SSH服务器,比如在家里或办公室。用动态的DNS服务[http://www.dyndns.org/ DynDNS]也可能是很有用的,这样你就不必记住你的IP了。
  
=== 第一步:开始连接 ===
+
==== 第一步:开始连接 ====
 
你只要在你喜欢的终端中执行这一个命令就能开始你的连接:
 
你只要在你喜欢的终端中执行这一个命令就能开始你的连接:
 
  $ ssh -ND 4711 user@host
 
  $ ssh -ND 4711 user@host
Line 278: Line 258:
 
加入冗长的“-v”标志更好,因为这样你可以验证是真的是从那个端口连接的。现在你只要执行命令“sshtunnel”就可以。 :)
 
加入冗长的“-v”标志更好,因为这样你可以验证是真的是从那个端口连接的。现在你只要执行命令“sshtunnel”就可以。 :)
  
=== 第二步:配置你的浏览器(或其它程序) ===
+
==== 第二步:配置你的浏览器(或其它程序) ====
  
 
如果你不配置你的web浏览器以便使用新创建的socks通道的话,上面的一步完全没用!
 
如果你不配置你的web浏览器以便使用新创建的socks通道的话,上面的一步完全没用!
Line 289: Line 269:
 
:享受你的安全通道吧!
 
:享受你的安全通道吧!
  
== X11 Forwarding ==
+
=== X11 Forwarding ===
 +
{{translateme (简体中文)}}
 +
为了通过SSH运行图形程序你必须使用X11 Forwarding。一个选项就是需要设置服务器和客户端的配置文件。(here "client" means your (desktop) machine your X11 Server runs on, and you will run X applications on the "server").
  
为了通过SSH运行图形程序你必须使用X11 Forwarding。一个选项就是需要设置服务器和客户端的配置文件。
+
在服务器上安装xorg-xauth:
 
+
1.在服务器上安装xorg-xauth:
+
 
  # pacman -S xorg-xauth
 
  # pacman -S xorg-xauth
  
2.在服务器端修改 /etc/ssh/sshd_config 配置文件,将“X11Forwarding”这个选项去掉注释。
+
* Enable the '''AllowTcpForwarding''' option in {{ic|ssh'''d'''_config}} on the '''server'''.
 +
* Enable the '''X11Forwarding''' option in {{ic|ssh'''d'''_config}} on the '''server'''.
 +
* Set the '''X11DisplayOffset''' option in {{ic|ssh'''d'''_config}} on the '''server''' to 10.
 +
* Enable the '''X11UseLocalhost''' option in {{ic|ssh'''d'''_config}} on the '''server'''.
 +
Also:
 +
* Enable the '''ForwardX11''' option in {{ic|ssh_config}} on the '''client'''.
  
3.在客户端修改 /etc/ssh/ssh_config:
+
Enable the '''ForwardX11Trusted''' can help when gui drawing badly.
ForwardAgent yes
+
ForwardX11 yes
+
ForwardX11Trusted yes
+
4.登录
+
ssh -X user@hostname
+
  
== 用SSHFS挂载远程文件系统 ==
+
To use the forwarding, log on to your server through ssh:
 +
$ ssh -X -p port user@server-address
 +
If you receive errors trying to run graphical applications try trusted forwarding instead:
 +
$ ssh -Y -p port user@server-address
 +
You can now start any X program on the remote server, the output will be forwarded to your local session:
 +
$ xclock
 +
 
 +
If you get "Cannot open display" errors try the following command as the non root user:
 +
$ 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. Type "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 running Firefox or use the following start parameter to start a remote instance on the local machine
 +
$ firefox -no-remote
 +
 
 +
=== Forwarding Other Ports ===
 +
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 {{Ic|-L}} switch and it's accompanying forwarding specification in the form of {{Ic|<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 {{Ic|-R}} switch and a forwarding specification in the form of {{Ic|<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. {{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.
 +
 
 +
=== Speed up SSH ===
 +
You can make all sessions to the same host use a single connection, which will greatly speed up subsequent logins, by adding these lines under the proper host in {{ic|/etc/ssh/ssh_config}}:
 +
ControlMaster auto
 +
ControlPath ~/.ssh/socket-%r@%h:%p
 +
 
 +
Changing the ciphers used by SSH to less cpu-demanding ones can improve speed. In this aspect, 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 them, run SSH with the {{Ic|"c"}} flag, like this:
 +
$ ssh -c arcfour,blowfish-cbc user@server-address
 +
To use them permanently, add this line under the proper host in {{ic|/etc/ssh/ssh_config}}:
 +
Ciphers arcfour,blowfish-cbc
 +
Another option to improve speed is to enable compression with the {{Ic|"C"}} flag. A permanent solution is to add this line under the proper host in {{ic|/etc/ssh/ssh_config}}:
 +
Compression yes
 +
Login time can be shorten by using the {{Ic|"4"}} flag, which bypasses IPv6 lookup. This can be made permanent by adding this line under the proper host in {{ic|/etc/ssh/ssh_config}}:
 +
AddressFamily inet
 +
Another way of making these changes permanent is to create an alias in {{ic|~/.bashrc}}:
 +
alias ssh='ssh -C4c arcfour,blowfish-cbc'
 +
 
 +
==== Troubleshooting ====
 +
Make sure your DISPLAY string is resolveable on the remote end:
 +
 
 +
$ ssh -X user@server-address
 +
server $ echo $DISPLAY
 +
localhost:10.0
 +
server $ telnet localhost 6010
 +
localhost/6010: lookup failure: Temporary failure in name resolution 
 +
 
 +
can be fixed by adding localhost to {{ic|/etc/hosts}}.
 +
 
 +
=== 用SSHFS挂载远程文件系统 ===
  
 
安装sshfs
 
安装sshfs
Line 328: Line 380:
 
如果我们需要经常在这个文件夹下,让它通过/etc/fstab挂载是一个明智的选择。这个办法可以让它在启动的时候挂载或者通过手动挂载(如果是noauto选项的话),而不需要每次都去挂载它。下面是一个简单的样本:  
 
如果我们需要经常在这个文件夹下,让它通过/etc/fstab挂载是一个明智的选择。这个办法可以让它在启动的时候挂载或者通过手动挂载(如果是noauto选项的话),而不需要每次都去挂载它。下面是一个简单的样本:  
 
  sshfs#USER@remote_server:/tmp /full/path/to/directory fuse    defaults,auto    0 0
 
  sshfs#USER@remote_server:/tmp /full/path/to/directory fuse    defaults,auto    0 0
 +
=== Keep Alive ===
 +
Your ssh session will automatically log out if it is idle. To keep the connection active (alive) add this to {{ic|~/.ssh/config}} or to {{ic|/etc/ssh/ssh_config}} on the client.
 +
 +
ServerAliveInterval 120
 +
 +
This will send a "keep alive" signal to the server every 120 seconds.
 +
 +
Conversely, to keep incoming connections alive, you can set
 +
 +
ClientAliveInterval 120
 +
 +
(or some other number greater than 0) in {{ic|/etc/ssh/sshd_config}} on the server.
 +
 +
=== Save connection data in ssh config ===
 +
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 {{ic|$HOME/.ssh/config}} or the global {{ic|/etc/ssh/ssh_config}} files as shown in the following example:
 +
 +
{{hc|$HOME/.ssh/config|
 +
Host myserver
 +
    HostName 123.123.123.123
 +
    Port 12345
 +
    User bob
 +
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 [http://www.openbsd.org/cgi-bin/man.cgi?query=ssh_config ssh_config documentation] on the official website.
 +
 +
=== Change bash prompt when logged over ssh ===
 +
It can sometimes be useful to be able to make the difference between your local and your remote prompt, in particular when they are both configured in the same way.  To do that, just insert this in your bashrc:
 +
 +
{{hc|$HOME/.bashrc|2=
 +
if [ -n "$SSH_CLIENT" ]; then
 +
        PS1='\[\e[0;33m\]\u@\h:\wSSH$\[\e[m\] '
 +
else
 +
        PS1='\[\e[0;32m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[1;32m\]\$\[\    e[m\] '
 +
fi
 +
}}
 +
 +
See [[Color Bash Prompt]] for more information about the PS1 variable customization.
 +
 +
=== Automatically logout all ssh users when the sshd server is shutdown ===
 +
To automatically log out all remote ssh users when the sshd server system shuts down, for reboot or halt, add this line to /etc/rc.local.shutdown on the sshd server:
 +
 +
who | cut -d " " -f1 | uniq | xargs pkill -KILL -u
 +
 +
This prevents ssh client terminals from hanging during a lengthy timeout, which eventually ends with:
 +
 +
Write failed: Broken pipe
 +
 +
== Troubleshooting ==
 +
=== Connection Refused or Timeout Problem ===
 +
==== Is SSH running and listening? ====
 +
# netstat -tnlp | grep ssh
 +
 +
If the above command doesn't display anything, then SSH is NOT running. Check {{ic|/var/log/messages}} for errors etc.
 +
 +
==== Are there firewall rules blocking the connection? ====
 +
Flush your iptables rules to make sure they are not interfering:
 +
 +
# rc.d stop iptables
 +
 +
or:
 +
 +
# iptables -P INPUT ACCEPT
 +
# iptables -P OUTPUT ACCEPT
 +
# iptables -F INPUT
 +
# iptables -F OUTPUT
 +
 +
==== 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.).
 +
 +
==== Read from socket failed: Connection reset by peer ====
 +
Recent versions of openssh sometimes fail with the above error message, due to a bug involving elliptic curve cryptography.  In that case, edit the file
 +
 +
~/.ssh/config
 +
 +
or create it, if it doesn't already exist.  Add the line
 +
 +
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
 +
 +
With openssh 5.9, the above fix doesn't work.  Instead, put the following lines in ~/.ssh/config
 +
 +
Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc
 +
MACs hmac-md5,hmac-sha1,hmac-ripemd160
 +
 +
See also the [http://www.gossamer-threads.com/lists/openssh/dev/51339 discussion] on the openssh bug forum.
 +
 +
=== "[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 {{Ic|whereis -b [your shell]}}, for instance) in {{Ic|$SHELL}}, even if the shell's binary is located in one of the {{Ic|$PATH}} entries. Another reason can be that the user is no member of the ''network'' group.
 +
 +
== See Also ==
 +
*[[SSH Keys]]
 +
*[[Pam abl]]
 +
*[[fail2ban]]
 +
*[[sshguard]]
 +
*[[Sshfs]]
  
= 链接和参考=
+
== 链接和参考==
 
*[http://www.soloport.com/iptables.html A Cure for the Common SSH Login Attack]
 
*[http://www.soloport.com/iptables.html A Cure for the Common SSH Login Attack]
 
*[[使用SSH密钥]]
 
*[[使用SSH密钥]]
 
*[http://www.la-samhna.de/library/brutessh.html Defending against brute force ssh attacks]
 
*[http://www.la-samhna.de/library/brutessh.html Defending against brute force ssh attacks]

Revision as of 14:40, 17 December 2012

Secure Shell(SSH)是一个允许两台电脑之间通过安全的连接进行数据交换的网络协议。加密技术保证了数据的保密性和完整性。如果有必要的话,SSH采用公匙加密技术来验证远程主机,以及必要时允许远程主机验证用户。

SSH 通常用于远程访问和执行命令,但是它也支持隧道,转发任意 TCP 端口以及 X11 连接;它还能够用 SFTP 或 SCP 协议来传递文件。

一个 SSH 服务器,默认地,在 TCP 端口 22 进行监听。一个 SSH 客户端程序通常被用来建立一个接受远程连接的 sshd 守护进程。这两者都以专利的,自由软件的以及开源版本的形式和不同的复杂性和完整性,被广泛地应用在现代的操作系统中,包括 Mac OS X,GNU/Linux,Solaris 和 OpenVMS 等。

OpenSSH

OpenSSH (OpenBSD Secure Shell) 是一套用ssh协议,通过电脑网络,提供加密通讯会话的电脑程序。它相对于SSH Communications Security公司拥有专利的Secure Shell软件套装,被创建为开源。OpenSSH是由Theo de Raadt领导的OpenBSD项目的一部分。

人们常把OpenSSH与相似的OpenSSL搞混,但是,这两个项目是由不同的团队开发出来的,有不同的用途,相似的名字只是由于相似的目标。

安装OpenSSH

pacman -S openssh

配置SSH

客户端

SSH客户端的配置文件是/etc/ssh/ssh_config

以下是一个范例::

/etc/ssh/ssh_config
#	$OpenBSD: ssh_config,v 1.26 2010/01/11 01:39:46 dtucker Exp $

# This is the ssh client system-wide configuration file.  See
# ssh_config(5) for more information.  This file provides defaults for
# users, and the values can be changed in per-user configuration files
# or on the command line.

# Configuration data is parsed as follows:
#  1. command line options
#  2. user-specific file
#  3. system-wide file
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.

# Site-wide defaults for some commonly used options.  For a comprehensive
# list of available options, their meanings and defaults, please see the
# ssh_config(5) man page.

# Host *
#   ForwardAgent no
#   ForwardX11 no
#   RhostsRSAAuthentication no
#   RSAAuthentication yes
#   PasswordAuthentication yes
#   HostbasedAuthentication no
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   BatchMode no
#   CheckHostIP yes
#   AddressFamily any
#   ConnectTimeout 0
#   StrictHostKeyChecking ask
#   IdentityFile ~/.ssh/identity
#   IdentityFile ~/.ssh/id_rsa
#   IdentityFile ~/.ssh/id_dsa
#   Port 22
#   Protocol 2,1
#   Cipher 3des
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc
#   MACs hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160
#   EscapeChar ~
#   Tunnel no
#   TunnelDevice any:any
#   PermitLocalCommand no
#   VisualHostKey no
#   ProxyCommand ssh -q -W %h:%p gateway.example.com

推荐将“Protocol”行改为:

Protocol 2

这表示只有协议2将被用到,因为协议1 被认为不太安全。

守护进程

SSH客户端的配置文件是/etc/ssh/sshd_config

以下是一个范例::

/etc/ssh/sshd_config
#	$OpenBSD: sshd_config,v 1.82 2010/09/06 17:10:19 naddy Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options change a
# default value.

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

# The default requires explicit activation of protocol 1
#Protocol 2

# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 1024

# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKeysFile	.ssh/authorized_keys

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

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

# Change to no to disable s/key passwords
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

# Set this to 'yes' to enable PAM authentication, account processing, 
# and session processing. If this is enabled, PAM authentication will 
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10
#PermitTunnel no
#ChrootDirectory none

# no default banner path
#Banner none

# override default of no subsystems
Subsystem	sftp	/usr/lib/ssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#	X11Forwarding no
#	AllowTcpForwarding no
#	ForceCommand cvs server

只允许某些用户访问的话,加入这一行:

AllowUsers    user1 user2

要禁止通过SSH进行root用户登录,加入以下行:

PermitRootLogin no

你也可以取消BANNER选项的注释,然后编辑/etc/issue加入友好的欢迎信息内容。

Tip: 你可能想要把默认的端口从22改成其它更高的端口(参考 security through obscurity).

尽管ssh的运行端口可以被像nmap这样的端口扫描器侦测到,但改变它可以减少由于自动验证的尝试造成登录次数。

Tip: 完全取消密码登录方式也可以增强安全性,因为每个访问服务器的用户都需要创建ssh密钥。(参考 Using SSH Keys).
/etc/ssh/sshd_config
PasswordAuthentication no
ChallengeResponseAuthentication no

管理sshd守护进程

你可以使用下面的命令开机启动sshd:

# systemctl enable sshd.service
Warning: Systemd is an asynchronous starting process. If you bind the SSH daemon to a specific IP address ListenAddress 192.168.1.100 it may fail to load during boot since the default sshd.service unit file has no dependency on network interfaces being enabled. When binding to an IP address, you will need to add After=network.target to a custom sshd.service unit file. See Systemd#Replacing provided unit files.

或者你可以启用SSH Daemon socket,这样当第一次传入连接时启动守护进程:

# systemctl enable sshd.socket

如果你使用非默认端口22,你必须在文件(/lib/systemd/system/sshd.socket)中设置"ListenStream"为相应的端口。

连接到服务器

运行下面的命令:

$ ssh -p port user@server-address

小细节和小戏法

加密Socks通道

对于连接到各种不安全的无线网络上的笔记本电脑用户来说,这个是特别有用的!唯一所需要的就是一个一定程度上处于安全的地点的SSH服务器,比如在家里或办公室。用动态的DNS服务DynDNS也可能是很有用的,这样你就不必记住你的IP了。

第一步:开始连接

你只要在你喜欢的终端中执行这一个命令就能开始你的连接:

$ ssh -ND 4711 user@host

这里的“user”是你在“host”这台SSH服务器上运行的用户名。它会让你输入密码,然后你就能连上了。“N”表示不采用交互提示,而“D”表示指定监听的本地端口(你可以使用任何你喜欢的数字)

一个办法可以让这个过程更简单,那就是在~/.bashrc中加入这样一行:

alias sshtunnel="ssh -ND 4711 -v user@host"

加入冗长的“-v”标志更好,因为这样你可以验证是真的是从那个端口连接的。现在你只要执行命令“sshtunnel”就可以。 :)

第二步:配置你的浏览器(或其它程序)

如果你不配置你的web浏览器以便使用新创建的socks通道的话,上面的一步完全没用!

  • 对于Firefox: Edit -> Preferences -> Advanced -> Network -> Connection -> Setting:
检查"Manual proxy configuration" radio button?, 并且在"SOCKS host" 文本段输入"localhost" , 然后在接下来的一个文本框中输入你的端口数(上面我们用的是4711)。
确定你选择使用SOCKS4。这个程序对不会对SOCKS5起作用.
享受你的安全通道吧!

X11 Forwarding

Tango-preferences-desktop-locale.png本页面需要更新翻译,内容可能已经与英文脱节。要贡献翻译,请访问简体中文翻译组Tango-preferences-desktop-locale.png

附注: please use the first argument of the template to provide more detailed indications.

为了通过SSH运行图形程序你必须使用X11 Forwarding。一个选项就是需要设置服务器和客户端的配置文件。(here "client" means your (desktop) machine your X11 Server runs on, and you will run X applications on the "server").

在服务器上安装xorg-xauth:

# pacman -S xorg-xauth
  • Enable the AllowTcpForwarding option in sshd_config on the server.
  • Enable the X11Forwarding option in sshd_config on the server.
  • Set the X11DisplayOffset option in sshd_config on the server to 10.
  • Enable the X11UseLocalhost option in sshd_config on the server.

Also:

  • Enable the ForwardX11 option in ssh_config on the client.

Enable the ForwardX11Trusted can help when gui drawing badly.

To use the forwarding, log on to your server through ssh:

$ ssh -X -p port user@server-address

If you receive errors trying to run graphical applications try trusted forwarding instead:

$ ssh -Y -p port user@server-address

You can now start any X program on the remote server, the output will be forwarded to your local session:

$ xclock

If you get "Cannot open display" errors try the following command as the non root user:

$ 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. Type "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 running Firefox or use the following start parameter to start a remote instance on the local machine

$ firefox -no-remote

Forwarding Other Ports

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.

Speed up SSH

You can make all sessions to the same host use a single connection, which will greatly speed up subsequent logins, by adding these lines under the proper host in /etc/ssh/ssh_config:

ControlMaster auto
ControlPath ~/.ssh/socket-%r@%h:%p

Changing the ciphers used by SSH to less cpu-demanding ones can improve speed. In this aspect, 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 them, run SSH with the "c" flag, like this:

$ 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

Another option to improve speed is to enable compression with the "C" flag. A permanent solution is to add this line under the proper host in /etc/ssh/ssh_config:

Compression yes

Login time can be shorten 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

Another way of making these changes permanent is to create an alias in ~/.bashrc:

alias ssh='ssh -C4c arcfour,blowfish-cbc'

Troubleshooting

Make sure your DISPLAY string is resolveable on the remote end:

$ ssh -X user@server-address
server $ echo $DISPLAY
localhost:10.0
server $ telnet localhost 6010
localhost/6010: lookup failure: Temporary failure in name resolution   

can be fixed by adding localhost to /etc/hosts.

用SSHFS挂载远程文件系统

安装sshfs

# pacman -S sshfs

将你想要允许挂载SSH文件夹的用户添加到fuse组里

# gpasswd -a USER fuse

加载fuse模块(比如说在/etc/rc.conf中)

And then然后,在登录后,你就可以试着挂用sshfs载远程文件夹了:

# mkdir ~/remote_folder
# sshfs USER@remote_server:/tmp ~/remote_folder

上面的命令将把远程服务器上的/tmp文件夹挂载到本地的~/remote_folder目录下。复制任何文件到这个目录将使文件通过SCP通过网络传输。 Same concerns direct file editing, creating or removing.

当我们完成在远程文件夹下的工作,我们可以这样来卸载它:

# fusermount -u ~/remote_folder

如果我们需要经常在这个文件夹下,让它通过/etc/fstab挂载是一个明智的选择。这个办法可以让它在启动的时候挂载或者通过手动挂载(如果是noauto选项的话),而不需要每次都去挂载它。下面是一个简单的样本:

sshfs#USER@remote_server:/tmp /full/path/to/directory fuse    defaults,auto    0 0

Keep Alive

Your ssh session will automatically log out if it is idle. To keep the connection active (alive) add this to ~/.ssh/config or to /etc/ssh/ssh_config on the client.

ServerAliveInterval 120

This will send a "keep alive" signal to the server every 120 seconds.

Conversely, to keep incoming connections alive, you can set

ClientAliveInterval 120

(or some other number greater than 0) in /etc/ssh/sshd_config on the server.

Save connection data in ssh config

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 $HOME/.ssh/config or the global /etc/ssh/ssh_config files as shown in the following example:

$HOME/.ssh/config
Host myserver
    HostName 123.123.123.123
    Port 12345
    User bob
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.

Change bash prompt when logged over ssh

It can sometimes be useful to be able to make the difference between your local and your remote prompt, in particular when they are both configured in the same way. To do that, just insert this in your bashrc:

$HOME/.bashrc
if [ -n "$SSH_CLIENT" ]; then
        PS1='\[\e[0;33m\]\u@\h:\wSSH$\[\e[m\] '
else
        PS1='\[\e[0;32m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[1;32m\]\$\[\    e[m\] '
fi

See Color Bash Prompt for more information about the PS1 variable customization.

Automatically logout all ssh users when the sshd server is shutdown

To automatically log out all remote ssh users when the sshd server system shuts down, for reboot or halt, add this line to /etc/rc.local.shutdown on the sshd server:

who | cut -d " " -f1 | uniq | xargs pkill -KILL -u

This prevents ssh client terminals from hanging during a lengthy timeout, which eventually ends with:

Write failed: Broken pipe

Troubleshooting

Connection Refused or Timeout Problem

Is SSH running and listening?

# netstat -tnlp | grep ssh

If the above command doesn't display anything, then SSH is NOT running. Check /var/log/messages for errors etc.

Are there firewall rules blocking the connection?

Flush your iptables rules to make sure they are not interfering:

# rc.d stop iptables

or:

# iptables -P INPUT ACCEPT
# iptables -P OUTPUT ACCEPT
# iptables -F INPUT
# iptables -F OUTPUT

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.).

Read from socket failed: Connection reset by peer

Recent versions of openssh sometimes fail with the above error message, due to a bug involving elliptic curve cryptography. In that case, edit the file

~/.ssh/config

or create it, if it doesn't already exist. Add the line

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

With openssh 5.9, the above fix doesn't work. Instead, put the following lines in ~/.ssh/config

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

See also the discussion on the openssh bug forum.

"[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. Another reason can be that the user is no member of the network group.

See Also

链接和参考