Unexpected SSH outbound connections often indicate compromised credentials, misconfigured authorized keys, or malicious scripts running on your system. This guide helps you identify the source of these unauthorized sessions and secure your Linux server by auditing active processes, reviewing authentication logs, and hardening SSH configurations to prevent future intrusions.
Identify Active Outbound Connections
The first step in troubleshooting is to determine which process is initiating the connection. You can use
netstat or
ss to list all established TCP connections involving port 22. Look for entries where the local address is your server and the remote address is an unknown IP. The command
ss -tnp | grep :22 provides a detailed view including the PID and program name responsible for the connection. If you see a process you do not recognize, note its PID immediately. Another effective method is using
lsof -i :22, which lists open files associated with network sockets, giving you precise insight into which user and application are making the call.
Audit Authentication Logs
Once you have identified suspicious activity, check the authentication logs to understand how the connection was established. On most Linux distributions, these logs are located at
/var/log/auth.log or
/var/log/secure. Use
grep sshd /var/log/auth.log to filter relevant entries. Pay attention to timestamps that coincide with the unexpected connections. Look for messages indicating "Accepted publickey" or "Accepted password." If you see successful authentications from users who should not be logging in, this confirms a breach. Additionally, check for failed attempts followed by successes, which might indicate brute-force attacks that eventually succeeded due to weak passwords. Understanding the authentication method used helps you decide whether to disable password authentication or rotate keys.
Review Authorized Keys
A common cause of unauthorized access is the presence of rogue public keys in
~/.ssh/authorized_keys files. Review these files for every user account, especially those with shell access. Remove any keys that you did not generate or explicitly authorize. Be cautious when editing these files directly; it is safer to copy them, edit the copy, and then replace the original to avoid syntax errors that could lock you out. Also, check for hidden directories or alternative locations where keys might be stored, such as
/etc/ssh/ssh_known_hosts or custom paths specified in
sshd_config.
Check for Malicious Scripts or Cron Jobs
Sometimes, the SSH connection is initiated by automated scripts rather than manual intervention. Inspect cron jobs for all users using
crontab -l for each account. Look for entries that execute commands connecting to external servers. Malware often uses cron jobs to maintain persistence by re-establishing connections if they are dropped. Additionally, review startup scripts in
/etc/rc.local or systemd services for any anomalies. If you find a suspicious script, analyze its contents before deleting it to understand what data might have been exfiltrated. In some cases, malware may disguise itself as legitimate system utilities, so compare file hashes against known good versions if possible.
Scan for Rootkits
If standard checks do not reveal the source, consider scanning for rootkits. Tools like
rkhunter or
chkrootkit can detect hidden processes and modified binaries. These tools scan for common signs of compromise, such as backdoors or altered system binaries. Run them with elevated privileges and review the output carefully. While false positives can occur, any flagged items should be investigated thoroughly. This step is crucial if you suspect that the attacker has deeper access to the system beyond just SSH.
Hardening SSH Configuration
Preventing future issues requires strengthening your SSH configuration. Edit
/etc/ssh/sshd_config to enforce security best practices. Disable password authentication by setting
PasswordAuthentication no and relying solely on key-based authentication. Restrict access to specific users or groups using the
AllowUsers or
AllowGroups directives. Enable
StrictModes yes to ensure proper permissions on key files. Consider changing the default port to reduce noise from automated scanners, though this is not a strong security measure on its own. After making changes, restart the SSH service with
systemctl restart sshd to apply the new settings.
Implement Fail2Ban
To protect against brute-force attacks, install and configure
fail2ban. This tool monitors log files for repeated failed login attempts and bans the offending IP addresses temporarily or permanently. Configure it to monitor
sshd logs and set appropriate thresholds for banning. This adds an extra layer of defense by blocking attackers before they can establish a connection. Regularly update the jail configurations to adapt to evolving threats. For more information on managing keys securely, you might find our guide on
Managing SSH Keys with Keepassxc on Win10 helpful for organizing your credentials safely.
Monitor and Alert
Continuous monitoring is essential for early detection. Set up alerts for unusual SSH activity using tools like
ossec or commercial SIEM solutions. Configure email or SMS notifications for critical events such as root logins or failed attempts from new IPs. Regularly review these alerts to stay informed about potential threats. Automation can help by sending daily summaries of SSH activity, allowing you to spot patterns quickly. Proactive monitoring reduces the window of opportunity for attackers and ensures that any breach is addressed immediately.
Frequently Asked Questions
How do I kill an active SSH session?
You can terminate an active SSH session by identifying its PID using
ss -tnp or
lsof -i :22 and then running
kill -9 [PID]. Alternatively, if you know the username, you can use
pkill -u [username] to end all their sessions. Always verify the process before killing it to avoid disrupting legitimate work.
Can SSH outbound connections be caused by a virus?
Yes, malware or rootkits can initiate outbound SSH connections to communicate with command-and-control servers. If you suspect infection, isolate the machine from the network and perform a full system scan using trusted security tools. Removing the malware is necessary to stop the unauthorized connections permanently.
What is the safest way to manage SSH keys?
Use a dedicated password manager like KeePassXC to store private keys securely, ensuring they are encrypted and protected by a strong master password. Avoid storing keys in plain text files or shared directories. Regularly rotate keys and remove unused ones to minimize the risk of exposure. Our article on
Managing SSH Keys with Keepassxc on Win10 provides detailed steps for this process.
How do I prevent brute-force attacks on SSH?
Install and configure
fail2ban to automatically block IP addresses after multiple failed login attempts. Additionally, disable password authentication and use only key-based methods. Changing the SSH port to a non-standard one can also reduce the volume of automated scans, although it is not a complete solution on its own.
Where are SSH logs stored on Ubuntu?
On Ubuntu systems, SSH logs are typically found in
/var/log/auth.log. You can view recent entries using
tail -f /var/log/auth.log while attempting a connection. For older versions or different distributions, check
/var/log/secure. These logs contain valuable information about authentication success and failure.