Most persistence on a compromised Linux host lives in a small number of configuration locations, cron tables, systemd units and timers, SSH authorised keys and login scripts, the dynamic linker preload list and the PAM stack, and each one can be examined with a repeatable method based on how the software documents it. This guide takes each mechanism in turn: where it is stored, how precedence works, what a malicious entry tends to look like and what evidence to preserve. It is for incident responders and forensic analysts examining a Linux image or a live host under investigation.
For the wider Linux investigation, including collection order, journald, auditd and anti-forensics, use the Linux Forensics Guide. For quick first-hour triage of a server, see How to check a Linux server for signs of compromise. This page goes deeper on the five mechanisms in its title.
Key takeaways
- Persistence analysis is a precedence problem. Cron, systemd and PAM all read several locations, and the one that wins is not always the one you open first.
- In systemd, unit files in earlier search path directories override files with the same name lower down, and drop-in
.d/*.conffiles are merged after the main file. A clean looking unit can be changed entirely by a drop-in. - User crontabs live in the spool directory, while
/etc/crontaband/etc/cron.d/entries carry an extra username field.@rebootruns a job once after boot. - SSH key persistence is more than a new line in
authorized_keys. Key options such ascommand=andenvironment=, plus~/.ssh/rcand/etc/ssh/sshrc, can all run code at login. /etc/ld.so.preloadmakes every program on the system load the listed libraries. The dynamic linker documentation calls this usually undesirable, so any entry needs explaining.- If
/etc/pam.dexists, Linux-PAM ignores/etc/pam.conf. Unexpected modules, unusual module paths andsufficientrules near the top of an auth stack are the patterns to examine. - Work from a forensic image or a read-only mount where you can, and record file metadata before you open anything.
Before you start: evidence handling
Every location in this guide is a file, so the core evidence is the file content plus its metadata: owner, mode, size, and modification and change times. Capture metadata for each candidate file before reading it, and hash the file. On a live host, reading a file can update its access time depending on mount options, so record access times early or work from an image.
Compare candidate files against a known good source: the package manager's record of what it installed, a clean build of the same image, or your configuration management repository. A file that the package manager does not own, in a directory where most files are package owned, is a strong lead. How to check a Linux server for signs of compromise covers package verification in more detail.
Illustrative commands on this page assume the evidence is mounted read-only at /mnt/evidence. Adjust paths for live work and record every command you run.
Cron
ATT&CK tracks cron abuse as T1053.003 Cron. The crontab(5) manual page from the cronie project describes three places that define jobs:
- User crontabs in the spool directory
/var/spool/cron/. Each line has five time fields followed by the command. - The main system crontab,
/etc/crontab. - System crontabs in
/etc/cron.d/.
Entries in /etc/crontab and /etc/cron.d/ need a username field after the time fields, because they serve more than one user. That gives you two checks: whether the user named in a system crontab exists and should run jobs, and whether a user crontab in the spool belongs to an account that should have one at all. Spool directory layout differs between cron implementations and distributions, so confirm the path on your build.
What to look for
- The
@rebootstring. crontab(5) documents it as running once after boot. It is a straightforward way to survive restarts and deserves review wherever it appears. The page also lists@yearly,@annually,@monthly,@weekly,@dailyand@hourly. - Environment lines. Crontabs can set variables as
name = value. cron sets SHELL to/bin/shby default, and HOME and SHELL can be overridden in the crontab. An overridden SHELL changes what interprets every following command. Other recognised variables include MAILTO, CRON_TZ and RANDOM_DELAY. - Commands that fetch or decode. Jobs that download content, decode encoded strings or run from temporary or hidden directories are classic persistence.
- File type and permissions. The crontab(5) caveats say crontab files must be regular files or symlinks to regular files, and must not be executable or writable by anyone other than the owner. Files that break this rule may be ignored by cron, but a writable crontab is still a finding because someone may have prepared it.
- Comments. Lines whose first non-whitespace character is
#are comments, and inline comments after commands are not allowed. A long commented block can hide an entry from a quick read; parse rather than eyeball.
Illustrative collection
- List all cron definition files with metadata:
find /mnt/evidence/etc/crontab /mnt/evidence/etc/cron.d /mnt/evidence/var/spool/cron -type f -printf '%M %u %g %s %TY-%Tm-%Td %TT %p\n' - Extract every non-comment line with its file name:
grep -HnvE '^\s*(#|$)' <files>
Also review the scripts that system crontabs call. A legitimate looking job that runs an existing script is a common way to hide a change: the crontab is clean and the script it calls is not.
systemd services and timers
ATT&CK tracks T1543.002 Systemd Service and T1053.006 Systemd Timers. systemd is the richest persistence surface on most modern distributions because of its layered configuration.
Search paths and precedence
The systemd.unit manual lists unit search directories from highest to lowest priority and states that unit files found in directories listed earlier override files with the same name lower in the list. For system units, the notable directories are:
| Directory | Purpose per systemd.unit | Forensic note |
|---|---|---|
/etc/systemd/system | Administrator created units | Highest of the common directories. A same named unit here overrides the distribution's copy. |
/run/systemd/system | Runtime units | Volatile. Only present on a live host or in memory captures. |
/usr/local/lib/systemd/system | Sits just above /usr/lib/systemd/system | Rarely used by packages, so contents need explaining. |
/usr/lib/systemd/system | Distribution installed units | Compare with package records. |
/run/systemd/generator, .early, .late | Generated units | Created at boot by generators; check generator binaries if units here are unexpected. |
The $SYSTEMD_UNIT_PATH variable overrides the default load path, so check how systemd was started if the usual directories do not explain what ran.
User units are searched in locations including ~/.config/systemd/user (or $XDG_CONFIG_HOME/systemd/user), /etc/systemd/user, /run/systemd/user, ~/.local/share/systemd/user and /usr/lib/systemd/user. User units are easy to miss because they sit in home directories. Sweep every home directory, including those of service accounts.
Drop-ins
For a unit foo.service, systemd merges files matching foo.service.d/*.conf in alphanumeric order after the main file is parsed. Drop-ins in /etc/systemd/system take precedence over /run/systemd/system, which takes precedence over /usr/lib/systemd/system. For a dashed name such as foo-bar-baz.service, the directories foo-bar-.service.d/ and foo-.service.d/ are also searched, and a type-wide service.d/ directory applies to all service units with lower precedence than name-specific drop-ins.
This is where careful attackers hide. A drop-in can add or replace the command a trusted, package owned service runs, leaving the main unit file byte for byte identical to the package. Always review the main file together with every drop-in directory that could apply to it, including prefix and type-wide directories.
Enablement: .wants and .requires
Symlinks inside a .wants/ directory add implicit Wants= dependencies, and .requires/ directories add Requires= dependencies. The manual describes creating these through the unit's [Install] section with systemctl enable or preset, and notes that systemd does not read [Install] during normal operation. In practice that means the symlink is what makes a unit start at boot. Record the symlink's own timestamps; they often date the enablement more precisely than the unit file.
Masking
A unit file that is empty or symlinked to /dev/null is masked and cannot be activated. Attackers can mask security tooling or update services to stop them running. A masked security agent unit is a finding, not a configuration detail.
Timers
A timer unit has a name ending in .timer. If Unit= is not set, it activates the service with the same name, so foo.timer starts foo.service. Review both files together. OnBootSec= fires relative to boot and OnCalendar= uses wall clock calendar expressions. With Persistent= on an OnCalendar= timer, the last trigger time is saved to disk and a run missed while the system was down starts when the timer is activated, which can explain job executions shortly after boot.
SSH authorised keys and login scripts
ATT&CK tracks T1098.004 SSH Authorized Keys. The sshd(8) manual says that if AuthorizedKeysFile is not set, the default files are ~/.ssh/authorized_keys and ~/.ssh/authorized_keys2. Check the effective sshd configuration first: an AuthorizedKeysFile setting pointing elsewhere changes where you must look, and is itself a persistence technique if someone added it.
Key options
Each key line can carry options. Those most relevant to forensics:
command=forces a specific command whenever the key is used. Legitimate for restricted automation keys; suspicious on an interactive account.environment=adds a variable at login.from=limits logins to listed hosts or addresses. Its absence on an automation key is a hygiene gap; an unfamiliar address in it is a lead.no-ptyblocks terminal allocation, andrestrictenables all restrictions at once.expiry-time=sets a time after which the key will not be accepted.
Login time scripts and environment
sshd(8) documents ~/.ssh/rc, which it describes as containing initialisation routines, and /etc/ssh/sshrc, its machine-wide counterpart. Both are tied to SSH login and are rarely present on most systems, so any content needs explaining. ~/.ssh/environment is read into the environment at login if it exists, and may contain only blank lines, comments and name=value assignments. Shell start-up files in home directories and system-wide profile directories are a related surface, tracked by ATT&CK as T1546.004 Unix Shell Configuration Modification.
Permissions
If authorized_keys, the ~/.ssh directory or the home directory is writable by other users, sshd will not allow it to be used unless StrictModes has been set to "no". A StrictModes no setting in sshd configuration, combined with loose permissions, is a sign that someone prepared the ground for a planted key.
What to record for each key
- File, line number, key type, key comment and fingerprint.
- All options on the line.
- File modification and change times, and the account the file belongs to.
- Whether the key appears in your approved key inventory, and who owns it.
- Authentication log entries showing the fingerprint being used, covered in the Linux SSH and Authentication Log Detection Guide.
Dynamic linker preloading: LD_PRELOAD and /etc/ld.so.preload
ATT&CK tracks this as T1574.006 Dynamic Linker Hijacking. The ld.so(8) manual describes LD_PRELOAD as a list of additional, user specified ELF shared objects to be loaded before all others, separated by spaces or colons and loaded in list order.
/etc/ld.so.preload is a whitespace separated list of ELF shared objects loaded before the program. It applies system-wide, so every dynamically linked program preloads those libraries. The manual notes this is usually undesirable and typically an emergency remedy. The documented order is the LD_PRELOAD environment variable, then the --preload command line option, then /etc/ld.so.preload.
Why this matters to an investigation
A preloaded library runs inside every process that loads it, including the tools you use to investigate. On a live host, output from commands such as process and file listings may be filtered by a malicious preload. That is a reason to examine /etc/ld.so.preload from a trusted environment or from the image, and to compare live tool output with evidence gathered outside the host.
Secure-execution mode
The manual describes secure-execution mode, which applies when the AT_SECURE auxiliary vector entry is non-zero, such as when real and effective user or group IDs differ in set-user-ID programs. In that mode, preload pathnames containing slashes are ignored and preloading is limited to standard search directories and set-user-ID objects. LD_LIBRARY_PATH and LD_AUDIT are also restricted. These rules tell you which programs an LD_PRELOAD setting could affect; /etc/ld.so.preload is the file to treat as system-wide.
What to collect
/etc/ld.so.preload: content, metadata and hash. On many systems it does not exist; its presence is itself notable.- Each library it lists: path, owner, hash, package ownership and timestamps.
LD_PRELOADorLD_AUDITsettings in service units, drop-ins, cron environment lines, shell start-up files and~/.ssh/environment./etc/ld.so.cache, which the manual describes as a compiled list of directories and candidate shared objects, for comparison with a known good host.
PAM
ATT&CK tracks T1556.003 Pluggable Authentication Modules, which spans persistence and credential access. A modified PAM stack can accept a hidden password or record credentials as users log in, which makes it as much an identity incident as a host one. For PAM fundamentals, see the Linux PAM Guide.
Configuration and precedence
The pam.conf(5) manual says that if /etc/pam.d exists, Linux-PAM ignores /etc/pam.conf. Files in /etc/pam.d/ omit the service field because the file name is the service name. Each rule then has a type, a control value, a module path and module arguments.
- Types:
account,auth,passwordandsession. Credential capture and backdoor logic usually sit inauthorpassword. - Controls:
requiredreports failure after the rest of the stack runs;requisitereturns immediately on failure;sufficientreturns immediately on success if no earlier required module has failed;optionalmatters only if it is the only module for that service and type;includeandsubstackpull in lines from another file. - Module paths: a path starting with
/is used as given. Otherwise it is relative to the default module location,/lib/security/or/lib64/security/depending on architecture.
What to look for
- A
sufficientauth rule placed above the normal password check that calls an unfamiliar module. Success there skips the rest of the stack. - Absolute module paths outside the standard module directory.
- Module files in the standard directory that the package manager does not own, or whose hashes differ from the package.
- Changes to shared files that many services
include, which spread a change across every login path at once. - Arguments that write to files, run commands or reference unusual paths.
Because include and substack chain files together, resolve the full effective stack for each service of interest, such as SSH and console login, rather than reading one file.
Building the persistence timeline
- Inventory. List every file in the locations above with owner, mode, size, times and hash.
- Baseline. Mark each as package owned and unchanged, package owned and changed, or not package owned.
- Resolve precedence. For systemd, cron and PAM, work out what was actually effective, including drop-ins, includes and overriding directories.
- Follow the payload. For each suspicious entry, collect what it runs or loads and repeat the inventory for those files.
- Correlate. Place change times next to authentication logs, journal entries and audit records. The Linux Logging and auditd for Defenders Guide covers which sources record file and login activity.
- Report with precedence explained. Say not just that a file existed, but that it was effective and why.
Where identity fits
Every mechanism here runs as an account. Cron jobs and units run as a named user or service account, keys grant access to an account, and PAM changes affect every identity that authenticates through the stack. Service accounts are attractive because they are rarely interactive and their home directories are rarely reviewed. When you find persistence, record which identity it runs as and which credentials it exposes: a planted key or a credential capturing PAM module means every affected secret needs rotation, and automation keys found during the sweep should be checked against your key inventory and owner records.
Common failure patterns
- Reading the main unit file only. Drop-ins can replace what a trusted unit runs.
- Skipping home directories. User units, user crontabs,
~/.ssh/rcand shell start-up files all live there, including for service accounts. - Trusting live tool output on a host with a preload. Examine
/etc/ld.so.preloadfrom a trusted environment. - Reading one PAM file. Includes and substacks mean the effective stack spans several files.
- Removing before recording. Deleting a malicious entry before capturing metadata and payload destroys evidence of when and how it arrived.
- Ignoring the sshd configuration. A changed
AuthorizedKeysFileorStrictModessetting moves or weakens key checks.
Practitioner checklist
- Work from an image or read-only mount where possible, and record metadata and hashes before reading files.
- Inventory
/etc/crontab,/etc/cron.d/and the user crontab spool, and flag@reboot, environment overrides and calls to unowned scripts. - Review every systemd unit search directory, all applicable drop-in directories,
.wants/symlinks, masked units and timers with their matching services. - Sweep user unit directories and
~/.ssh/in every home directory, including service accounts. - Record each authorised key with its options and match it to an approved key inventory.
- Check
~/.ssh/rc,/etc/ssh/sshrc,~/.ssh/environmentand sshd's effectiveAuthorizedKeysFileandStrictModes. - Collect
/etc/ld.so.preloadand every library it lists, and search configuration forLD_PRELOADandLD_AUDIT. - Resolve the effective PAM stack for SSH and console login and verify every module against package records.
- Rotate credentials for any identity touched by confirmed persistence.
Standards and references
- systemd: systemd.unit manual
- systemd: systemd.timer manual
- Linux man-pages: crontab(5)
- Linux man-pages: sshd(8)
- Linux man-pages: ld.so(8)
- Linux man-pages: pam.conf(5)
- MITRE ATT&CK: T1543.002 Systemd Service
- NIST: SP 800-86 Guide to Integrating Forensic Techniques into Incident Response
Related NHI Mgmt Group resources: Linux Forensics Guide · Persistence Techniques Guide · Linux PAM Guide · How to check a Linux server for signs of compromise