Fix SSH outbound undesired/unknown connections

Abstract: Resolve unexpected SSH outbound connections by identifying rogue processes, auditing logs, and removing unauthorized keys.

Created: 2026-09-19 by
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.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More