One place for hosting & domains

      OpenSSH

      How To Harden OpenSSH on Ubuntu 20.04


      A previous version of this tutorial was written by Jamie Scaife.

      Introduction

      Linux servers are often administered remotely using SSH by connecting to an OpenSSH server, which is the default SSH server software used within Ubuntu, Debian, CentOS, FreeBSD, and most other Linux/BSD-based systems.

      OpenSSH server is the server side of SSH, also known as SSH daemon or sshd. You can connect to an OpenSSH server using the OpenSSH client, specifically by running the ssh command. You can learn more about the SSH client-server model in SSH Essentials: Working with SSH Servers, Clients, and Keys. Properly securing your OpenSSH server is very important, as it acts as the front door or entry-point into your server.

      In this tutorial, you will harden your OpenSSH server by using different configuration options to ensure that remote access to your server is as secure as possible.

      Prerequisites

      To complete this tutorial, you will need:

      Once you have this ready, log in to your server as your non-root user to begin.

      Step 1 — General Hardening

      In this first step, you will implement some initial hardening configurations to improve the overall security of your SSH server.

      The exact hardening configuration that is most suitable for your own server depends heavily on your own threat model and risk threshold. However, the configuration you’ll use in this step is a general secure configuration that will suit the majority of servers.

      You will edit the main OpenSSH configuration file in /etc/ssh/sshd_config to set the majority of the hardening options in this tutorial. Before continuing it is a good idea create a backup of your existing configuration file so that you can restore it in the unlikely event that something goes wrong.

      Create a backup of the file using the following cp command:

      • sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

      This will save a backup copy of the file to /etc/ssh/sshd_config.bak.

      Next, review the current default OpenSSH configuration options that correspond to the settings in /etc/ssh/sshd_config. To do this, run the following command:

      This will run OpenSSH server in extended test mode, which will validate the full configuration file and print out the effective configuration values.

      You can now open the configuration file using nano or your favorite text editor to begin implementing the initial hardening measures:

      • sudo nano /etc/ssh/sshd_config

      Note: The OpenSSH server configuration file that is installed with Ubuntu 20.04 includes many default options and configurations. Depending on your existing server configuration, some of the recommended hardening options may already have been set.

      When editing your configuration file, some options may be commented out by default using a single hash character (#) at the start of the line. In order to edit these options, or enable the option, you’ll need to uncomment them by removing the hash.

      The first hardening option is to disable logging in via SSH as the root user. Set the PermitRootLogin option to no by uncommenting or editing the line:

      sshd_config

      PermitRootLogin no
      

      This option will prevent a potential attacker from logging into your server directly as root. It also encourages good operational security practices on your part, such as operating as a non-privileged user and using sudo to escalate privileges only when absolutely needed.

      Next, you can limit the maximum number of authentication attempts for a particular login session by configuring the MaxAuthTries option:

      sshd_config

      MaxAuthTries 3
      

      A standard value of 3 is acceptable for most setups, but you may wish to set this higher or lower depending on your own risk threshold.

      If required, you can also set a reduced login grace period, which is the amount of time a user has to complete authentication after initially connecting to your SSH server:

      sshd_config

      LoginGraceTime 20
      

      The configuration file specifies this value in seconds.

      Setting this to a lower value helps to prevent certain denial-of-service attacks where multiple authentication sessions are kept open for a prolonged period of time.

      If you have configured SSH keys for authentication, rather than using passwords, disable SSH password authentication to prevent leaked user passwords from allowing an attacker to log in:

      sshd_config

      PasswordAuthentication no
      

      As a further hardening measure related to passwords, you may also wish to disable authentication with empty passwords. This will prevent logins if a user’s password is set to a blank or empty value:

      sshd_config

      PermitEmptyPasswords no
      

      In the majority of use cases, SSH will be configured with public key authentication as the only in-use authentication method. However, OpenSSH server also supports many other authentication methods, some of which are enabled by default. If these are not required, you can disable them to further reduce the attack surface of your SSH server:

      sshd_config

      ChallengeResponseAuthentication no
      KerberosAuthentication no
      GSSAPIAuthentication no
      

      If you’d like to know more about some of the additional authentication methods available within SSH, you may wish to review these resources:

      X11 forwarding allows for the display of remote graphical applications over an SSH connection, but this is rarely used in practice. Disable it if you are not running a graphical environment on your server:

      sshd_config

      X11Forwarding no
      

      OpenSSH server allows connecting clients to pass custom environment variables. For example, a client can attempt to set its own $PATH or to configure terminal settings. However, like X11 forwarding, these are not commonly used, so you can disable the option in most cases:

      sshd_config

      PermitUserEnvironment no
      

      If you decide to restrict this option by setting it to no, then you should also make sure to comment out any references in the configuration file to AcceptEnv by adding a hash (#) to the beginning of any line that specifies that option.

      Next, you can disable several miscellaneous options related to tunneling and forwarding if you won’t be using these on your server:

      sshd_config

      AllowAgentForwarding no
      AllowTcpForwarding no
      PermitTunnel no
      

      Finally, you can disable the verbose SSH banner that is enabled by default, as it shows various information about your system, such as the operating system version:

      sshd_config

      DebianBanner no
      

      Note that this option most likely won’t already be present in the configuration file, so you may need to add it manually. Save and exit the file once you’re done. If you are using nano press CTRL+O to save the file and press ENTER when prompted with the file name. Then press CTRL+X to exit the editor.

      Now validate the syntax of your new configuration by running sshd in test mode with the -t flag:

      If your configuration file has a valid syntax, there will be no output. In the event of a syntax error, there will be an output describing the issue.

      Once you’re satisfied with your configuration file, you can reload sshd using systemd to apply the new settings:

      • sudo systemctl reload sshd.service

      In this step, you completed some general hardening of your OpenSSH server configuration file. Next, you’ll implement an IP address allowlist to further restrict who can log in to your server.

      Step 2 — Implementing an IP Address Allowlist

      You can use IP address allowlists to limit the users who are authorized to log in to your server on a per-IP address basis. In this step, you will configure an IP allowlist for your OpenSSH server.

      In many cases, you will only be logging on to your server from a small number of known, trusted IP addresses. For example, your home internet connection, a corporate VPN appliance, or a static jump box or bastion host in a data center.

      By implementing an IP address allowlist, you can ensure that people will only be able to log in from one of the pre-approved IP addresses, greatly reducing the risk of a breach in the event that your private keys and/or passwords are leaked.

      Note: Please take care in identifying the correct IP addresses to add to your allowlist, and ensure that these are not floating or dynamic addresses that may regularly change, for example as is often seen with consumer internet service providers.

      You can identify the IP address that you’re currently connecting to your server with by using the w command:

      This will output something similar to the following:

      Output

      14:11:48 up 2 days, 12:25, 1 user, load average: 0.00, 0.00, 0.00 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT your_username pts/0 203.0.113.1 12:24 1.00s 0.20s 0.00s w

      Locate your user account in the list and take a note of the connecting IP address. Here we use the example IP of 203.0.113.1

      In order to begin implementing your IP address allowlist, open the OpenSSH server configuration file in nano or your preferred text editor:

      • sudo nano /etc/ssh/sshd_config

      You can implement IP address allowlists using the AllowUsers configuration directive, which restricts user authentications based on username and/or IP address.

      Your own system setup and requirements will determine which specific configuration is the most appropriate. The following examples will help you to identify the most suitable one:

      • Restrict all users to a specific IP address:
      AllowUsers *@203.0.113.1
      
      AllowUsers *@203.0.113.0/24
      
      • Restrict all users to a specific IP address range (using wildcards):
      AllowUsers *@203.0.113.*
      
      • Restrict all users to multiple specific IP addresses and ranges:
      AllowUsers *@203.0.113.1 *@203.0.113.2 *@192.0.2.0/24 *@172.16.*.1
      
      • Disallow all users except for named users from specific IP addresses:
      AllowUsers sammy@203.0.113.1 alex@203.0.113.2
      
      • Restrict a specific user to a specific IP address, while continuing to allow all other users to log in without restrictions:
      Match User ashley
        AllowUsers ashley@203.0.113.1
      

      Warning: Within an OpenSSH configuration file, all configurations under a Match block will only apply to connections that match the criteria, regardless of indentation or line breaks. This means that you must be careful and ensure that configurations intended to apply globally are not accidentally put within a Match block. It is recommended to put all Match blocks at the bottom/end of your configuration file to help avoid this.

      Once you have finalized your configuration, add it to the bottom of your OpenSSH server configuration file:

      sshd_config

      AllowUsers *@203.0.113.1
      

      Save and close the file, and then proceed to test your configuration syntax:

      If no errors are reported, you can reload OpenSSH server to apply your configuration:

      • sudo systemctl reload sshd.service

      In this step, you implemented an IP address allowlist on your OpenSSH server. Next, you will restrict the shell of a user to limit the commands that they are allowed to use.

      Step 3 — Restricting the Shell of a User

      In this step, you’ll explore the various options for restricting the shell of an SSH user.

      In addition to providing remote shell access, SSH is also great for transferring files and other data, for example, via SFTP. However, you may not always want to grant full shell access to users when they only need to be able to carry out file transfers.

      There are multiple configurations within OpenSSH server that you can use to restrict the shell environment of particular users. For instance, in this tutorial, we will use these to create SFTP-only users.

      Firstly, you can use the /usr/sbin/nologin shell to disable interactive logins for certain user accounts, while still allowing non-interactive sessions to function, like file transfers, tunneling, and so on.

      To create a new user with the nologin shell, use the following command:

      • sudo adduser --shell /usr/sbin/nologin alex

      Alternatively, you can change the shell of an existing user to be nologin:

      • sudo usermod --shell /usr/sbin/nologin sammy

      If you then attempt to interactively log in as one of these users, the request will be rejected:

      This will output something similar to the following message:

      Output

      This account is currently not available.

      Despite the rejection message on interactive logins, other actions such as file transfers will still be allowed.

      Next, you should combine your usage of the nologin shell with some additional configuration options to further restrict the relevant user accounts.

      Begin by opening the OpenSSH server configuration file in nano or your preferred editor again:

      • sudo nano /etc/ssh/sshd_config

      There are two configuration options that you can implement together to create a tightly restricted SFTP-only user account: ForceCommand internal-sftp and ChrootDirectory.

      The ForceCommand option within OpenSSH server forces a user to execute a specific command upon login. This can be useful for certain machine-to-machine communications, or to forcefully launch a particular program.

      However, in this case, the internal-sftp command is particularly useful. This is a special function of OpenSSH server that launches an in-place SFTP daemon that doesn’t require any supporting system files or configuration.

      This should ideally be combined with the ChrootDirectory option, which will override/change the perceived home directory for a particular user, essentially restricting them to a specific directory on the system.

      Add the following configuration section to your OpenSSH server configuration file for this:

      sshd_config

      Match User alex
        ForceCommand internal-sftp
        ChrootDirectory /home/alex/
      

      Warning: As noted in Step 2, within an OpenSSH configuration file, all configurations under a Match block will only apply to connections that match the criteria, regardless of indentation or line breaks. This means that you must be careful and ensure that configurations intended to apply globally are not accidentally put within a Match block. It is recommended to put all Match blocks at the bottom/end of your configuration file to help avoid this.

      Save and close your configuration file, and then test your configuration again:

      If there are no errors, you can then apply your configuration:

      • sudo systemctl reload sshd.service

      This has created a robust configuration for the alex user, where interactive logins are disabled, and all SFTP activity is restricted to the home directory of the user. From the perspective of the user, the root of the system, that is, /, is their home directory, and they will not be able to traverse up the file system to access other areas.

      You’ve implemented the nologin shell for a user and then created a configuration to restrict SFTP access to a specific directory.

      Step 4 — Advanced Hardening

      In this final step, you will implement various additional hardening measures to make access to your SSH server as secure as possible.

      OpenSSH server can impose restrictions on a per-key basis. Specifically, restrictions restrictions can be applied to any public keys that are present in the .ssh/authorized_keys file. This ability is particularly useful to control access for machine-to-machine sessions, as well as providing the ability for non-sudo users to control the restrictions for their own user account.

      While you can apply most of these restrictions at the system or user level using the /etc/ssh/sshd_configuration file, it can be advantageous to implement them at the key-level as well, to provide defence-in-depth and an additional failsafe in the event of accidental system-wide configuration errors.

      Note: You can only implement these additional security configurations if you’re using SSH public-key authentication. If you’re only using password authentication, or have a more complex setup such as an SSH certificate authority, these options will not be usable.

      Begin by opening your .ssh/authorized_keys file in nano or your preferred editor:

      • nano ~/.ssh/authorized_keys

      Note: Since these configurations apply on a per-key basis, you’ll need to edit each individual key within each individual authorized_keys file that you want them to apply to, for all users on your system. Usually you will only need to edit one key/file, but this is worth considering if you have a complex multi-user system.

      Once you’ve opened your authorized_keys file, you will see that each line contains an SSH public key, which will most likely begin with something like ssh-rsa AAAB.... Additional configuration options can be added to the beginning of the line, and these will only apply to successful authentications against that specific public key.

      The following restriction options are available:

      • no-agent-forwarding: Disable SSH agent forwarding.
      • no-port-forwarding: Disable SSH port forwarding.
      • no-pty: Disable the ability to allocate a tty (i.e. start a shell).
      • no-user-rc: Prevent execution of the ~/.ssh/rc file.
      • no-X11-forwarding: Disable X11 display forwarding.

      You can apply these to disable specific SSH features for specific keys. For example, to disable agent forwarding and X11 forwarding for a key, you would use the following configuration:

      ~/.ssh/authorized_keys

      no-agent-forwarding,no-X11-forwarding ssh-rsa AAAB...
      

      By default, these configurations work using an “allow by default, block by exception” methodology; however, it is also possible to use “block by default, allow by exception,” which is generally preferable for ensuring security.

      You can do this by using the restrict option, which will implicitly deny all SSH features for the specific key, requiring them to be explicitly re-enabled only where absolutely needed. You can re-enable features using the same configuration options described earlier in this tutorial, but without the no- prefix.

      For example, to disable all SSH features for a particular key, apart from X11 display forwarding, you can use the following configuration:

      ~/.ssh/authorized_keys

      restrict,X11-forwarding ssh-rsa AAAB...
      

      You may also wish to consider using the command option, which is very similar to the ForceCommand option described in Step 3. This doesn’t provide a direct benefit if you’re already using ForceCommand, but it is good defense-in-depth to have it in place, just in the unlikely event that your main OpenSSH server configuration file is overwritten, edited, and so on.

      For example, to force users authenticating using a specific key to execute a specific command upon login, you can add the following configuration:

      ~/.ssh/authorized_keys

      command="top" ssh-rsa AAAB...
      

      Warning: The command configuration option acts purely as a defense-in-depth method, and should not be solely relied on to restrict the activities of an SSH user, as there are potentially ways to override or bypass it depending on your environment. Instead, you should use the configuration in tandem with the other controls described in this article.

      Finally, to best use the per-key restrictions for the SFTP-only user that you created in Step 3, you can use the following configuration:

      ~/.ssh/authorized_keys

      restrict,command="false" ssh-rsa AAAB...
      

      The restrict option will disable all interactive access, and the command="false" option acts as a second line of defense in the event that the ForceCommand option or nologin shell were to fail.

      Save and close the file to apply the configuration. This will take effect immediately for all new logins, so you don’t need to reload OpenSSH manually. Be sure to test the commands that you intend to use before disconnecting your current SSH session.

      In this final step, you implemented some additional advanced hardening measures for OpenSSH server by using the custom options within your .ssh/authorized_keys file(s).

      Conclusion

      In this article, you reviewed your OpenSSH server configuration and implemented various hardening measures to help secure your server.

      The options that you configured have reduced the overall attack surface of your server by disabling unused features and locking down the access of specific users.

      You may wish to review the manual pages for OpenSSH server and its associated configuration file, to identify any potential further tweaks that you want to make.



      Source link

      How To Harden OpenSSH Client on Ubuntu 20.04


      A previous version of this tutorial was written by Jamie Scaife.

      Introduction

      Linux servers are often administered remotely using SSH by connecting to an OpenSSH server, which is the default SSH server software used within Ubuntu, Debian, CentOS, FreeBSD, and most other Linux/BSD-based systems. Significant effort is put into securing the server-side aspect of SSH, as SSH acts as the entry into your server.

      However, it is also important to consider security on the client-side, such as OpenSSH client.

      OpenSSH client is the “client” side of SSH, also known as the ssh command. You can learn more about the SSH client-server model in SSH Essentials: Working with SSH Servers, Clients, and Keys.

      When hardening SSH at the server side, the primary objective is to make it harder for malicious actors to access your server. However, hardening at the client side is very different, as instead you are working to defend and protect your SSH connection and client from various different threats, including:

      • Attackers on the network, known as “person-in-the-middle” attacks.
      • Compromised or malicious servers sending malformed data packets, nefarious control sequences, or large amounts of data to overload your client.
      • Human error, such as mistyping server addresses or configuration values.

      In this tutorial, you will harden your Ubuntu 20.04 OpenSSH client in order to help ensure that outgoing SSH connections are as secure as possible.

      Prerequisites

      To complete this tutorial, you will need:

      • A device that you will use as an SSH client, for example:

      • An SSH server that you want to connect to, for example:

        • A cloud server
        • A public service such as GitHub or GitLab
        • A third-party device that you are permitted to access

      Once you have these ready, log in to your SSH client device as a non-root user to begin.

      Step 1 — General Hardening

      In this first step, you will implement some initial hardening configurations in order to improve the overall security of your SSH client.

      The exact hardening configuration that is most suitable for your client depends heavily on your own threat model and risk threshold. However, the configuration described in this step is a general, all-round secure configuration that should suit the majority of users.

      Many of the hardening configurations for OpenSSH client are implemented using the global OpenSSH client configuration file, which is located at /etc/ssh/ssh_config. In addition to this file, some configurations may also be set using the local SSH configuration file for your user, located at ~/.ssh/config.

      to set the majority of the hardening options in this tutorial. Before continuing it is a good idea create a backup of your existing configuration file so that you can restore it in the unlikely event that something goes wrong.

      Create a backup of the file using the following cp command:

      • sudo cp /etc/ssh/ssh_config /etc/ssh/ssh_config.bak
      • cp ~/.ssh/config ~/.ssh/config.bak

      These commands will save backup copies of the files in their default location, but with the .bak extension added.

      Note that your local SSH configuration file (~/.ssh/config) may not exist if you haven’t used it in the past. If this is the case, it can be safely ignored for now.

      You can now open the global configuration file using nano or your favorite text editor to begin implementing the initial hardening measures:

      • sudo nano /etc/ssh/ssh_config

      Note: The OpenSSH client configuration file includes many default options and configurations. Depending on your existing client setup, some of the recommended hardening options may already have been set.

      When editing your configuration file, some options may be commented out by default using a single hash character (#) at the start of the line. In order to edit these options, or enable the option, you’ll need to uncomment them by removing the hash.

      First, disable X11 display forwarding if you are not using it by setting the following options:

      /etc/ssh/ssh_config

      ForwardX11 no
      ForwardX11Trusted no
      

      X11 forwarding allows for the display of remote graphical applications over an SSH connection, however this is rarely used in practice. By disabling it, you can prevent potentially malicious or compromised servers from attempting to forward an X11 session to your client, which in some cases can allow for filesystem permissions to be bypassed, or for local keystrokes to be monitored.

      Next, consider disabling SSH tunneling. SSH tunneling is quite widely used, so you may need to keep it enabled. You will generally know if you are using it. If it isn’t required for your particular setup, you can safely disable it as a further hardening measure:

      /etc/ssh/ssh_config

      Tunnel no
      

      You should also consider disabling SSH agent forwarding if it isn’t required, in order to prevent servers from requesting to use your local SSH agent to authenticate onward SSH connections:

      /etc/ssh/ssh_config

      ForwardAgent no
      

      In the majority of cases, your SSH client will be configured to use password authentication or public-key authentication when connecting to servers. However, OpenSSH client also supports other authentication methods, some of which are enabled by default. If these are not required, they can be disabled to further reduce the potential attack surface of your client:

      /etc/ssh/ssh_config

      GSSAPIAuthentication no
      HostbasedAuthentication no
      

      If you’d like to know more about some of the additional authentication methods available within SSH, you may wish to review these resources:

      OpenSSH client allows you to automatically pass custom environment variables when connecting to servers, for example, to set a language preference or configure terminal settings. However, if this isn’t required in your setup, you can prevent any variables being sent by ensuring that the SendEnv option is commented out or completely removed:

      /etc/ssh/ssh_config

      # SendEnv
      

      Finally, you should ensure that strict host key checking is enabled, to ensure that you are appropriately warned when the host key/fingerprint of a remote server changes, or when connecting to a new server for the first time:

      /etc/ssh/ssh_config

      StrictHostKeyChecking ask
      

      This will prevent you from connecting to a server when the known host key has changed, which could mean that the server has been rebuilt or upgraded, or could be indicative of an ongoing person-in-the-middle attack.

      When connecting to a new server for the first time, your SSH client will ask you whether you want to accept the host key and save it in your ~/.ssh/known_hosts file. It’s important that you verify the host key before accepting it, which usually involves asking the server administrator or browsing the documentation for the service (in the case of GitHub/GitLab and other similar services).

      Save and exit the file.

      Now that you’ve completed your initial configuration file hardening, you should validate the syntax of your new configuration by running SSH in test mode:

      You can substitute the . with any hostname to test/simulate any settings contained within Match or Host blocks.

      If your configuration file has a valid syntax, the options that will apply to that specific connection will be printed out. In the event of a syntax error, there will be output that describes the issue.

      You do not need to restart any system services for your new configuration to take effect, although existing SSH sessions will need to be re-established if you want them to inherit the new settings.

      In this step, you completed some general hardening of your OpenSSH client configuration file. Next, you’ll restrict the ciphers that are available for use in SSH connections.

      Step 2 — Restricting Available Ciphers

      OpenSSH supports a number of different cipher algorithms to encrypt data over a connection. In this step you will disable deprecated or legacy cipher suites within your SSH client.

      Begin by opening your global configuration file in nano or your preferred text editor:

      • sudo nano /etc/ssh/ssh_config

      Ensure that the existing Ciphers configuration line is commented out by prefixing it with a single hash (#).

      Then, add the following to the top of the file:

      /etc/ssh/ssh_config

      Ciphers -arcfour*,-*cbc
      

      This will disable the legacy Arcfour ciphers, as well as all ciphers using Cipher Block Chaining (CBC), which are no longer recommended for use.

      If there is a requirement to connect to systems that only support these legacy ciphers, you can explicitly re-enable the required ciphers for specific hosts by using a Match block. For example, to enable the 3des-cbc cipher for a specific legacy host, the following configuration could be used:

      /etc/ssh/ssh_config

      Match host legacy-server.your-domain
        Ciphers +3des-cbc
      

      Save and exit the file when you are done editing it. If you are using nano press CTRL+O and then ENTER to save the file, then CTRL+X to exit.

      Finally, as in Step 1, test your SSH client configuration to check for any potential errors:

      If you have added a Match block to enable legacy ciphers for a specific host, you can also specifically target that configuration during the test by specifying the associated host address:

      • ssh -G legacy-server.your-domain

      You’ve secured the ciphers available to your SSH client. Next, you will review the access permissions for files used by your SSH client.

      Step 3 — Securing Configuration File and Private Key Permissions

      In this step, you’ll lock down the permissions for your SSH client configuration files and private keys to help prevent accidental or malicious changes, or private key disclosure. This is especially useful when using a shared client device between multiple users.

      By default on a fresh installation of Ubuntu, the OpenSSH client configuration file(s) are configured so that each user can only edit their own local configuration file (~/.ssh/config), and sudo/administrative access is required to edit the system-wide configuration (/etc/ssh/ssh_config).

      However, in some cases, especially on systems that have been in existence for a long time, these configuration file permissions may have been accidentally modified or adjusted, so it’s best to reset them to make sure that the configuration is secure.

      You can begin by checking the current permissions value for the system-wide OpenSSH client configuration file using the stat command, which you can use to show the status or files and/or filesystem objects:

      • stat -c "%a %A %U:%G" /etc/ssh/ssh_config

      You use the -c argument to specify a custom output format.

      Note: On some operating systems, such as macOS, you will need to use the -f option to specify a custom format rather than -c.

      In this case, the %A %a %U:%G options will print the permissions for the file in octal and human-readable format, as well as the user/group that owns the file.

      This will output something similar to the following:

      Output

      644 -rw-r--r-- root:root

      In this case, the permissions are correct, root owns the file entirely, and only root has permission to write to/modify it.

      Note: If you’d like to refresh your knowledge on Linux permissions before continuing, you may wish to review An Introduction to Linux Permissions.

      However, if your own output is different, you should reset the permissions back to the default using the following commands:

      • sudo chown root:root /etc/ssh/ssh_config
      • sudo chmod 644 /etc/ssh/ssh_config

      If you repeat the stat command from earlier in this step, you will now receive the correct values for your system-wide configuration file.

      Next, you can carry out the same checks for your own local SSH client configuration file, if you have one:

      • stat -c "%a %A %U:%G" ~/.ssh/config

      Now the stat command should output the following:

      Output

      644 -rw--r--r-- user:user

      If the permissions for your own client configuration file permissions are any different, you should reset them using the following commands, similarly to earlier in the step:

      • chown user:user ~/.ssh/config
      • chmod 644 ~/.ssh/config

      Next, you can check the permissions for each of the SSH private keys that you have within your ~/.ssh directory, as these files should only be accessible by yourself, and not any other users on the system.

      Begin by printing the current permission and ownership values for each private key:

      • stat -c "%a %A %U:%G" ~/.ssh/id_rsa

      This will output something similar to the following:

      Output

      600 -rw------- user:user

      It is extremely important that you properly lock down the permissions for your private key files, as failing to do so could allow other users of your device to steal them and access the associated servers or remote user accounts.

      If the permissions aren’t properly configured, use the following commands on each private key file to reset them to the secure defaults:

      • chown user:user ~/.ssh/id_rsa
      • chmod 600 ~/.ssh/id_rsa

      In this step, you assessed and locked down the file permissions for your SSH client configuration files and private keys. Next, you will implement an outbound allowlist to limit which servers your client is able to connect to.

      Step 4 — Restricting Outgoing Connections Using a Host Allowlist

      In this final step, you will implement an outgoing allowlist in order to restrict the hosts that your SSH client is able to connect to. This is especially useful for shared/multi-user systems, as well as SSH jump hosts or bastion hosts.

      This security control is specifically designed to help protect against human error/mistakes, such as mistyped server addresses or hostnames. It can be easily bypassed by the user by editing their local configuration file, and so isn’t designed to act as a defense against malicious users/actors.

      If you want to restrict outbound connections at the network level, the correct way to do this is using firewall rules. This is beyond the scope of this tutorial, but you can check out UFW Essentials: Common Firewall Rules and Commands.

      However, if you want to add some additional fail-safes, then this security control may be of benefit to you.

      It works by using a wildcard rule within your SSH client configuration file to null route all outbound connections, apart from those to specific addresses or hostnames. This means that if you were ever to accidentally mistype a server address, or attempt to connect to a server that you’re not supposed to, the request would be stopped immediately, giving you the opportunity to realize your mistake and take corrective action.

      You can apply this at either the system-level (/etc/ssh/ssh_config) or using your local user configuration file (~/.ssh/config). In this example, we will use the local user configuration file.

      Begin by opening the file using nano, creating it if it doesn’t already exist:

      At the bottom of the file, add the following content, substituting in your own list of allowed IP addresses and hostnames:

      ~/.ssh/config

      Match host !203.0.113.1,!192.0.2.1,!server1.your-domain,!github.com,*
        Hostname localhost
      

      This configuration tells your SSH client that for any host or IP that is not included in the list, the client should substitute the name localhost instead before attempting to connect. The wildcard (*) option without a prefixed exclamation point option at the end of the Match line ensures that any host that is not included in the list will default to being null routed.

      You must prefix IP addresses or hostnames with an exclamation point (!) since this tells SSH to not apply the null routing for the hostname or IP address. Additionally, you must use commas to separate each item in the list.

      If you’re running an SSH server on your machine too, you may wish to use a hostname value other than localhost, as this will cause the null routed connections to be sent to your own local SSH server, which could be counterproductive or confusing. Any nullrouted hostname is acceptable, such as null, do-not-use, or disallowed-server.

      Save and close the file once you’ve made your changes.

      You can now test that the configuration is working by attempting to connect to a disallowed destination using your SSH client. For example:

      • ssh disallowed.your-domain

      If the configuration is working properly, you will immediately receive an error similar to the following:

      Output

      Cannot connect to localhost: connection refused

      However, when you attempt to connect to an allowed destination, the connection will succeed as normal.

      In this final step, you implemented some additional fail-safes to help protect against human error and mistakes when using your SSH client.

      Conclusion

      In this article you reviewed your OpenSSH client configuration and implemented various hardening measures.

      This will have improved the security of your outgoing SSH connections, as well as helping to ensure that your local configuration files cannot be accidentally or maliciously modified by other users.

      You may wish to review the manual pages for OpenSSH client and its associated configuration file to identify any potential further tweaks that you want to make:

      Finally, if you want to harden OpenSSH at the server side too, check out How To Harden OpenSSH on Ubuntu 20.04.



      Source link

      How To Create SSH Keys with OpenSSH on macOS, Linux, or Windows Subsystem for Linux


      Introduction

      When setting up a remote Linux server, you’ll need to decide upon a method for securely connecting to it. While passwords are one way of verifying a user’s identity, passwords have multiple vulnerabilities and can be cracked by a brute force attack. Secure Shell keys — better known as SSH keys — are often used instead of passwords, as they offer a more secure method of connecting to remote Linux servers. As part of the Secure Shell cryptographic network protocol, SSH keys also enable users to securely perform network services over an unsecured network, such as delivering text-based commands to a remote server or configuring its services.

      This tutorial will guide you through the steps of creating SSH keys with OpenSSH, a suite of open source SSH tools, on macOS and Linux, as well as on Windows through the use of the Windows Subsystem for Linux. It is written for an audience that is just getting started with the command line and will provide guidance on accessing the terminal on a personal computer. After completing this tutorial, you will have SSH keys that can be used to securely set up a server in the tutorial How To Set Up an Ubuntu 20.04 Server on a DigitalOcean Droplet that is part of the Introduction to the Cloud Curriculum (coming soon).

      If you are already familiar with the command line and looking for instructions on using SSH to connect to a remote server, please see our collection of tutorials on Setting Up SSH Keys for a range of Linux operating systems.

      Prerequisites

      To complete this tutorial, you will need:

      • A local machine running one of the following operating systems: macOS, Linux, or Windows with Windows Subsystem for Linux installed. If you are using Windows, you can find instructions for downloading or updating the Windows Subsystem for Linux on Microsoft’s documentation page. Note that while OpenSSH should work for a range of Linux distributions, this tutorial has been tested using Ubuntu 20.04.

      Note: If you are looking for instructions on how to create SSH keys on a Windows machine that does not have the Windows Subsystem for Linux, please visit our product documentation How to Create SSH Keys with PuTTY on Windows.

      • Some familiarity with working with a terminal and the command line. If you need an introduction to working with terminals and the command line, you can visit our guide A Linux Command Line Primer (coming soon).

      Step 1 — Understanding SSH Keys

      SSH keys are two long strings of characters that can be used to authenticate the identity of a user requesting access to a remote server. These keys are generated by the user on their local computer using a SSH utility. One key is private and stored on the user’s local machine. The other key is public and shared with the remote server or any other entity the user wishes to securely communicate with.

      When a user requests to connect to a server with SSH, the server sends a message encrypted with the public key that can only be decrypted by the associated private key. The user’s local machine then uses its private key to attempt to decrypt the message. If the message is successfully decrypted, the server grants the user access without the need of a password. Once authenticated, users can launch a remote shell session in their local terminal to deliver text-based commands to the remote server.

      In the next step, you will open a terminal on your computer so that you can access the SSH utility used to generate a pair of SSH keys.

      Step 2 — Opening a Terminal on Your Computer

      A terminal allows you to interact with your computer through text-based commands rather than a graphical user interface. The way you access the terminal on your computer will depend on what type of operating system you are using.

      On machines running macOS, the Terminal application is typically located in the Utilities folder inside the Applications folder. You can also find it by searching for “terminal” in the Search Spotlight.

      If you are working on a Linux computer, your distribution’s default terminal application is also typically located in the Utilities folder inside the Applications folder. You can also find it by searching for “terminal” with the Desktop search functionality.

      If you are working on a Windows machine running Windows Subsystem for Linux, a Linux terminal should open immediately after installation. You can also find it by searching for “Ubuntu” with the Desktop search functionality.

      Once you have located your system’s terminal application, open up a new terminal window. Your terminal should display your user name, a dollar sign ($), and a cursor. This is where you will begin to type commands to tell the terminal what to do.

      In the next step, you will enter a text-based command to generate a pair of SSH keys.

      Step 3 — Generating Keys With OpenSSH

      Your macOS or Linux operating system should have the standard OpenSSH suite of tools already installed. This suite of tools includes the utility ssh-keygen, which you will use to generate a pair of SSH keys.

      Type the following command into your terminal:

      You will then be prompted to select a location for the keys. By default, the keys are stored in the ~/.ssh directory with the filenames id_rsa for the private key and id_rsa.pub for the public key. Using the default locations allows your SSH client to automatically find your SSH keys when authenticating, so we recommend accepting these default options. To do so, press ENTER:

      Output

      Generating public/private rsa key pair. Enter file in which to save the key (/home/sammy/.ssh/id_rsa):

      Warning: If you have previously generated a key pair, you will be prompted to confirm that you actually want to overwrite the existing key:

      Output

      /home/sammy/.ssh/id_rsa already exists. Overwrite (y/n)?

      If you choose to overwrite the key on disk, you will not be able to authenticate using the previous key anymore. Selecting “yes” is an irreversible destructive process.

      If you’re certain that you want to overwrite the existing key on disk, you can do so by pressing Y and then ENTER.

      If you choose the default location, your public key will be located in /home/sammy/.ssh/id_rsa.pub and your private key will be located in /home/sammy/.ssh/id_rsa. Note that in your filepath, sammy will be replaced with your username.

      After selecting a location for the key, you’ll be prompted to enter an optional passphrase which encrypts the private key file on disk.

      If you enter a passphrase, you will have to provide it every time you use this key (unless you are running SSH agent software that stores the decrypted key). We recommend using a passphrase, but you can just press ENTER to bypass this prompt:

      Output

      Created directory '/home/sammy/.ssh'. Enter passphrase (empty for no passphrase): Enter same passphrase again:

      Following that final prompt, your system will generate the SSH key pair:

      Output

      Your identification has been saved in /home/sammy/.ssh/id_rsa. Your public key has been saved in /home/sammy/.ssh/id_rsa.pub. The key fingerprint is: a9:49:EX:AM:PL:E3:3e:a9:de:4e:77:11:58:b6:90:26 sammy@203.0.113.0 The key's randomart image is: +--[ RSA 2048]----+ | ..o | | E o= . | | o. o | | .. | | ..S | | o o. | | =o.+. | |. =++.. | |o=++. | +-----------------+

      You now have a public and private key that you can use to authenticate.

      Conclusion

      Congratulations, you have now generated a pair of SSH keys. These keys can be used to securely connect with a remote server and are necessary for the tutorial How To Set Up an Ubuntu 20.04 Server on a DigitalOcean Droplet that follows this tutorial in the Introduction to the Cloud Curriculum (coming soon).

      For a deeper dive on working using SSH, please visit our guide SSH Essentials: Working With SSH Servers, Clients, and Keys.



      Source link