Hunting persistence on a compromised Linux server: cron, systemd, rc files and startup scripts
After a break-in, attackers make sure they survive a reboot. Most of the places they use are ordinary and easy to check. If you find one, assume there are others and plan to rebuild the server from a clean source.
Cron jobs for every user
List user crontabs and system cron folders, looking for downloads, base64 strings or odd paths.
for u in $(cut -d: -f1 /etc/passwd); do sudo crontab -l -u $u 2>/dev/null | sed "s/^/$u: /"; done ls -la /etc/cron.* /etc/cron.dSystemd services and timers
Look for recently created units and timers outside the packages' own folders.
systemctl list-unit-files --state=enabled | head -n 80 sudo find /etc/systemd/system /usr/lib/systemd/system -newermt '7 days ago' -type fShell startup and login scripts
Check files that run at login for every user.
sudo grep -rIl -E 'curl|wget|base64|nc ' /etc/profile /etc/profile.d /etc/bash.bashrc /root/.bashrc /home/*/.bashrc /home/*/.profile 2>/dev/nullPreload and library tricks
A file here loads code into every process.
ls -la /etc/ld.so.preload 2>/dev/null sudo cat /etc/ld.so.preload 2>/dev/nullNew accounts and setuid files
Look for users with UID 0, accounts you did not create and unexpected setuid binaries.
awk -F: '$3==0' /etc/passwd sudo find / -xdev -perm -4000 -type f 2>/dev/nullCompare against the package database
Verify that installed files match their packages, which highlights replaced binaries.
sudo debsums -c 2>/dev/null | head -n 30
Common mistakes
- Deleting only the file you found and leaving the rest.
- Trusting the tools on the compromised server: a rootkit can hide things.
- Rebooting before saving the evidence.
How to undo it
These checks are read-only. If you remove a unit or a cron entry, keep its copy in /root so you can restore it, and rebuild from a clean source for anything serious.
Sources
Commands are for Debian and Ubuntu unless noted. Test on a copy first and keep a backup: you are responsible for changes on your own systems.