How to Use The SSH Config File

January 19, 2023

Introduction

The SSH protocol creates a secure connection between two remote machines. An SSH config file helps easily configure the default values for these connections and enables efficient streamlining of SSH connections.

This article explains how to use SSH config files to manage SSH connections.

How to Use The SSH Config File

Prerequisites

  • Access to the terminal (CTRL+Alt+T).
  • Access to a text editor, such as nano or Vim.
  • A remote server to test connections.

What are SSH Config Files?

SSH configuration files are a powerful tool for automating SSH connections. The default location of a user-specific config file is in ~/.ssh/config, whereas the system-wide configuration file for all users is in /etc/ssh/ssh_config. Both file locations should stay unchanged.

SSH config file local and global locations cmd output

A config file is a plain text file with various SSH connection options. Use any text editor to open, read, or edit a config file.

How are SSH Config Files Used?

When an SSH config file is in the appropriate location, run an ssh command with the correct parameters to read the options specified in the config file.

For example, if an SSH config file contains an example Host section like the following:

Host my-website.com
    HostName my-website.com
    User my-user
    IdentityFile ~/.ssh/id_rsa

This ssh command connects to the remote host:

ssh my-website.com

The command applies the options for the given HostName of the server, such as the User and IdentityFile. The configuration file contains default connection information for a host and avoids having to enter connection details manually.

A chain of multiple host options and wildcards enables the creation of default values for all servers or lets you add specific parameters for some servers.

How to Create SSH Config Files?

To create an SSH config file, do the following:

1. Open the terminal (CTRL+Alt+T).

2. Navigate to the .ssh directory:

cd ~/.ssh

Note: If the directory does not exist, create it with the mkdir command:

mkdir ~/.ssh

3. Use a text editor to create and open the config file. For example, if you use nano, run:

nano config

The editor creates and opens the file for editing.

4. After filling out the file with information, close nano and save the changes.

5. Give read and write permissions to the current user only:

chmod 600 ~/.ssh/config

The file requires strict permissions due to abuse potential.

The sections below explain how to format the SSH config file and all the available parameters.

Format of the SSH Config File

SSH config files follow a specific format to work correctly. An example config file looks like the following:

Host hostname_1
    PARAMETER argument
    PARAMETER argument

Host hostname_2
    PARAMETER argument

Host *
    PARAMETER argument
SSH config sample file structure

The SSH config file is divided into Host sections with specific configuration options for every host. The argument is the exact hostname, IP address, or a match pattern.

Use whitespace as a separator between parameters and arguments or an equals sign (=). If the value contains whitespaces, encase the string between quotation marks ("). Use a comma-separated list for multiple arguments.

The following characters help define different patterns:

  • An asterisk (*) matches zero or more characters. For example, Host *.com matches any host ending in the .com domain set, whereas Host * matches any host.
  • A question mark (?) matches exactly one character. For example, 192.168.1.? matches all hosts in 192.168.1.[0-9] range.
  • An exclamation mark (!) negates a pattern. For example, !192.168.1.1, 192.168.1.*

Empty lines and lines starting with the hash sign (#) are comments. SSH ignores these lines and uses the first obtained values when searching through the config file. Place host-specific information near the beginning of the file and general default information near the end.

Parameters for SSH Config Files

The SSH config file offers many parameters to configure SSH connections. Below is a brief description of all the available parameter keywords and their functionality.

Note: The parameters and arguments are case-sensitive.

AddressFamily

The AddressFamily parameter sets the address family to use when connecting via SSH. Possible arguments are inet (IPv4 only), inet6 (IPv6 only), or any.

BatchMode

The BatchMode parameter controls whether to prompt for a password or not. The value is set to no by default and asks to enter a password.

Set the argument to yes if using SSH in scripts.

BindAddress

The BindAddress parameter helps specify the bind address in a multi-address system. If the UserPrivilegedPort value is yes, the option does not work.

ChallengeResponseAuthentication

The ChallengeResponseAuthentication parameter controls whether to challenge-response authentication when using SSH to connect to a server. The default value is yes.

CheckHostIP

The CheckHostIP parameter tells SSH whether to perform additional checks on the host IP address in the known_hosts file. The parameter allows SSH to detect host key changes. By default, the value is yes.

Cipher

Cipher is a protocol version 1 parameter for stating the cipher type for encrypting sessions. Supported types are blowfishdes, and 3des (default).

Ciphers

The Ciphers parameter states the cipher type for encrypting sessions in protocol version 2. The available ciphers and default values are:

aes128-ctr, aes192-ctr, aes256-ctr, arcfour256, arcfour128, 
aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, aes192-cbc, aes256-cbc, arcfour

Provide multiple ciphers in a comma-separated list.

ClearAllForwardings

The parameter controls whether to clear all dynamic, local, and remote port forwarding from the command line or configuration file. The default value for ClearAllForwardings is no.

When running SSH from the command line, clear any preset configuration using the parameter.

Compression

The Compression parameter controls whether to use compression or not. The default value is no.

CompressionLevel

The CompressionLevel parameter sets the compression amount if the Compression parameter is yes. The level is an integer between 1 (fastest, worst) and 9 (slowest, best), with level 6 as default. The parameter applies to protocol version 1 only.

ConnectionAttempts

The ConnectionAttempts parameter controls how many connection attempts to try before exiting. One try happens per second, and the default number of attempts is 1. Add the parameter to a script if attempts sometimes fail.

ConnectTimeout

The ConnectTimeout parameter defines the connection timeout in seconds when connecting to an SSH server. The default timeout value is the system TCP timeout.

ControlMaster

The ControlMaster parameter allows sharing a connection through the same network. The parameter enables the following arguments:

  • yes - Enables listening on a control socket provided in ControlPath.
  • no - Disables listening but still allows connecting through the ControlPath through the master's network connection (default).
  • ask - Listens for connections and requires confirmation. If the ControlPath does not open, SSH continues without connecting to the master connection.
  • auto - Allows opportunistic multiplexing and creates a new connection if it does not exist.
  • autoask - Combines the ask and auto options.

ControlPath

The ControlPath parameter contains the information for the control socket in shared connections. The none argument disables connection sharing. If providing a path, the following substitutions are available:

  • %l - The local hostname.
  • %h - The target hostname.
  • %p - The connection port.
  • %r - The remote login username.

The minimum recommendation is %h, %p, and %r to ensure connections have unique identifiers.

DynamicForward

The DynamicForward parameter enables dynamic TCP port forwarding over the secure channel. The format is bind_address:port or bind_address/port.

Use localhost as the bind address to bind the port for local use or * to make the port available from all interfaces.

EnableSSHKeysign

The EnableSSHKeysign parameter in the global SSH configuration file (/etc/ssh/ssh_config) starts a program to generate digital signatures for host-based authentication. The available arguments are yes or no.

EscapeChar

The EscapeChar parameter defines the escape character. The default escape character is a tilde (~). Use none to turn off escape characters.

ExitOnForwardFailure

The ExitOnForwardFailure parameter indicates whether to terminate the connection if port forwarding fails. The possible arguments are yes or no (default).

ForwardAgent

The ForwardAgent parameter controls whether an authentication agent forwards to the remote machine. The default value is no. Enable the option with caution since users who can bypass file permissions can gain access to the local agent.

ForwardX11

The ForwardX11 parameter controls X11 (windowing system) forwards to the remote machine. The value is no by default and disallows forwarding X11 controls.

Users who bypass file permissions and have enabled ForwardX11Trusted can perform keystroke monitoring and other potentially unwanted tasks when the parameter value is yes.

ForwardX11Trusted

The ForwardX11Trusted parameter enables complete control over X11 clients to the original display. The default value is no, and the xauth token expires after twenty minutes for X11 clients. Enable the option with caution because it lifts all restrictions.

GatewayPorts

The GatewayPorts parameter defines whether remote hosts can connect to local forwarded ports. The default value is no, and the local forwarded ports bind to the loopback address when disabled.

GlobalKnownHostsFile

The GlobalKnownHostsFile parameter allows specifying a different location for the global host key file. The default location is /etc/ssh/ssh_known_hosts.

GSSAPIAuthentication

The GSSAPIAuthentication parameter is a protocol version 2 option that controls whether GSSAPI is enabled. The GSSAPI provides access to various security services, and by default, the parameter is disabled and set to no.

GSSAPIKeyExchange

The GSSAPIKeyExchange parameter is a protocol version 2 option that enables key exchange based on GSSAPI and is set to no by default. The server does not need a host key when the parameter value is yes.

GSSAPIClientIdentity

The GSSAPIClientIdentity parameter specifies the client identity SSH uses for GSSAPI. The parameter has no client identity by default, so SSH uses the default identity.

GSSAPIDelegateCredentials

The GSSAPIDelegateCredentials parameter controls whether to forward credentials to the server. The default value is no, and no credentials are delegated to the server.The parameter only works for protocol version 2.

GSSAPIRenewalForcesRekey

The GSSAPIRenewalForcesRekey parameter triggers rekeying the SSH connection if GSSAPI credentials renew. The parameter is no by default.

GSSAPITrustDns

The GSSAPITrustDns parameter controls whether to securely trust the DNS to normalize the host's name. The default argument value is no, and the hostname provided through the command line passes to the GSSAPI as is. The parameter is available for protocol version 2.

HashKnownHosts

The HashKnownHosts parameter controls whether to hash known host entries in the ~/.ssh/known_hosts file. SSH uses the hashed values as usual while not disclosing the file's contents.

By default, the parameter is set to no. Change the value to yes to hash all future entries. Old entries remain unchanged.

HostbasedAuthentication

The HostbasedAuthentication parameter indicates whether to try rhost based authentication with public key authentication. The default value for the parameter is no and applies only to protocol version 2.

HostKeyAlgorithms

The HostKeyAlgorithms parameter sets the preference order for host key algorithms in protocol version 2. The default order is ssh-rsa,ssh-dss.

HostKeyAlias

The HostKeyAlias parameter allows setting an alias name for the host key to use when saving or looking up the host key. Use the parameter when running multiple servers on a single host or for SSH tunneling.

HostName

The HostName parameter contains the actual login hostname. The default value is the hostname given in the command line. Use the parameter to specify nicknames, abbreviations, or numerical IP addresses.

The HostName parameter in the ssh config file.

IdentitiesOnly

The IdentitiesOnly parameter specifies to only use identity files stated in ssh_config. By default, the value is set to no. Use the parameter when ssh-agent offers multiple identities.

IdentityFile

The IdentityFile parameter contains the path to the identity file with a user's RSA or DSA identity. The default path for protocol version 1 is ~/.ssh/identity, whereas protocol version 2 uses either ~/.ssh/id_rsa or~/.ssh/id_dsa.

The identity file path allows using the tilde (~) for a user's home directory, and the following substitutions:

  • %d is the local user's home directory.
  • %u is the local user's username.
  • %l is the local hostname.
  • %h is the remote hostname.
  • %r is the remote username.

The parameter allows using multiple identity files which apply the provided order.

KbdInteractiveAuthentication

The KbdInteractiveAuthentication controls whether to use the interactive keyboard mode for authentication. The default value for the parameter is yes.

KbdInteractiveDevices

The KbdInteractiveDevices parameter contains a list of methods to use with keyboard-interactive authentication. The default values list depends on the server type. For example, an OpenSSH server uses zero or more of the following: bsdauth, pam, and skey.

LocalCommand

The LocalCommand parameter allows a command to run on the local machine after successfully connecting via SSH. The command string executes in the user's shell.

To permit executing the command, enable the PermitLocalCommand parameter.

The LocalCommand parameter in the ssh config file.

LocalForward

The LocalForward parameter specifies a local port to forward through the secure channel to a target host and a port on the remote machine. The parameter requires two arguments:

  • bind_address:port for IPv4 or bind_address/port for IPv6 addresses. The bind address is optional.
  • host:hostport for IPv4 or host/hostport for IPv6 addresses.

For multiple ports, specify multiple arguments or provide additional forwarding information via the command line.

LogLevel

The LogLevel parameter controls the output verbosity of SSH messages. The available options are:

QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3

The INFO argument is the default value, whereas DEBUG and DEBUG1 indicate the same level.

MACs

The MACs parameter allows listing the message authentication algorithms (MACs) for protocol version 2. The algorithms determine the algorithm for data integrity protection. Possible values are:

hmac-md5, hmac-sha1, [email protected], 
hmac-ripemd160, hmac-sha1-96, hmac-md5-96

State multiple algorithms in a comma-separated list. The algorithms apply in the specified order.

NoHostAuthenticationForLocalhost

The NoHostAuthenticationForLocalhost parameter disables authentication for localhost. The default value is no, meaning the host key check happens for localhost.

Enable the option to allow sharing a home directory across machines. Warnings for changed host keys appear because "localhost" refers to a different device on every machine.

NumberOfPasswordPrompts

The NumberOfPasswordPrompts parameter allows stating how many password prompts happen upon failure. The argument for the parameter is an integer value, which is 3 by default.

The NumberOfPasswordPrompts parameter in the ssh config file.

PasswordAuthentication

The PasswordAuthentication parameter controls whether there should be password authentication. The default value for the parameter is yes.

PermitLocalCommand

The PermitLocalCommand option controls whether the LocalCommand parameter executes a command on a local machine after connecting. By default, the parameter is turned off with the value no.

Port

The Port parameter contains the port number on the remote host. The default port for SSH is port number 22.

PreferredAuthentications

The PreferredAuthentications parameter is a list of authentication methods the client uses in order of preference. The list contains protocol version 2 authentication methods, and the possible values are:

gssapi-with-mic, hostbased, publickey, keyboard-interactive, password

Changing the order also changes the client's preference for authentication.

Protocol

The Protocol parameter contains the preferred protocol version for SSH. The possible values are 1 and 2. List the values in order of preference to create a fallback option if the first option does not work.

ProxyCommand

The ProxyCommand parameter defines the command for connecting to the server, and the argument is a command string that executes in the user's shell.

The command should connect to an OpenSSH daemon server running on a machine or execute sshd -i. For example, use Netcat to connect to an HTTP proxy with the following:

ProxyCommand nc -X connect -x <address>:<port> %h %p

The nc command contains proxy support and works with the ProxyCommand parameter to connect via proxy. The %h parameter substitutes the host, whereas %p is the port number.

PubkeyAuthentication

The PublicKeyAuthentication parameter controls whether to use public key authentication or not. The default value is no and works for protocol version 2 only.

RekeyLimit

The RekeyLimit parameter sets the maximum amount of data to transmit before the key renegotiates. The argument value is the number of bytes and allows suffixes for kilobytes (K), megabytes (M), and gigabytes (G).

Depending on the cipher, the default value is between 1G and 4G.

RemoteForward

The RemoteForward parameter defines a TCP port on a remote machine to forward through the secure connection. Provide the following two arguments:

  • bind_address:port for IPv4 or bind_address/port for IPv6 addresses. The bind address is optional.
  • host:hostport for IPv4 or host/hostport for IPv6 addresses.

To use multiple ports, specify multiple arguments or provide additional forwarding information via the command line.

RhostsRSAAuthentication

The RhostRSAAuthentication parameter sets whether to use rhost based authentication and RSA-host authentication. The available options are yes or no (default).

RSAAuthentication

The RSAAuthentication parameter controls whether to attempt RSA authentication. The parameter only applies to protocol version 1, and the default value is yes. The RSA authentication attempt occurs only when an identity file exists, or the authentication agent is running.

SendEnv

The SendEnv parameter contains environment variables to send from the local environment to the server. Configure the server to accept environment variables through the AcceptEnv parameter in the /etc/ssh/sshd_config file.

No variables are sent by default. To send multiple environment variables, use SendEnv multiple times or provide a comma-separated list with variable names.

ServerAliveCountMax

The ServerAliveCountMax parameter sets the maximum number of server alive messages (default is 3). The session terminates when the connection reaches the threshold, defined as ServerAliveInterval*ServerAliveCountMax, in seconds.

The messages help a client or server know when a connection is inactive.

ServerAliveInterval

The ServerAliveInterval parameter is the timeout interval in seconds where no data comes from the server. After the interval elapses, SSH sends an encrypted request to respond to the server. The default value for the parameter is 0, meaning SSH sends no messages to the server.

SmartcardDevice

The SmartcardDevice parameter controls which smartcard device to use. Smartcard support is inactive by default. If active, the default argument is the smartcard SSH public keys.

StrictHostKeyChecking

The StrictHostKeyChecking parameter flags whether to automatically add host keys to the ~/.ssh/known_hosts file upon changes. The default options are yes, no, or ask (default). The check is a good security measure against trojan horse attacks.

TCPKeepAlive

The TCPKeepAlive parameter sends TCP messages to the server to check for connectivity. If the network is down or the server crashes, the client gets the information through the TCP messages.

By default, the messages are set as yes. Turn the parameter off to avoid disconnecting during temporary route downtimes.

Tunnel

The Tunnel parameter requests a tunnel interface device forwarding between the client and server. The available options are yes, point-to-point, ethernet, or no (default). The tunnel option for yes is point-to-point.

TunnelDevice

The TunnelDevice parameter helps determine which devices to open on the client (local tunneling) and server (remote tunneling). The argument is local:remote, whose values are the device IDs or any. The remote device ID is optional and defaults to any when omitted.

The default value for the tunnel device is any:any and uses the next available device in both cases.

UsePrivilegedPort

The UserPrivilegedPort parameter determines whether to use a privileged port for outside connections. The possible values are yes or no (default). If using RhostsRSAAuthentication with older servers, set the parameter value to yes.

User

When establishing a connection, the User parameter sets the login username. Use the option when the username differs on machines or to avoid specifying it in the command line.

UserKnownHostsFile

The UserKnownHostsFile parameter sets the path for the known hosts file. The default location is ~/.ssh/known_hosts.

VerifyHostKeyDNS

The VerifyHostKeyDNS parameter determines whether to use DNS and SSHFP file records to verify the remote key. The default value is no, and changing it to yes automatically enables trusting keys that match the DNS fingerprint. Use the option ask to display fingerprint matches and to require confirmation.

VisualHostKey

The VisualHostKey parameter controls whether to print the ASCII art of the remote host key fingerprint for unknown host keys. By default, the value is no, and only the hex string fingerprint prints for unknown host keys.

XAuthLocation

The XAuthLocation parameter holds the full path to the X authority file utility. The default location is /usr/bin/xauth.

Conclusion

After reading this guide, you know how to use an SSH config file to set up connection options automatically.

Next, check out the most common SSH Linux commands.

Was this article helpful?
YesNo
Milica Dancuk
Milica Dancuk is a technical writer at phoenixNAP who is passionate about programming. Her background in Electrical Engineering and Computing combined with her teaching experience give her the ability to easily explain complex technical concepts through her content.
Next you should read
Telnet vs. SSH: How Is SSH Different From Telnet?
May 20, 2021

Telnet and SSH are network protocols used to connect to remote system. This tutorial covers the ways they work, what makes them different...
Read more
How to Fix the SSH "Connection Refused" Error
November 12, 2020

Fix SSH connection refused by troubleshooting some of the common causes for this problem. Take a look of all the reasons...
Read more
How to Use SSH Port Forwarding
May 18, 2020

This article demonstrates 3 distinct methods used to port forward SSH connections. It examines the syntax of the individual commands and...
Read more