Scenario
After gaining access (Lab 2) and escalating privileges (Lab 3), the attacker establishes persistence on the NAS server. This lab demonstrates adding an SSH public key for re-entry, then shows how to detect and respond on defense.
Offensive
Generate & Transfer SSH Key Pair
Generate an SSH key pair on Kali and place the public key on the target NAS.
Install the Key on the Target
Configure ~/.ssh/authorized_keys with proper permissions to enable key-based login.
~/.ssh, write authorized_keys, set secure perms.Confirm Persistent Access
Test the persistence by reconnecting via SSH using the private key.
Note: You may still need to repeat environment setup/escalation steps from Lab 3 to regain root in a new session, but the key ensures durable access post-reboot.
Defensive
1) Detect Key-Based Persistence
Audit ~/.ssh/authorized_keys for unexpected entries, strange comments, or keys referencing external systems (e.g., @kali).
authorized_keys.2) Review SSH Authentication Logs
Correlate logins in /var/log/auth.log (or platform equivalent) for key-based acceptances from unfamiliar sources.
3) Identify Recent File Modifications
Find recently modified authorized_keys files (7-day window example):
sudo find / -type f -name authorized_keys -mtime -7 2>/dev/null
4) Monitor Active Sessions
Check who is currently logged in and from where, then terminate suspicious sessions.
who shows session origin.
Immediate Response
Kill related processes (example using kill -9 on PIDs tied to the compromised user):
Mitigation — Remove Unauthorized Keys
Manually inspect and remove unknown keys from authorized_keys; restrict permissions to minimum required.
Mitigation — Reset Passwords
Reset affected user passwords in case credentials were also compromised.
Conclusion
SSH key-based persistence is effective and stealthy. Even with passwords disabled (keys-only mode), an attacker who obtains write access can add a key and regain entry after reboot. If SSH isn't required, disable the service entirely. Otherwise, harden: monitor authorized_keys, restrict which users may use SSH, consider 2FA, use IDS/IPS rules for key-file changes, and alert on anomalous logins.