Secure your WordPress Plugin : CSRF protection


I fixed this vulnerability in my WordPress ‘WP Database Backup‘ plugins and would like to share the same knowledge to other developers.

Lest you think this security stuff isn’t important, a major vulnerability was recently found in the WordPress plugins, which is installed on many WordPress sites and which allowed hackers to manipulate the WordPress database using CSRF(Cross-Site Request Forgery).

Cross-site request forgery, also known as a one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. Unlike cross-site scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user’s browser.

How to Prevent CSRF

We can stop CSRF attacks by using some handy functionality built into WordPress.

  1. A nonce is generated.
  2. That nonce is submitted with the form.
  3. On the back end, the nonce is checked for validity. If valid, the action continues. If invalid, everything halts – the request was probably forged (You verify the nonce before doing anything else).

The nonce field is used to validate that the contents of the form request came from the current site and not somewhere else. A nonce does not offer absolute protection, but should protect against most cases. It is very important to use nonce fields in forms.

Let’s Add a Nonce

1.First create nonce using wp_create_nonce  function and pass it along with your request.

<input name=”wpdbbackup_update_setting” type=”hidden” value=”<?php echo wp_create_nonce(‘wpdbbackup-update-setting’); ?>” />

2.Verify nonce using wp_verify_nonce function.

if (!isset($_POST[‘wpdbbackup_update_setting’]))
die(“<br><br>Invalid form data. form request came from the somewhere else not current site! “);
if (!wp_verify_nonce($_POST[‘wpdbbackup_update_setting’],’wpdbbackup-update-setting’))
die(“<br><br>Invalid form data. form request came from the somewhere else not current site! “);

Using nonces you can stop forgery, and foil hackers!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s