How to prevent WordPress CSRF attack

How to prevent WordPress CSRF attack

WordPress CSRF attack happens the same way as it happens on other sites. WordPress provides some inbuilt tools to protect against CSRF. We will see how to make use of these tools while creating our own wordpress plugins.

Wordpress CSRF Attack
Photo credit – 2508581015littleblackcamera

What is CSRF ?

CSRF meansCross-Site Request Forgery (CSRF). It is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user’s web browser to perform an unwanted action on a trusted site for which the user is currently authenticated.

How does it happen ?

For e.g. if you have a form on your website and you haven’t protected it for CSRF attacks then a hacker can create a similar form elsewhere and trick one of your users to submit the form. This means the hacker can fill any values in the form. The damage depends on the functioning of the form.

How to prevent CSRF

In short, to prevent CSRF attack all we need to do is to check if the right user is performing the right action on your website.

WordPress CSRF attack and Nonces

WordPress has inbuilt facility called as Nonces to prevent such attacks. Basically nonce is some code (mix of letters and numbers) which is automatically generated and sent as a hidden field in the form. This number is then compared with the number on the submit page and further action allowed only if both the numbers match. This number has limited lifetime and keeps changing after every regular interval i.e. after the lifetime of that particular nonce for that user has reached. Although the hacker could see this number in your source code the number would not be valid as it depends on the user and it keeps changing.

However wordpress nonces are not the only solution to prevent CSRF. We also need to check user permissions before executing a certain action.

CSRF protection on your forms

Some form fields here In the above form the function wp_nonce_field creates a hidden field with some nonce string.

Below code goes on your submit form action/page

On the submit page the nonce value in the hidden field is validated using the function wp_verify_nonce then only the form gets processed.

CSRF protection on your AJAX calls

Prevent wordpress csrf  attack by protecting your Ajax calls too. jQuery calling an unprotected PHP page can have severe security implications.

Here is how we can apply CSRF protection on Ajax calls

Below code goes on your PHP page

check_ajax_referrer verifies the AJAX request to prevent processing external (malicious) requests.