Skip to content
STAGE33R

Guides · Incident response and recovery · 7 steps · reviewed

WordPress site hacked: how to find and clean the infection with WP-CLI

Most hacked WordPress sites were entered through an outdated plugin or theme or a stolen password. WP-CLI lets you compare files with the official releases, which finds changed and extra files quickly.

  1. Back up the infected site first

    Keep a copy for analysis, outside the web root, and put the site in maintenance mode.

    cd /path/to/site
    sudo -u SITEUSER wp db export ~/infected-$(date +%F).sql
    tar czf ~/infected-files-$(date +%F).tgz .
    sudo -u SITEUSER wp maintenance-mode activate
  2. Compare core and plugin files with the official ones

    Anything reported as changed or added needs a look.

    sudo -u SITEUSER wp core verify-checksums
    sudo -u SITEUSER wp plugin verify-checksums --all
  3. Find PHP where it should not be

    Uploads should only hold media. A PHP file there is almost always a backdoor.

    find wp-content/uploads -type f -name '*.php'
    find . -type f -name '*.php' -mtime -7 -not -path './wp-content/cache/*'
  4. Check users and scheduled tasks

    Rogue administrators and cron events keep the attacker in.

    sudo -u SITEUSER wp user list --role=administrator
    sudo -u SITEUSER wp cron event list
  5. Reinstall core and plugins from clean sources

    This replaces every core file and keeps your content and settings.

    sudo -u SITEUSER wp core download --force --skip-content
    sudo -u SITEUSER wp plugin install $(sudo -u SITEUSER wp plugin list --field=name | tr '\n' ' ') --force
  6. Reset passwords and salts

    Salts log everybody out. Reset every administrator password and the database password.

    sudo -u SITEUSER wp config shuffle-salts
    sudo -u SITEUSER wp user update ADMIN --user_pass=NEW_LONG_PASSWORD
  7. Close the way in, then reopen

    Update everything, remove unused plugins and themes, then turn off maintenance mode and watch the logs for a week.

    sudo -u SITEUSER wp plugin update --all
    sudo -u SITEUSER wp maintenance-mode deactivate

Common mistakes

  • Cleaning only the file you found: backdoors usually come in several copies.
  • Reusing the same passwords on other sites.
  • Leaving abandoned plugins installed because they are inactive: they can still be reached.

How to undo it

Restore the pre-clean files and database from the archive you made in the first step if a replacement breaks the site, then repeat one step at a time.

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.