Securing VPS/Servers

WordPress Hacked: How to Find the Damage and Clean Up on a VPS

What to do when a WordPress site on your VPS is hacked: contain it, keep evidence, find the changes with WP-CLI and find, then decide between cleaning, restoring and rebuilding.

If your WordPress site redirects visitors to spam pages, has administrator accounts you did not create, or your provider or Google has flagged it, treat it as compromised. The order of work matters: contain the site, take a copy for evidence, find out what was changed, then rebuild from clean sources and close the hole that was used.

The reliable outcome is a rebuild: fresh WordPress core, plugins and themes from their official sources, with only the database and the uploads kept after checking them. Deleting the few files that look wrong usually leaves a backdoor behind.

This is general guidance based on the WP-CLI and WordPress documentation; the commands were not run on a test server for this article, and no procedure can guarantee that every trace is gone.

Signs of a hacked site

What you seeLikely causeWhere to look
Visitors, often only from search engines or phones, land on spam or scam sitesInjected JavaScript or PHP redirectDatabase content, theme files, wp-config.php
Unknown administrator accountsStolen password or a plugin flaw that creates userswp user list
Files changed or added that you did not touchBackdoor or malware dropperChecksums, find -mtime, uploads
Abuse notice from the host, outgoing spam, high CPUThe site is used to send mail or attack othersMail queue, process list, the server itself
Browser or search result warningGoogle found malware or phishing pagesSearch Console, Security issues

First hour: contain and copy

Restrict the site to your own IP address. This stops visitors being harmed and stops the attacker using the backdoor while you work. In the site's nginx server block:

allow 203.0.113.10;   # your own IP address
deny all;
sudo nginx -t && sudo systemctl reload nginx
curl -sI https://example.com/ | head -1    # from another network: 403

Take a full copy before changing anything. It is your evidence and your fallback.

sudo mkdir -p /root/incident && sudo chmod 700 /root/incident
sudo tar -czf /root/incident/files-$(date +%F).tar.gz -C /var/www example.com
sudo mariadb-dump --single-transaction wordpress | sudo tee /root/incident/db-$(date +%F).sql > /dev/null
sudo cp /var/log/nginx/access.log* /root/incident/

On MySQL the dump command is mysqldump. Replace wordpress with the database name from wp-config.php. Do not delete files, update plugins or restore anything yet.

Find the damage

WP-CLI loads the site's own code for most commands, and that code may be the malware. wp core verify-checksums does not load WordPress. For the others, add --skip-plugins --skip-themes. See the WP-CLI guide if wp is not installed.

Core files. This compares every core file with the checksums from WordPress.org; --include-root also reports files in the site root that do not belong to WordPress (WP-CLI 2.8 or later).

cd /var/www/example.com
wp core verify-checksums --include-root

Plugins.

wp plugin verify-checksums --all --skip-plugins --skip-themes

Checksums are published for plugins from the WordPress.org directory. Commercial plugins and all themes have to be compared with a fresh download from the vendor. Both commands are described in the WP-CLI reference.

Recently changed PHP files, and PHP where none belongs.

find . -name '*.php' -mtime -30 -printf '%TY-%Tm-%Td %TH:%TM  %p\n' | sort
find wp-content/uploads -type f \( -iname '*.php' -o -iname '*.phtml' -o -iname '.user.ini' \)

-mtime -30 lists files modified in the last 30 days. Attackers can fake modification times, so an empty result proves nothing. The uploads folder should contain no PHP at all.

Accounts and scheduled tasks.

wp user list --role=administrator --fields=ID,user_login,user_email,user_registered --skip-plugins --skip-themes
wp cron event list --skip-plugins --skip-themes

Look for administrators you do not recognise and for cron hooks with random-looking names.

Places that run on every request. Read these by eye:

  • wp-config.php: extra include or require lines, long encoded strings, code above the opening comment.
  • wp-content/mu-plugins/: "must-use" plugins load automatically and do not appear in the normal plugin list.
  • wp-content/object-cache.php, advanced-cache.php and db.php: drop-in files that should exist only if a plugin you use installed them.
  • .user.ini files, which can make PHP load another file before every script. On Apache, also every .htaccess.

The database. Search content and settings for injected scripts:

wp db prefix --skip-plugins --skip-themes
wp db query "SELECT ID, post_title FROM wp_posts WHERE post_content LIKE '%<script%' LIMIT 50;"
wp db query "SELECT option_name FROM wp_options WHERE option_value LIKE '%<script%' OR option_value LIKE '%base64_decode%';"
wp option get siteurl; wp option get home

Use the prefix the first command prints in place of wp_. Not every hit is malicious, since embeds and widgets can legitimately contain scripts; look for domains you do not know.

Finally, search the saved access log for requests to the files you found. The first request to a backdoor file, and what the same IP address did just before, often points to the entry point.

Clean, restore or rebuild

OptionWhen it fitsRisk
Clean in place (remove the bad files and entries)Rarely; a single known change with a clear causeHigh: a missed backdoor brings the attacker back
Restore a backupYou know when the compromise happened and have a backup from before itContent added since is lost; the hole is still open after the restore
Rebuild from clean sourcesThe default, and the only choice when the date is unknownLowest; takes the most work

Backdoors are often planted weeks before anything visible happens, so check the dates from the previous section against the backup date before trusting a restore. WordPress backups on a VPS describes the restore steps.

Rebuild from clean sources

  1. Write down the plugins and themes in use: wp plugin list --skip-plugins --skip-themes and wp theme list --skip-plugins --skip-themes.
  2. Create a new, empty site directory and download a fresh core into it.
  3. Create a new wp-config.php with a new database password, instead of copying the old file.
  4. Install each plugin and theme again from WordPress.org or the vendor. Do not copy them from the old site. Leave out anything abandoned or unused.
  5. Copy wp-content/uploads only after the check for PHP files comes back empty.
  6. Keep the database, after removing rogue users, injected content and unknown cron events.
sudo mariadb -e "ALTER USER 'wpuser'@'localhost' IDENTIFIED BY 'NEW-LONG-PASSWORD';"

mkdir /var/www/example.com-clean && cd /var/www/example.com-clean
wp core download
wp config create --dbname=wordpress --dbuser=wpuser --prompt=dbpass
wp plugin install PLUGIN-SLUG --activate
wp core verify-checksums

wp config create generates new salts, the keys that sign login cookies, so every existing session ends. If the old site used a table prefix other than wp_, add --dbprefix= with that value. Then reset the passwords of all remaining users and delete the accounts that should not exist:

wp user delete USER-ID --reassign=YOUR-USER-ID
wp user reset-password $(wp user list --field=user_login)

reset-password emails each user a notice; add --skip-email to prevent that and tell them to use "Lost your password?". Point nginx at the new directory, set ownership as described in WordPress file permissions, and keep the old directory out of the web root.

Rotate everything else the site could read: SFTP and SSH passwords, the hosting panel login, and API keys stored in plugin settings or wp-config.php (mail service, payment gateway, storage). Remove application passwords you do not recognise from each user's profile.

Close the hole

A rebuilt site with the same weakness is compromised again. The usual entry points are an outdated plugin or theme, a weak admin password, and credentials reused from another service or stolen from an infected computer. Use the access log lead from earlier to decide which one applies, then update, remove or replace it. WordPress security on nginx covers the server-side measures, including two-factor login.

Check whether the attack stopped at WordPress. Unknown system users, new SSH keys, processes running as www-data that are not PHP-FPM, or changed files outside the web root mean the server is affected. In that case follow what to do when your VPS is hacked.

Afterwards

Remove the IP restriction from nginx and reload. If Google flagged the site, open Search Console, go to the Security issues report and request a review once the site is clean.

If the site stores customer data, such as shop orders, accounts or form submissions, a compromise may create a legal duty to notify the people affected or a data protection authority, depending on where you and your customers are. Get professional incident response and legal advice in that situation, and keep the evidence copy untouched.

Share story:

Continue reading other guides on How VPS.