Skip to content
Back to Articles

From a Root Task Queue to a Kernel Rootkit: How a Localhost Broker Gave Every Account Root

Share:

A shared hosting server started running out of memory. The process list explained why: more than a hundred and fifty copies of the same small binary, all running as root, all with parent PID 1, all started from a four-letter directory at the root of the filesystem that nobody on the team had created. The binary was a reverse shell. Something kept launching it, and nothing in user space was doing the launching.

That something was a loadable kernel module. And the way the attacker got root to load it was not a kernel exploit, a stolen root password or a vulnerable control panel. It was an internal task queue, written in-house to automate a routine job, running as root and listening on localhost without a password.

This article follows the evidence in the order we found it: the rootkit, the way it was loaded, the false lead that looked like the loader, the accidental reboot that switched it off, and the small piece of glue code that gave every account on the server a way to root. Every command shown is read-only.

🧟 The symptom: root processes that kept coming back

The first view was a plain process listing, sorted by command line and filtered to root processes whose parent is PID 1:

ps -eo pid,ppid,user,lstart,args --sort=args |
  awk '$2 == 1 && $3 == "root"' | awk '{print $NF}' | sort | uniq -c | sort -rn | head

On a healthy server that list is short and boring: sshd, crond, the web server, the database, a few agents. Here one entry stood out with a count of 158. Killing the processes did not help for long, because new ones appeared. A process that is reparented to PID 1 and respawns without a service unit, a cron entry or a supervisor behind it is a strong hint that the launcher lives in the kernel.

The kernel log confirmed it. A kernel module can start user-space programs through the usermode helper interface, and the kernel logs when that happens with a NULL argument vector:

journalctl -k --no-pager | grep -E "launched '.*' with NULL argv"
dmesg -T | grep -iE "taint|khook|usermode"

The log showed a kernel worker thread launching a start script from the same unknown directory, and function names from the khook hooking framework attached to directory listing (filldir64). That combination is typical of Reptile-family rootkits: hook the functions that list directories and processes, hide anything with a chosen name, and keep a reverse shell alive.

🔬 Finding a module that wants to hide

A rootkit that hides files may also try to hide itself from lsmod. Two cheap checks catch the usual tricks, because they read the same information through different paths:

# 1. Compare what lsmod prints with the raw kernel list
diff <(lsmod | awk 'NR>1{print $1}' | sort) <(awk '{print $1}' /proc/modules | sort)

# 2. Out-of-tree (O) and unsigned (E) modules are marked in /proc/modules
grep -E '\((O|E|OE)\)' /proc/modules

# 3. The kernel taint value is non-zero once such a module has been loaded
cat /proc/sys/kernel/tainted

On this server the module was listed in /proc/modules as Live with the (OE) flags: out-of-tree and unsigned. Its file on disk had been placed inside the running kernel's module tree, in a new directory under kernel/drivers/ named after an audio component, so that a quick glance at the tree would not flag it. Module files that no package owns are easy to list:

# Every .ko file that is not owned by an installed package (RPM-based systems)
find /lib/modules -name '*.ko*' -print0 | xargs -0 rpm -qf 2>&1 | grep 'not owned'

# Debian/Ubuntu equivalent
find /lib/modules -name '*.ko*' -print0 | xargs -0 dpkg -S 2>&1 | grep 'no path found'

That search found three copies of the same module: one in the kernel's module tree, and two more inside a template directory that the hosting platform copies into every customer's isolated environment. Persistence came from two more places, both standard Linux mechanisms:

  • A one-line file in /etc/modules-load.d/ naming the module, so systemd-modules-load inserts it at every boot.
  • A fresh depmod run, so the kernel's modules.dep index knew where the module lived. Without that index, modprobe by name does not find a module in a non-standard directory.
# Anything loaded at boot by name
grep -rv '^\s*#' /etc/modules-load.d/ /usr/lib/modules-load.d/ /run/modules-load.d/ 2>/dev/null

# Module index entries that point outside the usual driver folders you know
grep -v '^kernel/\(fs\|net\|crypto\|lib\|arch\|sound\|block\|mm\)/' /lib/modules/$(uname -r)/modules.dep | grep -i drivers | head -50

⏱️ When did it arrive? Birth times beat modification times

Attackers often reset modification times with touch. On filesystems that record it, the birth time (stat shows it as "Birth") is much harder to fake from user space, and it was the key to the whole timeline:

stat -c '%w  %y  %U  %n' /path/to/unknown/dir/* /etc/modules-load.d/*.conf

The rootkit directory had been born on one morning at a precise second, and rewritten four hours later, again at a precise second. Searching the system log for anything that happened in those two seconds gave an exact match: an entry from a Celery worker saying it had received a task.

grep -n "Received task" /var/log/messages* | less

Lined up side by side, the second task left no doubt:

08:18:34.2  worker: Received task: <setup task>[...]      (ran 69.8 s)
08:18:34.5  rootkit files rewritten, module copied into the kernel module tree
08:18:34.5  /etc/modules-load.d/<name>.conf created
08:18:42.6  modules.dep / modules.alias rebuilt (depmod)
08:18:42    kernel: process 'kworker/...' launched '/<dir>/<start script>' with NULL argv

The first task, four hours earlier, matched the creation of the directory to within 200 milliseconds. The task queue was installing the rootkit.

🧵 The root task queue

The worker belonged to an internal automation tool. Its job was mundane: when a hosting account needed a private Redis instance, a task was queued with the account's username, and a worker running as root created the configuration, the systemd unit and the directories. The relevant part of the task looked like this pattern (rewritten here, not the original code):

@app.task
def setup_instance(username, port):
    # builds one shell command line from the task arguments
    subprocess.call("mkdir -p /etc/instances/" + username +
                    " && chown " + username + " /etc/instances/" + username,
                    shell=True)

Two design decisions combine into a full root compromise here:

  • Arguments go through a shell. With shell=True and string concatenation, a "username" such as x; any command here # becomes two commands. The worker runs as root, so the second command runs as root.
  • Anyone on the box can submit tasks. The Celery broker was a Redis instance on 127.0.0.1 with no password. "Only reachable from localhost" sounds safe until you remember that a shared hosting server has hundreds of local users, each with a shell or a PHP interpreter. Pushing a correctly formatted Celery message onto the queue's Redis list is a few lines of code.

You can test the second condition from any unprivileged account without changing anything:

# Which Redis instances are listening, and as which user?
ss -ltnp | grep -i redis

# Does it answer without authentication? PONG means yes; NOAUTH means a password is set.
redis-cli -h 127.0.0.1 -p <port> ping

And the first condition is a simple code search across whatever in-house tooling runs as root:

grep -rnE 'shell\s*=\s*True|os\.system\(|os\.popen\(|commands\.getoutput' /opt /usr/local/bin /usr/local/lib/python*/site-packages 2>/dev/null

# Which Python processes run as root, and from where?
ps -eo user,pid,args | awk '$1=="root" && /python/'

🧭 Working backwards: weeks of preparation

Once the queue was the suspect, the worker's log became a history book. The same task name appeared dozens of times on one day almost three weeks before the rootkit, then a handful of times on later days. That first day matched SSH logins into one ordinary hosting account using a key that the owner had not added. Almost all of the source addresses belonged to Tor exit relays.

The attacker left a tidy trail in that account's home directory, in hidden files and folders with numeric names:

  • A root proof file. A small file owned by root, containing the output of id: uid=0(root). Its birth time matched a queued task to the second. That was the test that the trick worked.
  • Queue injectors. Short Python scripts that build a Celery message with a malicious argument and push it onto the Redis list.
  • Root payloads. Shell scripts run by the worker that collected root's SSH configuration, database administrator credentials, monitoring keys, DNS data and API tokens, and wrote the results into the account's home directory, still owned by root.
  • A new key in root's authorized_keys, the same key used to log into the hosting account.
  • PHP probes in the account's trash folder that test which command-execution functions are available.

Root-owned files inside an ordinary user's home directory are rare on a hosting server and almost always worth a look:

find /home/*/ -maxdepth 3 -user root -type f -mtime -90 -printf '%TY-%Tm-%Td %u %s %p\n' 2>/dev/null | sort | tail -100

Another useful detail: the attacker had used the broker itself as a scratch pad, storing commands and their output under their own Redis keys. One of those outputs contained uid=0(root) and a timestamp that matched another queued task. Redis on this server ran without persistence, so the restart that came later wiped those keys. If you suspect a broker, dump its keys before anyone restarts it.

redis-cli -p <port> --scan | head -200
redis-cli -p <port> --scan | while read -r k; do echo "== $k $(redis-cli -p <port> type "$k")"; done

🪤 The false lead: an out-of-memory kill

The server owner had found their own explanation: an OOM kill in the kernel log at exactly the same second as the rootkit's first launch. The theory was that the OOM event somehow loaded the module.

It did not, and it is worth explaining why, because coincidences like this are common on busy servers:

  • The OOM kill was a memory cgroup limit being hit inside one customer's resource container by a PHP process. A cgroup OOM kills processes; it cannot insert a kernel module or start a usermode helper.
  • The installation had started eight seconds earlier, inside the queued root task. The "launched ... with NULL argv" line is the module's own work, right after depmod and the insertion.
  • The same container produced identical OOM kills at other times, with no module activity at all.

When two events share a timestamp, check which one started first and whether either has happened alone. The one that recurs on its own is usually background noise.

🔄 The reboot that disabled it by accident

A few hours into the investigation the server was rebooted. It came back with no rootkit processes and no module in /proc/modules. The boot log said why:

journalctl -b -u systemd-modules-load --no-pager
# systemd-modules-load: Failed to find module '<name>'

A newer kernel package had been installed days earlier, and the reboot booted into it. The rootkit's module file and its modules.dep entry existed only for the previous kernel version, so the boot-time loader found nothing. The persistence was not removed. It was pointed at the wrong kernel.

That is not a fix. Everything the attacker left behind was still on disk:

  • the module copies and their index entry for the previous kernel, one boot menu choice away from loading again;
  • the attacker's key in root's authorized_keys;
  • the toolkit in the user account;
  • and the task worker itself, restarted at boot with the same code and the same open broker.

Moving the rootkit's files to a quarantine folder was also done along the way. That is fine for evidence, but remember that moving or deleting a .ko file does nothing to a module that is already loaded. Only the absence of the module in /proc/modules after a clean boot tells you it is not running, and even then only for that boot.

🛠️ What actually fixes this

A kernel rootkit installed with root privileges means the attacker could have changed anything: binaries, PAM modules, SSH configuration, other kernel trees, firmware settings. There is no reliable way to prove a system clean after that, so the server has to be rebuilt from a clean installation and the data moved over after review. Before or alongside the rebuild:

  • Rotate every secret the root payloads collected: root and database administrator passwords, API tokens, monitoring keys and SSH host keys.
  • Remove unknown keys from every authorized_keys file, starting with root's. Compare fingerprints against the list you expect: ssh-keygen -lf /root/.ssh/authorized_keys.
  • Fix the task worker before it runs anywhere else, as below.

The code fix is small. Never pass task arguments through a shell, and validate them against what they are supposed to be:

import re, subprocess

USER_RE = re.compile(r'^[a-z][a-z0-9_-]{0,31}$')

@app.task
def setup_instance(username, port):
    if not USER_RE.match(username) or not (1024 < int(port) < 65536):
        raise ValueError("invalid task arguments")
    path = "/etc/instances/" + username
    subprocess.run(["mkdir", "-p", path], check=True)          # no shell
    subprocess.run(["chown", username, path], check=True)

And the broker needs to stop trusting everyone on the machine:

# redis.conf for the broker
requirepass <long random secret>
# or better: no TCP at all, a Unix socket readable only by the worker's group
port 0
unixsocket /run/broker/redis.sock
unixsocketperm 660

Finally, ask whether the worker needs root at all. Most "setup" jobs need root for two or three specific operations, which can be granted through narrow sudo rules or a small, well-reviewed helper, while the worker itself runs as an unprivileged user.

📋 A read-only checklist for your own servers

  • Root processes with parent PID 1 that respawn: ps -eo pid,ppid,user,args | awk '$2==1 && $3=="root"'
  • Usermode helper launches in the kernel log: journalctl -k | grep "with NULL argv"
  • Out-of-tree or unsigned modules and taint: grep -E '\((O|E|OE)\)' /proc/modules; cat /proc/sys/kernel/tainted
  • lsmod versus /proc/modules differences.
  • Module files no package owns, in every kernel version under /lib/modules, not only the running one.
  • Entries in all modules-load.d directories.
  • Local Redis, RabbitMQ or other brokers that answer without authentication.
  • In-house tools running as root that call a shell with arguments: grep -rn 'shell=True'.
  • Root-owned files in user home directories.
  • Unknown keys in root's authorized_keys.

💡 Takeaways

  • A root service that accepts work from localhost is a root service that accepts work from every local user. On shared hosting, that is everyone.
  • shell=True with arguments in a root task is a root shell with extra steps.
  • Birth times and task logs can date an intrusion to the second, even when modification times are faked.
  • Coincidences are common on busy servers. Before accepting a cause, check which event started first and whether the suspected cause happens on its own.
  • A reboot into a new kernel can switch a rootkit off without removing anything. A server that had root-level malware gets rebuilt.

❓ FAQ

Can I just unload the module with rmmod and delete the files?

You can try, but a rootkit that hooks the kernel may block or fake its own removal, and it has had root on the machine. Anything it changed while loaded, such as other binaries, keys or configuration, stays changed. Unloading is a containment step, not a cleanup.

Why did the module stop loading after the reboot?

Kernel modules are built for one kernel version and live in that version's directory under /lib/modules. The server booted into a newer kernel, so the module named in modules-load.d did not exist for it. Booting the older kernel again would load it again.

Could an out-of-memory event load a kernel module?

No. An OOM kill, whether system-wide or in a cgroup, only selects and kills processes. Loading a module needs a privileged process calling the module-loading system calls, which is exactly what the queued root task did a few seconds earlier.

Is a Redis bound to 127.0.0.1 safe?

Only if every local user is trusted. On a shared server, localhost is reachable by every hosting account through SSH, cron or a PHP script. Use a password, a Unix socket with tight permissions, or both, and never let a broker feed a root worker without them.