Cross site request forgery Concept
The CSRF vulnerability is the most famous web vulnerability, since … I don’t remember, too long! Yesterday I fixed this vulnerability in my WordPress plugins and would like to share the same knowledge to other developers.
Lets 1st discuss what is CSRF?
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.
In a nutshell: Every request that change state on server should have CSRF protection.
What is nonce?
Using a nonce (Number used ONCE) is the best way to protect your plugin against a cross-site request forgery (CSRF) hacker-attack. Nonces are used on requests (saving options in admin, Ajax requests, performing an action etc) and prevent unauthorized access by providing a secret ‘key’ and checking it each time the code is used.
According to http://codex.wordpress.org/Function_Reference/wp_nonce_field, the nonce field is used to validate
that the contents of the form came from the location on the current site and not somewhere else. For the maximum security, the nonce is also time sensitive and it’ll expire.
other must read:
https://crunchify.com/secure-your-wordpress-blog/
Nonces work in the following way:
- First you generate a nonce with a unique identifier
- You pass the nonce along other query data (link or form) to you script
- You verify the nonce before doing anything else
Details:
Step-1
First create nonce using wp_create_nonce
function and pass it along with your request.
<input name="my_aiowz_update_setting" type="hidden" value="<?php echo wp_create_nonce('aiowz-update-setting'); ?>" />
Step-2
Snippet screenshot from my plugin:
Step-3
Verify nonce using wp_verify_nonce
function.
if (!isset($_POST['my_aiowz_update_setting'])) die("<br><br>Hmm .. looks like you didn't send any credentials.. No CSRF for you! "); if (!wp_verify_nonce($_POST['my_aiowz_update_setting'],'aiowz-update-setting')) die("<br><br>Hmm .. looks like you didn't send any credentials.. No CSRF for you! ");
Snippet screenshot from my plugin:
And that’s all! If you have more ideas, please don’t hesitate to share with us!