How to Use the SSH Config File for OpenSSH Users

SSH Config File

The SSH protocol is used for establishing secure connections between remote machines. In modern system administration, this protocol forms the backbone of secure communication between the apps and devices on the networks.

An SSH config file is a valuable tool that simplifies the configuration of default values for these connections. Admins use these files to control various aspects of SSH communication. 

Rather than configuring the parameters for SSH communication every time a device or an application opens an SSH connection, admins can set values in the SSH config file and fine-tune the secure remote access experience.

In this comprehensive guide, we’ll start with a short discussion on the SSH config files. Then, we’ll explore how to customize your SSH experience to fit your needs perfectly. In the end, we’ll briefly describe the parameters in this file.

Table Of Contents

  1. What are SSH Config Files?
  2. How to Use SSH Config Files?
    1. Prerequisites
  3. Critical Portions of the SSH Config File
    1. Add Host Aliases
    2. Automatic Key Selection
    3. Change the Default Port
    4. Jump Hosts
    5. Forward Ports
    6. Multiplexing
    7. Disable Strict Host Key Checking
  4. How to Customize SSH Config Files
    1. Step #1: Open or Create the Config File
    2. Step #2: Edit the Config File
    3. Step #3: Add Configuration Parameters
    4. Step #4: Customize as Needed
    5. Step #5: Save the File
    6. Step #6: Set the Correct Permissions
    7. Step #7: Test the Configuration
  5. SSH Config File Parameters
  6. Conclusion
  7. FAQs

What are SSH Config Files?

An SSH config file is a personalized (custom) settings file that controls how the SSH connections are initiated and processed. This file is usually found at ~/.ssh/config for personal settings or /etc/ssh/ssh_config for system-wide settings. 

ssh config files example

You can set critical values such as default usernames, specific keys for certain destinations and port numbers for a server or group. These default values ensure easy and safe SSH connections to servers without entering them for each connection.

How to Use SSH Config Files?

SSH config files streamline and customize your SSH client’s behavior for different hosts and scenarios. 

Prerequisites

Before navigating through SSH config files, be sure you have the basic requirements ready:

  • You must be familiar with basic terminal commands. This allows you to execute specific commands and navigate the system.
  • You’ll need a text editor. We prefer native editors, such as Nano, Vi, or Vim, to create, edit, and manage SSH config files.
  • Access to a remote server for the SSH sessions.

Critical Portions of the SSH Config File

Here’s a detailed explanation of the important sections you can add to an SSH config file:

Add Host Aliases 

You can create shortcuts for long SSH commands, specifically for connecting to hosts. For instance, instead of typing $ ssh -i /path/to/private_key [email protected], you can set up a host alias in the SSH config file. Here’s an example:

Host myserver

    HostName 123.45.67.89

    User user

    IdentityFile /path/to/private_key

 

Once you’ve added this to the file, you can simply type ssh myserver to connect to the host.

Automatic Key Selection

If you have multiple SSH keys for different servers, you can specify which private key to use for a server:

Host server1

    IdentityFile ~/.ssh/server1_key

Host server2

    IdentityFile ~/.ssh/server2_key

Change the Default Port

If your server uses a non-standard SSH port, you can specify it in the config file:

Host example

    HostName example.com

    Port 2222

Jump Hosts 

If you need to access a server behind a firewall via a jump host, you can configure it as follows:

Host target

    HostName target.internal

    ProxyJump jump.host

Forward Ports

Use the following snippet to forward a local port to a remote server (also known as local port forwarding):

Host remoteweb

    HostName webserver.example.com

    LocalForward 8080 localhost:80

This forwards local port 8080 to port 80 on webserver.example.com.

Multiplexing

Speed up future connections by using multiplexing with Control Master settings. This simplifies the connection process by allowing multiple connections to share a single, pre-established connection, resulting in quicker and more efficient communication.

Host *

    ControlMaster auto

    ControlPath ~/.ssh/sockets/%r@%h-%p

    ControlPersist 600

Disable Strict Host Key Checking 

If you trust a host, you might want to disable strict host key checking with the following snippet:

Host trustedhost

    StrictHostKeyChecking no

    UserKnownHostsFile=/dev/null

We recommend extreme caution with this setting due to security implications.

How to Customize SSH Config Files

Creating and customizing an SSH config file involves the following straightforward steps:

Step #1: Open or Create the Config File

SSH config files are located in the .ssh directory of your user’s home folder. The full path is usually ~/.ssh/config.

If the file doesn’t already exist, you can create it using a text editor.

Step #2: Edit the Config File

Open the file in a text editor. For instance, you can use nano to open the config file with the following command:

# nano ~/.ssh/config

If you use a GUI-based system, you can open it in any text editor like Notepad on Windows or TextEdit on macOS.

Step #3: Add Configuration Parameters

Now, you can define parameters and configuration options for each of your SSH hosts.

A typical host declaration block follows the following structured format:

Host hostname_or_pattern

    Parameter value

    Parameter value

configuration parameters output

Step #4: Customize as Needed

You can add as many host blocks as you need, each with its set of configurations.

You can also set parameters like ServerAliveInterval, ControlMaster, LocalForward, and RemoteForward.

Step #5: Save the File

Once you’re finished, save the file and exit the editor. Since we’re using nano, press Ctrl + X, then Y to confirm, and Enter to save.

Step #6: Set the Correct Permissions

A hacker can easily compromise your system by altering values in the config file. That’s why it’s important that the config file is not publicly viewable for security reasons.

For this, set the right permissions with the following command:

# chmod 600 ~/.ssh/config

Step #7: Test the Configuration

To test the SSH configuration file, simply connect to one of your configured hosts using SSH:

testing configuration

If everything is set up correctly, SSH will use the settings from the config file for the connection.

SSH Config File Parameters

SSH config files provide many options for fine-tuning connection settings and ensuring flexibility. For this, you can set your desired values for the following parameters and their functions:

AddressFamily

AddressFamily in the SSH config file determines the address type (IPv4 or IPv6) used for connecting the client and server. This parameter determines whether the connection uses IPv4 or IPv6.

BatchMode

BatchMode in the SSH config file controls whether the client should attempt to prompt for passwords or passphrases interactively. When BatchMode is set to yes, SSH won’t prompt for user input. This setting is useful for automated or scripted processes.

BindAddress

BindAddress in the SSH config file specifies the client-side local address to use when establishing the connection. This setting allows you to bind the client to a specific network interface or IP address.

ChallengeResponseAuthentication

ChallengeResponseAuthentication in SSH config controls whether the server prompts users for extra authentication. When set to yes, the SSH client will provide additional info for authentication. Alternatively, when it’s set to no, SSH relies on other authentication methods.

CheckHostIP

This setting indicates whether to check the remote host’s IP address against the entries in the known-hosts file.

Cipher

This parameter sets the encryption cipher algorithm for the connection.

Ciphers

This parameter lists permitted ciphers in order of preference.

ClearAllForwardings

This setting removes all port forwardings mentioned in the configuration file.

Compression

The compression parameter controls the use of compression during SSH connections. Its default value is no.

CompressionLevel

When Compression is set to yes, CompressionLevel adjusts the compression level. The range is 1 (fastest, least effective) to 9 (slowest, most effective). The default value is 6

ConnectionAttempts

The ConnectionAttempts parameter sets the number of connection attempts before discontinuing the remote connection. By default, this number is one, and each attempt occurs at a rate of one per second. You can include this parameter in your script to handle situations where connection attempts sometimes fail.

ConnectTimeout Parameter

This parameter specifies the time limit (in seconds) for initiating an SSH connection. The default value for this setting is the Linux system’s TCP timeout.

ControlMaster

The ControlMaster parameter in the SSH config file determines whether to use a master connection configuration for multiple sessions.

When set to yes, the first connection acts as the master, and subsequent connections use the settings of the master connection. This can improve efficiency by reusing an existing connection, reducing the overhead of establishing new ones. 

This setting supports the following arguments:

control master

ControlPath

The ControlPath parameter determines the control socket details for shared connections. You can select none to deactivate connection sharing.

You can use the following substitutions for path parameters:

%l: Local hostname

%h: Target hostname

%p: Connection port

%r: Remote login username

On the minimum, we recommend including %h, %p, and %r to ensure connections have unique identifiers.

DynamicForward

The DynamicForward parameter activates dynamic TCP port forwarding through a secure channel, defined as either bind_address: port or bind_address/port

You can set localhost as the bind address for local port binding or * to open the ports across all interfaces.

EnableSSHKeysign

Found in the global SSH configuration file at /etc/ssh/ssh_config, the EnableSSHKeysign parameter activates a program to create digital signatures for host-based authentication. It accepts yes or no as options.

EscapeChar

The EscapeChar parameter defines the default escape character, a tilde (~). 

You can disable escape characters by setting it to none. It allows you to issue commands that are not part of the regular data stream and are interpreted by the SSH client instead of being sent to the remote server.

ExitOnForwardFailure

When set to yes, this option ensures that the connection terminates if there’s a failure in port forwarding. The default value is no.

ForwardAgent

This parameter controls whether an authentication agent forwards credentials to a remote machine. Activating it introduces security considerations, so use it carefully. That’s why, by default, this parameter is set to no. 

ForwardX11

This parameter in an SSH config file controls the forwarding of the X11 (windowing system) protocol to a remote machine. It lets you display graphical applications from the remote server on your local machine.

ForwardX11Trusted

When set to yes, this setting allows users to bypass file permissions and have ForwardX11 activated. As a result, they can perform actions like keystroke monitoring. By default, it’s set to no, ensuring security by allowing X11 clients to expire after twenty minutes. 

We recommend caution when using this option, as it removes certain restrictions to provide more comprehensive control over X11 clients linked to the original display.

GatewayPorts

This setting dictates whether remote hosts can connect to locally forwarded ports. By default, set to no, it restricts locally forwarded ports to bind only to the loopback address (127.0.0.1), enhancing security.

GlobalKnownHostsFile

This parameter allows you to specify an alternative global host key file location. The default location is /etc/ssh/ssh_known_hosts.

GSSAPIAuthentication

In SSH version 2, this parameter governs the activation of GSSAPI authentication that provides access to various security services. By default, it’s disabled (set to no).

GSSAPIKeyExchange

Also, for protocol version 2, this parameter enables key exchange using GSSAPI. When the value is set to yes, the server doesn’t require a host key. The default value is no.

GSSAPIClientIdentity

The GSSAPIClientIdentity parameter setting designates the client identity for use in GSSAPI authentication. If no client identity is defined, the SSH protocol defaults to using the default identity.

GSSAPIDelegateCredentials

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

GSSAPIRenewalForcesRekey

When set to yes, this parameter initiates SSH connection rekeying upon the renewal of GSSAPI credentials. By default, it’s set to no.

GSSAPITrustDns

This parameter, relevant for SSH version 2, determines whether to trust DNS for hostname normalization. Defaulted to no, it ensures that the hostname specified via the command line remains unaltered.

HashKnownHosts

This setting controls the hashing (conversion of any value containing a string of characters into another value for security purposes) of entries in the known_hosts file, securing their values in ~/.ssh/known_hosts. When set to yes, it hashes all future entries, keeping existing ones unchanged. By default, it’s set to no.

HostbasedAuthentication

This SSH version 2 parameter determines whether to attempt rhost-based authentication alongside public key authentication. The default is no.

HostKeyAlgorithms

The HostKeyAlgorithms is an SSH version 2 parameter that establishes the preferred sequence of host key algorithms. The default sequence is ssh-rsa,ssh-dss.

HostKeyAlias

This parameter permits the assignment of an alias for the host key. This is a useful consideration for managing multiple servers on a single machine or creating SSH tunnels.

HostName

The HostName parameter specifies the actual login hostname. The default value of this parameter is the hostname entered at the command line. This parameter can define nicknames, abbreviations, or numerical IP addresses.

cd. ssh

cd. ssh config

chmod 600 ssh config

host redswitches server

cat ssh config

IdentityFile

The IdentityFile parameter designates the path of the identity file, which stores a user’s RSA or DSA credentials. For SSH version 1, the default path is ~/.ssh/identity, while for SSH version 2, the file can be found at ~/.ssh/id_rsa or ~/.ssh/id_dsa.

You can apply various substitutions within the identity file path: 

  • %d (local user’s home directory) 
  • %u (local user’s username)
  • %l (local hostname)
  • %h (remote hostname) 
  • %r (remote username)

You can define and use multiple identity files, applying them in the specified order.

KbdInteractiveAuthentication

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

KbdInteractiveDevices

KbdInteractiveDevices is a directive used in the SSH configuration file on Linux systems. This setting specifies the devices to be used for keyboard-interactive authentication to handle difficult authentication methods. It proves particularly useful when integrating multi-factor authentication or other interactive methods into the SSH login process. 

By specifying certain devices or methods in the KbdInteractiveDevices parameter, administrators can fine-tune the authentication process to enhance security or accommodate specific authentication requirements. This directive plays a crucial role in customizing and securing SSH access in a Linux environment.

Here’s our comprehensive tutorial on using SSH to connect to a remote server in Linux/Windows with the best practices and precautions.  

LocalCommand

The LocalCommand parameter facilitates the execution of commands on the local machine after a successful SSH connection.

local commad output

The specified command string is executed in the user’s shell. Moreover, it requires the PermitLocalCommand parameter to be enabled and activated.

permit local command output

LocalForward

It specifies local port forwarding to a remote host and port through a secure channel. It requires bind_address:port for IPv4 or bind_address/port for IPv6.

LogLevel

The LogLevel parameter determines the verbosity of SSH message output. The supported values are QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG, DEBUG1, DEBUG2, and DEBUG3. The default value is INFO

Note that INFO is equivalent to DEBUG and DEBUG1.

MACs

The MACs parameter defines message authentication codes (MACs) for SSH version 2, offering protection for data integrity. You can specify multiple algorithms in a comma-separated list in the preferred order.

NoHostAuthenticationForLocalhost

This parameter deactivates host authentication for localhost. The default value is no, which means host key checks are performed for localhost

Activating this option permits sharing a home directory across multiple machines. However, you should be careful about altered host keys on various machines.

NumberOfPasswordPrompts

The NumberOfPasswordPrompts parameter specifies how many password prompts are presented after the initial authentication failure. In the sample file, we have set the default value to 5.

number of password prompts

As a result, you can see the error and disconnection messages when you use an incorrect password.

password failure output

PasswordAuthentication

This parameter governs the permission for password authentication. The default value is yes.

PermitLocalCommand

The PermitLocalCommand parameter dictates whether the system can allow the LocalCommand parameter to execute a command on the local machine after the connection has been established. Typically, this parameter is preset to no.

Port

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

PreferredAuthentications

The PreferredAuthentications parameter lists authentication methods in order of preference for SSH version 2. The supported values are gssapi-with-mic, hostbased, publickey, keyboard-interactive, and password.

Protocol

The Protocol parameter specifies the desired SSH protocol version, 1 or 2. These can be arranged in the preferred sequence to establish a fallback mechanism (a mechanism to restore to the other version if the primary option fails).

ProxyCommand

The ProxyCommand parameter defines the command used for connecting to the server. 

The argument constitutes a command string to be executed within the user’s shell environment. It should connect to an OpenSSH daemon server or execute sshd -i. A common user case is using netcat to connect to an HTTP proxy.

PubkeyAuthentication

The PubkeyAuthentication parameter controls whether public key authentication is used. The standard setting for this parameter is no, and it exclusively applies to SSH version 2.

RekeyLimit

The RekeyLimit parameter establishes the upper limit of data transfer before initiating the renegotiation of the encryption key. The value accommodates suffixes like kilobytes (K), megabytes (M), and gigabytes (G). The default values depend on the cipher used.

RemoteForward

The RemoteForward parameter specifies the forwarding of a TCP port on the remote machine through the secure connection. It uses bind_address:port for IPv4 or bind_address/port for IPv6.

RhostsRSAAuthentication

The RhostsRSAAuthentication parameter specifies if rhost-based and RSA-host authentication should be utilized, with options being yes or no (the default value).

RSAAuthentication

In SSH version 1, this parameter manages the attempts at RSA authentication. The default value is yes. RSA authentication occurs when an identity file is present or an authentication agent is operational.

SendEnv

The SendEnv parameter transmits the local environment variables to the destination server. You can enable the acceptance of these variables at the server by configuring the AcceptEnv parameter in the /etc/ssh/sshd_config file.

ServerAliveCountMax

This parameter sets the maximum allowable server alive messages, with the default value being 3. When this count is reached, the session terminates. These server alive messages help detect inactive connections.

ServerAliveInterval

The ServerAliveInterval parameter sets the timeout interval (in seconds) the system waits for data from the server. Once this interval expires, SSH dispatches an encrypted query to the server. The preset value is 0, indicating SSH does not send these messages by default.

SmartcardDevice

The SmartcardDevice parameter governs the choice of a smart card device. Smart card support is inactive by default, and the default argument pertains to smart card SSH public keys.

StrictHostKeyChecking

The StrictHostKeyChecking parameter specifies whether to automatically include host keys in the ~/.ssh/known_hosts file upon changes. The supported options are yes, no, or ask. Enabling StrictHostKeyChecking enhances security but may require confirmation for changed host keys.

TCPKeepAlive

The TCPKeepAlive parameter configures the transmission of TCP messages to verify server connectivity. By default, it is set to yes. Disabling it prevents disconnecting during temporary route downtimes.

Tunnel

This parameter is used to initiate the request for forwarding a tunnel interface device between the client and the server. Options include yes, point-to-point, ethernet, or no (the default value). When this parameter is set to yes, the system evaluates it to point-to-point.

TunnelDevice

The TunnelDevice parameter determines devices for local and remote tunneling. The format is local:remote, and the values are usually device IDs. The specification of the remote device ID is optional, defaulting to any if not provided. The default value for the tunnel device is any:any.

UsePrivilegedPort

This parameter dictates the use of a privileged port for outbound connections. Options include yes or no (the default value). You can set the value to yes for compatibility with older servers that use RhostsRSAAuthentication.

User

The User parameter sets the login username when establishing an SSh connection. This option is useful when the username differs between machines or you wish to avoid specifying it at the command line.

UserKnownHostsFile

The UserKnownHostsFile parameter defines the file path for the known_hosts file, which defaults to ~/.ssh/known_hosts.

VerifyHostKeyDNS

The VerifyHostKeyDNS parameter determines whether DNS and SSHFP records are used to verify remote keys. The default value is no. Changing this to yes automatically trusts keys matching the DNS fingerprint. Alternatively, you can set this parameter to ask to prompt for confirmation.

VisualHostKey

The VisualHostKey parameter controls the presentation of ASCII art renditions of the remote host’s key fingerprint for unfamiliar host keys. The default value is no, showing only the hex string fingerprint for unknown host keys.

XAuthLocation

The XAuthLocation parameter specifies the complete file path to the .Xauthority utility, with /usr/bin/xauth being the default location.

Conclusion

The SSH config file is essential for controlling all critical aspects of SSH connectivity. By allowing for detailed customization of SSH connections, it not only streamlines the process of connecting to various servers but also significantly boosts security and efficiency by making processing easier. 

RedSwitches offers the best dedicated server pricing and delivers instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated servers, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

FAQs

Q. What is an SSH client config file?

The SSH client config file is where you customize preferences for your Secure Shell connections. It lets you define settings like host patterns, authentication methods, and key file paths to tailor your SSH experience.

Q. How do I edit the SSH client config file in Vim?

To edit the SSH client config file in Vim, open the terminal and enter vim ~/.ssh/config. This opens the file in Vim, where you can edit it according to your requirements.

Q. What are host patterns in SSH, and how are they used?

Host patterns in SSH are like custom filters that match specific hosts or addresses. In the SSH config file, they help apply unique configurations to connections that meet these defined patterns.

Q. What is the default parameter value for TCPKeepAlive in SSH?

TCPKeepAlive is turned on by default in SSH, ensuring active connections by regularly sending keepalive messages.

Q. How does SSH tunneling work, and why is it important?

SSH tunneling is a method of forwarding network traffic securely through an SSH connection. It is crucial for securely accessing network services on a remote server, especially in scenarios where direct access is not possible or secure.

Q. What is the importance of the key file path in SSH configuration?

The key file path in the SSH configuration specifies the location of the authentication key file. This is necessary for setting up and using key-based authentication, a standard and secure method for SSH access.

Q. Can I specify a custom configuration file for SSH?

Yes, you can specify a custom configuration file for SSH using the -F option with the SSH command, followed by the path to your custom file.

Q. How do I attempt RSA authentication in SSH?

To attempt RSA authentication in SSH, you need to specify the RSA key in your SSH client config file or use the -i option in the SSH command to specify the path to your RSA private key.

Q. What is the role of file records in SSH client configuration?

File records in SSH client configuration hold specific configurations for host entries, including address schemes, authentication methods, and other settings relevant to individual sessions or host patterns.

Q. How do I provide root user access in SSH?

To provide root user access in SSH, you must configure the SSH server settings to permit root login. This is typically managed in the server’s SSH configuration file (/etc/ssh/sshd_config) by setting PermitRootLogin to yes.

Q. What is the default timeout for SSH connections?

The default timeout for SSH connections varies based on the server configuration, but typically, it is set to 60 seconds. This can be adjusted in the SSH config file.

Q. How do I use SSH for remote access in a multi-address system?

In a multi-address system, you can use SSH for remote access by specifying the SSH command’s exact hostname or IP address. You can also configure host patterns in your SSH client config file to handle different addresses efficiently.

Q. What are the standard methods of authentication in SSH?

SSH’s most common authentication methods include password, public key, and host-based authentication. Public key authentication is preferred for its security and convenience.