5 Best Ways to Solve WordPress Vulnerability

WordPress Security Vulnerability - CodeFlist

Presently, WordPress covers 33% of the web. It means a huge number of users are using it which will definitely attract more attackers and hackers. Due to this, there are more threats and attacks like SQL Injection attack, Redirection attack, CSRF attack, XSS attack, etc which causes a vulnerability in WordPress. For this reason, this doesn’t mean that WordPress is not secure. We have to focus on data sanitization, data validation, data escaping, using and verifying nonce, safe redirection, user capabilities, etc. to make WordPress secure. However, the vulnerabilities in WordPress makes it insecure. So, Let’s discuss WordPress Security Issues.

Vulnerabilities come to WordPress as well. But how?

On one hand, there are major threats and attacks due to WordPress vulnerability. On the other hand, we must overcome or prevent these attacks with our code during WordPress development.

Even if you are not a WordPress developer, we encourage you to read the post because you will be able to know the major attacks that attract hackers to attack your site. And you will also be able to understand how to know poorly coded plugins and themes of WordPress. If you run an online shop, it is useful for you to decide the Best WooCommerce plugins and themes that are secure.

WordPress Security Vulnerabilities

Where are the Vulnerable Codes Coming From?

At first, we should have a good understanding of where the WordPress Security issues are. WordPress consists of WordPress core code, themes, and plugins which include Php, Html, javascript and other codes.

The open-source community inspects the WordPress Core Code. There are a huge number of people who report the bug and fix the vulnerabilities and take credit for it. The vulnerability in WordPress can be exploited by SQL Injection attack, CSRF attack, XSS attack, Redirection attack, and other similar techniques. So, WordPress Vulnerability from core development is not much.

Neither the themes usually interact with wp databases, nor the sites change themes often. As Gutenberg is the default editor of WordPress, we need to choose Gutenberg Compatible WordPress Themes for better performance and security. So, fewer vulnerabilities occur with it.

On the other hand, WordPress plugins have complex features and behavior. Also, the interaction is high with users and databases. The site does include a large number of plugins to have external features. As a result, they may bring a large number of vulnerabilities to the site. Plugins introduce major vulnerabilities in WordPress.

WordPress Vulnerability - Threats and Attacks
WordPress Vulnerability – WPscan.org

According to wpscan.org, 11% of vulnerabilities come from themes while 37% of vulnerabilities come from WordPress Core development. In like manner, the rest 52% comes from Plugins. I assume you already know what is a WordPress Plugin

Threats and Attacks

If you are a WP theme or plugin developer, then you must have a good knowledge of threats and attacks to make your code secure and reduce WordPress Vulnerability.

Threats and Attacks-SQL Injection-XSS-CSRF-Redirection
Threats and Attacks

There are many attacks like SQL Injection attack, XSS attack, Redirection attack, CSRF attack which can be prevented by data sanitization, data validation, data escaping, using and verifying nonce, safe redirection, user capabilities, etc.

As a developer, your enemy is generally a malicious user. Such users harm our code. When we incorporate Never Trust User Inputs into our daily coding behavior then we are already halfway to writing more secure code to reduce security issues in WordPress. This will make your work easier as a WordPress Customizer.

WordPress Vulnerability – SQL Injection Attack

In an attempt to retrieve critical and sensitive data, the SQL injection attack injects a malicious SQL code into the WP database. They target WordPress sites that use a SQL database – MySQL, Oracle, SQL Server, etc.

With this intention, they have access to the password, email address or any sensitive data as they can easily add, edit or read the data.

We can take an example of The Famous “Bobby Tables” comic.

Famous bobby tables Comic- Threat and Attack
Famous bobby tables Comic

In this comic a lady keep his son’s name ‘ Robert’); DROP TABLE Students; –‘) ‘; with SQL command which when enters in the database will delete the entire student table of school if the name has not been sanitized.

So to avoid the SQL injection we must sanitize the user input data.

Let’s discuss data sanitization in detail.

Data Sanitization

Sanitizing means securing input, cleaning user input. This process removes invalid text, UTF-8characters or code from the input to lessen vulnerability in WordPress.

It converts HTML specific characters to entities, strips all tags. It also removes line breaks, tabs, and an extra whitespace, strip octets which are a reason for major security issues in WordPress.

There are lots of WordPress built-in function to sanitize the data. Few of them is in the list below:

  1. sanitize_email(): Strips out all characters that should not be in email
  2. sanitize_text_field(): Sanitizes a string (from the user input/database)
  3. sanitize_file_name(): Strips characters (from a filename)
  4. sanitize_key(): Strip keys except for Lowercase alphanumeric characters, dashes and underscores.

Data Sanitization example:


$title=sanitize_text_field($_POST['title']);
update_post_meta($post->ID,'title',$title);

Here, at first, we are sanitizing the title. After sanitization, we are updating the title value in the wp database.


$Name= ' Robert'); DROP TABLE Students; --') ';
INSERT INTO Students VALUES ('$Name');
INSERT INTO Students VALUES ('Robert'); DROP TABLE Students; --')

Here in the above SQL command the name has string and special characters and entities which inserted into student table, the name ‘ Robert’); This closes the insert SQL command and another command get to run with half of the name  DROP TABLE Students; –‘) ‘; and this drop table students delete all the student records of database.

So here if sanitization has been done before entering the value in the database then you would not have lost the entire student database table.

Let’s see an example below to do sanitization.



$Name=sanitize_text_field("' Robert'); DROP TABLE Students; --') ';");
$sql = $wpdb->prepare("INSERT INTO Students VALUES ($Name)");
/* this will only insert 'Robert DROP TABLE Students' */
$wpdb->query($sql);

Here in the above example the sanitization has removed the extra entities and character from the name and allows only the string to insert in a database. In this way, we can safely insert the data and be safe from SQL injections.

Follow this link to learn more about securing input.

WordPress Vulnerability – XSS Attack

Cross-Site Scripting(XSS) attack injects vulnerable scripting language javascript code to steal similar data of the other user like cookies, session tokens, and other information. If we have cookies information then we can connect automatically. Security issues in WordPress come with stolen cookies, as we can easily login with other identities.
It runs on a browser. Millions of people who are browsing the site will get affected by this attack. Undoubtedly, this attack is one of the most serious attacks.

XSS attack example:


<script type=”text/javascript”>
var hacker=’../hacker.php?cookie_data=’+escape(document.cookie);
</script>

Here in this XSS attack example, cookies escape and are sent to hacker.php script’s variable ‘cookie_data’

If the attacker would inject this script into the website’s code, then it will be executed in the user’s browser and cookies will be sent to the attacker which is a dangerous issue. So to avoid this we need to validate. Validate and sanitize all the user input data and escape output data.

Let’s discuss in details below.

Data Validation

Validating is checking user input. This is done to check if the user enters a valid value or not.
There are three ways to validate the data which are built-in PHP functions, core WordPress functions, and custom functions. Never escape this to avoid WordPress Vulnerability. Few of them is in the list below:

  1. isset()/empty(): check whether the variable exists or not
  2. is_email(): check whether given data is in email format or not
  3. is_serialized(): check whether the value is string or not

Data Validation example:


$number='12323';
if(intval(number)){
	//do your things
}
else{
	esc_html_e('Enter valid number','text-domain');
}

The above example checks whether the input data is a number or not, it will only run the program if it’s a number. Thus, data validation helps in reducing WordPress Security issues.

Follow this link to learn more about data validation

Data Escaping

Escaping is securing output. It is the process of stripping out unwanted data, like malformed HTML or script tags. Escaping not only converts the special HTML characters to HTML entities but it also displays, instead of execution. This is done to prevent XSS attack and also to make sure that the data displays the way the user expects it to be.
WordPress provides a few helper functions. They are used for most of the cases. Some of them are:

  1. esc_html(): Escapes HTML specific characters
  2. esc_attr(): Escapes the value of HTML tags attributes
  3. esc_url(): Escapes Hypertext REFerence attributes

Data Escaping example:

$url="javascript:alert('Hello')";
<a href="<?php echo esc_url($url);?>">Text</a>

In the above example, the hacker has entered the scripting language code to challenge the security issues of the WordPress site. So to avoid this, we have used esc_url to escape the URL value and after that only we are echoing the value in our code. In this way, we have prevented the XSS attack.

WordPress Vulnerability – CSRF Attack

Discussing further in WordPress Vulnerability, Cross-Site Request Forgery attack is one-click threats and attacks or session riding attack.
CSRF attack allows an attacker to force a logged-in user to perform an important action without their consent or knowledge.
Here, an authorized user transmits unauthorized commands.
It relies on the idea that an authorized user sent to a certain page or URL can possibly do things that they don’t realize they’ve done. Moreover, it can be fixed with the use of nonce and verify nonce.

Using Nonce

WP generates a security token called the nonce. It is a non-repeating unique number only to you which can be used by you for a specific operation. The nonce value is valid for 24 hours after which it expires and the new one will be generated by wp. You can also set validation time for nonce too.
It protects URLs and forms from misuse to reduce the existing security issues in WordPress.

Furthermore, in order to secure form with a nonce, create a nonce field that is hidden using wp_nonce_field() function:


<form method="post">
   <!-- some inputs here ... -->
   <?php wp_nonce_field( 'name_of_my_action', 'name_of_nonce_field' ); ?>
</form>

Below are few functions for nonce:

  1. wp_nonce_url() – To add a nonce to an URL.
  2. wp_create_nonce() – To Use a nonce in a custom way to process AJAX requests.

Verifying a Nonce

  1. check_ajax_referer() – Checks the nonce (but not the referrer), and if the check fails then by default it terminates script execution.
  2. wp_verify_nonce() – To verify a nonce.
if(isset($_POST['name_of_nonce_field']) && wp_verify_nonce($_POST['name_of_nonce_field'],'name_of_my_action')){
	//do something
}
else{
	esc_html_e('Sorry,your nonce did not verify.','text-domain');
}

Follow this link to learn more about nonce

WordPress Vulnerability – Redirection Attack

WordPress Vulnerability also causes site visitors with automatic redirection to a malicious website.
This generally occurs when a visitor redirects to any other page instead of the page or website they requested.
If your site has high traffic then this attack can lead to less traffic to your site. You will not even realize that your site visitor will be getting redirect to any other page. However, it can be fixed with the help of Safe Redirect.

Safe Redirect

After an action or form if you are redirecting a user to any page then use wp_safe_redirect. wp_safe_redirect checks for an allowed host. If the host is not allowed then it will redirect to the site URL. So, it will prevent malicious redirect to another host. But this is not checked by wp_redirect. So to reduce WordPress security issues, using wp_safe_redirect is a safer way to redirect the links.

$redirect=admin_url('edit.php');
wp_safe_redirect($redirect);

User Capabilities Vulnerability

Besides the Redirection attack, XSS attack, CSRF attack, and SQL Injection attack, WordPress is vulnerable from User Capabilities as well. If you are allowing any user to come to your site to submit any data then do check for user capabilities. Otherwise, you will be a victim of threats and attacks.
The higher the user role, the more capabilities the user has.
Sometimes developers just forget to make sure that the user who’s on a page submitting a form has the necessary privileges to perform the action or not. It will bring a common source of WordPress Vulnerability.


if ( current_user_can( 'edit_posts' ) ) {
    edit_post_link( esc_html__( 'Edit', 'wporg' ), '', '');
}

Let’s take an example of Contact Form 7 vulnerability (Type of WordPress Vulnerability)

The activation number of this plugin is 5+million users. If there is a single vulnerable code then it will affect 5+ million people.

Privilege Vulnerability-Contact Form 7
Privilege Vulnerability of Contact Form 7

There was a capability vulnerability in 5.0.3 and older versions. A logged-in user in the Contributor role can easily edit contact forms. By default, it was only accessible to Administrator and Editor-role users.
So, there was a greater chance of being a hack. The new version of the plugin has solved these errors.

Always Return or Exit in WordPress

If you have missed return or die after completion of your code while writing any function or ajax call. It may look simple but it may lead to important security issues.

Make sure you have always added return and die in the place you mean to. You can take an example of Apple’s #gotofail bug.


defined( 'ABSPATH' ) or die( "No script kiddies please!" );

 function adls_view(){
            global $wpdb;
            include( 'inc/frontend/smls-detail/smls-grid-inline.php' );
           exit();
        }

        function adls_generate_random_string( $length ){
            $string = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $random_string = '';
            for ( $i = 1; $i <= $length; $i ++ ) {
                $random_string .= $string[ rand( 0, 61 ) ];
            }
            return $random_string;
        }

Wrapping Up

This was an important post for WordPress Professionals who care about security. From this post, you have learned about the various threats and attacks that bring vulnerability to WordPress. It includes a brief introduction about SQL Injection attack, XSS attack, CSRF attack, Redirection attack and many more.

Validation-Sanitization-Escaping-Nonce
Points to remember

The various techniques like Data sanitization, Data validation, Data escaping, using and verifying nonce, safe redirection, and user capabilities were also discussed. Due to this, there are security issues in WordPress.

In conclusion,

  1. Never Trust User Input to avoid WordPress Vulnerability.
  2. Validate, Sanitize all inputs and escape all output data
  3. Let’s trust WordPress!

If you have faced any problems regarding the above-mentioned threats and attacks, Let us know about it. Our experts will give you a suitable solution based on your problem.

1 thought on “5 Best Ways to Solve WordPress Vulnerability”

Comments are closed.