Cleaning a WordPress MySQL database after a malware / hacking attack.

Summary: Using RegEx in MySQL to clean up an infected database

Requirements: MySQL 8.0+ or Maria DB. phpMyAdmin or MySQL console access.

There are many guides out there explaining how to clean up the actual WordPress PHP / HTML files after a site has been hacked. However, I have not found any good instructions on how to clean up a contaminated MySQL / Maria db database.

Many of the infections we come across inject malicious content using iFrames and most of the URL’s and the content are obfuscated using base64 encoding.

We recently helped clean an infected database where every post in the wp_posts table had this tag added at the end

Followed by javascript, RegEx and base64 encoded data

In order to find out whether the wp_posts table contained malware, we searched for commonly used malware phrases:

SELECT * FROM wp_posts where post_content LIKE ‘%iframe%’;
SELECT * FROM wp_posts where post_content LIKE ‘%JavaScript%’;
SELECT * FROM wp_posts where post_content LIKE ‘%RegEx%’;

Normally, legitimate WordPress posts do not contain these keywords. However, any hits would have to be reviewed manually, to ensure they are actual infections.

After doing a sanity check on the hits from the above queries, we checked what an infected post would look like post-cleanup:

SELECT REGEXP_REPLACE(post_content, ‘.*’, ‘xxx’) FROM wp_posts WHERE ID = 7360; (post ID 7360 is one of the infected posts)

This command replaces and anything that follows with just ‘xxx’.

The post looked clean with all infected content replaced by ‘xxx’

Finally, we went ahead and removed all infected content using this command:

UPDATE wp_posts
SET post_content = REGEXP_REPLACE(post_content, ‘.*’, ”);

If your database has infected content in the middle of a post, you’d have to use a more complicated RegEx in order to not delete the valid content that follows the infection.

One thought on “Cleaning a WordPress MySQL database after a malware / hacking attack.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>