SSH


Secure Shell (SSH) is a protocol for creating an encrypted communications channel between two networked hosts

SSH quickly spread to replace insecure protocols such as telnet, rsh, and rlogin.

OpenSSH

OpenBSD and OpenSSH Portable version

PuTTY

The most popular Microsoft Windows SSH client.

SSH protocol versions

How OpenSSH encryption works

Verifying server keys

View the fingerprint of a server public key from the server

ssh-keygen -lf /etc/ssh/ssh_host_*_key.pub

Rules of thumb

OpenSSH configuration

Basic server configuration

Port <number>

The TCP port the OpenSSH server should run in.

AddressFamily <string>

The TCP/IP version the server should use.

ListenAddress <ip address[:port]>

Many hosts have multiple IP addresses. By default, sshd listens for incoming requests on all of them. If you want limit the IP addresses that sshd attaches to, use this option.

Protocol <number[,number...]>

The SSH protocol to support. This can be 1, 2, or 1,2.

The path to the file containing the banner message.

PrintMotd <yes|no>

Whether to print /etc/motd after a client successfully connects.

PrintLastLog <yes|no>

Whether to print information about the last time the user logged in to the client, after it connects successfully.

LoginGraceTime <string>

How much time a user has to connect to the server. If the user fails to connect, then the connection is terminated.

Example:

MaxAuthTries <number>

The maximum amount of times a user can try to authenticate before closing the connection.

UseDNS <yes|no>

Verify the forward and reverse DNS names for a client’s IP address, to reject potentially malicious connection attempts where the client spoofs the DNS name.

For example:

If this option is set:

PidFile <path>

The path to store the PID file.

ChrootDirectory <string|none>

This option can take %h (host) and %u (username) macros.

Server logging

OpenSSH makes use of syslog.o

SyslogFacility <string>

Any valid syslog facility.

LogLevel <string>

This can be:

These may violate privacy:

User access control

You can use the following options, which take a comma-delimited list of identifiers, to tweak user access permissions:

These options may also accept an IP or host name after a @ sign to further control where the allowed users should be permitted to log in.

For example:

AllowUsers johndoe@192.0.2.0/25

Advices

Rules

Match blocks

Sometimes you need to dynamically set OpenSSH server options based on a certain pattern. You can use match statements for this:

Match <criteria> <value>

Anything that comes after the match statement applies if the conditions are true, until the next match statement or, the end-of-file mark.

Available criterias:

For example:

match User johndoe,janedoe
<rule 1>
<rule 2>
<rule 3>

match Group mygroup
<rule 1>
<rule 2>
<rule 3>

match Group mygroup Address 192.168.0.*
<rule 1>
<rule 2>
<rule 3>

OpenSSH server snippets

Run sshd with a custom configuration file

/usr/sbin/sshd -f path/to/sshd_config -p <port>

Run sshd in debugging mode

This will make sshd print a lot of verbose debugging information of everything is happening on the server.

/usr/sbin/sshd -d

Basic client configuration

Port <number>

The port to use by default.

User <string>

The username to connect as.

Host <string...>

Set a host for which the following settings apply, until a new Host keyword is encountered, or the end-of-file marked is reached.

For example:

Host *.example.com
  Port 2222

Host 192.168.0.* foobar.com
  Port 24

AddressFamily <inet|inet6>

Force a connection over IPv4 (inet) or IPv6 (inet6).

StrictHostKeyChecking <yes|no|ask>

Whether to require users to manually verify hosts and add them to known_hosts.

Setting it to no means that ssh will blindly trust any server.

HashKnownHosts <yes|no>

Whether to hash the entries of the known_hosts host file, so no-one can read them in plain-text.

AllowTcpForwarding <yes|no>

Whether to allow port forwarding or not.

GatewayPorts <yes|no|clientspecified>

This option controls whether a client can bind a forwarded port to any server address other than the localhost.

If set to “yes” all forwarded ports are bound to the network-facing IP address.

If set to “clientspecified,” the software will accept any configuration given by the SSH client.

PermitOpen <host:port...>

Restrict which TCP ports and addresses can receive forwarding.

For example:

PermitOpen localhost:80 localhost:221

Keeping SSH connections open

Server

ClientAliveInterval 90
ClientAliveCountMax 5

Client

ServerAliveInterval 90
ServerAliveCountMax 4

OpenSSH client snippets

Run ssh in debugging mode

ssh -v <host>

Pass a custom configuration file

ssh -F path/to/config <host>

Manually pass a configuration option

ssh -o <key>=<value> <host>

For example:

ssh -o Port=2222 <host>

Connect with a custom SSH key

ssh -i path/to/key <host>

Add a key to the ssh agent

ssh-add path/to/key

Copying files using scp

Copy files from two OpenSSH servers

scp source-hostname:<file> destination-hostname:<file>

Recursively copy files from two OpenSSH servers

scp -rf source-hostname:<file> destination-hostname:<file>

Copy files from the local file-system to an OpenSSH server

scp <file> destination-hostname:<file>

Copy files from an OpenSSH server to the local file-system

scp source-hostname:<file> file>

Managing files with sftp

sftp stands for SSH File Transfer Protocol, and its basically a reimplementation of the FTP protocol using SSH.

Open an FTP-like prompt

sftp <host>

Allow sftp-only users

For cases where some users need to copy files, but don’t need interactive sessions.

Match Group <group>
  ChrootDirectory %h
  ForceCommand internal-sftp
  AllowTcpForwarding no

Generate server keys

On newer systems

ssh-keygen -A

On older systems

ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N ''
ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key -N ''
ssh-keygen -t ecdsa -f /etc/ssh/ssh_host_dsa_key -N ''

Generate client keys

The following command will allow you pick all the options interactively:

ssh-keygen

Disable server passwords authentication

ChallengeResponseAuthentication no
PasswordAuthentication no
PubkeyAuthentication yes

Agent forwarding

If you ssh to host foo, and need to copy a file from foo to bar, you will need your private SSH keys in foo in order to access bar, which is a security issue.

You can enable agent forwarding to route private keys between hosts.

Server configuration

AllowAgentForwarding yes

Client configuration

ForwardAgent yes

X11 forwarding

Server configuration

X11Forwarding yes

Client configuration

Basic X11 forwarding (more secure)

ForwardX11 yes

Trusted X11 forwarding (less secure)

ForwardX11Trusted yes
ForwardX11 no

Host foo
  ForwardX11 yes
  ForwardX11Trusted yes

It is recommended to use ssh CLI options to enable X11 forwarding when you need it, instead of always enabling it for all connections to certain hosts:

Basic X11 forwarding

ssh -X <host>

Trusted X11 forwarding

ssh -Y <host>

You can check if X11 forwarding was successfull by checking the value of the DISPLAY environment variable, which will be undefined if X11 forwarding didn’t work.

Directly run an X11 program

The -f option tells ssh to go to the background after executing the command.

ssh -f <host> <x11-program>

Port forwarding

To create a background process that does the forwarding, do:

ssh -f -N <forwarding options> <host>

Local port forwarding

Bind a port of a server to a port of your local machine.

ssh -L localIP:localport:remoteIP:remoteport hostname

Or add an entry to ssh_config:

LocalForward client-IP:client-port server-IP:server-port

Remote port forwarding

Bind a port of your local machine to a port of a server.

ssh -R remoteIP:remoteport:localIP:localport hostname

Or add an entry to ssh_config:

RemoteForward client-IP:client-port server-IP:server-port

Dynamic port forwarding

Setups a generic gateway that can carry any TCP/IP traffic between two machines.

ssh -D localaddress:localport hostname

Or add an entry to ssh_config:

DynamicForward host:port

The authorized_keys file

Contains entries in the following standard form:

You can pass additional keywords and instructions at the beginning of these lines for more finer control. Separate multiple keywords by commas.

command="<command>"

Whenever someone logs in using the key, run the specified command.

environment="<name>=<value>"

Whenever someone logs in using the key, set the specified environment variable.

from="<ssh pattern>"

Only allow logins from a certain SSH pattern. For example:

from="192.168.0.1/25" ssh-rsa ... hostname

no-agent-forwarding

Disables agent forwarding.

no-port-forwarding

Disables port forwarding.

no-X11-forwarding

Disables X11 forwarding.

Key-pair authentication

OpenSSH servers keep a list of “trusted” public keys in a file called $HOME/.ssh/authorized_keys. This file contains a public key per line.

Appending entries to authorized_keys

Its recommended to:

  1. Copy the public key using scp or sftp
  2. Concatenate it to authorized_keys using cat
cat id_rsa.pub >> $HOME/.ssh/authorized_keys

This is to avoid any silly copy-pasting issues.

Host key cache

The OpenSSH client records approved keys in $HOME/.ssh/known_hosts.

The structure of each line is the following:

@cert-authority marker

An entry that starts with this comment indicates that the host key is for a certification authority.

References