SSH, or Secure Shell, is a cryptographic network protocol used to securely access, manage, and transfer data between remote machines. It uses public-key cryptography to authenticate the remote machine and encrypt data sent over the connection.

The sshd_config file is the core configuration file for the OpenSSH daemon (sshd) on Linux and Unix-like systems. It controls the operation of sshd, which handles incoming SSH connections – both legitmate users and potential attackers probing for access.

Properly configuring sshd_config is critical for securing SSH. In this comprehensive guide, we dive deep into all aspects of sshd_config for Linux systems.

How SSH Works

Before jumping into sshd_config, we need to understand how SSH connections are established at a protocol level:

  1. The client initiates a TCP handshake with the server on port 22 (or another configured listen port)
  2. The server sends its public host key which uniquely identifies it
  3. The client checks the host key against previously seen keys for that server IP/port
  4. If the key is valid, the client generates a random symmetric session key, encrypts it with the server‘s public key, and sends it
  5. The server decrypts the session key with its private key
  6. Client and server use the session key to encrypt all further communications

This handshake ensures secure key exchange between parties and enables encrypting the session. Both ends generate session keys independently every time.

Now let‘s explore how sshd_config controls this process and secures SSH connections overall.

Introduction to sshd_config

The main sshd configuration file is located at /etc/ssh/sshd_config. It must be readable by root only for security. The file has a simple format – each line contains a space-delimited pair:

Port 22
ListenAddress 0.0.0.0
HostKey /etc/ssh/ssh_host_rsa_key 

Everything after a # is a comment. Blank lines and whitespace is ignored.

If a directive is specified multiple times, the last occurrence wins. Unspecified directives fall back to default compile-time values.

Now let‘s explore the purpose of key sshd directives.

Main Configuration Directives

Port

Port 22

Sets the TCP port number sshd listens on for connections. The standard port is 22 but can be changed if desired, e.g. for security by obscurity reasons.

ListenAddress

ListenAddress 0.0.0.0
ListenAddress 192.168.1.5  

Restricts interfaces sshd binds to, default is all available interfaces. Often changed to whitelist internal IPs in cloud environments.

HostKey

  
HostKey /etc/ssh/ssh_host_rsa_key  

Specifies private host key files which identify the server. There should be one for each encryption algorithm – RSA, ED25519, ECDSA etc.

If these keys ever change, clients will show man-in-the-middle attack warnings.

SyslogFacility / LogLevel

SyslogFacility AUTH   
LogLevel INFO

Control logging verbosity and which syslog facility to log to. LOG_AUTH provides the most pertinent logs for sshd.

LoginGraceTime

LoginGraceTime 20

Sets maximum time in seconds allowed for successful login before disconnecting. Prevents brute-force password attacks.

There are many other important directives – we cover more next.

Authentication Directives

Authentication directives control what credentials are allowed to login:

PermitRootLogin

  
PermitRootLogin no

Allows/denies direct login access for root account. Should always be set to no except for specific emergency cases.

PasswordAuthentication

PasswordAuthentication no 

Enables/disables password-based login. Should be set to no to require public key authentication only unless explicitly needed.

AllowUsers/AllowGroups

AllowUsers john tim  
AllowGroups developers

Whitelist users and groups allowed to login. Often used to only allow developer accounts and not general users.

There are many other options – we focus on the most common directives here.

Secure Configuration Directives

Protocol

Protocol 2

Specifies SSH protocol version from 1-2. Version 1 is vulnerable and outdated, so always stick to 2.

Ciphers

Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com  

Selects permitted encryption ciphers in order of preference, with faster ones first. These modern ciphers offer high security.

Weak ciphers should be avoided as they are vulnerable to attacks.

MACs

  
MACs hmac-sha2-512-etm@openssh.com  

Message Authentication Code algorithms that verify packet integrity by detecting tampering. sha2 MACs offer robust security.

KexAlgorithms

KexAlgorithms curve25519-sha256 

Key exchange algorithms used to securely exchange session keys during the initial handshake. curver25519-sha256 is a high performance current standard.

These directives prevent downgrade attacks to weaker crypto options. There are many other advanced security directives as well – refer to sshd_config man pages for a complete reference.

Now let‘s look at some recommended general best practices for hardening SSH via sshd_config parameters.

Security Best Practices

Cybersecurity standards from organizations like NIST provide research-backed recommendations for optimally configuring sshd. Here are key best practices:

  • Use SSH Protocol 2 – it fixes vulnerabilities in earlier versions
  • Disable root login and password authentication
  • Whitelist specific user accounts allowed to login
  • Enforce SSH key-pair authentication only
  • Set idle login timeouts to prevent access from unattended sessions
  • Activate system logging at INFO or DEBUG level for auditability

These steps raise the bar for attackers remotely accessing a system via SSH.

We also need to keep OpenSSH updated to the latest version to incorporate security patches:

$ sudo apt update
$ sudo apt install openssh-server

Next we look at some examples of non-standard sshd_config usage.

Advanced Config Examples

Running Multiple sshd Instances

It‘s possible to run multiple sshd instances listening on different ports by passing the -f flag along with an alternate config file:

 
$ sudo /usr/sbin/sshd -f sshd_config_alt -p 2222  

Here we launch extra sshd on port 2222 using sshd_config_alt.

Port Forwarding

Tunnel traffic from remote hosts through SSH to other destinations:

AllowTcpForwarding yes
GatewayPorts yes

This permits port forwarding and gateway access to forwarded ports. Useful for certain network tools.

Privilege Separation

UsePrivilegeSeparation yes

Spawn unprivileged child process to contain impact of any vulnerabilities. Marginal performance hit but improved security.

We‘ve covered core concepts – now let‘s dive into troubleshooting sshd operation.

Troubleshooting sshd

Debugging connection issues or unexpected sshd behavior can be tricky. These steps help diagnose configurations:

1. Validate sshd_config Syntax

Always check new configs with:

$ sudo sshd -t  

If errors are reported, fix them before restarting sshd.

2. Restart sshd Service

For any config changes to apply:

 
$ sudo systemctl restart sshd

Current SSH connections will be dropped – warn users beforehand.

3. Invoke sshd in Debug Mode

$ sudo /usr/sbin/sshd -d

This prints verbose debugging output to pinpoint issues.

Alternatively logs can be checked with journalctl as well.

4. Run TCPDump

$ sudo tcpdump -i any ‘port 22‘

tcpdump sniffs SSH connection packets to analyze protocol discrepancies.

Together these steps help diagnose most sshd operational issues.

Comparing SSH Server Options

While OpenSSH is the most popular SSH implementation on Linux, alternatives like Dropbear offer reduced attack surface and smaller resource footprint more suited for embedded devices.

OpenSSH Dropbear
Config File sshd_config Dropbear itself
Memory Use High Low
Ciphers Many Fewer
Feature Set Very Extensive Minimal

Given its focus on minimalism, Dropbear lends itself better to IoT appliances vs. OpenSSH‘s vast capabilities and configurability suited for general purpose computing.

Conclusion

The sshd_config file enables detailed control over OpenSSH‘s functionality and security posture on Linux servers. Learning how to properly configure sshd_config directives like ciphers, protocols, keys, logging, and user access is critical for any Linux sysadmin. Following best practice hardening guidance from industry experts helps protect SSH against intrusions.

While we have covered the most important concepts here, there is incredible depth and flexibility to fully utilizing OpenSSH just within sshd_config alone. Refer to the man pages and continued education around infosec standards will serve Linux users well for further mastering the intricacies of SSH.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *