How do wordpress nonces work?

I am trying to understand how wordpress nonces work in terms of security. nonce is for a number used once, but according to wordpress, it can be valid up to 24 hours, which makes no sense, it could be used 9999 times during this period (from same client).

I thought that a wordpress nonce is really a number used once and that a nonce is valid only for one-time usage, but that's not the case. I guess for a better security, a one-time usage number would be better, e.g. you have a commenting system and someone clicks on "reply" two times. Instead of inserting the comment two times, it is being inserted one time, because of the one-time valid nonce (same one) given in the two requests.

Am I getting something wrong? What is the purpose of those wordpress nonces?

Upvotes: 1

Views: 356

Answers (3)

Md. Ziyed Uddin
Md. Ziyed Uddin

Reputation: 212

Nonce can protect several types of attacks including CSRF, but do not provide protection against replay attacks because they are not checked for one time use. That is why for authentication, authorization or any access control purpose we should not rely on nonce.

We can minimize nonce lifetime to any lower hour by adding filter to nonce_life hook

 add_filter( 'nonce_life', function () { return 4 * HOUR_IN_SECONDS; } );

The example above will give you nonces that are valid for 2-4 hours.

As Wordpress nonce are not providing one time use, for better protection we can add role permission checking after the nonce verification

 if( current_user_can( 'edit_posts' ) ){
     // Write you action code here after verifying the actual user permission
 }

Upvotes: 0

Artem
Artem

Reputation: 765

You are right WordPress nonce is not an actual nonce. It can be used multiple times during a period of time while nonce is valid (12-24 hours) check nonce tick function. The main reason why you need to use nonce is to prevent CSRF (Cross Site Request Forgery) and malicious scripts.

But in all other security cases, you shouldn't rely on WP nonce. Use current_user_can() to actually check what current user can and cannot do on your website. Check docs

Upvotes: 1

Haris
Haris

Reputation: 545

You are getting it kind of wrong. Although it is true that nonce is valid up to 24 hours, after which it will expire and a new one will be generated, a nonce can be only used once.

Hence the name nonce - number only used once.

Here is a website which will be able to help you more about understading the whole thing behind nonces - https://codex.wordpress.org/WordPress_Nonces

Upvotes: 0

Related Questions