Skip to content
ImagineWorld

Secure Remote Access with SSH

node_idnode-book_the-software-developer-s-guide-to-linux_chapter-11-secure-remote-access-with-ssh
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleSecure Remote Access with SSH
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 11 — Secure Remote Access with SSH

Section titled “Chapter 11 — Secure Remote Access with SSH”

The Secure Shell Protocol (SSH) is a Swiss Army knife – a do-everything tool – for creating secure connections and tunneling data through them. During your career, you’ll use SSH for a bit of everything:

  • Securely logging in to a remote system
  • Cloning your private Git repository
  • Transferring files from your laptop to a server, or between servers
  • Mapping a web service behind a VPN to a local port on your laptop so that someone on your home network can use it
  • Various other tasks that involve tunneling traffic or sending files through multiple network connections

In this chapter, we’ll give you everything you need to be comfortable with the basics. You’ll learn how public key cryptography works, which is essential to being able to reason about these kinds of tools and their usage. You’ll create SSH keys and use them to log in to a remote server. To cement the basics, we’ve even created a small project for you, where you’ll set up key-based logins for a remote host that you work with often.

For those times when you inevitably have issues when using SSH, we’ve collected some of the most common SSH errors we see in the wild. You’ll learn what the most common error messages indicate, and how to use SSH’s built-in “debug” option to troubleshoot your way out of them.

In this chapter, we’ll cover the following topics:

  • A primer in public key cryptography
  • Message encryption
  • Message signing
  • SSH keys
  • Converting SSH2 keys to the OpenSSH format
  • File transfer
  • SSH tunneling
  • The configuration file

Let’s jump right in with the very basics of what you need to understand about public key cryptography so that the rest of this chapter doesn’t just sound like obscure black magic to you.

Depending on what path your career has taken, you may have already come across the topic of public key cryptography. While cryptography is its own field, and this is not a book about cryptography, it is important to have an understanding of the basics. Thankfully, the core concepts are very simple and will get you far. We’ll make this section as short as possible, and then dive right into the commands you need to configure and use secure access with SSH.

Public key cryptography is a system that uses two separate keys, called the public key and the private key. Together, these make up what is called a key pair. As the names imply, the public key is a key that can be shared with everyone, while the private key is supposed to remain private at all costs.

Once you’ve created a key pair, any message that has been encrypted using that key pair’s public key can be decrypted with the corresponding private key.

Imagine a person named Alice, who wants to send Bob an encrypted message. To do this, Alice downloads Bob’s public key and uses it to encrypt the message. Alice then sends the encrypted message to Bob. As he owns the matching private key, Bob will be able to decrypt and read the message. Even if someone else sees the encrypted message, they won’t be able to decrypt and read it because only Bob has the private key.

For this reason, it is important to never share your private key with a third party. Doing so would be a breach of security.

There is another way to use these two keys: they can be used to sign a message. “Signing” a message is a way to cryptographically prove that a message was really written by the person owning the key. This makes use of the fact that while a message encrypted with the public key can be decrypted with the private key, the reverse is also true – a message encrypted with the private key can be decrypted using the public key.

When Alice wants to sign a message, the private key can be used to encrypt the message (or a cryptographically secure hash of the message). Everyone who possesses Alice’s public key can use it to decrypt the message and, if it works, knows that it must have been encrypted with Alice’s private key.

Both mechanisms, encryption and signing, are often used together. Additionally, signatures themselves are frequently used to ensure security (by verifying authorship) when you’re downloading software, for example, through package managers or app stores.

It’s worth noting that these core public-key encryption and signing mechanisms are used for everything from encrypting emails to securing HTTPS web traffic to thousands of other things in the modern world. In other words, Alice and Bob don’t have to be people; they can be computers, services, and so on.

Now that you’ve seen the basic cryptographic building blocks that SSH takes advantage of to secure your remote access, you’re ready to make practical use of all of this fancy technology!

One of the first things you are likely to do when it comes to SSH is create your very own key pair. This will allow you to authenticate to an SSH server. A classic command for creating a key pair is this:

ssh-keygen -t ed25519 -C 'John Doe <[email protected]>'

This will create an ed25519 (a modern elliptic curve cryptography algorithm) key pair using John Doe <[email protected]> as a comment. Comments are like the comments you know from programming languages, in that they can be any string of text and won’t interfere with anything on a functional level. In the case of SSH, this comment will be appended to your public key, making it easier to distinguish keys when they are uploaded to a server, for example, in an authorized_keys file. Later in this chapter, we’ll dive deeper into the authorized_keys files and how to use them to set up seamless, secure access to remote servers.

After you run this command, OpenSSH will ask you a few questions about where to store the key files it creates and what password you’d like to use to encrypt the private key. Since this will be the key used to access remote systems, make sure to set a strong password.

Note

By default, keys will be placed in your ~/.ssh directory.

Now that you’ve created a key pair, it’s time to reiterate the most important practical point: never, ever share the private key. Doing so would allow a third party to impersonate you. No service should ever ask you to share your private key. The public key, which is supposed to be shared and is safe to make public, will contain a .pub suffix, so you can tell the difference.

Thankfully, the contents of these files look very different, so if you ever get confused, you can peek at them to see which is which:

  • The public key is in the format of <algorithm> <key> <comment>.
  • The private key starts with a line like -----BEGIN OPENSSH PRIVATE KEY-----, followed by the key and a similar ending line.

Be careful never to overwrite these key files, and ensure that you have stored both of them in a secure backup. Again, your password manager is a good choice for this. Many password managers even have a specific option to store private key files or generic text.

For personal use – on your laptop, for example – you’ll always want to encrypt your private key (by specifying a password during key creation), and then never share it, as mentioned before.

However, there are some situations where it’s okay to break these rules – specifically when setting up keys for automated systems to use. If you want your build server to authenticate to GitHub before checking out your code base, you’d likely use a key pair whose private key is not encrypted (unless you want to have to manually type in that password every time your build service runs).

Machine-to-machine authentication and encryption are great reasons to use cryptographic key pairs. Just be sure to always make dedicated, single-purpose key pairs for jobs like these, and do not reuse or share those key pairs across machines or services.

Logging in to a remote system using SSH-based authentication looks similar to this:

user is the username that you want to log in as, and example.org is a stand-in for any remote system you’d like to connect to. This is often just an IP address, as opposed to a fully qualified domain name.

If you’re logging in with an SSH key, or you need to specify a specific key (identity, or -i), it’ll look like this:

ssh -i ~/.ssh/id_ecdsa [email protected]

When accessing an SSH server that you have never connected to before, you will be presented with the fingerprint of the remote server. This allows you to make sure that the server you are talking to is indeed the one you intend to connect to and that no man-in-the-middle attack is taking place. You should make sure this is correct.

Once you type yes and mark that fingerprint as trusted, it will be saved to a file. Should it ever change – for example, if someone sets up a malicious server at the same IP address that your trusted server was using before – you will be notified by your SSH client, and authentication will not be possible.

After you mark the server as trusted, your local client and the server will negotiate which form of authentication to use. OpenSSH offers a wide variety of options, with the two most common ones involving a password or a key pair. Depending on which is chosen, OpenSSH will ask you to enter the password (or the password to decrypt your private key). Once the authentication step succeeds, you will be logged in.

Practical project: Set up a key-based login to a remote server

Section titled “Practical project: Set up a key-based login to a remote server”

Presuming you have access to a long-running Linux server that you want to allow key-based login on, follow these steps.

Step 1: Open your terminal on the SSH client (not the server)

Section titled “Step 1: Open your terminal on the SSH client (not the server)”

You’ll be using your local command-line environment for the rest of these steps.

If you’ve already set up a key pair because you were following along earlier in this chapter, good for you! You can skip this step.

If you don’t yet have an SSH key pair, create one by typing the following command and hitting Enter:

ssh-keygen -t ed25519
# ensure that the public key is not world-readable
chmod 600 ~/.ssh/id_ed25519

As mentioned before, we strongly recommend adding a passphrase for extra security.

Step 3: Copy the public key to your server

Section titled “Step 3: Copy the public key to your server”

After generating the keys, you’ll need to place the public key on your server. The public key usually has the extension .pub and by default will be located in your ~/.ssh directory.

You can manually copy it to the remote user’s authorized_keys file (a file that contains all authorized public keys for that user, one key per line), or you can condense all of those actions into a single command using the ssh-copy-id program:

ssh-copy-id [email protected]

Replace username with your user on the remote server and remote_server_address with the server’s IP address or domain name.

This command will ask for your user password on the remote server. After entering it, the public key will be appended to the ~/.ssh/authorized_keys file of the remote user’s home directory. This allows you to log in and execute commands on the remote machine without being prompted for a password.

Now try logging in to the server:

If everything worked, you should be logged in without being asked for a password (unless you set up a passphrase for your SSH key). Instead of using a small password string that might be guessed by an attacker, you’re now using a much more secure cryptographic key to authenticate yourself.

Welcome to the wonderful world of secure, password-free SSH access!

Converting SSH2 keys to the OpenSSH format

Section titled “Converting SSH2 keys to the OpenSSH format”

When not using a Unix-based operating system, you’ll often come across the SSH2 public key format. PuTTY is probably the most famous software using this format and many people using Windows use it to connect via SSH. To connect to an SSH File Transfer Protocol (SFTP) server, Git repository, or other system that uses the OpenSSH key format, you need to convert an SSH2 public key into the OpenSSH format. Here is how to convert it.

We start with an SSH2-formatted public key that looks like this:

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20160402"
AAAAB3NzaC1yc2EAAAABJQAAAgEAiL0jjDdFqK/kYThqKt7THrjABTPWvXmB3URI
pGKCP/jZlSuCUP3Oc+IxuFeXSIMvVIYeW2PZAjXQGTn60XzPHr+M0NoGcPAvzZf2
u57aX3YKaL93cZSBHR97H+XhcYdrm7ATwfjMDgfgj7+VTvW4nI46Z+qjxmYifc8u
VELolg1TDHWY789ggcdvy92oGjB0VUgMEywrOP+LS0DgG4dmkoUBWGP9dvYcPZDU
F4q0XY9ZHhvyPWEZ3o2vETTrEJr9QHYwgjmFfJn2VFNnD/4qeDDHOmSlDgEOfQcZ
Im+XUOn9eVsv//dAPSY/yMJXf8d0ZSm+VS29QShMjA4R+7yh5WhsIhouBRno2PpE
VVb37Xwe3V6U3o9UnQ3ADtL75DbrZ5beNWcmKzlJ7jVX5QzHSBAnePbBx/fyeP/f
144xPtJWB3jW/kXjtPyWjpzGndaPQ0WgXkbf8fvIuB3NJTTcZ7PeIKnLaMIzT5XN
CR+xobvdC8J9d6k84/q/laJKF3G8KbRGPNwnoVg1cwWFez+dzqo2ypcTtv/20yAm
z86EvuohZoWrtoWvkZLCoyxdqO93ymEjgHAn2bsIWyOODtXovxAJqPgk3dxM1f9P
AEQwc1bG+Z/Gc1Fd8DncgxyhKSQzLsfWroTnIn8wsnmhPJtaZWNuT5BJa8GhnzX0
9g6nhbk=
---- END SSH2 PUBLIC KEY ----

The goal is to convert it to an OpenSSH public key like the following:

ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAgEAiL0jjDdFqK/kYThqKt7THrjABTPWvXmB3URIpGK
CP/jZlSuCUP3Oc+IxuFeXSIMvVIYeW2PZAjXQGTn60XzPHr+M0NoGcPAvzZf2u57aX3YKaL93cZSBHR
97H+XhcYdrm7ATwfjMDgfgj7+VTvW4nI46Z+qjxmYifc8uVELolg1TDHWY789ggcdvy92oG
jB0VUgMEywrOP+LS0DgG4dmkoUBWGP9dvYcPZDUF4q0XY9ZHhvyPWEZ3o2vETTrEJr9QHYwgjmFf
Jn2VFNnD/4qeDDHOmSlDgEOfQcZIm+XUOn9eVsv//dAPSY/yMJXf8d0ZSm+VS29QShMjA4R+7yh5Wh
sIhouBRno2PpEVVb37Xwe3V6U3o9UnQ3ADtL75DbrZ5beNWcmKzlJ7jVX5QzHSBAnePbBx/fyeP/
f144xPtJWB3jW/kXjtPyWjpzGndaPQ0WgXkbf8fvIuB3NJTTcZ7PeIKnLaMIzT5XNCR+xobvdC8
J9d6k84/q/laJKF3G8KbRGPNwnoVg1cwWFez+dzqo2ypcTtv/20yAmz86EvuohZoWrtoWvkZLCoyxdqO93ymE
jgHAn2bsIWyOODtXovxAJqPgk3dxM1f9PAEQwc1bG+Z/Gc1Fd8DncgxyhKSQzLsfWroTn
In8wsnmhPJtaZWNuT5BJa8GhnzX09g6nhbk=

How to convert the SSH2-formatted key to OpenSSH

Section titled “How to convert the SSH2-formatted key to OpenSSH”

The ssh-keygen command, which we used to create a new key, can also convert it with this very simple command:

ssh-keygen -i -f ssh2.pub > openssh.pub

The command above will take the key from the file ssh2.pub and write it to openssh.pub.

If you just want to look at the OpenSSH key material or have it ready for copying and pasting, then you don’t have to worry about piping stdout into a file (the same command as above, without the last part):

ssh-keygen -i -f ssh2.pub

This will simply display the public key in the OpenSSH format.

A more practical example of this might be converting and appending a coworker’s key to a server’s authorized_keys file. This can be achieved using the following command:

ssh-keygen -i -f coworker.pub >> ~/.ssh/authorized_keys

After this, a coworker using the relevant private key will be able to log in to the system as the user who runs this command.

The other direction: Converting SSH2 keys to the OpenSSH format

Section titled “The other direction: Converting SSH2 keys to the OpenSSH format”

The opposite – converting OpenSSH to SSH2 keys – is also possible. Simply use the -e (for export) flag, instead of -i (for import):

ssh-keygen -e -f openssh.pub > ssh2.pub

When you’re frequently logging in to servers using SSH keys, it can be annoying to have to retype your private key password over and over, every time you connect (or reconnect) to a host. SSH-Agent allows you to store an identity (private key) for a local session – in other words, it lets you decrypt your private key once, and then keep it in memory until you log out or start a new shell session. This means that you add an identity (key pair) once, and get to use it over and over again without re-decrypting your private key.

Note

The SSH Agent doesn’t always run in your local shell session – various IDEs, window managers, desktop managers, and password managers can also run an agent for you. You’ll know this is the case when you only have to enter the password for an identity once.

To add a key to the agent, just use the ssh-add command – the argument is the path to your private key for that identity:

ssh-add ~/.ssh/id_ecdsa

We recommend that you make it a habit to use the –t option, which adds a time limit to how long your keys are kept decrypted in memory. The following command is the same as the one above, except it sets a time limit of 30 seconds, after which the agent will delete the keys from memory:

ssh-add –t 30 ~/.ssh/id_ecdsa

To show which keys have been added to the agent, use the following command:

ssh-add -L

To remove all identities from the SSH agent, use -D:

ssh-add -D

Note

If you’ve added more than three identities to the agent, you may still have to specify -i $YOUR_IDENTITY when logging in via SSH. This is because most servers are configured to reject logins after three incorrect attempts, and SSH will try each of the keys stored in the agent, one by one, when logging in. If the first key doesn’t work, it’ll try the second one, and so on. If the server aborts the login attempt after three tries, you’ll never get to the fourth key in your agent.

You can enable agent forwarding when using SSH to log in to remote machines with -A; however, you should do so sparingly and carefully, for reasons we’ll explain:

ssh -A user@remotehost

After logging in to remotehost with this command, SSH will forward your keys to that host so you can use them to jump to additional hosts from there. The reason we recommend doing this sparingly is that it allows a compromised host to see your private keys, which we’ve hopefully taught you should always stay private, preferably on your machine or, during your wildest moments, in your password manager. In other words, if remotehost has been hacked, then your SSH keys are now compromised.

One final note about security: some Linux desktop environments like GNOME/MATE will keep your SSH key in memory indefinitely when you use and decrypt it once. This happens by default and is a security risk you should be aware of.

Common SSH errors and the -v (verbose) argument

Section titled “Common SSH errors and the -v (verbose) argument”

The -v flag in the SSH command enables verbose mode, which prints out a detailed, step-by-step log of the connection process. This feature is particularly useful for diagnosing common issues such as authentication failures, connection timeouts, and key mismatches. Use it like this:

You’ll receive step-by-step information about each stage of the SSH handshake and connection, making it easier to identify and resolve any issues that may arise.

Here are some of the frequent errors that you might encounter, which verbose output can help you diagnose:

  • Permission Denied (public key/password): This indicates that the server rejected your login attempt. The verbose log will show you which keys were tried, helping you to pinpoint whether the correct key was used or even offered. This is an incredibly common issue when you have more than three key pairs stored on the client, and the server only allows three tries.
  • Connection Timed Out: If the connection is taking too long, you might have a network issue or an incorrect IP address or port. The -v flag will show where the process gets stuck, helping you understand whether the client even reached the server.
  • Connection Refused: This usually means that SSH isn’t running (or reachable) on the target port on the server. The verbose output will clearly indicate that the connection attempt was rejected, helping you focus on firewall rules or SSH server settings.
  • Host Key Verification Failed: The server’s key doesn’t match the one saved in your system’s known_hosts file. The –v flag will show the mismatched keys, at which point you can focus on figuring out why (for example, is there a new server at this IP address or hostname?).
  • Could not resolve hostname: Often related to DNS or network issues.
  • No Route to Host: This suggests network issues, maybe involving firewalls or incorrect routing.
  • Too Many Authentication Failures: The maximum number of authentication attempts has been reached. The verbose mode will show all the methods tried, which may include unwanted or unexpected key offers.
  • Key Load Errors: These usually indicate a problem with the format or permissions of your SSH key. The -v flag will identify which key the SSH client is trying to load, allowing you to check for formatting or permission issues.

Using the –v flag will help you understand what exactly is going wrong and how you might be able to fix it. At the very least, it will help you start looking in the right direction.

In the sections below we will explore the sftp and scp commands for file transfer. Going through a few examples using these commands will help you understand how you can handle files in most situations. That said, we will also cover file transfer without SFTP or SCP, in case they are disabled on the server.

While OpenSSH is frequently used as a way to log in to remote systems, it also allows for file transfer independently of a login session. This is usually accomplished via the SFTP subsystem. Though SFTP resembles File Transfer Protocol (FTP), it is actually a completely custom protocol. Like FTP, SFTP allows authenticated users to transfer files to and from remote servers. Unlike FTP, which is insecure, SFTP’s authentication and file transfers are secure and fully encrypted.

There are many FTP clients that also support SFTP. One famous example is Filezilla, which has an excellent graphical user interface. However, since this is a book about the Linux command line, we will give you a basic overview of how to use SFTP on the command line.

Authentication is nearly identical to ssh:

After this, you’ll be presented with an FTP-style interface. It accepts simpler/modified versions of some shell commands that we have already gone over in previous chapters, and also introduces some new ones. Here are the most common commands:

  • help: lists all commands and gives a short summary
  • ls: lists the contents of a remote directory
  • lls: lists the contents of a local directory
  • cd: changes the remote directory
  • lcd: changes the local directory
  • pwd: displays the remote directory you are in
  • lpwd: displays the local directory you are in
  • get: downloads a file from the remote server
  • put: uploads a file to the remote server
  • chmod: changes the permissions of a remote file or directory
  • chown: changes the owner of a remote file or directory
  • quit, exit, bye: exits SFTP (CTRL + D also works)

The scp command is often a more practical way to upload and download files and directories than sftp. While it was historically independent of SFTP, today it uses the SFTP subsystem. It is meant to work as a replacement for the cp command, except that it allows copying to and from remote servers.

Commands are in the following format:

scp $SOURCE:filepath $DESTINATION:filepath

$SOURCE, $DESTINATION, or both can be remote systems; scp uses the SSH [email protected] syntax that you’ve already seen.

Here is what it looks like in practice:

scp [email protected]:/home/user/my_remote_file /home/user/my_local_file

This will do the following:

  1. Connect to example.org.
  2. Authenticate as user (prompting you for a password unless you’re using SSH keys and the SSH agent).
  3. Copy the file to the local path /home/user/my_local_file.

As you can see, the argument order is the same as for the Linux cp (copy) command.

Reversing the source and destination arguments – uploading a file, instead of downloading it – looks like you might expect:

scp /home/user/my_local_file [email protected]:/home/user/my_remote_file

Just like with cp, you can specify relative paths. The following command will copy the remote file to the current (local) directory:

scp [email protected]:/home/user/my_remote_file .

As with the cp command, it is also possible to recursively copy an entire directory using the -r (recurse, also -R on some systems) flag:

scp -r [email protected]:/home/user/directory local_directory

As with all commands and tools, ssh and scp can also be used in scripts; for example, you can use ssh to quickly back up a database:

ssh [email protected] "pg_dump databasename | gzip -c" > database_backup.sql.gz

If you use clever shell hacks like this in a script, take care to alert on errors; otherwise, the process might just silently remain stuck when it runs into an issue. For development situations, this kind of command can really come in handy.

In some rare situations, you’ll find that SFTP has been disabled on a server and you can only log in to an interactive shell. You still want to transfer a file to the remote system, and while it might be possible to just open a file in an editor, this isn’t always possible (for example, with whole directories or binary files). Here are a few tricks that you can use to still achieve your goal (they all make use of the Unix pipe in combination with an SSH session).

The simplest case is downloading a file from a remote server:

ssh [email protected] "cat /path/to/file" > local_target_file

This command will do the following:

  1. Log in to the server.
  2. Run the command cat /path/to/file on the remote server, which will result in the contents of that file being streamed to stdout.
  3. stdout can then be locally piped into a file of our choice.

Like most well-behaved Unix software, errors and other possibly interfering output will be sent to STDERR, so you do not have to fear that a password prompt will get in the way and corrupt the file content being piped across your SSH tunnel, as an example.

Let’s do something different and upload a whole directory. Since this is potentially quite a lot of data, we will also compress it with the tar program. tar is a command that turns multiple files and/or directories into a single file (an “archive”).

It’s common to add a compression step after archiving – you’ve probably seen files with the tar.gz or tar.bz2 endings, for example. This means that the files have first been archived into a single file with tar, and then compressed using gzip or bzip2:

tar czf - /home/user/directory_to_upload | ssh [email protected] "tar -xvzf -C /home/user/"

Here, we first archive /home/user/directory with tar, turning the result into a stream of bytes.

The - is the target file. In the case that you want to store it immediately instead of streaming it to another program, this would be something like /home/user/directory.tar.gz. As is customary with many Unix commands, a dash symbolizes that this should instead be written to stdout.

This resulting stream will then be piped into the ssh process, which uses it as input (stdin) for a tar command on the remote system, which decompresses and unarchives that stream, writing the resulting directory to /home/user/directory_to_upload.

SSH tunnelling is used to transport data over an SSH connection. In the following sections, we will look at two methods of tunnelling: local forwarding and proxying.

SSH can create secure, encrypted tunnels to remote systems. This functionality is similar to what a VPN provides and can allow you to access services reachable from the remote system.

That’s powerful functionality, and with SSH, it’s actually simple to achieve. All you have to do is specify an additional argument, -L, with the destination and the local port to bind it to when establishing an SSH session.

Imagine a remote system running an HTTP server on port 8080. You want to access it on your laptop, on port 3000. Here is how to accomplish that with a simple command:

ssh -L 3000:localhost:8080 [email protected]

You can now open a browser and visit http://localhost:3000/ to access the web server as if you were opening that browser on the remote system and visiting http://localhost:8080.

The same would be true if you wanted to access a server that you don’t have access to, but the remote server does. Imagine app.example.org is where your web application runs. This web application connects to a database server like PostgreSQL at db.example.org, which is only accessible from the www.example.org internal network. Like most production databases, it’s guarded by a firewall that prevents direct connections from outside.

From a network perspective, it looks like this:

(localhost) ——-> (app.example.org) ——-> (db.example.org)

You might want to use your local psql Postgres client to connect to that database. What you’d do is create a tunnel like this:

ssh -L 5000:db.example.org:5432 [email protected]

This will open a new SSH session to app.example.org, reach out to the DB server from there, and map db.example.org:5432 to localhost:5000.

Now, running psql --port=5000 --host=localhost dbname on your laptop will connect you to the Postgres database at db.example.org:5432, by bouncing through app.example.org to get access.

It is possible to specify host configuration in .ssh/config. This can be helpful in various situations, as it allows you to specify:

  • Custom (friendly) names for hosts
  • The default user to use
  • The port
  • Tunnels to open before connecting
  • Identity files (keys)

Among many other things.

Note

If a server you connect to has a permanent IP address, it can make sense to specify it in your SSH config file to avoid relying on DNS or CDNs during a disaster recovery situation.

SSH configuration files aren’t particularly complicated, so we’ll show you an example here that uses many of the available features:

# Set Defaults for all hosts using the glob character (*)Host *
ServerAliveInterval 30 # Check if the connection is alive every 30 seconds
ForwardAgent yes # Forward SSH agent to the remote host
Compression yes # Enable compression
IdentityFile ~/.ssh/id_rsa # Default identity file
# Specific settings for host "example1.com"
Host example1
HostName example1.com # The real hostname to connect to
User john # Default username for this host
Port 22 # SSH port (default is 22)
IdentityFile ~/.ssh/id_ecdsa # Different identity file for this host
# Settings for another specific host "example2.com"
Host example2
HostName example2.com
User jane
Port 22000 # Different SSH port for this host
IdentityFile ~/.ssh/id_ed25519
# Using a jump host to connect to a host behind a firewall
Host target-behind-fw
HostName 192.168.0.2 # Private IP of the target host
User alice
Port 22
ProxyJump jump-host # Use 'jump-host' as a jump host
# Configuration for the jump host
Host jump-host
HostName jump.example.com # Public IP or domain of the jump host
User jumpuser
Port 22
IdentityFile ~/.ssh/jump_key
# Using a SOCKS proxy to connect to a host
Host proxy-host
HostName proxy-target.com # The real hostname to connect to
User proxyuser
Port 22
ProxyCommand nc -X 5 -x localhost:1080 %h %p # Using SOCKS proxy on localhost port 1080

OpenSSH is a very versatile tool, and we hope that the introduction you received in this chapter has motivated you to experiment and learn more. Just think of everything we’ve covered:

You’ve learned the basics of how public key cryptography works, which is essential to being able to reason about these kinds of tools and their usage. You saw how to create SSH keys and use them for remote shell sessions.

Hopefully, you got some practical experience, too, by following along and setting up key-based logins for a remote host that you work with often. If that remote host happens to be on Amazon Web Services (AWS) or another platform that uses .pem keys, you learned how to convert between key formats (that trick alone is sure to impress your coworkers).

Even if you didn’t run into them yourself, we exposed you to some of the most common SSH errors we see people get stuck on in the wild, and how to track them down with the –v option.

We even covered SSH usage beyond remote interactive shell sessions – file transfers, tunneling network traffic, and setting up custom configurations for different servers. Surprisingly, there’s even more that OpenSSH can do:

  • Encrypt and sign files with ssh-keygen
  • Add two-factor authentication via FIDO/U2F, storing your key on an external device
  • Force certain commands to be run after login, which both limits the attack vector and allows SSH to be an interface to a service

The OpenSSH project provides excellent documentation on its manual pages and on its website. If you have a problem that requires secure connections between machines and you want technology that is battle-tested and proven, OpenSSH is worth checking out. Now go forth and encrypt!