Every day, thousands of website databases around the world are targeted by hackers looking to steal, destroy, or alter website data and content. A hacked database can have severe repercussions for a website, including loss of sensitive customer information, damage to reputation, and even legal consequences.
A database hack occurs when an unauthorized individual gains access to your database environment, often by exploiting vulnerabilities in your website or server. Once inside, they can inject malicious code, alter your data, or even lock you out of your own website.
This guide aims to educate website owners about how to detect and clean malware and spam from a hacked database, as well as how to secure it against future threats.
Contents
When a user visits a page on your site, the CMS combines content stored in your database with the logic in the CMS’s source code to display the page.
If your website database becomes compromised, it can directly impact your website’s functionality — even if you replace the CMS’s source code with a fresh copy.
So, in the aftermath of a hack, it’s vital not only to identify but also permanently remove any malware present in the database. Thoroughly cleaning your database is a critical step towards recovering from a security breach, ensuring your website operates as intended, and safeguarding your site’s overall security.
Understanding how a database becomes compromised is the first step in preventing future attacks. Here are some of the most common ways a hacker can gain unauthorized access to a website’s database.
This technique is one of the most prevalent methods of hacking a database. SQL (Structured Query Language) is the language that is used to communicate with and manipulate databases. SQL injections occur when a hacker inserts malicious SQL code into a query.
Often, this is done through website forms or URL parameters. For instance, if you have a form on your website that asks for a user’s email address, a hacker might input SQL statements instead of a legitimate email address. If your website is not properly secured, these statements can be run against your database, leading to unauthorized access or data manipulation. From a CMS perspective, improper input sanitization in themes, plugins or extensions may lead to SQL injection, giving attackers a direct hold over the CMS database.
Malware, short for malicious software, is a broad term that encompasses various types of harmful software, including viruses, trojans, ransomware, and spyware. Hackers often use malware to gain unauthorized access to a database, steal data, or disrupt database operations.
The process usually starts with the hacker finding a way to deliver the malware to your website or server. This could be through a malicious email attachment, a compromised download, or an infected website that your server interacts with. Although endpoint devices are not among the top causes of website infection they are still part of the attack surface for website administrators.
Once the malware is on your website or server, it can perform a variety of malicious tasks. Some malware is designed to search for and exploit vulnerabilities in your database software, giving the hacker access to your data. Other types might create a backdoor, allowing the hacker to come and go as they please.
If your website or server software is out of date, it may have known vulnerabilities that hackers can exploit.
These security holes or vulnerabilities can occur in any part of your system – your website’s content management system (CMS), plugins or extensions you’re using, your server’s operating system, or even the database software itself.
Here’s an example: suppose you’re running an outdated version of a CMS like WordPress. A vulnerability in this older version might allow a hacker to upload and execute a malicious script on your server. Once this script is running, it could then be used to access or manipulate your database.
Hackers are always on the lookout for systems running outdated software, and they often use automated tools to find and exploit these vulnerabilities. If a vulnerability is well-known and your software is unpatched, it’s not a matter of if your database will be hacked, but when.
If your database username and password are easy to guess, or if they have been stolen, they can be used to gain direct access to your database.
There are several ways weak or stolen credentials can lead to a hacked database:
Each of these methods relies on a different type of vulnerability in your database, whether it’s in the software you’re using, your website code, or your own security practices.
Here’s a simplified breakdown of how a typical website database hack might occur:
Let’s take a quick look at the steps illustrated in the diagram.
Understanding this process can help you secure your database at each stage. For instance, regular security audits can help detect reconnaissance activity, up-to-date software can prevent exploitation, and monitoring user activity can help detect unauthorized access.
Cleaning a hacked database can seem intimidating, but by following a systematic process, you can remove the malware, restore your site’s functionality, and harden it against future attacks.
The first step in the cleanup process is to log into your database administration panel. This could be a web-based interface like phpMyAdmin (accessed through cPanel), a tool such as Adminer, or a software application like MySQL Workbench, depending on your hosting environment.
This panel gives you direct access to your database and allows you to run SQL queries, view and modify database tables, and perform other administrative tasks. You’ll need this access to search for and remove malicious content in your database.
To log in, you’ll need your database username and password. If you don’t have this information, you can typically find it in your website’s configuration file (like ‘wp-config.php‘ for WordPress sites) or get it from your hosting provider.
Once you’ve logged in, you can navigate to the section where you can manage your databases (in cPanel, this would be under the ‘Databases‘ section). From there, select the database that you suspect has been hacked.
Remember to proceed with caution. The database admin panel lets you directly interact with your database, which means you could accidentally alter or delete important data. Always make sure you have a backup before making any changes (see step 2).
Backing up your website and database is a critical step before making any changes to your website or trying to clean up a hack. A backup serves as a safety net, allowing you to restore your site to its current state if something goes wrong during the cleanup process.
1 – Backup your website files
Start by backing up all your website’s files. This includes all scripts, images, plugins, themes, and configurations.
If you’re using a hosting control panel like cPanel, there’s usually an option to backup all the files in your home directory. Alternatively, you can use an FTP client like FileZilla to manually download all your site’s files to your local machine.
2 – Backup your database
Next, you need to create a backup of your database. In your database management tool (like phpMyAdmin or MySQL Workbench), there should be an option to “Export” your database. This will create a .sql file that contains all the data in your database and the commands to recreate it. Save this file to a secure location.
Note:
If the infection is in a particular database table you may want to also make an additional backup of that specific table as it will make the restore process much easier if something goes wrong during the remediation process.
3 – Verify that your backups actually work
After creating the backups, verify them to ensure they’re not corrupted and that they contain all necessary data. Try opening the .sql file with a text editor to ensure it’s not empty, and consider restoring it on a local test environment to confirm it works as expected.
4 – Safely store your backups offsite
Store your backups in a safe and secure location. This could be a secure cloud storage service or an external hard drive — just don’t keep them on the same server as your website. Make sure wherever you choose is secure and not easily accessible to potential hackers.
Remember that backups should be a routine part of your website maintenance, not just something you do when facing a security issue. Regular backups help mitigate the damage of potential future hacks, allowing you to restore your site quickly and easily.
After you’ve backed up your website and database, the next step is to begin the investigative process. Hackers often leave traces in your database tables in the form of suspicious keywords, links, or scripts.
To perform this step, you’ll need to use a tool that allows you to run SQL queries on your database. This could be a web-based tool like phpMyAdmin, a part of your web hosting control panel, or a standalone application like MySQL Workbench.
Here are the steps you can take to check your tables.
Start by identifying what you are actually looking for. Manually checking database tables and columns one by one is a fool’s errand so you’ll need to know what to search for.
Start by running your website through our Sucuri SiteCheck tool – it should flag any known malware or spam lodged in the website, and oftentimes this will be lodged within the database (especially for spam and Balada malware). If you are noticing your website redirect to third party websites or see any other strange behavior or content, take note of what they are so you can search for those particular strings.
Database tables which are most commonly affected by malware and spam in a WordPress environment are as follows:
While on Magento environments our teams most commonly find credit card skimmers in the core_config_data table, but also tables such as cms_block, cms_page and variable_value.
You’ll want to take note of your database prefix as well. WordPress databases commonly use wp_ as the prefix, but some sites may use other unique variations.
SQL (Structured Query Language) is a language used to manage and manipulate databases. Database management tools like PHPMyAdmin and Adminer have built-in search functions which allow you to easily search for strings lodged in the database. You can also use SQL queries with regular expressions to search for specific patterns in your database that indicate the presence of malicious content.
For instance, you could search for links to known malicious websites, SEO spam keywords, or even query for common malware scripts.
Here’s a sample query for this scenario that you can customize for your environment:
SELECT * FROM your_table WHERE your_column REGEXP 'suspicious_pattern';
This uses the REGEXP command to search for items matching a specific pattern, but you can also just use the basic search function if you’re not familiar with crafting regular expressions.
Let’s provide another example to elaborate further on the query. Imagine you happen to be searching for gambling spam keywords in your WordPress posts.
The query would then look like this:
SELECT * FROM `wp_posts` WHERE `post_content` LIKE '%gambling%';
And if you were looking for gambling keywords in your WordPress website’s post titles, you might use the following command instead:
SELECT * FROM `wp_posts` WHERE `post_title` LIKE '%gambling%';
You can find an extensive list of common WordPress database tables in the WordPress Codex.
Certain keywords may indicate the presence of malware. These could be terms related to hacking, pharmaceuticals, gambling, or any other keywords that seem out of context for your website.
Remember, false positives are possible when searching for suspicious content. Be careful not to mistakenly flag or delete legitimate content. When in doubt, investigate further before making any changes.
You will also want to check your database for any links that seem out of place or lead to unfamiliar websites. Hackers often inject their own URLs into a website’s database to redirect traffic, host phishing pages, or spread malware.
According to our latest hacked website report, 53.75% of all infected databases were found to contain SEO spam, the majority of which were hidden links. Another 11.15% of infected databases were found to contain injected scripts from known malicious domains.
In 2022 these five domains were found injected into 7.6% of all infected databases, all of which are related to the massive Balada Injector campaign:
Comment spam has plagued WordPress websites for many years. Although it’s not usually explicitly harmful it can be a major nuisance for websites which have comments enabled. Automated bots will pollute WordPress websites with spam links to pharmaceutical knockoffs, essay writing services, and bootleg designer wear. If publicly viewable these spam comments can harm your site’s SEO and alienate genuine users. To prevent comment spam from getting onto your website in the first place consider using an anti-spam plugin.
Of course, you can always just use the wp-admin interface for searching for and removing spam comments, but it can be done directly in the database as well. That also might be a bit more effective and efficient if you are dealing with many thousands of them.
Here’s how to check your comments meta for spam directly in the database:
Start by identifying the database table that stores your website’s comments. In WordPress, for instance, this is typically the “wp_comments” table and the related “wp_commentmeta” table.
Much like you did when checking for suspicious content, you can use SQL queries to search through your comments as well. Look for comments with suspicious or out-of-place content, such as links to irrelevant or shady websites, comments written in poor or nonsensical English, or comments that seem overly promotional.
An example SQL query to search for gambling spam might look like this:
SELECT * FROM wp_comments WHERE comment_content LIKE '%gambling%';
Spammers often use a fake or suspicious name, email, or URL when posting their comments. Check the comment_author, comment_author_email, and comment_author_url fields in your comments table for any suspicious entries.
PHP is a scripting language widely used in web development, including in content management systems like WordPress. While PHP functions are essential for your website to work correctly, some functions are often misused in hacking attempts.
These malicious functions can be used to execute arbitrary code, obfuscate malicious activity, or create backdoors for persistent access.
Some commonly misused functions include:
Here’s how to check for these PHP functions in your database:
Although it’s not overwhelmingly common, sometimes PHP code can be injected into tables related to your website’s theme or plugin settings, options, or any custom tables that might store executable code.
Much like you did when checking for suspicious content, you can use SQL queries to search for these functions.
For example:
SELECT * FROM db_table WHERE db_column LIKE '%eval\\(%';
This query will return all records in ‘your_table’ where ‘your_column’ contains the string ‘eval(‘.
If your query returns any results, investigate these thoroughly. Remember that these functions have legitimate uses, so their presence doesn’t necessarily mean your site has been hacked. Look for suspicious patterns, such as long, obfuscated strings of code, or functions being used in places where you wouldn’t expect.
As soon as you’ve identified and confirmed the presence of any suspicious links, malicious code, unwanted keywords, or spam comments, you can delete them from your database. Be sure to also delete any related entries in the commentmeta table to keep your database clean and organized.
You can use either SQL DELETE or UPDATE commands to delete rows or update specific fields in your database.
Here’s an example query that will fully remove spam comments containing the string “gambling”:
DELETE FROM `wp_comments` WHERE `comment_content` LIKE '%gambling%';
Be aware that this specific command will fully remove the database content that contains that string, so you would only want to use this for the wp_comments table. Using this command to remove a JavaScript injection in wp_posts, for example, will fully remove the posts and quite likely remove legitimate content from your website.
Remember
Both posts and pages are stored in wp_posts, so act accordingly!
Here’s an example command that will find a specified string in the database and replace it with content of your choosing (for the purposes of malware removal, you’d normally want to replace it with empty content):
UPDATE wp_posts SET post_content = REPLACE ( post_content, 'text to find here', 'text to replace here');
These queries need to be properly escaped lest the command get truncated. So any instance of an apostrophe ‘ will need to be preceded by a backslash \ and some other special characters will require escaping as well.
Let’s say we wanted to remove this (fictitious) JavaScript injection from wp_posts:
We would run the following SQL query to get rid of that and replace it with empty content, thereby cleansing the injection from the database:
UPDATE wp_posts SET post_content = REPLACE ( post_content, '<script src=\'https://badwebsite.info/stat.js?ft=ms\' type=\'text/javascript\'></script>', '');
Notice how the apostrophes all have a backslash before them. The reason for this is that the MySQL syntax itself uses apostrophes, so without escaping them (with backslashes) it would prematurely terminate the query and result in a syntax error. Placing the backslash before it causes MySQL to treat it as a normal character, rather than as part of the query.
Remember, manual code removal can be risky and might not fully clean your website if the malicious code has spread or if there are multiple variants present in your environment. For example, sometimes content in the database is serialized, particularly in wp_options. Removing this outright can damage your website, as doing so will break the serialization. For such cases, it is safer to remove the malicious content directly from your wp-admin or other CMS administration panel.
An example of serialized database content might look something like this:
a:2:{i:0;s:5:"first";i:1;s:6:"second";}
Furthermore, deleting the symptom will not address the root cause of the issue. For that, you’ll need to identify and fix the original reason your database was compromised in the first place.
In short, always keep a backup and consider seeking professional help if you’re unsure.
The Sucuri Web Application Firewall (WAF) and Intrusion Prevention System (IPS) prevents hacks and protects your website from hackers, brute force attacks, bad bots, DDoS, and malware.
Say on top emerging website security threats with our helpful guides, email, courses, and blog content.
Sucuri Cookie Policy
See our policy>>
Our website uses cookies, which help us to improve our site and enables us to deliver the best possible service and customer experience.