[wp-trac] [WordPress Trac] #58636: Automatic Sanitization of Nonces in wp_verify_nonce

WordPress Trac noreply at wordpress.org
Mon Jun 26 21:28:18 UTC 2023


#58636: Automatic Sanitization of Nonces in wp_verify_nonce
------------------------------+-----------------------------
 Reporter:  lucasbustamante   |      Owner:  (none)
     Type:  enhancement       |     Status:  new
 Priority:  normal            |  Milestone:  Awaiting Review
Component:  Security          |    Version:
 Severity:  normal            |   Keywords:
  Focuses:  coding-standards  |
------------------------------+-----------------------------
 There's a [in-depth discussion](https://github.com/WordPress/WordPress-
 Coding-Standards/issues/869) in the WordPress Coding Standards repository
 over the question of whether nonces should be sanitized prior to being
 passed to `wp_verify_nonce()`.

 At present, developers are required to sanitize the input themselves
 before it's passed to `wp_verify_nonce`. This practice is mandates by the
 PHPCS WordPress Coding Standard:

 {{{
 #!php
 <?php
 if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['my-
 nonce'] ), 'my-action' ) ) ) {
   return;
 }
 }}}

 ''Please note: There's a concurrent discussion on the necessity of
 `wp_unslash` when reading from superglobals such as $_POST and $_GET over
 [here](https://core.trac.wordpress.org/ticket/18322#comment:53).''

 Given that WordPress generates nonces composed of hexadecimal digits, it
 should be feasible to sanitize the nonce before use:

 `$nonce = preg_replace( '/[^a-f0-9]/i', '', $nonce );`

 This level of automation would be highly convenient for developers, much
 in the same vein as the `$wpdb->insert` function is advantageous due to
 its automatic data preparation.

 However, this solution does raise a potential issue with pluggable nonces.
 If a nonce created by `wp_create_nonce` employs characters outside of the
 standard range and if `wp_verify_nonce` is not also plugged to accommodate
 these special characters, this implementation could potentially break.

 We must also assume that a plugged `wp_verify_nonce` should sanitize the
 nonce it receives.

 While there are some concerns associated with sanitizing nonces, the
 benefits largely outweigh the risks. These benefits include improved
 development experience, and stronger security, especially given the fact
 that many WordPress developers do not utilize PHPCS with WordPress Core
 Security Rules in their codebase, and may therefore be unaware of the need
 for nonce sanitization. This presents an opportunity to build a safer and
 more developer-friendly environment.

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/58636>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list