Linux · Lesson 09
SSH & Remote Access Security
Secure Linux remote administration by reviewing SSH service state, effective configuration, users, keys, authentication methods, listening exposure, firewall rules, and logs before changing access.
SSH is often both a security boundary and a required management path. The goal is to preserve authorized administration while reducing unnecessary users, authentication methods, and network exposure.
Lesson Snapshot
Learning objectives
Secure SSH without locking out the required administrator
Explain how SSH fits into Linux remote administration and why remote-access security must preserve required access.
Inspect SSH server state, effective configuration, listening ports, authorized users, and key-based access before changing anything.
Distinguish server-wide SSH policy from user-level SSH authorization.
Review password authentication, public-key authentication, root login, port exposure, and firewall dependencies without applying one universal setting everywhere.
Use sshd validation and effective-configuration commands before restarting the service.
Verify required remote access from the client perspective after every meaningful SSH or firewall change.
Core idea
Required remote access should be narrowed, not destroyed
If the scenario requires SSH, the job is to permit the correct administrator, use appropriate authentication, expose only the necessary network path, and preserve evidence.
Lockout risk
Authentication and firewall changes can remove your own access
Validate configuration first, keep the current session open when practical, and test a second authorized connection before ending the known-good administrative path.
SSH fundamentals
Six concepts behind remote administration
SSH server
The OpenSSH server accepts remote administrative connections when installed, enabled, running, reachable, and permitted by authentication policy.
SSH client
The ssh command initiates outbound connections. A system can have an SSH client installed even when no SSH server is running.
Authentication method
SSH can use passwords, public keys, and other methods depending on configuration. The scenario determines which methods must remain available.
Authorization
An account may exist locally but still be denied SSH through server policy, shell restrictions, key configuration, groups, or firewall controls.
Network exposure
The service must listen on an address and port and be reachable through host firewall and network controls. Security involves both authentication and exposure.
Effective configuration
The active SSH configuration may come from the main file, included drop-ins, defaults, and Match blocks. Inspect the effective result rather than trusting one line.
Important SSH paths
Server policy and user authorization live in different places
/etc/ssh/sshd_configPrimary OpenSSH server configuration file on systems where the server is installed.
Do not restart sshd after editing until the configuration validates.
/etc/ssh/sshd_config.d/Drop-in directory that can add or override SSH server settings.
Effective behavior may differ from the main file because included configuration applies later.
~/.ssh/authorized_keysCommon per-user file containing public keys authorized for SSH login.
A locked local password does not necessarily prevent key-based SSH access.
~/.ssh/User-level SSH directory that can contain authorized keys, known hosts, configuration, and private keys.
Permissions matter. Private keys and authorization files should not be exposed broadly.
/etc/ssh/ssh_host_*Server host keys used to identify the SSH server to clients.
Do not regenerate or delete host keys casually; doing so changes server identity and can trigger client warnings.
/var/log/auth.log or journalAuthentication evidence may include successful and failed SSH activity depending on system logging configuration.
Log location and retention vary. Use journalctl and available log files together.
Inspection first
Build the SSH access picture before changing it
systemctl status sshShow current SSH service state, recent logs, and process information on Ubuntu-family systems using the ssh unit name.
systemctl is-enabled sshCheck whether SSH is configured for automatic startup.
sudo sshd -tValidate SSH server configuration syntax without restarting the service.
sudo sshd -TShow effective SSH server settings after defaults and includes are processed.
sudo sshd -T | grep -E '^(port|listenaddress|passwordauthentication|pubkeyauthentication|permitrootlogin|maxauthtries|allowusers|allowgroups|denyusers|denygroups)'Review selected effective access-control and exposure settings quickly.
ss -tulpn | grep -E '(:22\b|sshd)'Check whether sshd is listening and on which addresses/ports.
sudo ufw status verboseReview host firewall policy and whether SSH traffic is allowed.
getent passwd usernameCheck the account's shell and home directory as part of remote-access review.
id usernameReview groups that may affect SSH AllowGroups or other authorization rules.
sudo ls -la /home/username/.sshInspect user SSH files, ownership, and permissions before changing them.
sudo cat /home/username/.ssh/authorized_keysReview authorized public keys when permitted and relevant to the scenario.
sudo journalctl -u ssh --since todayReview recent SSH service events and connection-related evidence.
Effective configuration matters
SSH can use includes and conditional Match blocks. Usesshd -Tto understand the effective server policy rather than assuming one configuration file tells the whole story.
Effective SSH settings
Important controls need scenario context
PortTCP port on which sshd listens.
Defensive reasoning
Changing the port is not a substitute for authentication and firewall security. Preserve the scenario-required client path.
ListenAddressControls which local addresses sshd binds to.
Defensive reasoning
A narrower bind can reduce exposure, but only if the required management network still reaches the service.
PasswordAuthenticationControls whether password-based SSH authentication is accepted.
Defensive reasoning
Disable only when a verified alternative such as authorized public keys exists and the scenario allows it.
PubkeyAuthenticationControls public-key authentication.
Defensive reasoning
If required administrators depend on keys, disabling this can cause immediate lockout.
PermitRootLoginControls whether and how the root account may authenticate directly over SSH.
Defensive reasoning
Review scenario requirements and sudo-based administration. Do not treat one value as universally correct.
AllowUsers / AllowGroupsCan explicitly restrict which users or groups may authenticate through SSH.
Defensive reasoning
Useful for narrowing access, but a mistake can exclude the required administrator.
DenyUsers / DenyGroupsCan explicitly block selected users or groups.
Defensive reasoning
Check interactions with allow rules and Match blocks before editing.
MaxAuthTriesLimits authentication attempts per connection.
Defensive reasoning
May reduce brute-force opportunity but should be set according to scenario and operational needs.
Access path
Trace SSH from account to client
Account
Does the authorized user exist, and is the account state appropriate?
Evidence
getent passwd, id, passwd/chage review
Shell
Does the user have a login shell compatible with required SSH access?
Evidence
/etc/passwd record
SSHD policy
Does effective sshd configuration permit the required authentication method and user?
Evidence
sshd -T, Match blocks, allow/deny rules
User keys
If key authentication is required, is the correct authorized key present with safe ownership and permissions?
Evidence
~/.ssh/authorized_keys, ls -la, key fingerprints if needed
Service
Is the SSH service running and healthy?
Evidence
systemctl status ssh, journalctl -u ssh
Network
Is sshd listening on the expected address and port?
Evidence
ss -tulpn, sshd -T
Firewall
Does UFW allow the required source and port while limiting unnecessary exposure?
Evidence
ufw status verbose
Client test
Can the authorized administrator actually connect using the scenario-required method?
Evidence
Controlled client-side SSH test
Evidence-based reasoning
Replace one-size-fits-all SSH hardening with scenario reasoning
SSH is running on the image
Weak response
Disable SSH because remote access increases attack surface.
Better reasoning
Read the scenario first. If SSH is required, secure authentication and firewall exposure while preserving authorized administration.
PasswordAuthentication is enabled
Weak response
Turn it off immediately.
Better reasoning
Verify whether the required administrator has tested key-based access and whether the scenario permits disabling passwords before changing the setting.
Root SSH login is possible
Weak response
Delete or lock the root account.
Better reasoning
Review PermitRootLogin, sudo requirements, root account state, and scenario policy. Correct the remote-access policy rather than damaging the system account.
An unknown public key exists in authorized_keys
Weak response
Delete the whole authorized_keys file.
Better reasoning
Preserve the key, comment, file metadata, ownership, timestamps, logs, and user context; remove only the confirmed unauthorized key if justified.
UFW allows SSH from anywhere
Weak response
Delete the SSH firewall rule.
Better reasoning
If remote administration is required, narrow the rule to the required network or source when the scenario supports that restriction.
SSH uses a non-default port
Weak response
Change it back to 22.
Better reasoning
Determine whether the scenario or environment intentionally uses the alternate port. Security depends on access control and exposure, not port familiarity.
Public-key access
Keys are authorization data and forensic evidence
Authorized keys belong to a user
Each user's authorized_keys file controls keys permitted for that account. Review account authorization before reviewing the key list.
Ownership matters
The .ssh directory and files should be owned by the intended user unless the environment deliberately uses another managed arrangement.
Permissions matter
OpenSSH may reject unsafe file or directory permissions. Tightening permissions can improve security, but verify the user's login afterward.
Private keys are different
Private keys authenticate clients and should not be broadly readable. Do not expose private key material in notes, screenshots, or examples.
Comments are not proof
A key comment such as an email address or device name is descriptive metadata, not proof of ownership.
Fingerprinting helps comparison
When authorized and needed, key fingerprints can help compare keys without copying full key material.
Never expose private keys
Public keys are designed to be shared for authorization. Private keys are secret authentication material and should not be copied into course notes, screenshots, or public examples.
Controlled changes
Preserve a known-good management path
Goal
Validate SSH configuration
Example
sudo sshd -tCaution
Run before restart or reload after configuration edits.
Goal
Reload validated SSH configuration
Example
sudo systemctl reload sshCaution
Use only after syntax validation. Keep the current administrative session open until a second connection test succeeds when practical.
Goal
Restart SSH service
Example
sudo systemctl restart sshCaution
A restart can interrupt or fail required access. Prefer reload when supported and sufficient.
Goal
Allow SSH through UFW
Example
sudo ufw allow OpenSSHCaution
Only use when SSH is required and the rule scope matches scenario needs. Narrow source ranges when appropriate.
Goal
Allow SSH from a specific network
Example
sudo ufw allow from 192.0.2.0/24 to any port 22 proto tcpCaution
Use documentation/example networks in training. In a real authorized environment, substitute only the scenario-approved source range and actual SSH port.
Goal
Remove one unauthorized key
Example
sudoedit /home/username/.ssh/authorized_keysCaution
Preserve the original file and remove only the confirmed unauthorized entry. Do not delete all keys blindly.
SSH evidence
Preserve authentication context before cleanup
SSH service journal
sudo journalctl -u ssh --since todayService startup, configuration errors, and connection-related events where logged.
Authentication journal
sudo journalctl --since today | grep -iE 'sshd|authentication|failed|accepted'Broad authentication clues when messages are present in the journal.
Traditional auth log
sudo less /var/log/auth.logAuthentication and sudo events on systems where this log is present.
Last login records
lastRecorded login sessions from wtmp where retained.
Last-login indicator
lastlogPer-user last-login record where available. Use as supporting evidence, not complete proof.
Current sessions
whoShows currently logged-in users and session information.
Verification
Prove policy, service, network, and client access
Syntax
Run sshd -t and confirm the configuration validates.
Effective policy
Run sshd -T and confirm authentication, root-login, port, and allow/deny behavior match the intended state.
Service
Confirm systemctl status ssh shows a healthy service after reload or restart.
Listening socket
Use ss -tulpn to confirm sshd listens on the expected address and port.
Firewall
Confirm UFW allows the required management path without unnecessary broad exposure.
Authorized user
Test a new SSH connection from the authorized client perspective before ending the working administrative session.
Test a new session
An existing session can remain alive even when new logins are broken. Test a separate authorized connection before declaring the SSH change successful.
High-risk shortcuts
SSH changes that can lock out the team
Disable SSH before reading the scenario
Can remove a required administration path and make later work harder.
Turn off password authentication before testing keys
Can lock out the required administrator if key-based login is not actually working.
Delete every authorized key
Can remove legitimate administrator access and destroy useful forensic evidence.
Edit sshd_config and restart without sshd -t
A syntax error can prevent the service from loading correctly.
Open SSH to everyone in the firewall for convenience
Expands network exposure beyond the intended management scope.
Close the working SSH session before verification
If the new configuration blocks access, the team may lose the easiest recovery path.
Defensive lab
Secure a fictional required SSH service
Read the fictional scenario: Morgan is the only authorized administrator and must manage the Linux host over SSH from the training network; Avery and Riley are standard users and do not need remote shell access.
Inspect service state, effective sshd settings, listening sockets, UFW rules, and Morgan's account state without changing anything.
Review Morgan's authorized_keys file and preserve the original metadata and contents before any key-related change.
Identify a fictional unknown key in Avery's authorized_keys file as Investigate rather than deleting the entire SSH directory.
If the scenario requires Morgan-only SSH access, use effective allow/deny policy and firewall scope to reduce access while preserving Morgan's tested login path.
Validate sshd configuration before reload and keep the existing administrative session open while testing a new connection.
Verify Morgan can still connect, Avery and Riley cannot use unauthorized SSH access, UFW remains active, logs are preserved, and the SSH service is healthy.
Lesson checklist
Before moving on
I understand the difference between the SSH client and SSH server.
I inspect effective SSH configuration with sshd -T rather than reading only one file.
I validate syntax with sshd -t before reload or restart.
I know password locking does not necessarily disable key-based SSH access.
I review user authorized_keys files and preserve evidence before removing keys.
I do not disable password authentication until a required alternate method is verified.
I coordinate SSH configuration with UFW and network exposure.
I keep required remote administration available while reducing unnecessary access.
I preserve authentication logs and session evidence before cleanup.
I test a new authorized SSH connection before closing the working session when practical.
Reflection
Check your reasoning
Question 1
Why is sshd -T more useful than reading only /etc/ssh/sshd_config?
Question 2
Why can disabling password authentication lock out an authorized administrator?
Question 3
Why should an unknown authorized key be preserved before removal?
Question 4
How do SSH policy and UFW work together to control remote access?
Question 5
Why is changing the SSH port not a complete security strategy?
Question 6
What should you verify before closing the current administrative session after SSH changes?
Carry this forward
Secure remote administration combines identity, authentication, service configuration, keys, listening exposure, firewall policy, logs, and client verification. Harden the complete path, not just one SSH setting.