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 is typically used to log into a remote machine and execute commands, but it also supports tunneling, forwarding arbitrary TCP ports and X11 connections; it can transfer files using the associated SFTP or SCP protocols.

−

An SSH server, by default, listens on the standard TCP port 22. An ssh client program is typically used for establishing connections to an sshd daemon accepting remote connections. Both are commonly present on most modern operating systems, including Mac OS X, Linux, Solaris and OpenVMS. Proprietary, freeware and open source versions of various levels of complexity and completeness exist.

OpenSSH (OpenBSD Secure Shell) is a set of computer programs providing encrypted communication sessions over a computer network using the ssh protocol. It was created as an open source alternative to the proprietary Secure Shell software suite offered by SSH Communications Security. OpenSSH is developed as part of the OpenBSD project, which is led by Theo de Raadt.

+

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

−

OpenSSH is occasionally confused with the similarly-named OpenSSL; however, the projects have different purposes and are developed by different teams, the similar name is drawn only from similar goals.

+

=== 安装OpenSSH ===

+

pacman -S openssh

−

== 安装OpenSSH ==

+

=== 配置SSH ===

−

# pacman -Sy openssh

+

====客户端====

+

SSH客户端的配置文件是{{ic|/etc/ssh/ssh_config}}。

−

== 设置Configuring the SSH服务器 ==

+

以下是一个范例：：

−

To configure you must edit the configuration file:

−

$ su -c 'nano /etc/ssh/sshd_config'

−

You may want to change the default port from 22 to any higher port (see [http://en.wikipedia.org/wiki/Security_through_obscurity security through obscurity]).

+

{{hc|/etc/ssh/ssh_config|

−

+

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

−

Even though the port ssh is running on, could be detected by using a port-scanner like nmap, changing it will reduce the number of log entries caused by automated authentication attempts.

−

−

=== 调整设置 ===

−

配置文件是“/etc/ssh/ssh_config”，通常是像这样的：

−

−

<pre>

−

# $OpenBSD: sshd_config,v 1.75 2007/03/19 01:01:29 djm Exp $

# This is the ssh client system-wide configuration file. See

# This is the ssh client system-wide configuration file. See

Line 50:

Line 46:

# configuration file, and defaults at the end.

# configuration file, and defaults at the end.

−

# Site-wide defaults for various options

+

# Site-wide defaults for some commonly used options. For a comprehensive

+

# list of available options, their meanings and defaults, please see the

{{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&#61;network.target}} to a custom sshd.service unit file. See [[Systemd#Replacing provided unit files]].}}

* 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'''.

+

+

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

−

= Tips and Tricks =

+

Similarly:

−

== Encrypted Socks Tunnel ==

+

$ ssh -L 2000:192.168.0.100:6001 192.168.0.100

−

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 [http://www.dyndns.org/ DynDNS] so you don't have to remember your IP-address.

−

=== 第一步：开始连接 ===

+

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.

−

You only have to execute this single command in your favorite terminal to start the connection:

−

$ ssh -ND 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're connected! The "N" flag disables the interactive prompt, and the "D" flag specifies the local port on wich to listen on (you can choose any port number if you want).

−

One way to make this easier is to put an alias line in your ~/.bashrc file as following:

+

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

−

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

−

It's nice to add the verbose "-v" flag, because then you can verify that it's actually connected from that output. Now you just have to execute the "sshtunnel" command :)

−

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

+

Thus:

−

The above step is completely useless if you don't configure your web browser (or other programs) to use this newly created socks tunnel.

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.

−

: 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 (I used 4711 above).

−

: Make sure you select SOCKS4 as the protocol to use. This procedure will not work for SOCKS5.

+

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.

−

Enjoy your secure tunnel!

+

=== 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

−

== X11 Forwarding ==

+

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'

−

To run graphical programs through a SSH connection you can enable X11 forwarding. An option needs to be set in the configuration files on the server and client.

+

==== Troubleshooting ====

+

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

−

Install xorg-xauth on the server:

+

$ ssh -X user@server-address

−

# pacman -Sy xorg-xauth

+

server $ echo $DISPLAY

+

localhost:10.0

+

server $ telnet localhost 6010

+

localhost/6010: lookup failure: Temporary failure in name resolution

−

* Enable the ''X11Forwarding'' option in ''sshd_config'' on the server.

+

can be fixed by adding localhost to {{ic|/etc/hosts}}.

−

* Enable the ''ForwardX11'' option in ''ssh_config'' on the client.

−

== 用SSHFS挂载远程文件系统 ==

+

=== 用SSHFS挂载远程文件系统 ===

−

Install sshfs

+

安装sshfs

−

# pacman -Sy sshfs

+

# pacman -S sshfs

−

Add the user that we want to give the permission to mount SSH folders to the fuse group

+

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

# gpasswd -a USER fuse

# gpasswd -a USER fuse

−

Load the fuse module (in /etc/rc.conf for example)

+

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

−

And then, after logging in, we can try to mount a remote folder using sshfs:

+

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

# mkdir ~/remote_folder

# mkdir ~/remote_folder

# sshfs USER@remote_server:/tmp ~/remote_folder

# sshfs USER@remote_server:/tmp ~/remote_folder

−

The command above will cause the folder /tmp on the remote server to be mounted as ~/remote_folder on the local machine. Copying any file to this folder will result in transparent copying over the network using SCP. Same concerns direct file editing, creating or removing.

When we’re done working with the remote filesystem, we can unmount the remote folder by issuing:

+

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

# fusermount -u ~/remote_folder

# fusermount -u ~/remote_folder

−

If we work on this folder on a daily basis, it is wise to add it to the /etc/fstab table. This way is can be automatically mounted upon system boot or mounted manually (if noauto option is chosen) without the need to specify the remote location each time. Here is a sample entry in the table:

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:

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

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]

管理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.

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:

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:

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:

Are there firewall rules blocking the connection?

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

"[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.