Linux Server Hardening and Incident Response: What to Do First When You've Been Hacked?

2026-10-16 07:32:17

Let's start with a scenario many people assume "won't happen to them": a Linux server sitting in an equipment room or in the cloud, running the company's web, database, ERP or production management software. One day you notice the machine's fans never stop and the load stays high, or the cloud platform sends a security alert, or a customer asks "why is your website so slow?" You check, and there in the process list sits a miner you don't recognize, the CPU is pegged, and the boot time shows three in the morning.

Another scenario: you walk in in the morning and the business system won't let anyone log in. You connect and look - every file extension has been changed to a strange long string of characters, and on the desktop sits a note saying "your data has been encrypted, pay within the deadline".

This is not alarmism. Scanners on the internet probe port 22 (SSH) and 80/443 around the clock, and for a machine with a weak password, the time from exposure to compromise is often measured in minutes. Server compromise is not a question of "whether", it is a question of "how soon".

Here is the conclusion up front: Linux server security comes down to two things - harden in normal times and keep the doors locked; respond after an incident and handle it in order. Hardening has a checklist: get SSH, passwords, the firewall, patches and backups solid, and the vast majority of automated scanning and brute force will be shut out at the door. And if you really are breached, don't panic - disconnect the network, don't reboot, preserve evidence, and follow the playbook.

Linux Server Hardening and Incident Response: What to Do First When You've Been Hacked?

1. First, See Clearly: What Is the Attacker Here For?

The most dangerous thing in handling an intrusion is not that the machine was taken, but running around checking everything without knowing what the other side wants - you turn the process list inside out yet never learn whether they wanted compute or data, so evidence that should have been preserved isn't, and outbound connections that should have been blocked aren't.

The same machine being taken means completely different damage patterns, investigation priorities and response strategies depending on motive. Determine the motive first, then act - half the effort, twice the result. For intrusions against small-company servers, the motives generally fall into these categories:

Cryptomining - they want compute (the most common). They use your CPU/GPU to mine, turning the machine into a mining rig. This is the number one reason small and medium servers get breached - automated scanning doesn't pick its targets, it finds a weak password, takes the box, and hangs a miner on it. Typical traces: the CPU stays pegged and the load stays high, yet the business itself doesn't slow noticeably (mining processes usually lower their priority and yield to business workloads, precisely because they don't want you to spot them early); outbound connections to fixed IPs or domains on ports such as 3333, 5555, 14444 and 45700 (ports commonly used by mining pool protocols); process names often disguised as system names; and for machines in the cloud, a bill whose traffic volume is noticeably higher than usual. What this means for response: the target is usually compute, not your data, so recovery can be fast - but if persistence isn't cleaned out completely it will come back, and if outbound connections aren't blocked you keep paying the electricity bill.

Ransomware - they want money, holding your data hostage. They encrypt your files, leave a ransom note, and demand payment within a deadline in exchange for the key. Typical traces: files renamed in bulk with new extensions, a ransom note appears, abnormal disk I/O; sometimes they lurk and watch for a few days first - learning your backup habits and your business peak hours, then striking on a weekend night. What this means for response: the timeline determines the scope of loss, and the core of response is isolation, preserving samples, identifying the variant (some older variants already have public decryption tools), and restoring from backup. The industry's clear position is that paying the ransom is not recommended - paying doesn't guarantee decryption, if they hand you a broken tool you can't verify it, and the money funds further crime.

Data theft - they want the data itself. They lurk silently, moving customer records, drawings, process documents, accounting data and source code out of the building. This type is the most insidious - you may be breached for six months without knowing. Typical traces: abnormal outbound connections and upload traffic outside working hours (sometimes over DNS queries, sometimes to unfamiliar object storage endpoints), logins from other locations, suspicious accounts reading large numbers of files, suspicious webshell files appearing on the web server. What this means for response: the investigation focuses on exfiltration channels and the timeline, and the response focuses on assessing the scope of impact, changing all passwords, and fulfilling notification obligations as appropriate. Silence is the hallmark of this motive and late discovery is the norm; scoping the impact as quickly as possible is the real priority.

Jump host - they want your network position. Your machine is just a tool: they use you to scan others, send spam, or host a control endpoint. Typical traces: records of scans against other subnets in the internal network, abnormal spikes in the mail queue, connections to known malicious addresses. What this means for response: there is a risk of joint liability - if someone else is attacked and the trail leads back to you, you may be reported and blocked. Beyond cleanup, you need to preserve evidence to prove your own position and cooperate with upstream handling.

Destruction - they want you down. Dropping databases, deleting data, wrecking configurations. Relatively rare, and usually with a clear target. What this means for response: backup is the only answer, and the focus is recovery rather than investigation.

Hit by indiscriminate scanning - no clear goal. A script tries weak passwords, gets in without any plan, hangs a miner or just leaves it alone. You still go through the full process, but there's no need to panic - most "hacks" fall into this category, and closing the entry point is the end of it.

Three quick clues for judging motive: who is occupying CPU/IO (mining and ransomware are both loud, data theft is usually quiet); where the network traffic goes and in what pattern (exfiltrating data, connecting to a mining pool, or scanning others); how the file system was touched (encryption means ransomware, bulk outbound transfer means data theft, deletion means destruction). Line up the three and the motive can basically be characterized. Characterize it before you investigate, and you'll know what to focus on and what to preserve first.

One honest caveat: the motive is not always singular - the same machine may host both a miner and data theft, and it is not rare for a miner to package up data and sell it on the side. The categories above are the starting point of an investigation, not the end; once the timeline is reconstructed, evidence is what counts.

2. Why Investigation Is Far From Simple

"Glance at the process list, skim the scheduled jobs, reboot if nothing looks wrong" - that routine is enough for script kiddies, but far from enough for a real intrusion. Investigation is hard in eight places:

1. The commands you see may all be fake. Once the attacker has root, the first thing they do is make the watchdog tools lie: process names can be forged - the name shown in the list is only the first item of the launch arguments, so renaming it is enough to masquerade as a system process; the commands you use to view processes, connections and open files may themselves have been replaced with versions that hide malicious content; they may even inject a library through /etc/ld.so.preload so that when system commands are called they filter out the attacker's traces along the way - the command is still the original command, but its output has been tampered with. The countermeasure is not to trust a single source: run a statically compiled busybox (which doesn't depend on system libraries and therefore can't be hijacked) and cross-check its output against the system commands; where the two disagree is where to look. The harder approach is to read /proc directly - that is raw information exposed by the kernel, never touched by user-space tools. When hardening a machine, put a static busybox on a USB stick or a jump host as a side task; when something happens, it is your "trusted reference".

2. Processes have to be dug out of /proc. The process list is only a process's "business card"; the truth is under /proc: where the executable points (if it shows as deleted while the process is still running, that is a classic sign of "cleaning up the scene after the job" - copy the file out of /proc immediately as evidence, because the deleted binary itself is physical evidence); the real launch arguments (the displayed name is a disguise, but these can't hide, and carrying a mining pool address and wallet address is very common); the working directory (sometimes revealing which directory it is rummaging through); environment variables, which may carry the mining pool address, wallet address or controller domain - direct physical evidence for characterizing motive; and which files it has open and which addresses it is connected to. Order of interpretation: first locate the real binary, then copy it as evidence, then look at the launch arguments and environment variables to confirm what it connects to, and finally see which business files it has touched.

3. Network connections are not a matter of one glance. Where a connection goes matters more than whether one exists: is it an IP or a domain (domains change at any time, IPs are relatively stable); is the port a common mining pool port; is it uploading to an unfamiliar object storage endpoint; and don't overlook DNS query logs - data exfiltration increasingly travels over DNS queries, which cannot be stopped by blocking IPs at all, so you have to look at resolution logs. Large outbound traffic outside working hours deserves more suspicion than any single anomaly - mining is a steady trickle, data theft is often a concentrated burst, and the traffic profile says more than any single point.

4. Persistence is a checklist, not one line in cron. Kill the process and it grows back half an hour later - because only the branches were cut and the root is still there. Places to go through one by one: the cron family (system-level crontab, the cron.d directory, each user's own jobs, at jobs - looking only at the current user's crontab will miss more than half); systemd services, and timers, which fewer people think of than cron; global library hijacking through /etc/ld.so.preload, where a single line with a path is enough to stay hidden; SUID files (extra SUID binaries equal permanent root backdoors - this one needs a baseline to judge, so run find / -perm -4000 when the system is freshly installed and save the output, and only then will you know what is "extra" when something happens); unfamiliar public keys in SSH authorized keys files are only one item, and every user's home directory must be checked, not just root; modified SSH configuration (enabling root login, adding a high port) must be checked too - public keys are the keys, while changing the config is "leaving the door open", and leaving the door open is often the attacker's first step after getting in; extra accounts and sudoers entries; lines stuffed into shell startup files that execute on every login; and kernel modules.

5. Logs are scattered across a dozen places, and may have been altered. Login traces are more than failed-login records: the system security log shows authentication successes and failures, the binary login ledger, systemd's journal shows service events, the web access log (to find anomalous webshell requests and unusual user agents), the application's own logs, and the cloud platform's security audit - each of them may hold part of a timeline. And logs may have been deleted or truncated - command history wiped, the security log truncated to zero bytes; "the log that should be there is gone" is itself an important clue, showing that whoever came in not only got in but took the trouble to cover their tracks. This is also why the hardening section repeatedly stresses shipping logs off-box: keep one copy locally and sync one copy remotely, so that when the local copy is wiped the remote one is still there.

6. A single point means nothing; rebuild the timeline. The goal of an investigation is not "find a malicious process" but to string the whole event together in time: when the first anomalous login happened, where it came from, which account was used, how privileges were escalated, when what was implanted, when persistence was set up, when data exfiltration began. Once the timeline is clear, the entry point, the technique, the motive and the scope of loss all have answers. For example, a reconstructed timeline looks like this: 2:17 a.m. an unfamiliar IP logs in successfully for the first time (weak password) -> 2:19 privilege escalation succeeds -> 2:25 a suspicious binary lands in the temp directory -> 2:31 an extra line appears in cron -> from 3:00 the CPU stays above 90% -> from the next day, a fixed outbound connection every day at 3 a.m. Entry point, technique, motive - all in that line. Note that log timestamps and file times may both have been tampered with; cross-verify across multiple sources and don't trust a single clock.

7. Don't forget memory forensics, file timestamps and lateral movement. Memory holds things that vanish on reboot: running malicious processes, connections that never hit disk, keys and configurations in memory - this is the fundamental reason for "don't reboot first"; if you really need forensics, capture a memory image before rebooting. The file system's own timestamps are also a timeline: executables modified in the last few days, extra items in temporary directories, suspicious files newer than some system file you know is clean - all of them can pin down when the implant happened; timestamps can be smoothed over, but the abruptness of "it is the only new file in the whole directory" cannot be hidden. Often more than one machine is compromised: the same password used on three machines means getting into one is getting into three; scan records against other internal machines in the logs are hard proof of lateral movement, and machines that share passwords or sit on the same subnet all need checking.

8. The honest boundary: rootkit detection. User-space rootkits can be partly found by tools such as chkrootkit and rkhunter; once a kernel-mode rootkit is loaded, the system itself is no longer trustworthy, detection becomes extremely difficult, and offline analysis is basically required. For the vast majority of situations, the pragmatic answer is: if you can't say for sure it's clean, reinstall - a reinstall removes every user-space backdoor, and combined with changing all passwords, closing the entry point and restoring from a clean backup, it is the standard play for reducing risk to an acceptable level. There's no need to feel the machine is "ruined", but neither should you imagine that running an antivirus makes it clean.

3. The Hardening Checklist: Lock the Doors That Should Be Locked

Below is the baseline configuration a production Linux server should have, ordered from highest to lowest priority. Every backdoor location in the investigation checklist above is, conversely, a hardening checkpoint:

1. SSH: the remote entry point is the top priority. Prohibit direct root login (log in as a normal user and then sudo, so that any problem can be traced to a person); switch to key-based login and turn off password login, and brute-force tools basically have no way in against keys. One practical ordering reminder: configure the public key and verify you can log in first, then disable password authentication; reversing the order will lock you out, and this is the most common self-inflicted accident on hardening jobs. Use the firewall to restrict login sources, allowing only the company's fixed IPs or requiring a jump host first; install Fail2ban so that repeated failed logins from the same IP are automatically blocked for a period. Only with several layers stacked is the remote entry point truly locked.

2. Passwords and accounts. Strong passwords on all accounts, no empty passwords; different passwords on different machines, never reuse - with reused passwords, breaking one machine means breaking a whole set. Use sudo to manage privilege escalation rather than letting everyone switch to root for convenience. Disable or delete any account not in use, and periodically review the account list and SUID files to reduce the guessing surface.

3. Firewall: deny by default, allow as needed. Use firewalld or iptables to establish the policy: deny inbound by default, open only the ports the business requires. Database, cache and management ports must never be exposed to the public internet. Outbound deserves management too - mining callbacks and data exfiltration both travel over outbound connections, and restricting outbound to the endpoints the business requires has been the most cost-effective line of defense in hijacking scenarios over the past two years: if the machine really is taken, outbound doesn't work, the mining pool can't be reached and data can't get out, and the damage is cut in half on the spot. The same applies to cloud servers: the security group allows only business ports and operations source IPs, and everything else is closed.

4. Patches: let security updates run automatically. On CentOS/RHEL systems enable dnf-automatic, on Ubuntu/Debian enable unattended-upgrades, so that security patches install automatically - don't wait until something happens to remember that "it's been a long time since we updated". Application-layer components must keep up with versions too - several of the most impactful vulnerabilities in recent years (Heartbleed, Shellshock, Log4Shell, the XZ Utils backdoor) all came from foundational components, so follow community security advisories. A sound strategy: security patches install automatically, regular updates accumulate into a monthly window, and when a high-severity vulnerability breaks out, schedule it as a separate emergency.

5. Minimize: turn off what you don't use. Services you don't run, packages you don't install, ports you don't open - turn them all off. Every additional listening port is another attack surface; a production server is not an experimental plot.

6. Backup: the last line of defense. Even the most stable system can be breached or held for ransom, and only backups can save you. One principle: store backups separately from production (off-site, offline, at least on another machine), and run restore drills regularly - a backup that has never been drilled is no backup at all. Be careful not to leave the backup directory permanently writable and connected to the production machine - mainstream ransomware now specifically hunts for sync drives and writable network backups to encrypt. This topic is covered separately in How Server Backups Should Really Be Done.

7. Logging and monitoring: traceability after an incident. Enable auditd, send login logs to another machine for centralized storage (local logs get deleted; only an off-box copy can be investigated), and set up monitoring and alerting for CPU, memory, disk and traffic. Intrusions are not the scary part; discovering you've been hacked for three months is - one day earlier makes the loss one size smaller.

4. Responding by Motive: Same Bottom Line, Different Emphasis

Whatever the motive, the general bottom line doesn't change: isolate the network, preserve evidence, investigate, clear persistence, change all passwords, assess and restore. But on top of that bottom line, the motive determines where each step puts its emphasis:

Mining motive, where the focus is wiping out the whole nest plus blocking outbound: clean every persistence location one by one according to the checklist in section 2, block mining pool communication at the firewall (IP plus port), change passwords across the machine, and find the entry point (most likely a weak password or an exposed port). Data is generally untouched, so recovery can be fast - but don't skip steps because of that; missing one persistence item means the work was wasted. After cleanup, observe for another two or three days; only when the CPU curve is normal and outbound traffic is clean are you done.

Ransomware motive, a battle measured in minutes: isolate first (disconnect the network, unplug shared drives, and never let an encrypting machine keep scanning internal shares); preserve samples (copy the encrypted file samples, the ransom note and suspicious processes for variant identification and later reporting); identify the variant (some older variants have public decryption tools); check the backups - if they are usable and were not encrypted through sync, that is the biggest win and you go straight to restore; paying the ransom is not recommended; the first thing after recovery is to find the entry point and harden. If there is no backup and the data must be recovered, have professionals assess it first rather than making a snap decision yourself.

Data theft motive, where the core is the exfiltration timeline plus the scope of impact: reconstruct from logs and traffic "when it started, through which channel, which data was taken", and use that to assess whom to notify (customers, partners, and legal or regulatory channels where necessary); change all passwords - however long the attacker lurked inside is how long the passwords were exposed; and close the suspicious exfiltration channels as well. Silence is the hallmark of this motive and late discovery is the norm; scoping the impact as quickly as possible is the real priority.

Jump host motive, with two extra steps beyond cleanup: preserve evidence (to prove you are the victim rather than the attack source, for use when cooperating with upstream notifications); assess the associated risk (whether your IP has been used for malicious activity and may be reported or blocked - proactively appealing and handling it beats waiting passively).

Destruction motive, where investigation is secondary and recovery is primary: how complete the backups are, how long recovery takes, which business system to restore first - follow that order, and leave finding out who did it to later.

For a production server whose cleanliness you can't be sure of, reinstalling the system and restoring from backup is the most reliable answer - a reinstall removes every user-space backdoor, and combined with changing passwords and closing the entry point, the risk is reduced to an acceptable level. Remember to preserve evidence before reinstalling.

5. The Most Common Pitfalls

"Killing the process makes it clean." Killing a process only pushes down what is visible; the scheduled jobs, startup items, backdoor public keys and the entry-point vulnerability are all still there, and within half a day it comes back on its own.

"Let's just reboot and see." A reboot destroys the evidence in memory, and may trigger a scheduled job that wipes the scene on startup. Isolate the network and preserve evidence first, then talk about rebooting.

"If there's nothing unusual in the process list, we weren't hacked." The process list lies - process names can be disguised, commands can be replaced, libraries can be hijacked. A tool's output is a clue, not a conclusion.

"The firewall is on and the ports are open, so we're safe." The firewall allowing 80/443 doesn't mean the web application itself has no vulnerabilities - a webshell comes in through the very port you allowed. Application vulnerabilities, weak passwords, outdated components - any one of them gets around it.

"It's an internal server, it's fine." An internal network is not a safe: a USB stick, one compromised edge device, or one remote entry point with a weak password can all bring risk inside.

"The cloud platform handles security, so buying a server means peace of mind." The cloud platform is responsible for the security of the data center and the virtualization layer; everything above the operating system - accounts, passwords, patches, firewall, applications - is the tenant's own responsibility. This boundary is called "shared responsibility", and the platform can't help you when something goes wrong.

"We installed antivirus, so we're safe." "Antivirus" on Linux is limited in what it can do; real protection is hardening itself - closing the entry points, keeping patches current, and keeping backups in place.

"Nobody watches a small company, hackers won't bother." Automated scanning doesn't care about company size; it only looks at whether your ports are open and your passwords are weak. If you're used as a "bot" to attack others, the joint liability is still yours.

6. This Work Can Be Handed to Professionals

Security hardening is a classic one-off short-term project - configure item by item against the baseline, accept the delivery, hand over the documentation, with a clear start and end. Intrusion response is even more of a race against the clock: isolate the network, preserve evidence, investigate, clear the entry point, recover - an hour earlier means one less slice of loss. The genuinely hard part (motive characterization, timeline reconstruction, rootkit determination, forensics and evidence preservation) runs on experience, not on a checklist - overlook one direction during an investigation and you may miss the most critical evidence.

Our own core business systems at Moges (the production management software Moges PMS9 and PMS5) have run on Linux for fourteen years, and we have installed, configured, hardened and rescued them machine by machine at hundreds of manufacturing customers. When we handle this kind of work we follow the same two lines as this article: keep the doors that should be locked locked in normal times, and after an incident handle it in order, preserving evidence before cleanup - motive judged accurately, evidence preserved reliably, loss kept under control.

To understand why systems deserve to be built on Linux, see Why Our Systems Have Run on Linux From Day One; for how to bring a production line system back up within minutes after a midnight outage, see How to Bring a Production Line System Up in Minutes After a Midnight Outage; and for the scope of short-term services such as Linux server emergency response, security hardening and backup setup, see Linux Server Services.

Conclusion

Linux server security, in the end, comes down to two sentences: keep the doors locked in normal times (work through the hardening checklist item by item), and handle things in order after an incident (isolate the network first, preserve evidence, determine the motive, then clean up). Attackers look for entry points and slack, not company size; what really makes the difference is whether hardening was done, whether backups exist, and whether you stay calm when something happens. There is no shortcut in investigation that lets you "glance at the process list and go home", but there is a method - "determine the motive first, then follow the checklist". None of this is esoteric knowledge; it is a question of whether you take it seriously and whether you follow the playbook.

« Back to News list