Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Difference between revisions of "WordPress Nonces"

m (added link to Japanese translation)
(Migrated to DevHub)
 
(27 intermediate revisions by 15 users not shown)
Line 1: Line 1:
  +
Migrated to https://developer.wordpress.org/apis/security/nonces/
  +
  +
<!--
 
{{Languages|
 
{{Languages|
 
{{en|WordPress Nonces}}
 
{{en|WordPress Nonces}}
 
{{fr|Les Nonces WordPress}}
 
{{fr|Les Nonces WordPress}}
{{ja|WordPress Nonces}}
+
{{ja|WordPress Nonce}}
 
}}
 
}}
   
  +
A ''[[Glossary#Nonce|nonce]]'' is a "number used once" to help protect URLs and forms from certain types of misuse, malicious or otherwise. WordPress nonces aren't numbers but are a hash made up of numbers and letters. Nor are they used only once, but have a limited "lifetime" after which they expire. During that time period, the same nonce will be generated for a given user in a given context. The nonce for that action will remain the same for that user until that nonce life cycle has completed.
''This article should deal with the WordPress implementation of nonces in the future. Meanwhile, you can visit WordPress Glossary for a [[Glossary#Nonce|general description of nonces]]; see the [[#Related|Related]] section which contains [[Plugin_API|WordPress Plugin API]] functions, action and filter [[Glossary#Hook|hooks]] for handling nonces; or check the links in the [[#Resources|Resources]] section which temporarily substitutes this article''
 
  +
  +
WordPress's security tokens are called "nonces" (despite the above-noted differences from true nonces) because they serve much the same purpose as nonces do. They help protect against several types of attacks including CSRF, but do not protect against replay attacks because they aren't checked for one-time use. Nonces should never be relied on for authentication, authorization, or access control. Protect your functions using [[Function Reference/current_user_can|<tt>current_user_can()</tt>]], and always assume nonces can be compromised.
  +
  +
== Why use a nonce? ==
  +
  +
For an example of why a nonce is used, consider that an admin screen might generate a URL like this that trashes post number 123.
  +
  +
<nowiki>http://example.com/wp-admin/post.php?post=123&action=trash</nowiki>
  +
  +
When you go to that URL, WordPress will validate your authentication cookie information and if you're allowed to delete that post will proceed to delete it. What an attacker can do with this is make your browser go to that URL without your knowledge. For example, the attacker could craft a disguised link on a 3rd party page like this:
  +
  +
<nowiki><img src="http://example.com/wp-admin/post.php?post=123&action=trash" /></nowiki>
  +
  +
This would trigger your browser to make a request to WordPress, and the browser would automatically attach your authentication cookie and WordPress would consider this a valid request.
  +
  +
Adding a nonce would prevent this. For example, when using a nonce, the URLs that WordPress generate for the user look like this:
  +
  +
<nowiki>http://example.com/wp-admin/post.php?post=123&action=trash&_wpnonce=b192fc4204</nowiki>
  +
  +
If anyone attempts to trash post number 123 without having the correct nonce generated by WordPress and given to the user, WordPress will send a "403 Forbidden" response to the browser, with the error message: "Are you sure you want to do this?"
  +
  +
== Creating a nonce ==
  +
  +
You can create a nonce and add it to the query string in a URL, you can add it in a hidden field in a form, or you can use it some other way.
  +
  +
For nonces that are to be used in AJAX requests, it is common to add the nonce to a hidden field, from which JavaScript code can fetch it.
  +
  +
Note that the nonces are unique to the current user's session, so if a user logs in or out asynchronously any nonces on the page will no longer be valid.
  +
  +
=== Adding a nonce to a URL ===
  +
  +
To add a nonce to a URL, call [[Function_Reference/wp_nonce_url|wp_nonce_url()]] specifying the bare URL and a string representing the action. For example:
  +
  +
$complete_url = wp_nonce_url( $bare_url, 'trash-post_'.$post->ID );
  +
  +
For maximum protection, ensure that the string representing the action is as specific as possible.
  +
  +
By default, wp_nonce_url() adds a field named <code>_wpnonce</code>. You can specify a different name in the function call. For example:
  +
  +
$complete_url = wp_nonce_url( $bare_url, 'trash-post_'.$post->ID, 'my_nonce' );
  +
  +
=== Adding a nonce to a form ===
  +
  +
To add a nonce to a form, call [[Function_Reference/wp_nonce_field|wp_nonce_field()]] specifying a string representing the action. By default wp_nonce_field() generates two hidden fields, one whose value is the nonce and one whose value is the current URL (the referrer), and it echoes the result. For example, this call:
  +
  +
wp_nonce_field( 'delete-comment_'.$comment_id );
  +
  +
might echo something like:
  +
  +
<input type="hidden" id="_wpnonce" name="_wpnonce" value="796c7766b1" />
  +
<input type="hidden" name="_wp_http_referer" value="/wp-admin/edit-comments.php" />
  +
  +
For maximum protection, ensure that the string representing the action is as specific as possible.
  +
  +
You can specify a different name for the nonce field, you can specify that you do not want a referrer field, and you can specify that you want the result to be returned and not echoed. For details of the syntax, see: [[Function_Reference/wp_nonce_field|wp_nonce_field()]]
  +
  +
=== Creating a nonce for use in some other way ===
  +
  +
To create a nonce for use in some other way, call [[Function_Reference/wp_create_nonce|wp_create_nonce()]] specifying a string representing the action. For example:
  +
  +
$nonce = wp_create_nonce( 'my-action_'.$post->ID );
  +
  +
This simply returns the nonce itself. For example: <code>295a686963</code>
  +
  +
For maximum protection, ensure that the string representing the action is as specific as possible.
  +
  +
== Verifying a nonce ==
  +
  +
You can verify a nonce that was passed in a URL, a form in an admin screen, an AJAX request, or in some other context.
  +
  +
=== Verifying a nonce passed from an admin screen ===
  +
  +
To verify a nonce that was passed in a URL or a form in an admin screen, call [[Function_Reference/check_admin_referer|check_admin_referer()]] specifying the string representing the action. For example:
  +
  +
check_admin_referer( 'delete-comment_'.$comment_id );
  +
  +
This call checks the nonce and the referrer, and if the check fails it takes the normal action (terminating script execution with a "403 Forbidden" response and an error message).
  +
  +
If you did not use the default field name (<code>_wpnonce</code>) when you created the nonce, specify the field name. For example:
  +
  +
check_admin_referer( 'delete-comment_'.$comment_id, 'my_nonce' );
  +
  +
=== Verifying a nonce passed in an AJAX request ===
  +
  +
To verify a nonce that was passed in an AJAX request, call [[Function_Reference/check_ajax_referer|check_ajax_referer()]] specifying the string representing the action. For example:
  +
  +
check_ajax_referer( 'process-comment' );
  +
  +
This call checks the nonce (but not the referrer), and if the check fails then by default it terminates script execution.
  +
  +
If you did not use one of the default field names (<code>_wpnonce</code> or <code>_ajax_nonce</code>) when you created the nonce, or if you want to take some other action instead of terminating execution, you can specify additional parameters. For details, see: [[Function_Reference/check_ajax_referer|check_ajax_referer()]]
  +
  +
=== Verifying a nonce passed in some other context ===
  +
  +
To verify a nonce passed in some other context, call [[Function_Reference/wp_verify_nonce|wp_verify_nonce()]] specifying the nonce and the string representing the action. For example:
  +
  +
wp_verify_nonce( $_REQUEST['my_nonce'], 'process-comment'.$comment_id );
  +
  +
If the result is false, do not continue processing the request. Instead, take some appropriate action. The usual action is to call [[Function_Reference/wp_nonce_ays|wp_nonce_ays()]], which sends a "403 Forbidden" response to the browser with the error message: "Are you sure you want to do this?".
  +
  +
== Modifying the nonce system ==
  +
  +
You can modify the nonce system by adding various [[Plugin_API#Actions|actions]] and [[Plugin_API#Filters|filters]].
  +
  +
=== Modifying the nonce lifetime ===
  +
  +
By default, a nonce has a lifetime of one day. After that, the nonce is no longer valid even if it matches the action string. To change the lifetime, add a <code>nonce_life</code> filter specifying the lifetime in seconds. For example, to change the lifetime to four hours:
  +
  +
add_filter( 'nonce_life', function () { return 4 * HOUR_IN_SECONDS; } );
  +
  +
Note that just as a WordPress nonce is not "a number used once", nonce lifetime isn't really nonce lifetime. WordPress uses a system with two ticks (half of the lifetime) and validates nonces from the current tick and the last tick. In default settings (24h lifetime) this means that the time information in the nonce is related to how many 12h periods of time have passed since the Unix epoch. This means that a nonce made between midday and midnight will have a lifetime until midday the next day. The actual lifetime is thus variable between 12 and 24 hours. The example above will give you nonces that are valid for 2-4 hours.
  +
  +
=== Performing additional verification ===
  +
  +
To perform additional verification when check_admin_referrer() has found that the nonce and the referrer are valid, add a <code>check_admin_referer</code> action. For example:
  +
  +
function my_additional_check ( $action, $result ) { ... }
  +
add_action( 'check_admin_referer', 'my_additional_check', 10, 2 );
  +
  +
For check_ajax_referer() add a <code>check_ajax_referer</code> action in the same way.
  +
  +
=== Changing the error message ===
  +
  +
You can change the error message sent when a nonce is not valid, by using the translation system. For example:
  +
  +
function my_nonce_message ($translation) {
  +
if ($translation === 'Are you sure you want to do this?') {
  +
return 'No! No! No!';
  +
}
  +
  +
return $translation;
  +
}
  +
  +
add_filter('gettext', 'my_nonce_message');
  +
  +
== Additional information ==
  +
  +
This section contains additional information about the nonce system in WordPress that might occasionally be useful.
  +
  +
=== Nonce lifetime ===
  +
  +
The lifetime of a nonce is divided into two ''ticks''. When a nonce is valid, the functions that validate nonces return the current tick number, 1 or 2. You could use this information, for example, to refresh nonces that are in their second tick so that they do not expire.
  +
  +
=== Nonce security ===
  +
  +
Nonces are generated using a key and salt that are unique to your site if you have installed WordPress correctly. NONCE_KEY and NONCE_SALT are defined in your [[Editing_wp-config.php|wp-config.php]] file, and the file contains comments that provide more information.
  +
  +
Nonces should never be relied on for authentication or authorization, access control. Protect your functions using [[Function Reference/current_user_can|<tt>current_user_can()</tt>]], always assume Nonces can be compromised.
  +
  +
== Replacing the nonce system ==
  +
  +
Some of the functions that make up the nonce system are [[Pluggable_Functions|pluggable]] so that you can replace them by supplying your own functions.
  +
  +
To change the way admin requests or AJAX requests are verified, you can replace check_admin_referrer() or check_ajax_referrer(), or both.
  +
  +
To replace the nonce system with some other nonce system, you can replace wp_create_nonce(), wp_verify_nonce() and wp_nonce_tick().
   
 
== Related ==
 
== Related ==
Line 17: Line 176:
 
== Resources ==
 
== Resources ==
 
* [http://markjaquith.wordpress.com/2006/06/02/wordpress-203-nonces/ WordPress 2.0.3: Nonces | Mark on WordPress]
 
* [http://markjaquith.wordpress.com/2006/06/02/wordpress-203-nonces/ WordPress 2.0.3: Nonces | Mark on WordPress]
* [http://www.prelovac.com/vladimir/improving-security-in-wordpress-plugins-using-nonces Improving security in Wordpress plugins using Nonces | Prelovac.com]
+
* [http://www.prelovac.com/vladimir/improving-security-in-wordpress-plugins-using-nonces Improving security in WordPress plugins using Nonces | Prelovac.com]
 
* [[Wikipedia:Cryptographic_nonce|Cryptographic nonce - Wikipedia, the free encyclopedia]]
 
* [[Wikipedia:Cryptographic_nonce|Cryptographic nonce - Wikipedia, the free encyclopedia]]
 
* [[Wikipedia:Cross-site_request_forgery|Cross-site request forgery - Wikipedia, the free encyclopedia]]
 
* [[Wikipedia:Cross-site_request_forgery|Cross-site request forgery - Wikipedia, the free encyclopedia]]
  +
*[http://www.wp-entwickler.at/wordpress-sicherheit-bei-formulareingaben-und-ajax-aufrufen-verwendet-nonces/ Einführung zu Nonces und deren Verwendung] '''Artikel auf Deutsch'''
  +
*[https://codeseekah.com/2016/01/21/wordpress-nonces-vulnerabilities/ WordPress Nonce Vulnerabilities | codeseekah.com]
  +
*[https://www.bynicolas.com/code/wordpress-nonce/ How do WordPress nonces really work]
   
   
 
[[Category:Advanced_Topics]]
 
[[Category:Advanced_Topics]]
 
[[Category:Functions]]
 
[[Category:Functions]]
  +
-->
 
{{Stub}}
 

Latest revision as of 17:17, 6 December 2022

Migrated to https://developer.wordpress.org/apis/security/nonces/