Managing SSH
Theory Questions
1. Identify common approaches to prevent brute-force attacks against SSH servers.
- Command(s) / Configuration:
In
/etc/ssh/sshd_configor/etc/ssh/sshd_config.d/01-hardening.conf:
PermitRootLogin no
PasswordAuthentication no
Port 2022
MaxAuthTries 3
AllowUsers lisa user1
Firewalld rate-limiting rich rule:
firewall-cmd --permanent --add-rich-rule='rule service name="ssh" accept limit value="4/m"'
firewall-cmd --reload
- Why: Disabling direct root login and password authentication forces attackers to compromise unprivileged key-authenticated accounts first. Changing the default port (TCP 22) eliminates automated script scanning, while
MaxAuthTriesand firewalld rich rules rate-limit repeated connection attempts. - Gotchas: Disabling
PasswordAuthenticationbefore adding your public SSH key to~/.ssh/authorized_keyswill lock you out of remote system access. - Verify:
sshd -T | grep -E "permitrootlogin|passwordauthentication|maxauthtries"
2. Limit SSH server access to specific users only.
- Command(s) / Configuration:
Add the
AllowUsersdirective to/etc/ssh/sshd_config.d/01-users.conf:
AllowUsers lisa john adminuser
Then reload the daemon:
systemctl reload sshd
- Why:
AllowUsersacts as an explicit whitelist. When populated, only listed usernames are permitted to authenticate; all other user accounts are automatically denied SSH access. - Gotchas: If you configure
AllowUsersand omit your current active administrative account, you will be locked out of SSH access as soon as the daemon reloads. - Verify:
sshd -T | grep -i "allowusers"
3. Provide the correct SELinux label for a non-default SSH port.
- SELinux Type / Command:
semanage port -a -t ssh_port_t -p tcp 2022
- Why: The SELinux target type
ssh_port_tdefines which network port numbers the SSH daemon process domain (sshd_t) is authorized to bind to. - Gotchas: Updating
sshd_configwith a custom port and opening the firewall port without labeling the port in SELinux will causesshd.serviceto crash on startup with aPermission deniederror. - Verify:
semanage port -l | grep ssh_port_t
4. Interpret the MaxAuthTries SSH option.
- Command(s) / Configuration:
MaxAuthTries 3
- Why:
MaxAuthTriesspecifies the maximum number of failed authentication attempts permitted per network connection. Once this threshold is reached,sshddrops the connection and logs an error to/var/log/secure. - Gotchas: Setting
MaxAuthTriestoo low (e.g.,1or2) can cause issues for client systems using SSH agents that automatically offer multiple identity keys before presenting the correct one. - Verify:
sshd -T | grep maxauthtries
5. Identify the log file for failed SSH login attempts.
- Path / Command:
/var/log/secure
# OR
journalctl -u sshd | grep "Failed"
- Why: On RHEL distributions,
rsyslogroutes authentication, PAM, and daemon security events (including SSH login successes and failures) to/var/log/secure. - Gotchas: Searching for
/var/log/auth.logon RHEL systems (which is the Debian/Ubuntu default file location). - Verify:
grep "Failed password" /var/log/secure | tail -n 10
6. Diagnose slow SSH login in a test environment.
- Command(s) / Configuration:
Add the following directives to
/etc/ssh/sshd_config.d/01-performance.conf:
UseDNS no
GSSAPIAuthentication no
Reload the service:
systemctl reload sshd
- Why:
UseDNS yesforcessshdto perform a reverse DNS PTR lookup on connecting client IP addresses. If DNS resolution is misconfigured or unreachable, the connection hangs until the lookup times out (typically 10–30 seconds). - Gotchas: Assuming login delays are caused by network bandwidth issues; delayed password prompts are almost always caused by failed reverse DNS lookups (
UseDNS). - Verify:
sshd -T | grep -E "usedns|gssapiauthentication"
7. Identify SSH options used to keep connections alive.
- Command(s) / Configuration:
Server-side (
/etc/ssh/sshd_config):
ClientAliveInterval 300
ClientAliveCountMax 3
Client-side (~/.ssh/config or /etc/ssh/ssh_config):
ServerAliveInterval 300
ServerAliveCountMax 3
- Why: Sends encrypted probe packets across idle tunnels to prevent stateful network firewalls and NAT routers from dropping inactive TCP sessions.
- Gotchas: Leaving
ClientAliveIntervalat0(the default), which causes the server to never send keep-alive checks to idle clients. - Verify:
sshd -T | grep clientalive
8. Set the ServerKeepAliveInterval for an individual SSH client user.
- Command(s) / Configuration:
Edit
~/.ssh/config:
Host *
ServerAliveInterval 300
ServerAliveCountMax 3
Set file permissions:
chmod 0600 ~/.ssh/config
- Why:
ServerAliveIntervalsends keep-alive messages from client to server at defined second intervals without modifying global system configurations under/etc/ssh/. - Gotchas: Misspelling the client directive as
ServerKeepAliveIntervalinstead ofServerAliveInterval. - Verify:
ssh -G hostname | grep -i "serveraliveinterval"
9. Configure passphrase caching so it must be entered only once per session.
- Command(s):
eval $(ssh-agent)
ssh-add ~/.ssh/id_rsa
- Why:
ssh-agentholds decrypted private key passphrases in volatile RAM memory. Subsequent outbound SSH connections retrieve the decrypted key directly from the agent via socket. - Gotchas: Closing the terminal window or logging out terminates the active subshell context, requiring
eval $(ssh-agent)to be run again unless integrated into user profile scripts. - Verify:
ssh-add -l
10. Identify the default value for the MaxSessions SSH option.
- Command(s):
sshd -T | grep maxsessions
- Why: The default value for
MaxSessionsis10. It specifies the maximum number of open shell, login, or subsystem (e.g., SFTP) channels permitted per single TCP network connection. - Gotchas: Confusing
MaxSessions(multiplexed channels per single TCP connection) withMaxStartups(unauthenticated concurrent connection attempts). - Verify: Output displays:
maxsessions 10
11. Cache the passphrase set on a private key.
- Command(s):
ssh-add ~/.ssh/id_rsa
- Why:
ssh-addprompts for the private key passphrase once and caches the identity in the backgroundssh-agentdaemon environment. - Gotchas: Executing
ssh-addwhenssh-agentis not running returnsCould not open a connection to your authentication agent. - Verify:
ssh-add -l
12. Disallow root login and allow only a specific user to log in.
- Command(s) / Configuration:
Add the following lines to
/etc/ssh/sshd_config.d/01-hardening.conf:
PermitRootLogin no
AllowUsers lisa
Apply settings:
systemctl reload sshd
- Why: Explicitly revokes administrative root access over SSH while whitelisting
lisaas the single user account authorized to establish remote SSH sessions. - Gotchas: Omitting
systemctl reload sshd; configuration file changes will not affect active or new daemon sessions until reloaded. - Verify:
sshd -T | grep -E "permitrootlogin|allowusers"
13. Configure the SSH server to listen on multiple ports.
- Command(s) / Configuration:
In
/etc/ssh/sshd_configor drop-in file:
Port 22
Port 2022
Configure SELinux and Firewalld:
semanage port -a -t ssh_port_t -p tcp 2022
firewall-cmd --permanent --add-port=2022/tcp
firewall-cmd --reload
systemctl restart sshd
- Why: Specifying multiple
Portlines causessshdto bind socket listeners to each declared TCP port simultaneously. - Gotchas: Forgetting to update SELinux port context (
semanage port) or firewall rules for the secondary port, causing binding or connection failures. - Verify:
ss -tulpn | grep sshd
14. Identify the main SSH server configuration file.
- Path / Command:
/etc/ssh/sshd_config
/etc/ssh/sshd_config.d/*.conf
- Why:
/etc/ssh/sshd_configis the primary runtime configuration file forsshd.service. In RHEL 9, modular drop-in files under/etc/ssh/sshd_config.d/are included at the top of the file. - Gotchas: Editing
/etc/ssh/ssh_config(the client configuration file) instead of/etc/ssh/sshd_config(the server daemon configuration file). - Verify:
sshd -t
(Returns zero output if configuration file syntax is valid)
15. Identify where a cached passphrase is stored.
- Location / Command:
Volatile RAM memory managed by the
ssh-agentprocess (accessed via UNIX socket$SSH_AUTH_SOCK). - Why: Passphrases are stored in memory to prevent plain-text credentials from being written to disk storage.
- Gotchas: Passphrase caches do not persist across system reboots; restarting the host clears the agent memory cache.
- Verify:
echo $SSH_AUTH_SOCK
16. Identify the file containing SSH client settings for all users.
- Path / Command:
/etc/ssh/ssh_config
/etc/ssh/ssh_config.d/*.conf
- Why:
/etc/ssh/ssh_configprovides global default configuration properties for outbound connections initiated by thesshbinary for all users on the host. - Gotchas: Confusing client settings (
/etc/ssh/ssh_config) with server settings (/etc/ssh/sshd_config). - Verify:
cat /etc/ssh/ssh_config
17. Set the maximum number of concurrent SSH sessions.
- Command(s) / Configuration:
In
/etc/ssh/sshd_config.d/01-limits.conf:
MaxSessions 5
Or to restrict unauthenticated concurrent connection attempts:
MaxStartups 10:30:100
Reload daemon:
systemctl reload sshd
- Why:
MaxSessionslimits the number of open channel sessions per single network connection.MaxStartupslimits unauthenticated concurrent connections to prevent denial-of-service attacks. - Gotchas: Setting
MaxSessions 0prevents users from opening interactive shell sessions or running remote commands. - Verify:
sshd -T | grep -E "maxsessions|maxstartups"
18. Configure SELinux to allow SSH on a non-default port.
- Command(s):
semanage port -a -t ssh_port_t -p tcp 2022
- Why:
--add(-a) maps port2022/tcpto SELinux typessh_port_t, allowing the confined daemon domain (sshd_t) to open listening sockets on that port. - Gotchas: Running
semanage port -aon a port already defined in SELinux policy returns an error; usesemanage port -m(modify) if the port exists under another type. - Verify:
semanage port -l | grep ssh_port_t
19. Configure the firewall to allow incoming SSH connections on a non-default port.
- Command(s):
firewall-cmd --permanent --add-port=2022/tcp
firewall-cmd --reload
- Why: Standard service definition
--add-service=sshopens default TCP port 22 only. Custom ports require explicit--add-portrules in Firewalld. - Gotchas: Running
firewall-cmd --add-port=2022/tcpwithout--permanent. The rule will work immediately but will be lost on the next system reboot or firewall reload. - Verify:
firewall-cmd --list-ports
20. Resolve long timeouts when establishing SSH connections.
- Command(s) / Configuration:
In
/etc/ssh/sshd_config.d/01-fastlogin.conf:
UseDNS no
Reload configuration:
systemctl reload sshd
- Why: Setting
UseDNS noskips reverse DNS PTR lookups during authentication, resolving connection stalls caused by missing or misconfigured DNS servers. - Gotchas: Forgetting to run
systemctl reload sshdafter modifying the drop-in file. - Verify:
sshd -T | grep usedns
Lab Tasks
Lab 20.1: SSH Hardening Practice
Task: Configure the SSH server so that inactive sessions remain open for at least one hour. Secure the SSH server to listen on port 2022 only, and allow only user lisa to log in. Test the settings from server2. Ensure both the firewall and SELinux are configured to support the new port and restrictions.
- Command(s):
# Step 1: Ensure user lisa exists on the server
id lisa &>/dev/null || useradd lisa
echo "password" | passwd --stdin lisa
# Step 2: Configure SELinux to allow SSH on TCP port 2022
semanage port -a -t ssh_port_t -p tcp 2022
# Step 3: Configure Firewalld to allow port 2022 and remove default SSH port
firewall-cmd --permanent --add-port=2022/tcp
firewall-cmd --permanent --remove-service=ssh
firewall-cmd --reload
# Step 4: Create modular drop-in file for SSH hardening configuration
cat << 'EOF' > /etc/ssh/sshd_config.d/01-hardening.conf
Port 2022
ClientAliveInterval 3600
ClientAliveCountMax 0
AllowUsers lisa
EOF
# Step 5: Test configuration file syntax before restarting service
sshd -t
# Step 6: Restart SSH daemon to bind exclusively to port 2022
systemctl restart sshd
-
Why:
-
semanage port -a -t ssh_port_t -p tcp 2022: Updates SELinux policy sosshdcan bind to non-standard port 2022. -
firewall-cmd --permanent --add-port=2022/tcp: Opens incoming TCP port 2022 persistently in Firewalld. -
ClientAliveInterval 3600&ClientAliveCountMax 0: Keeps idle sessions active for 3600 seconds (1 hour) before timing out. -
Port 2022: Overrides default port 22 sosshdbinds exclusively to port 2022. -
AllowUsers lisa: Limits remote SSH logins strictly to accountlisa. -
Gotchas:
-
Changing
Port 2022insshd_configwithout configuring SELinux first.sshd.servicewill fail to start upon restart. -
Forgetting
--permanentonfirewall-cmdcommands, causing port 2022 to become unreachable after system reboot. -
Excluding user
lisaor failing to set a valid user password during testing fromserver2. -
Verify from Local Host:
# Check listening ports:
ss -tulpn | grep sshd
# Verify active runtime settings:
sshd -T | grep -E "port|clientaliveinterval|allowusers"
(Output should display port 2022, clientaliveinterval 3600, and allowusers lisa)
- Verify Remote Connectivity from
server2:
# Test connection as lisa on port 2022 (Should succeed):
ssh -p 2022 lisa@server1.example.com
# Test connection on default port 22 (Should fail/time out):
ssh -p 22 lisa@server1.example.com
# Test connection as another user on port 2022 (Should be denied):
ssh -p 2022 root@server1.example.com
- Reboot Persistence Verification:
# Reboot system:
reboot
# Post-reboot checks:
systemctl is-active sshd
semanage port -l | grep ssh_port_t
firewall-cmd --list-ports | grep 2022
(Confirms sshd is running on port 2022 with SELinux and Firewalld rules intact across system reboots)