Difference between revisions of "Secure Shell"

From ArchWiki
Jump to: navigation, search
(Connecting to the server: Move from Comprehensive Server Guide.)
m (added persian translation)
 
(242 intermediate revisions by 79 users not shown)
Line 1: Line 1:
 
[[Category:Secure Shell]]
 
[[Category:Secure Shell]]
[[ar:Ssh]]
+
[[fa:SSH]]
[[es:Secure Shell]]
+
[[ar:Secure Shell]]
 
[[de:SSH]]
 
[[de:SSH]]
 +
[[es:Secure Shell]]
 
[[fr:ssh]]
 
[[fr:ssh]]
 
[[it:Secure Shell]]
 
[[it:Secure Shell]]
 +
[[ja:Secure Shell]]
 
[[ko:Secure Shell]]
 
[[ko:Secure Shell]]
 
[[pl:Secure Shell]]
 
[[pl:Secure Shell]]
Line 10: Line 12:
 
[[ru:Secure Shell]]
 
[[ru:Secure Shell]]
 
[[sr:Secure Shell]]
 
[[sr:Secure Shell]]
[[zh-CN:Secure Shell]]
+
[[zh-cn:Secure Shell]]
'''Secure Shell''' ('''SSH''') is a network protocol that allows data to be exchanged over a secure channel between two computers. Encryption provides confidentiality and integrity of data. SSH uses public-key cryptography to authenticate the remote computer and allow the remote computer to authenticate the user, if necessary.
+
{{Related articles start}}
 +
{{Related|SSH keys}}
 +
{{Related|Pam abl}}
 +
{{Related|fail2ban}}
 +
{{Related|sshguard}}
 +
{{Related|Sshfs}}
 +
{{Related|Syslog-ng}}
 +
{{Related|SFTP chroot}}
 +
{{Related|SCP_and_SFTP}}
 +
{{Related articles end}}
 +
 
 +
Secure Shell (SSH) is a network protocol that allows data to be exchanged over a secure channel between two computers. Encryption provides confidentiality and integrity of data. 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; file transfer can be accomplished using the associated SFTP or SCP protocols.
 
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; file transfer can be accomplished 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, GNU/Linux, Solaris and OpenVMS. Proprietary, freeware and open source versions of various levels of complexity and completeness exist.
+
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 macOS, GNU/Linux, Solaris and OpenVMS. Proprietary, freeware and open source versions of various levels of complexity and completeness exist.
 
+
(Source: [[Wikipedia:Secure Shell]])
+
  
 
== OpenSSH ==
 
== OpenSSH ==
Line 24: Line 35:
 
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 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.
  
=== Installing OpenSSH ===
+
=== Installation ===
[[pacman|Install]] {{Pkg|openssh}} from the [[official repositories]].
+
  
=== Configuring SSH ===
+
[[Install]] the {{Pkg|openssh}} package.
====Client====
+
The SSH client configuration file is {{ic|/etc/ssh/ssh_config}} or {{ic|~/.ssh/config}}.
+
  
An example configuration:
+
=== Client usage ===
  
{{hc|/etc/ssh/ssh_config|
+
To connect to a server, run:
# $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 -p ''port'' ''user''@''server-address''
# 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:
+
If the server only allows public-key authentication, follow [[SSH keys]].
#  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
+
==== Configuration ====
# list of available options, their meanings and defaults, please see the
+
# ssh_config(5) man page.
+
  
# Host *
+
The client can be configured to store common options and hosts. All options can be declared globally or restricted to specific hosts. For example:
#  ForwardAgent no
+
 
#   ForwardX11 no
+
{{hc|~/.ssh/config|# global options
#  RhostsRSAAuthentication no
+
User user
#  RSAAuthentication yes
+
 
#   PasswordAuthentication yes
+
# host-specific options
#  HostbasedAuthentication no
+
Host ''myserver''
#  GSSAPIAuthentication no
+
    HostName ''server-address''
#  GSSAPIDelegateCredentials no
+
    Port    ''port''}}
#  BatchMode no
+
 
#  CheckHostIP yes
+
With such a configuration, the following commands are equivalent
#  AddressFamily any
+
 
#  ConnectTimeout 0
+
$ ssh -p ''port'' ''user''@''server-address''
#  StrictHostKeyChecking ask
+
$ ssh ''myserver''
#  IdentityFile ~/.ssh/identity
+
 
#  IdentityFile ~/.ssh/id_rsa
+
See {{man|5|ssh_config}} for more information.
#  IdentityFile ~/.ssh/id_dsa
+
 
#  Port 22
+
Some options do not have command line switch equivalents, but you can specify config options on the command line with {{ic|-o}}. For example {{ic|1=-oKexAlgorithms=+diffie-hellman-group1-sha1}}.
#  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
+
}}
+
  
It is recommended to change the Protocol line into this:
+
=== Server usage ===
Protocol 2
+
  
That means that only Protocol 2 will be used, since Protocol 1 is considered somewhat insecure.
+
==== Configuration ====
  
====Daemon====
 
 
The SSH daemon configuration file can be found and edited in {{ic|/etc/ssh/ssh'''d'''_config}}.
 
The SSH daemon configuration file can be found and edited in {{ic|/etc/ssh/ssh'''d'''_config}}.
  
 
To allow access only for some users add this line:
 
To allow access only for some users add this line:
  AllowUsers    user1 user2
+
  AllowUsers    ''user1 user2''
 +
 
 +
To allow access only for some groups:
 +
AllowGroups  ''group1 group2''
  
 
To disable root login over SSH, change the PermitRootLogin line into this:
 
To disable root login over SSH, change the PermitRootLogin line into this:
 
  PermitRootLogin no
 
  PermitRootLogin no
  
To add a nice welcome message edit the file {{ic|/etc/issue}} and change the Banner line into this:
+
{{Note|1={{ic|PermitRootLogin prohibit-password}} is the default since version 7.0p1. See {{man|5|sshd_config}}.}}
 +
 
 +
To add a nice welcome message (e.g. from the {{ic|/etc/issue}} file), configure the {{ic|Banner}} option:
 
  Banner /etc/issue
 
  Banner /etc/issue
  
{{Tip| 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]).}}
+
Host keys will be generated automatically by the ''sshd'' [[#Daemon_management|service files]]. If you want sshd to use a particular key which you have provided, you can configure it manually:
 +
HostKey /etc/ssh/ssh_host_rsa_key
  
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. To help select a port review the [[Wikipedia:List of TCP and UDP port numbers|list of TCP and UDP port numbers]].
+
If the server is to be exposed to the WAN, it is recommended to change the default port from 22 to a random higher one like this:
 +
Port 39901
  
{{Tip|Disabling password logins entirely will greatly increase security, see [[SSH Keys]] for more information.}}
+
To help select a port review the [[Wikipedia:List of TCP and UDP port numbers|list of TCP and UDP port numbers]]. You can also find port information locally in {{ic|/etc/services}}. Select an alternative port that is '''not''' already assigned to a common service to prevent conflicts. A port change from default port 22 is recommended, because it will reduce the ''number'' of log entries caused by automated authentication attempts - not eliminate them. See [[Port knocking]] for related information.  
  
=== Managing the sshd daemon ===
+
{{Note|OpenSSH can also listen on multiple ports simply by having multiple '''Port x''' lines in the config file.}}
You can start the sshd daemon with the following command:
+
# systemctl start sshd
+
  
You can enable the sshd daemon at startup with the following command:
+
It is also recommended to disable password logins entirely. This will greatly increase security, see [[#Force public key authentication]] for more information.
  # systemctl enable sshd.service
+
  
{{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]].}}
+
==== Daemon management ====
  
Or you can enable SSH Daemon socket so the daemon is started on the first incoming connection:
+
{{Pkg|openssh}} comes with two kinds of [[systemd]] service files:
# systemctl enable sshd.socket
+
#{{ic|sshd.service}}, which will keep the SSH daemon permanently active and fork for each incoming connection.[https://projects.archlinux.org/svntogit/packages.git/tree/trunk/sshd.service?h=packages/openssh#n16] It is especially suitable for systems with a large amount of SSH traffic.[https://projects.archlinux.org/svntogit/packages.git/tree/trunk/sshd.service?h=packages/openssh&id=4cadf5dff444e4b7265f8918652f4e6dff733812#n15]
If you use a different port than the default 22, you have to set "ListenStream" in the unit file. Copy /lib/systemd/system/sshd.socket to /etc/systemd/system/sshd.socket to keep your unit file from being overwritten on upgrades. In /etc/systemd/system/sshd.socket change "ListenStream" the appropriate port.
+
#{{ic|sshd.socket}} + {{ic|sshd@.service}}, which spawn on-demand instances of the SSH daemon per connection. Using it implies that ''systemd'' listens on the SSH socket and will only start the daemon process for an incoming connection. It is the recommended way to run {{ic|sshd}} in almost all cases.[https://projects.archlinux.org/svntogit/packages.git/tree/trunk/sshd.service?h=packages/openssh&id=4cadf5dff444e4b7265f8918652f4e6dff733812#n18][http://lists.freedesktop.org/archives/systemd-devel/2011-January/001107.html][http://0pointer.de/blog/projects/inetd.html]
  
=== Connecting to the server ===
+
You can [[start]] and [[enable]] either {{ic|sshd.service}} '''or''' {{ic|sshd.socket}} to begin using the daemon.
To connect to a server, run:
+
 
$ ssh -p port user@server-address
+
If using the socket service, you will need to [[systemd#Editing provided units|edit]] the unit file if you want it to listen on a port other than the default 22:
 +
 
 +
{{hc|# systemctl edit sshd.socket|<nowiki>
 +
[Socket]
 +
ListenStream=
 +
ListenStream=12345
 +
</nowiki>}}
 +
 
 +
{{Warning|Using {{ic|sshd.socket}} negates the {{ic|ListenAddress}} setting, so it will allow connections over any address. To achieve the effect of setting {{ic|ListenAddress}}, you must specify the port ''and'' IP for {{ic|ListenStream}} (e.g. {{ic|1=ListenStream=192.168.1.100:22}}). You must also add {{ic|1=FreeBind=true}} under {{ic|[Socket]}} or else setting the IP address will have the same drawback as setting {{ic|ListenAddress}}: the socket will fail to start if the network is not up in time.}}
 +
 
 +
{{Tip|When using socket activation neither {{ic|sshd.socket}} nor the daemon's regular {{ic|sshd.service}} allow to monitor connection attempts in the log, but executing {{ic|# journalctl /usr/bin/sshd}} does.}}
 +
 
 +
==== Protection ====
  
=== Protecting SSH ===
 
 
Allowing remote log-on through SSH is good for administrative purposes, but can pose a threat to your server's security. Often the target of brute force attacks, SSH access needs to be limited properly to prevent third parties gaining access to your server.
 
Allowing remote log-on through SSH is good for administrative purposes, but can pose a threat to your server's security. Often the target of brute force attacks, SSH access needs to be limited properly to prevent third parties gaining access to your server.
* Use non-standard account names and passwords
+
 
* Only allow incoming SSH connections from trusted locations
+
Several other good guides are available on the topic, for example:
* Use [[fail2ban]] or [[sshguard]] to monitor for brute force attacks, and ban brute forcing IPs accordingly
+
*[https://wiki.mozilla.org/Security/Guidelines/OpenSSH Article by Mozilla Infosec Team]
 +
*[https://stribika.github.io/2015/01/04/secure-secure-shell.html Secure sshd]
 +
 
 +
===== Force public key authentication =====
 +
 
 +
If a client cannot authenticate through a public key, by default the SSH server falls back to password authentication, thus allowing a malicious user to attempt to gain access by [[#Protecting against brute force attacks|brute-forcing]] the password. One of the most effective ways to protect against this attack is to disable password logins entirely, and force the use of [[SSH keys]]. This can be accomplished by disabling the following options in {{ic|sshd_config}}:
 +
 
 +
PasswordAuthentication no
 +
ChallengeResponseAuthentication no
 +
 
 +
{{Warning|Before adding this to your configuration, make sure that all accounts which require SSH access have public-key authentication set up in the corresponding {{ic|authorized_keys}} files. See [[SSH keys#Copying the public key to the remote server]] for more information.}}
 +
 
 +
===== Two-factor authentication and public keys =====
 +
 
 +
Since OpenSSH 6.2, you can add your own chain to authenticate with using the {{ic|AuthenticationMethods}} option. This enables you to use public keys as well as a two-factor authorization.
 +
 
 +
See [[Google Authenticator]] to set up Google Authenticator.
 +
 
 +
To use [[PAM]] with OpenSSH, edit the following files:
 +
 
 +
{{hc|/etc/ssh/sshd_config|
 +
ChallengeResponseAuthentication yes
 +
AuthenticationMethods publickey keyboard-interactive:pam
 +
}}
 +
 
 +
Then you can log in with either a publickey '''or''' the user authentication as required by your PAM setup.
 +
 
 +
If, on the other hand, you want to authenticate the user on both a publickey '''and''' the user authentication as required by your PAM setup, use a comma instead of a space to separate the AuthenticationMethods:
 +
 
 +
{{hc|/etc/ssh/sshd_config|
 +
ChallengeResponseAuthentication yes
 +
AuthenticationMethods publickey,keyboard-interactive:pam
 +
}}
 +
 
 +
With required pubkey '''and''' pam authentication you may wish to disable the password requirement:
 +
{{hc|/etc/pam.d/sshd|
 +
auth      required  pam_securetty.so    #disable remote root
 +
#Require google authenticator
 +
auth      required  pam_google_authenticator.so
 +
#But not password
 +
#auth      include  system-remote-login
 +
account  include  system-remote-login
 +
password  include  system-remote-login
 +
session  include  system-remote-login
 +
}}
  
 
===== Protecting against brute force attacks =====
 
===== Protecting against brute force attacks =====
Brute forcing is a simple concept: One continuously tries to log in to a webpage or server log-in prompt like SSH with a high number of random username and password combinations. You can protect yourself from brute force attacks by using an automated script that blocks anybody trying to brute force their way in, for example [[fail2ban]] or [[sshguard]].
+
Brute forcing is a simple concept: One continuously tries to log in to a webpage or server log-in prompt like SSH with a high number of random username and password combinations.
  
===== Deny root login =====
+
====== Using iptables ======
It is generally considered bad practice to allow the user '''root''' to log in over SSH: The '''root''' account will exist on nearly any Linux system and grants full access to the system, once login has been achieved. Sudo provides root rights for actions requiring these and is the more secure solution, third parties would have to find a username present on the system, the matching password and the matching password for sudo to get root rights on your system. More barriers to be breached before full access to the system is reached.
+
  
Configure SSH to deny remote logins with the root user by editing {{ic|/etc/ssh/sshd_config}} and look for this section:
+
{{Merge|Simple_stateful_firewall#Bruteforce_attacks|Out of scope, same technique as already described in the SSF.}}
# Authentication:
+
+
#LoginGraceTime 2m
+
''#PermitRootLogin yes''
+
#StrictModes yes
+
#MaxAuthTries 6
+
#MaxSessions 10
+
  
Now simply change ''#PermitRootLogin yes'' to no, and uncomment the line:
+
If you are already using iptables you can easily protect SSH against brute force attacks by using the following rules.
PermitRootLogin no
+
 
 +
{{note|In this example the SSH port was changed to port 42660 TCP.}}
 +
 
 +
Before the following rules can be used we create a new rule chain to log and drop to many connection attempts:
 +
 
 +
# iptables -N LOG_AND_DROP
 +
 
 +
The first rule will be applied to packets that signal the start of new connections headed for TCP port 42660
 +
 
 +
# iptables -A INPUT -p tcp -m tcp --dport 42660 -m state --state NEW -m recent --set --name DEFAULT --rsource
 +
 
 +
The next rule tells iptables to look for packets that match the previous rule's parameters, and which also come from hosts already added to the watch list.
 +
 
 +
# iptables -A INPUT -p tcp -m tcp --dport 42660 -m state --state NEW -m recent --update --seconds 90 --hitcount 4 --name DEFAULT --rsource -j LOG_AND_DROP
 +
 
 +
Now iptables decides what to do with TCP traffic to port 42660 which does not match the previous rule.
 +
 
 +
# iptables -A INPUT -p tcp -m tcp --dport 42660 -j ACCEPT
 +
 
 +
We are appending this rule to the LOG_AND_DROP table, and we use the -j (jump) operator to pass the packet's information to the logging facility
 +
 
 +
# iptables -A LOG_AND_DROP -j LOG --log-prefix "iptables deny: " --log-level 7
 +
 
 +
After they are logged by the first rule, all packets are then dropped
 +
 
 +
# iptables -A LOG_AND_DROP -j DROP
 +
 
 +
====== Anti-brute-force tools ======
 +
 
 +
You can protect yourself from brute force attacks by using an automated script that blocks anybody trying to brute force their way in, for example [[fail2ban]] or [[sshguard]].
 +
 
 +
* Only allow incoming SSH connections from trusted locations
 +
* Use [[fail2ban]] or [[sshguard]] to automatically block IP addresses that fail password authentication too many times.
 +
* Use [https://github.com/jtniehof/pam_shield pam_shield] to block IP addresses that perform too many login attempts within a certain period of time. In contrast to [[fail2ban]] or [[sshguard]], this program does not take login success or failure into account.
 +
 
 +
===== Limit root login =====
 +
It is generally considered bad practice to allow the root user to log in without restraint over SSH. There are two methods by which SSH root access can be restricted for increased security.
 +
 
 +
====== Deny ======
 +
 
 +
Sudo selectively provides root rights for actions requiring these without requiring authenticating against the root account. This allows locking the root account against access via SSH and potentially functions as a security measure against brute force attacks, since now an attacker must guess the account name in addition to the password.
 +
 
 +
SSH can be configured to deny remote logins with the root user by editing the "Authentication" section in {{ic|/etc/ssh/sshd_config}}. Simply change {{ic|#PermitRootLogin prohibit-password}} to {{ic|no}} and uncomment the line:
 +
 
 +
{{hc|/etc/ssh/sshd_config|
 +
PermitRootLogin no
 +
...
 +
}}
 +
 
 +
Next, [[restart]] the SSH daemon.
 +
 
 +
You will now be unable to log in through SSH under root, but will still be able to log in with your normal user and use [[su]] or [[sudo]] to do system administration.
 +
 
 +
====== Restrict ======
 +
 
 +
Some automated tasks such as remote, full-system backup require full root access. To allow these in a secure way, instead of disabling root login via SSH, it is possible to only allow root logins for selected commands. This can be achieved by editing {{ic|~root/.ssh/authorized_keys}}, by prefixing the desired key, e.g. as follows:
 +
 
 +
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 {{ic|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
 +
 
 +
===== Securing the authorized_keys file =====
 +
 
 +
For additional protection, you can prevent users from adding new public keys and connecting from them.
 +
 
 +
In the server, make the {{ic|authorized_keys}} file read-only for the user and deny all other permissions:
 +
$ chmod 400 ~/.ssh/authorized_keys
  
Next, restart the SSH daemon:
+
To keep the user from simply changing the permissions back, [[File permissions and attributes#chattr and lsattr|set the immutable bit]] on the {{ic|authorized_keys}} file. After that the user could rename the {{ic|~/.ssh}} directory to something else and create a new {{ic|~/.ssh}} directory and {{ic|authorized_keys}} file. To prevent this, set the immutable bit on the {{ic|~/.ssh}} directory too.
# systemctl restart sshd
+
  
You will now be unable to log in through SSH under root, but will still be able to log in with your normal user and use ''su'' - or ''sudo'' to do system administration.
+
{{Note|If you find yourself needing to add a new key, you will first have to remove the immutable bit from {{ic|authorized_keys}} and make it writable. Follow the steps above to secure it again.}}
  
 
== Other SSH clients and servers ==
 
== Other SSH clients and servers ==
Apart from OpenSSH, there are many SSH [[Wikipedia:Comparison of SSH clients|clients]] and [[Wikipedia:Comparison of SSH servers|servers]] avaliable.
+
Apart from OpenSSH, there are many SSH [[Wikipedia:Comparison of SSH clients|clients]] and [[Wikipedia:Comparison of SSH servers|servers]] available.
  
 
=== Dropbear ===
 
=== Dropbear ===
[[Wikipedia:Dropbear (software)|Dropbear]] is a SSH-2 client and server. {{AUR|dropbear}} is available in the [[AUR]].
+
[[Wikipedia:Dropbear (software)|Dropbear]] is a SSH-2 client and server. {{Pkg|dropbear}} is available in the [[official repositories]].
  
The commandline ssh client is named dbclient.
+
The command-line ssh client is named dbclient.
  
=== SSH alternative: Mobile Shell - responsive, survives disconnects ===
+
=== Mosh ===
 
From the Mosh [http://mosh.mit.edu/ website]:
 
From the Mosh [http://mosh.mit.edu/ website]:
  
Remote terminal application that allows roaming, supports intermittent connectivity, and provides intelligent local echo and line editing of user keystrokes. Mosh is a replacement for SSH. It's more robust and responsive, especially over Wi-Fi, cellular, and long-distance links.
+
:Remote terminal application that allows roaming, supports intermittent connectivity, and provides intelligent local echo and line editing of user keystrokes. Mosh is a replacement for SSH. It is more robust and responsive, especially over slow connections such as Wi-Fi, cellular, and long-distance.
  
[[pacman|Install]] {{Pkg|mosh}} from the [[official repositories]] or the latest revision {{AUR|mosh-git}} in the [[AUR]].
+
[[Install]] the {{Pkg|mosh}} package, or {{AUR|mosh-git}} for the latest revision.
 +
 
 +
Mosh has an undocumented command line option {{ic|1=--predict=experimental}} which produces more aggressive echoing of local keystrokes. Users interested in low-latency visual confirmation of keyboard input may prefer this prediction mode.
 +
 
 +
{{Note|Mosh by design does not let you access session history, consider installing a terminal multiplexer such as [[tmux]] or [[screen]].}}
  
 
== Tips and tricks ==
 
== Tips and tricks ==
 +
 +
{{Accuracy|According to the current layout, this section seems rather generic, but in fact most of the offered tips work only in ''openssh''. For example ''dropbear'' (listed in [[#Other SSH clients and servers]]) does not support SOCKS proxy.[https://en.wikipedia.org/wiki/Comparison_of_SSH_clients#Technical]}}
  
 
=== Encrypted SOCKS tunnel ===
 
=== Encrypted SOCKS tunnel ===
Line 173: Line 288:
  
 
==== Step 1: start the connection ====
 
==== Step 1: start the connection ====
 +
 
You only have to execute this single command to start the connection:
 
You only have to execute this single command to start the connection:
$ ssh -TND 4711 user@host
 
where {{Ic|"user"}} is your username at the SSH server running at the {{Ic|"host"}}. It will ask for your password, and then you're connected! The {{Ic|"N"}} flag disables the interactive prompt, and the {{Ic|"D"}} flag specifies the local port on which to listen on (you can choose any port number if you want).  The {{Ic|"T"}} flag disables pseudo-tty allocation.
 
  
It's nice to add the verbose {{Ic|"-v"}} flag, because then you can verify that it's actually connected from that output.
+
$ ssh -TND 4711 ''user''@''host''
 +
 
 +
where {{Ic|''user''}} is your username at the SSH server running at the {{Ic|''host''}}. It will ask for your password, and then you are connected! The {{Ic|N}} flag disables the interactive prompt, and the {{Ic|D}} flag specifies the local port on which to listen on (you can choose any port number if you want).  The {{Ic|T}} flag disables pseudo-tty allocation.
 +
 
 +
It is nice to add the verbose ({{Ic|-v}}) flag, because then you can verify that it is actually connected from that output.
  
 
==== Step 2: configure your browser (or other programs) ====
 
==== Step 2: configure your browser (or other programs) ====
 +
 
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.
 
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 &rarr; Preferences &rarr; Advanced &rarr; Network &rarr; Connection &rarr; Setting'':
+
* For Firefox: ''Edit > Preferences > Advanced > Network > Connection > Setting'': <br> Check the ''Manual proxy configuration'' radio button, and enter {{ic|localhost}} in the ''SOCKS host'' text field, and then enter your port number in the next text field ({{ic|4711}} in the example above).
: 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).
+
  
 
Firefox does not automatically make DNS requests through the socks tunnel. This potential privacy concern can be mitigated by the following steps:
 
Firefox does not automatically make DNS requests through the socks tunnel. This potential privacy concern can be mitigated by the following steps:
Line 213: Line 331:
  
 
=== X11 forwarding ===
 
=== X11 forwarding ===
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 (here "client" means your (desktop) machine your X11 Server runs on, and you will run X applications on the "server").
+
X11 forwarding is a mechanism that allows graphical interfaces of X11 programs running on a remote system to be displayed on a local client machine. For X11 forwarding the remote host does not need to have a full X11 system installed, however it needs at least to have ''xauth'' installed. ''xauth'' is a utility that maintains {{ic|Xauthority}} configurations used by server and client for authentication of X11 session ([http://xmodulo.com/2012/11/how-to-enable-x11-forwarding-using-ssh.html source]).
  
[[pacman|Install]] {{Pkg|xorg-xauth}} from the [[official repositories]] onto the server.
+
{{Warning|X11 forwarding has important security implications which should be at least acknowledged by reading relevant sections of {{man|1|ssh}}, {{man|5|sshd_config}}, and {{man|5|ssh_config}} manual pages. See also [https://security.stackexchange.com/questions/14815/security-concerns-with-x11-forwarding a short writeup]}}
  
* Enable the '''AllowTcpForwarding''' option in {{ic|ssh'''d'''_config}} on the '''server'''.
+
==== Setup ====
* 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''' if gui is drawing badly.
+
  
You need to restart the ssh daemon on the server for these changes to take effect, of course.
+
On the remote system:
  
To use the forwarding, log on to your server through ssh:
+
*[[pacman#Installing specific packages|install]] {{Pkg|xorg-xauth}} and {{Pkg|xorg-xhost}} from the [[official repositories]]
  $ ssh -X -p port user@server-address
+
*in {{ic|/etc/ssh/ssh'''d'''_config}}:
If you receive errors trying to run graphical applications try trusted forwarding instead:
+
**verify that {{ic|AllowTcpForwarding}} and {{ic|X11UseLocalhost}} options are set to ''yes'', and that {{ic|X11DisplayOffset}} is set to ''10'' (those are the default values if nothing has been changed, see {{man|5|sshd_config}})
  $ ssh -Y -p port user@server-address
+
**set {{ic|X11Forwarding}} to ''yes''
 +
* then [[restart]] the [[#Daemon management|''sshd'' daemon]].
 +
 
 +
On the client's side, enable the {{ic|ForwardX11}} option by either specifying the {{ic|-X}} switch on the command line for opportunistic connections, or by setting {{ic|ForwardX11}} to ''yes'' in the [[#Configuration|client's configuration]].
 +
 
 +
{{Tip|You can enable the {{ic|ForwardX11Trusted}} option ({{ic|-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 [http://www.x.org/wiki/Development/Documentation/Security/ X11 SECURITY extension] controls. Be sure you have read [[#X11 forwarding|the warning]] at the beginning of this section if you do so.}}
 +
 
 +
==== Usage ====
 +
 
 +
{{Accuracy|{{ic|xhost}} is [http://unix.stackexchange.com/questions/12755/how-to-forward-x-over-ssh-from-ubuntu-machine#comment-17148 generally not needed]}}
 +
 
 +
Log on to the remote machine normally, specifying the {{ic|-X}} switch if ''ForwardX11'' was not enabled in the client's configuration file:
 +
  $ ssh -X ''user@host''
 +
If you receive errors trying to run graphical applications, try ''ForwardX11Trusted'' instead:
 +
  $ ssh -Y ''user@host''
 
You can now start any X program on the remote server, the output will be forwarded to your local session:
 
You can now start any X program on the remote server, the output will be forwarded to your local session:
 
  $ xclock
 
  $ xclock
 
  
 
If you get "Cannot open display" errors try the following command as the non root user:
 
If you get "Cannot open display" errors try the following command as the non root user:
 
  $ xhost +
 
  $ xhost +
  
the above command will allow anybody to forward X11 applications. To restrict forwarding to a particular host type:
+
The above command will allow anybody to forward X11 applications. To restrict forwarding to a particular host type:
 
  $ xhost +hostname
 
  $ xhost +hostname
  
where hostname is the name of the particular host you want to forward to. Type "man xhost" for more details.
+
where hostname is the name of the particular host you want to forward to. See {{man|1|xhost|url=https://docs.oracle.com/cd/E36784_01/html/E36870/xhost-1.html}} 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
+
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
+
  $ 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"), try to either
+
If you get "X11 forwarding request failed on channel 0" when you connect (and the server {{ic|/var/log/errors.log}} shows "Failed to allocate internet-domain X11 display socket"), make sure package {{Pkg|xorg-xauth}} is installed. If its installation is not working, try to either:
* Enable the '''AddressFamily any''' option in {{ic|ssh'''d'''_config}} on the '''server''', or
+
 
* Set the '''AddressFamily''' option in {{ic|ssh'''d'''_config}} on the '''server''' to inet.
+
* enable the {{ic|AddressFamily any}} option in {{ic|ssh'''d'''_config}} on the ''server'', or
 +
* set the {{ic|AddressFamily}} option in {{ic|ssh'''d'''_config}} on the ''server'' to inet.
 
Setting it to inet may fix problems with Ubuntu clients on IPv4.
 
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 {{Ic|xauth add}} the authentication line taken from {{Ic|xauth list}} of the SSH logged in user.
 +
 +
{{Tip|[http://unix.stackexchange.com/a/12772/29867 Here] are [http://unix.stackexchange.com/a/46748/29867 some] useful [http://superuser.com/a/805060/185665 links] for troubleshooting {{ic|X11 Forwarding}} issues.}}
  
 
=== Forwarding other ports ===
 
=== 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.
 
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>}}.
+
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 is accompanying forwarding specification in the form of {{Ic|<tunnel port>:<destination address>:<destination port>}}.
  
 
Thus:
 
Thus:
Line 277: Line 407:
  
 
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.
 +
 +
=== Multiplexing ===
 +
 +
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|
 +
Port 22
 +
Port 443
 +
}}
 +
 +
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.
  
 
=== Speeding up SSH ===
 
=== Speeding 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}}:
+
 
 +
{{Tip|If you intend to use SSH for SFTP or SCP, installing {{AUR|openssh-hpn-git}} can significantly increase throughput.[https://www.psc.edu/index.php/hpn-ssh]}}
 +
 
 +
There are several [[#Configuration|client configuration]] options which can speed up connections either globally or for specific hosts. See {{man|5|ssh_config}} for full descriptions of these options.
 +
 
 +
You can make all sessions to the same host share a single connection using these options:
 
  ControlMaster auto
 
  ControlMaster auto
  ControlPath ~/.ssh/socket-%r@%h:%p
+
ControlPersist yes
 +
  ControlPath ~/.ssh/sockets/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:
+
where {{ic|~/.ssh/sockets}} can be any directory not writable by other users.  
$ 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'
+
  
=== Mounting a remote filesystem with SSHFS ===
+
Another option to improve speed is to enable compression with the {{ic|Compression yes}} option or the {{ic|-C}} flag.
Please refer to the [[Sshfs]] article to use sshfs to mount a remote system - accessible via SSH - to a local folder, so you will be able to do any operation on the mounted files with any tool (copy, rename, edit with vim, etc.). Using sshfs instead of shfs is generally preferred as a new version of shfs hasn't been released since 2004.
+
  
=== Keep alive ===
+
{{Warning|{{man|1|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.}}
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
+
Login time can be shortened by bypassing IPv6 lookup using the {{ic|AddressFamily inet}} option or {{ic|-4}} flag.
  
This will send a "keep alive" signal to the server every 120 seconds.
+
=== Mounting a remote filesystem with SSHFS ===
 +
Please refer to the [[Sshfs]] article to use sshfs to mount a remote system - accessible via SSH - to a local folder, so you will be able to do any operation on the mounted files with any tool (copy, rename, edit with vim, etc.). Using sshfs instead of shfs is generally preferred as a new version of shfs has not been released since 2004.
  
Conversely, to keep incoming connections alive, you can set
+
=== Keep alive ===
+
Your ssh session will automatically log out if it is idle. To send a "keep alive" signal to the server every 120 seconds add the {{ic|ServerAliveInterval 120}} option to your [[#Configuration|client configuration]]. See also the {{ic|ServerAliveCountMax}} and {{ic|TCPKeepAlive}} options.
ClientAliveInterval 120
+
  
(or some other number greater than 0) in {{ic|/etc/ssh/sshd_config}} on the server.
+
Conversely, to keep incoming connections alive, set the {{ic|ClientAliveInterval}} option in your [[#Configuration_2|server configuration]].
  
=== Saving connection data in ssh config ===
+
=== Automatically restart SSH tunnels with systemd ===
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|
+
[[systemd]] can automatically start SSH connections on boot/login ''and'' restart them when they fail. This makes it a useful tool for maintaining SSH tunnels.
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:
+
The following service can start an SSH tunnel on login using the connection settings in your [[#Saving connection data in ssh config|ssh config]]. If the connection closes for any reason, it waits 10 seconds before restarting it:
  
$ ssh myserver
+
{{hc|~/.config/systemd/user/tunnel.service|<nowiki>
 +
[Unit]
 +
Description=SSH tunnel to 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.
+
[Service]
 +
Type=simple
 +
Restart=always
 +
RestartSec=10
 +
ExecStart=/usr/bin/ssh -F %h/.ssh/config -N myserver
 +
</nowiki>}}
 +
 
 +
Then [[enable]] and [[start]] the user service. See [[#Keep alive]] for how to prevent the tunnel from timing out. If you wish to start the tunnel on boot, you will need to rewrite the unit as a system service.
  
 
=== Autossh - automatically restarts SSH sessions and tunnels ===
 
=== Autossh - automatically restarts SSH sessions and tunnels ===
When a ssh session or tunnel cannot be kept alive, because for example bad network conditions cause the sshd client to disconnect, you can use [http://www.harding.motd.ca/autossh/ Autossh] to automatically restart them. Autossh can be installed from the [[official repositories]].  
+
 
 +
When a session or tunnel cannot be kept alive, for example due to bad network conditions causing client disconnections, you can use {{Pkg|autossh}} to automatically restart them.
  
 
Usage examples:
 
Usage examples:
 
  $ autossh -M 0 -o "ServerAliveInterval 45" -o "ServerAliveCountMax 2" username@example.com
 
  $ autossh -M 0 -o "ServerAliveInterval 45" -o "ServerAliveCountMax 2" username@example.com
Combined with [[ sshfs ]]:
+
 
 +
Combined with [[sshfs]]:
 
  $ sshfs -o reconnect,compression=yes,transform_symlinks,ServerAliveInterval=45,ServerAliveCountMax=2,ssh_command='autossh -M 0' username@example.com: /mnt/example  
 
  $ sshfs -o reconnect,compression=yes,transform_symlinks,ServerAliveInterval=45,ServerAliveCountMax=2,ssh_command='autossh -M 0' username@example.com: /mnt/example  
Connecting through a SOCKS-proxy set by [[ Proxy_settings ]]:
+
 
  $ autossh -M 0 "ServerAliveInterval 45" -o "ServerAliveCountMax 2" -NCD 8080 username@example.com  
+
Connecting through a SOCKS-proxy set by [[Proxy settings]]:
With the {{ic|-f}} option autossh can be made to run as a background process. Running it this way however means the passprase cannot be entered interactively.
+
  $ autossh -M 0 -o "ServerAliveInterval 45" -o "ServerAliveCountMax 2" -NCD 8080 username@example.com  
 +
 
 +
With the {{ic|-f}} option autossh can be made to run as a background process. Running it this way however means the passphrase cannot be entered interactively.
  
 
The session will end once you type {{ic|exit}} in the session, or the autossh process receives a SIGTERM, SIGINT of SIGKILL signal.
 
The session will end once you type {{ic|exit}} in the session, or the autossh process receives a SIGTERM, SIGINT of SIGKILL signal.
  
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:
+
==== Run autossh automatically at boot via systemd ====
  
[Unit]
+
If you want to automatically start autossh, you can create a systemd unit file:
Description=AutoSSH service for port 2222
+
After=network.target
+
+
[Service]
+
ExecStart=/usr/bin/autossh -M 0 2222:localhost:2222 foo@bar.com
+
+
[Install]
+
WantedBy=multi-user.target
+
  
Then place this in, for example, /etc/systemd/system/autossh.service. 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.
+
{{hc|/etc/systemd/system/autossh.service|2=
 +
[Unit]
 +
Description=AutoSSH service for port 2222
 +
After=network.target
  
You can then enable your autossh tunnels with, e.g.:
+
[Service]
 +
Environment="AUTOSSH_GATETIME=0"
 +
ExecStart=/usr/bin/autossh -M 0 -NL 2222:localhost:2222 -o TCPKeepAlive=yes foo@bar.com
  
$ systemctl start autossh
+
[Install]
(or whatever you called the service file)
+
WantedBy=multi-user.target
 +
}}
  
If this works OK for you, you can make this permanent by running
+
Here {{ic|1=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 {{ic|-f}} implying {{ic|1=AUTOSSH_GATETIME=0}} does not work with systemd.
  
$ systemctl enable autossh
+
Remember to [[start]] and/or [[enable]] the service afterwards.
  
That way autossh will start automatically at boot.
+
You may also need to disable ControlMaster e.g.
  
It is also easy to maintain several autossh processes, to keep several tunnels alive. Just create multiple .service files with different names.
+
$ ExecStart=/usr/bin/autossh -M 0 -o ControlMaster=no -NL 2222:localhost:2222 -o TCPKeepAlive=yes foo@bar.com
 +
 
 +
{{Tip|It is also easy to maintain several autossh processes, to keep several tunnels alive. Just create multiple service files with different names.}}
  
 
== Troubleshooting ==
 
== Troubleshooting ==
=== Connection refused or timeout problem ===
 
  
==== Is your router doing port forwarding? ====
+
=== Checklist ===
  
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.
+
Check these simple issues before you look any further.
  
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.
+
# The config directory {{ic|~/.ssh}} and its contents should be accessible only by your user (check this on both the client and the server): {{bc|<nowiki>
 +
$ chmod 700 ~/.ssh
 +
$ chmod 600 ~/.ssh/*
 +
$ chown -R $USER ~/.ssh
 +
</nowiki>}}
 +
# Check that the client's public key (e.g. {{ic|id_rsa.pub}}) is in {{ic|~/.ssh/authorized_keys}} on the server.
 +
# Check that you did not limit SSH access with {{ic|AllowUsers}} or {{ic|AllowGroups}} in the [[#Configuration_2|server config]].
 +
# Check if the user has set a password. Sometimes new users who have not yet logged in to the server do not have a password.
 +
# [[Restart]] {{ic|sshd}} and logout/login on both client and server.
  
Find your internal network address.
+
=== SSH connection hangs after poweroff/reboot ===
  
ip a
+
SSH connections hang after poweroff or reboot if systemd stops the network before sshd. To fix this, change the {{ic|After}} statement for user sessions:
 +
{{hc|# systemctl edit systemd-user-sessions.service|2=
 +
[Unit]
 +
After=network.target}}
  
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 [http://portforward.com/] for more instructions on how to do so for your particular router.
+
=== Connection refused or timeout problem ===
 +
 
 +
==== Port forwarding ====
 +
 
 +
If you are behind a NAT mode/router (which is likely unless you are on a VPS or publicly addressed host), make sure that your router is forwarding incoming ssh connections to your machine. Find the server's internal IP address with {{ic|$ ip addr}} and set up your router to forward TCP on your SSH port to that IP. [http://portforward.com portforward.com] can help with that.
  
 
==== Is SSH running and listening? ====
 
==== Is SSH running and listening? ====
Line 392: Line 544:
  
 
==== Are there firewall rules blocking the connection? ====
 
==== Are there firewall rules blocking the connection? ====
{{out of date|rc.d is deprecated with systemd}}
 
Flush your iptables rules to make sure they are not interfering:
 
  
# rc.d stop iptables
+
[[Iptables]] may be blocking connections on port {{ic|22}}. Check this with:
 
+
{{bc|# iptables -nvL}}
or:
+
and look for rules that might be dropping packets on the {{ic|INPUT}} chain. Then, if necessary, unblock the port with a command like:
 
+
{{bc|
# iptables -P INPUT ACCEPT
+
# iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT
# iptables -P OUTPUT ACCEPT
+
}}
# iptables -F INPUT
+
For more help configuring firewalls, see [[firewalls]].
# iptables -F OUTPUT
+
  
 
==== Is the traffic even getting to your computer? ====
 
==== Is the traffic even getting to your computer? ====
Start a traffic dump on the computer you're having problems with:
+
Start a traffic dump on the computer you are having problems with:
  
 
  # tcpdump -lnn -i any port ssh and tcp-syn
 
  # tcpdump -lnn -i any port ssh and tcp-syn
Line 412: Line 561:
  
 
==== Your ISP or a third party blocking default port? ====
 
==== Your ISP or a third party blocking default port? ====
{{Note|Try this step if you '''KNOW''' you aren't running any firewalls and you know you have configured the router for DMZ or have forwarded the port to your computer and it still doesn't work. Here you will find diagnostic steps and a possible solution.}}
+
{{Note|Try this step if you '''know''' you are not running any firewalls and you know you have configured the router for DMZ or have forwarded the port to your computer and it still does not work. Here you will find diagnostic steps and a possible solution.}}
  
 
In some cases, your ISP might block the default port (SSH port 22) so whatever you try (opening ports, hardening the stack, defending against flood attacks, et al) ends up useless. To confirm this, create a server on all interfaces (0.0.0.0) and connect remotely.  
 
In some cases, your ISP might block the default port (SSH port 22) so whatever you try (opening ports, hardening the stack, defending against flood attacks, et al) ends up useless. To confirm this, create a server on all interfaces (0.0.0.0) and connect remotely.  
Line 419: Line 568:
 
  ssh: connect to host www.inet.hr port 22: Connection refused
 
  ssh: connect to host www.inet.hr port 22: Connection refused
  
That means the port '''ISN'T ''' being blocked by the ISP, but the server doesn't run SSH on that port (See [http://en.wikipedia.org/wiki/Security_through_obscurity security through obscurity]).
+
That means the port is '''not''' being blocked by the ISP, but the server does not run SSH on that port (See [[wikipedia:Security_through_obscurity|security through obscurity]]).
  
 
However, if you get an error message comparable to this:
 
However, if you get an error message comparable to this:
 
  ssh: connect to host 111.222.333.444 port 22: Operation timed out  
 
  ssh: connect to host 111.222.333.444 port 22: Operation timed out  
  
That means that something is rejecting your TCP traffic on port 22. Basically that port is stealth, either by your firewall or 3rd party intervetion (like an ISP blocking and/or rejecting incoming traffic on port 22). If you know you aren't running any firewall on your computer, and you know that Gremlins aren't growing in your routers and switches, then your ISP is blocking the traffic.
+
That means that something is rejecting your TCP traffic on port 22. Basically that port is stealth, either by your firewall or 3rd party intervention (like an ISP blocking and/or rejecting incoming traffic on port 22). If you know you are not running any firewall on your computer, and you know that Gremlins are not growing in your routers and switches, then your ISP is blocking the traffic.
  
To double check, you can run Wireshark on your server and listen to traffic on port 22. Since Wireshark is a Layer 2 Packet Sniffing utility, and TCP/UDP are Layer 3 and above (See [http://en.wikipedia.org/wiki/TCP/IP_model IP Network stack]), if you don't receive anything while connecting remotely, a third party is most likely to be blocking the traffic on that port to your server.
+
To double check, you can run Wireshark on your server and listen to traffic on port 22. Since Wireshark is a Layer 2 Packet Sniffing utility, and TCP/UDP are Layer 3 and above (see [[wikipedia:Internet protocol suite|IP Network stack]]), if you do not receive anything while connecting remotely, a third party is most likely to be blocking the traffic on that port to your server.
  
===== Diagnosis via Wireshark =====
+
===== Diagnosis =====
[[pacman|Install]] Wireshark with the {{Pkg|wireshark-cli}} package, available in the [[official repositories]].
+
  
And then run it using,
+
[[Install]] either {{Pkg|tcpdump}} or Wireshark with the {{Pkg|wireshark-cli}} package.
tshark -f "tcp port 22" -i NET_IF
+
  
where NET_IF is the network interface for a WAN connection (see {{ic|ip a}} to check). If you aren't receiving any packets while trying to connect remotely, you can be very sure that your ISP is blocking the incoming traffic on port 22.
+
For tcpdump:
 +
 
 +
# tcpdump -ni ''interface'' "port 22"
 +
 
 +
For Wireshark:
 +
 
 +
$ tshark -f "tcp port 22" -i ''interface''
 +
 
 +
where {{ic|''interface''}} is the network interface for a WAN connection (see {{ic|ip a}} to check). If you are not receiving any packets while trying to connect remotely, you can be very sure that your ISP is blocking the incoming traffic on port 22.
  
 
===== Possible solution =====
 
===== Possible solution =====
The solution is just to use some other port that the ISP isn't blocking. Open the {{ic|/etc/ssh/sshd_config}} and configure the file to use different ports. For example, add:
+
The solution is just to use some other port that the ISP is not blocking. Open the {{ic|/etc/ssh/sshd_config}} and configure the file to use different ports. For example, add:
  
 
  Port 22
 
  Port 22
 
  Port 1234
 
  Port 1234
  
Also make sure that other "Port" configuration lines in the file are commented out. Just commenting "Port 22" and putting "Port 1234" won't solve the issue because then sshd will only listen on port 1234. Use both lines to run the SSH server on both ports.  
+
Also make sure that other "Port" configuration lines in the file are commented out. Just commenting "Port 22" and putting "Port 1234" will not solve the issue because then sshd will only listen on port 1234. Use both lines to run the SSH server on both ports.  
  
Restart the server {{ic|systemctl restart sshd.service}} and you're almost done. You still have to configure your client(s) to use the other port instead of the default port. There are numerous solutions to that problem, but let's cover two of them here.
+
[[Restart]] the server {{ic|sshd.service}} and you are almost done. You still have to configure your client(s) to use the other port instead of the default port. There are numerous solutions to that problem, but let us cover two of them here.
  
 
==== Read from socket failed: connection reset by peer ====
 
==== 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 add the following line to {{ic|~/.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
+
Recent versions of openssh sometimes fail with the above error message when connecting to older ssh servers. This can be worked around by setting various [[#Configuration|client options]] for that host. See {{man|5|ssh_config}} for more information about the following options.
  
With openssh 5.9, the above fix doesn't work.  Instead, put the following lines in {{ic|~/.ssh/config}}:
+
The problem could be the {{ic|ecdsa-sha2-nistp*-cert-v01@openssh}} elliptical host key algorithms. These can be disabled by setting {{ic|HostKeyAlgorithms}} to a list excluding those algorithms.
  
Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc
+
If that does not work, it could be that the list of ciphers is too long. Set the {{ic|Ciphers}} option to a shorter list (fewer than 80 characters should be enough). Similarly, you can also try shortening the list of {{ic|MACs}}.
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.
 
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 ===
 
=== "[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.
+
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.
  
 
==="Terminal unknown" or  "Error opening terminal" error message===
 
==="Terminal unknown" or  "Error opening terminal" error message===
With ssh it is possible to receive errors like "Terminal unknown" upon logging in. Starting ncurses applications like nano fails with the message "Error opening terminal". There are two methods to this problem, a quick one using the $TERM variable and a profound one using the terminfo file.
+
If you receive the above errors upon logging in, this means the server does not recognize your terminal. Ncurses applications like nano may fail with the message "Error opening terminal".
 +
 
 +
The correct solution is to install the client terminal's terminfo file on the server. This tells console programs on the server how to correctly interact with your terminal. You can get info about current terminfo using {{ic|$ infocmp}} and then find out [[Pacman#Querying_package_databases|which package owns it]].
 +
 
 +
If you cannot [[install]] it normally, you can copy your terminfo to your home directory on the server:
 +
 
 +
$ ssh myserver mkdir -p  ~/.terminfo/${TERM:0:1}
 +
$ scp /usr/share/terminfo/${TERM:0:1}/$TERM myserver:~/.terminfo/${TERM:0:1}/
 +
 
 +
After logging in and out from the server the problem should be fixed.
 +
 
 +
==== TERM hack ====
 +
 
 +
{{warning|This should only be used as a last resort.}}
 +
 
 +
Alternatively, you can simply set {{ic|1=TERM=xterm}} in your environment on the server (e.g. in {{ic|.bash_profile}}). This will silence the error and allow ncurses applications to run again, but you may experience strange behavior and graphical glitches unless your terminal's control sequences exactly match xterm's.
  
====Workaround by setting the $TERM variable====
+
=== Connection closed by x.x.x.x [preauth] ===
After connecting to the remote server set the $TERM variable to "xterm" with the following command.
+
If you are seeing this error in your sshd logs, make sure you have set a valid HostKey
 +
HostKey /etc/ssh/ssh_host_rsa_key
  
{{ic|TERM&#61;xterm}}
+
=== id_dsa refused by OpenSSH 7.0 ===
  
This method is a workaround and should be used on ssh servers you do seldomly connect to, because it can have unwanted side effects. Also you have to repeat the command after every connection, or alternatively set it in ~.bashrc .
+
OpenSSH 7.0 deprecated DSA public keys for security reasons. If you absolutely must enable them, set the [[#Configuration|config]] option {{ic|PubkeyAcceptedKeyTypes +ssh-dss}} (http://www.openssh.com/legacy.html does not mention this).
====Solution using terminfo file====
+
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:
+
  
{{ic| mkdir -p ~/.terminfo/r/}}
+
=== No matching key exchange method found by OpenSSH 7.0 ===
  
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.
+
OpenSSH 7.0 deprecated the diffie-hellman-group1-sha1 key algorithm because it is weak and within theoretical range of the so-called Logjam attack (see http://www.openssh.com/legacy.html). If the key algorithm is needed for a particular host, ssh will produce an error message like this:
  
{{ic|$ scp /usr/share/terminfo/r/''rxvt-unicode-256color'' ssh-server:~/.terminfo/r/}}
+
  Unable to negotiate with 127.0.0.1: no matching key exchange method found.
 +
Their offer: diffie-hellman-group1-sha1
  
After logging in and out from the ssh server the problem should be fixed.
+
The best resolution for these failures is to upgrade/configure the server to not use deprecated algorithms. If that is not possible, you can force the client to reenable the algorithm with the [[#Configuration|client option]] {{ic|KexAlgorithms +diffie-hellman-group1-sha1}}.
  
 
== See also ==
 
== See also ==
*[[SSH Keys]]
 
*[[Pam abl]]
 
*[[fail2ban]]
 
*[[sshguard]]
 
*[[Sshfs]]
 
*[[Syslog-ng]] : To send ssh log data to another file
 
  
== Links & references ==
+
* [[Wikipedia:Secure Shell]]
*[http://www.soloport.com/iptables.html A Cure for the Common SSH Login Attack]
+
* [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]
+
* [http://www.ibm.com/developerworks/library/l-keyc/index.html OpenSSH key management, Part 1] and [http://www.ibm.com/developerworks/library/l-keyc2 Part 2] on IBM developerWorks
*[http://www.ibm.com/developerworks/library/l-keyc/index.html OpenSSH key management, Part 1] and [http://www.ibm.com/developerworks/library/l-keyc2 Part 2] on IBM developerWorks
+
* [https://stribika.github.io/2015/01/04/secure-secure-shell.html Secure Secure Shell]

Latest revision as of 06:23, 7 October 2016

Secure Shell (SSH) is a network protocol that allows data to be exchanged over a secure channel between two computers. Encryption provides confidentiality and integrity of data. 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; file transfer can be accomplished 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 macOS, GNU/Linux, Solaris and OpenVMS. Proprietary, freeware and open source versions of various levels of complexity and completeness exist.

Contents

OpenSSH

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

Installation

Install the openssh package.

Client usage

To connect to a server, run:

$ ssh -p port user@server-address

If the server only allows public-key authentication, follow SSH keys.

Configuration

The client can be configured to store common options and hosts. All options can be declared globally or restricted to specific hosts. For example:

~/.ssh/config
# global options
User user

# host-specific options
Host myserver
    HostName server-address
    Port     port

With such a configuration, the following commands are equivalent

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

See ssh_config(5) for more information.

Some options do not have command line switch equivalents, but you can specify config options on the command line with -o. For example -oKexAlgorithms=+diffie-hellman-group1-sha1.

Server usage

Configuration

The SSH daemon configuration file can be found and edited in /etc/ssh/sshd_config.

To allow access only for some users add this line:

AllowUsers    user1 user2

To allow access only for some groups:

AllowGroups   group1 group2

To disable root login over SSH, change the PermitRootLogin line into this:

PermitRootLogin no
Note: PermitRootLogin prohibit-password is the default since version 7.0p1. See sshd_config(5).

To add a nice welcome message (e.g. from the /etc/issue file), configure the Banner option:

Banner /etc/issue

Host keys will be generated automatically by the sshd service files. If you want sshd to use a particular key which you have provided, you can configure it manually:

HostKey /etc/ssh/ssh_host_rsa_key

If the server is to be exposed to the WAN, it is recommended to change the default port from 22 to a random higher one like this:

Port 39901

To help select a port review the list of TCP and UDP port numbers. You can also find port information locally in /etc/services. Select an alternative port that is not already assigned to a common service to prevent conflicts. A port change from default port 22 is recommended, because it will reduce the number of log entries caused by automated authentication attempts - not eliminate them. See Port knocking for related information.

Note: OpenSSH can also listen on multiple ports simply by having multiple Port x lines in the config file.

It is also recommended to disable password logins entirely. This will greatly increase security, see #Force public key authentication for more information.

Daemon management

openssh comes with two kinds of systemd service files:

  1. sshd.service, which will keep the SSH daemon permanently active and fork for each incoming connection.[1] It is especially suitable for systems with a large amount of SSH traffic.[2]
  2. sshd.socket + sshd@.service, which spawn on-demand instances of the SSH daemon per connection. Using it implies that systemd listens on the SSH socket and will only start the daemon process for an incoming connection. It is the recommended way to run sshd in almost all cases.[3][4][5]

You can start and enable either sshd.service or sshd.socket to begin using the daemon.

If using the socket service, you will need to edit the unit file if you want it to listen on a port other than the default 22:

# systemctl edit sshd.socket
[Socket]
ListenStream=
ListenStream=12345
Warning: Using sshd.socket negates the ListenAddress setting, so it will allow connections over any address. To achieve the effect of setting ListenAddress, you must specify the port and IP for ListenStream (e.g. ListenStream=192.168.1.100:22). You must also add FreeBind=true under [Socket] or else setting the IP address will have the same drawback as setting ListenAddress: the socket will fail to start if the network is not up in time.
Tip: When using socket activation neither sshd.socket nor the daemon's regular sshd.service allow to monitor connection attempts in the log, but executing # journalctl /usr/bin/sshd does.

Protection

Allowing remote log-on through SSH is good for administrative purposes, but can pose a threat to your server's security. Often the target of brute force attacks, SSH access needs to be limited properly to prevent third parties gaining access to your server.

Several other good guides are available on the topic, for example:

Force public key authentication

If a client cannot authenticate through a public key, by default the SSH server falls back to password authentication, thus allowing a malicious user to attempt to gain access by brute-forcing the password. One of the most effective ways to protect against this attack is to disable password logins entirely, and force the use of SSH keys. This can be accomplished by disabling the following options in sshd_config:

PasswordAuthentication no
ChallengeResponseAuthentication no
Warning: Before adding this to your configuration, make sure that all accounts which require SSH access have public-key authentication set up in the corresponding authorized_keys files. See SSH keys#Copying the public key to the remote server for more information.
Two-factor authentication and public keys

Since OpenSSH 6.2, you can add your own chain to authenticate with using the AuthenticationMethods option. This enables you to use public keys as well as a two-factor authorization.

See Google Authenticator to set up Google Authenticator.

To use PAM with OpenSSH, edit the following files:

/etc/ssh/sshd_config
ChallengeResponseAuthentication yes
AuthenticationMethods publickey keyboard-interactive:pam

Then you can log in with either a publickey or the user authentication as required by your PAM setup.

If, on the other hand, you want to authenticate the user on both a publickey and the user authentication as required by your PAM setup, use a comma instead of a space to separate the AuthenticationMethods:

/etc/ssh/sshd_config
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive:pam

With required pubkey and pam authentication you may wish to disable the password requirement:

/etc/pam.d/sshd
auth      required  pam_securetty.so     #disable remote root
#Require google authenticator
auth      required  pam_google_authenticator.so
#But not password
#auth      include   system-remote-login
account   include   system-remote-login
password  include   system-remote-login
session   include   system-remote-login
Protecting against brute force attacks

Brute forcing is a simple concept: One continuously tries to log in to a webpage or server log-in prompt like SSH with a high number of random username and password combinations.

Using iptables

Merge-arrows-2.pngThis article or section is a candidate for merging with Simple_stateful_firewall#Bruteforce_attacks.Merge-arrows-2.png

Notes: Out of scope, same technique as already described in the SSF. (Discuss in Talk:Secure Shell#)

If you are already using iptables you can easily protect SSH against brute force attacks by using the following rules.

Note: In this example the SSH port was changed to port 42660 TCP.

Before the following rules can be used we create a new rule chain to log and drop to many connection attempts:

# iptables -N LOG_AND_DROP

The first rule will be applied to packets that signal the start of new connections headed for TCP port 42660

# iptables -A INPUT -p tcp -m tcp --dport 42660 -m state --state NEW -m recent --set --name DEFAULT --rsource

The next rule tells iptables to look for packets that match the previous rule's parameters, and which also come from hosts already added to the watch list.

# iptables -A INPUT -p tcp -m tcp --dport 42660 -m state --state NEW -m recent --update --seconds 90 --hitcount 4 --name DEFAULT --rsource -j LOG_AND_DROP

Now iptables decides what to do with TCP traffic to port 42660 which does not match the previous rule.

# iptables -A INPUT -p tcp -m tcp --dport 42660 -j ACCEPT

We are appending this rule to the LOG_AND_DROP table, and we use the -j (jump) operator to pass the packet's information to the logging facility

# iptables -A LOG_AND_DROP -j LOG --log-prefix "iptables deny: " --log-level 7

After they are logged by the first rule, all packets are then dropped

# iptables -A LOG_AND_DROP -j DROP
Anti-brute-force tools

You can protect yourself from brute force attacks by using an automated script that blocks anybody trying to brute force their way in, for example fail2ban or sshguard.

  • Only allow incoming SSH connections from trusted locations
  • Use fail2ban or sshguard to automatically block IP addresses that fail password authentication too many times.
  • Use pam_shield to block IP addresses that perform too many login attempts within a certain period of time. In contrast to fail2ban or sshguard, this program does not take login success or failure into account.
Limit root login

It is generally considered bad practice to allow the root user to log in without restraint over SSH. There are two methods by which SSH root access can be restricted for increased security.

Deny

Sudo selectively provides root rights for actions requiring these without requiring authenticating against the root account. This allows locking the root account against access via SSH and potentially functions as a security measure against brute force attacks, since now an attacker must guess the account name in addition to the password.

SSH can be configured to deny remote logins with the root user by editing the "Authentication" section in /etc/ssh/sshd_config. Simply change #PermitRootLogin prohibit-password to no and uncomment the line:

/etc/ssh/sshd_config
PermitRootLogin no
...

Next, restart the SSH daemon.

You will now be unable to log in through SSH under root, but will still be able to log in with your normal user and use su or sudo to do system administration.

Restrict

Some automated tasks such as remote, full-system backup require full root access. To allow these in a secure way, instead of disabling root login via SSH, it is possible to only allow root logins for selected commands. This can be achieved by editing ~root/.ssh/authorized_keys, by prefixing the desired key, e.g. as follows:

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
Securing the authorized_keys file

For additional protection, you can prevent users from adding new public keys and connecting from them.

In the server, make the authorized_keys file read-only for the user and deny all other permissions:

$ chmod 400 ~/.ssh/authorized_keys

To keep the user from simply changing the permissions back, set the immutable bit on the authorized_keys file. After that the user could rename the ~/.ssh directory to something else and create a new ~/.ssh directory and authorized_keys file. To prevent this, set the immutable bit on the ~/.ssh directory too.

Note: If you find yourself needing to add a new key, you will first have to remove the immutable bit from authorized_keys and make it writable. Follow the steps above to secure it again.

Other SSH clients and servers

Apart from OpenSSH, there are many SSH clients and servers available.

Dropbear

Dropbear is a SSH-2 client and server. dropbear is available in the official repositories.

The command-line ssh client is named dbclient.

Mosh

From the Mosh website:

Remote terminal application that allows roaming, supports intermittent connectivity, and provides intelligent local echo and line editing of user keystrokes. Mosh is a replacement for SSH. It is more robust and responsive, especially over slow connections such as Wi-Fi, cellular, and long-distance.

Install the mosh package, or mosh-gitAUR for the latest revision.

Mosh has an undocumented command line option --predict=experimental which produces more aggressive echoing of local keystrokes. Users interested in low-latency visual confirmation of keyboard input may prefer this prediction mode.

Note: Mosh by design does not let you access session history, consider installing a terminal multiplexer such as tmux or screen.

Tips and tricks

Tango-inaccurate.pngThe factual accuracy of this article or section is disputed.Tango-inaccurate.png

Reason: According to the current layout, this section seems rather generic, but in fact most of the offered tips work only in openssh. For example dropbear (listed in #Other SSH clients and servers) does not support SOCKS proxy.[6] (Discuss in Talk:Secure Shell#)

Encrypted SOCKS tunnel

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.

Step 1: start the connection

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.

Step 2: configure your browser (or other programs)

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 forwarding

X11 forwarding is a mechanism that allows graphical interfaces of X11 programs running on a remote system to be displayed on a local client machine. For X11 forwarding the remote host does not need to have a full X11 system installed, however it needs at least to have xauth installed. xauth is a utility that maintains Xauthority configurations used by server and client for authentication of X11 session (source).

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

Setup

On the remote system:

On the client's side, enable the ForwardX11 option by either specifying the -X switch on the command line for opportunistic connections, or by setting ForwardX11 to yes in the client's configuration.

Tip: 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.

Usage

Tango-inaccurate.pngThe factual accuracy of this article or section is disputed.Tango-inaccurate.png

Reason: xhost is generally not needed (Discuss in Talk:Secure Shell#)

Log on to the remote machine normally, specifying the -X switch if ForwardX11 was not enabled in the client's configuration file:

$ ssh -X user@host

If you receive errors trying to run graphical applications, try ForwardX11Trusted instead:

$ ssh -Y user@host

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. See xhost(1) 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.

Tip: Here are some useful links for troubleshooting X11 Forwarding issues.

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

Multiplexing

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 sshd listen additionally on one of the whitelisted ports:

/etc/ssh/sshd_config
Port 22
Port 443

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 sslh, which listens on the multiplexed port and can intelligently forward packets to many services.

Speeding up SSH

Tip: If you intend to use SSH for SFTP or SCP, installing openssh-hpn-gitAUR can significantly increase throughput.[7]

There are several client configuration options which can speed up connections either globally or for specific hosts. See ssh_config(5) for full descriptions of these options.

You can make all sessions to the same host share a single connection using these options:

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

where ~/.ssh/sockets can be any directory not writable by other users.

Another option to improve speed is to enable compression with the Compression yes option or the -C flag.

Warning: ssh(1) 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 bypassing IPv6 lookup using the AddressFamily inet option or -4 flag.

Mounting a remote filesystem with SSHFS

Please refer to the Sshfs article to use sshfs to mount a remote system - accessible via SSH - to a local folder, so you will be able to do any operation on the mounted files with any tool (copy, rename, edit with vim, etc.). Using sshfs instead of shfs is generally preferred as a new version of shfs has not been released since 2004.

Keep alive

Your ssh session will automatically log out if it is idle. To send a "keep alive" signal to the server every 120 seconds add the ServerAliveInterval 120 option to your client configuration. See also the ServerAliveCountMax and TCPKeepAlive options.

Conversely, to keep incoming connections alive, set the ClientAliveInterval option in your server configuration.

Automatically restart SSH tunnels with systemd

systemd can automatically start SSH connections on boot/login and restart them when they fail. This makes it a useful tool for maintaining SSH tunnels.

The following service can start an SSH tunnel on login using the connection settings in your ssh config. If the connection closes for any reason, it waits 10 seconds before restarting it:

~/.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

Then enable and start the user service. See #Keep alive for how to prevent the tunnel from timing out. If you wish to start the tunnel on boot, you will need to rewrite the unit as a system service.

Autossh - automatically restarts SSH sessions and tunnels

When a session or tunnel cannot be kept alive, for example due to bad network conditions causing client disconnections, you can use autossh to automatically restart them.

Usage examples:

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

Combined with sshfs:

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

Connecting through a SOCKS-proxy set by Proxy settings:

$ 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 passphrase 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.

Run autossh automatically at boot via systemd

If you want to automatically start autossh, you can create a systemd unit file:

/etc/systemd/system/autossh.service
[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.

Remember to start and/or enable the service afterwards.

You may also need to disable ControlMaster e.g.

$ ExecStart=/usr/bin/autossh -M 0 -o ControlMaster=no -NL 2222:localhost:2222 -o TCPKeepAlive=yes foo@bar.com
Tip: It is also easy to maintain several autossh processes, to keep several tunnels alive. Just create multiple service files with different names.

Troubleshooting

Checklist

Check these simple issues before you look any further.

  1. The config directory ~/.ssh and its contents should be accessible only by your user (check this on both the client and the server):
    $ chmod 700 ~/.ssh
    $ chmod 600 ~/.ssh/*
    $ chown -R $USER ~/.ssh
    
  2. Check that the client's public key (e.g. id_rsa.pub) is in ~/.ssh/authorized_keys on the server.
  3. Check that you did not limit SSH access with AllowUsers or AllowGroups in the server config.
  4. Check if the user has set a password. Sometimes new users who have not yet logged in to the server do not have a password.
  5. Restart sshd and logout/login on both client and server.

SSH connection hangs after poweroff/reboot

SSH connections hang after poweroff or reboot if systemd stops the network before sshd. To fix this, change the After statement for user sessions:

# systemctl edit systemd-user-sessions.service
[Unit]
After=network.target

Connection refused or timeout problem

Port forwarding

If you are behind a NAT mode/router (which is likely unless you are on a VPS or publicly addressed host), make sure that your router is forwarding incoming ssh connections to your machine. Find the server's internal IP address with $ ip addr and set up your router to forward TCP on your SSH port to that IP. portforward.com can help with that.

Is SSH running and listening?

$ ss -tnlp

If the above command do not show SSH port is open, SSH is NOT running. Check /var/log/messages for errors etc.

Are there firewall rules blocking the connection?

Iptables may be blocking connections on port 22. Check this with:

# iptables -nvL

and look for rules that might be dropping packets on the INPUT chain. Then, if necessary, unblock the port with a command like:

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

For more help configuring firewalls, see firewalls.

Is the traffic even getting to your computer?

Start a traffic dump on the computer you are 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.).

Your ISP or a third party blocking default port?

Note: Try this step if you know you are not running any firewalls and you know you have configured the router for DMZ or have forwarded the port to your computer and it still does not work. Here you will find diagnostic steps and a possible solution.

In some cases, your ISP might block the default port (SSH port 22) so whatever you try (opening ports, hardening the stack, defending against flood attacks, et al) ends up useless. To confirm this, create a server on all interfaces (0.0.0.0) and connect remotely.

If you get an error message comparable to this:

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

That means the port is not being blocked by the ISP, but the server does not run SSH on that port (See security through obscurity).

However, if you get an error message comparable to this:

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

That means that something is rejecting your TCP traffic on port 22. Basically that port is stealth, either by your firewall or 3rd party intervention (like an ISP blocking and/or rejecting incoming traffic on port 22). If you know you are not running any firewall on your computer, and you know that Gremlins are not growing in your routers and switches, then your ISP is blocking the traffic.

To double check, you can run Wireshark on your server and listen to traffic on port 22. Since Wireshark is a Layer 2 Packet Sniffing utility, and TCP/UDP are Layer 3 and above (see IP Network stack), if you do not receive anything while connecting remotely, a third party is most likely to be blocking the traffic on that port to your server.

Diagnosis

Install either tcpdump or Wireshark with the wireshark-cli package.

For tcpdump:

# tcpdump -ni interface "port 22"

For Wireshark:

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

where interface is the network interface for a WAN connection (see ip a to check). If you are not receiving any packets while trying to connect remotely, you can be very sure that your ISP is blocking the incoming traffic on port 22.

Possible solution

The solution is just to use some other port that the ISP is not blocking. Open the /etc/ssh/sshd_config and configure the file to use different ports. For example, add:

Port 22
Port 1234

Also make sure that other "Port" configuration lines in the file are commented out. Just commenting "Port 22" and putting "Port 1234" will not solve the issue because then sshd will only listen on port 1234. Use both lines to run the SSH server on both ports.

Restart the server sshd.service and you are almost done. You still have to configure your client(s) to use the other port instead of the default port. There are numerous solutions to that problem, but let us cover two of them here.

Read from socket failed: connection reset by peer

Recent versions of openssh sometimes fail with the above error message when connecting to older ssh servers. This can be worked around by setting various client options for that host. See ssh_config(5) for more information about the following options.

The problem could be the ecdsa-sha2-nistp*-cert-v01@openssh elliptical host key algorithms. These can be disabled by setting HostKeyAlgorithms to a list excluding those algorithms.

If that does not work, it could be that the list of ciphers is too long. Set the Ciphers option to a shorter list (fewer than 80 characters should be enough). Similarly, you can also try shortening the list of MACs.

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.

"Terminal unknown" or "Error opening terminal" error message

If you receive the above errors upon logging in, this means the server does not recognize your terminal. Ncurses applications like nano may fail with the message "Error opening terminal".

The correct solution is to install the client terminal's terminfo file on the server. This tells console programs on the server how to correctly interact with your terminal. You can get info about current terminfo using $ infocmp and then find out which package owns it.

If you cannot install it normally, you can copy your terminfo to your home directory on the server:

$ ssh myserver mkdir -p  ~/.terminfo/${TERM:0:1}
$ scp /usr/share/terminfo/${TERM:0:1}/$TERM myserver:~/.terminfo/${TERM:0:1}/

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

TERM hack

Warning: This should only be used as a last resort.

Alternatively, you can simply set TERM=xterm in your environment on the server (e.g. in .bash_profile). This will silence the error and allow ncurses applications to run again, but you may experience strange behavior and graphical glitches unless your terminal's control sequences exactly match xterm's.

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

If you are seeing this error in your sshd logs, make sure you have set a valid HostKey

HostKey /etc/ssh/ssh_host_rsa_key

id_dsa refused by OpenSSH 7.0

OpenSSH 7.0 deprecated DSA public keys for security reasons. If you absolutely must enable them, set the config option PubkeyAcceptedKeyTypes +ssh-dss (http://www.openssh.com/legacy.html does not mention this).

No matching key exchange method found by OpenSSH 7.0

OpenSSH 7.0 deprecated the diffie-hellman-group1-sha1 key algorithm because it is weak and within theoretical range of the so-called Logjam attack (see http://www.openssh.com/legacy.html). If the key algorithm is needed for a particular host, ssh 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

The best resolution for these failures is to upgrade/configure the server to not use deprecated algorithms. If that is not possible, you can force the client to reenable the algorithm with the client option KexAlgorithms +diffie-hellman-group1-sha1.

See also