Make WordPress Core

Opened 10 months ago

#58636 new enhancement

Automatic Sanitization of Nonces in wp_verify_nonce

Reported by: lucasbustamante's profile lucasbustamante Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Security Keywords:
Focuses: coding-standards Cc:

Description

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
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.

Change History (0)

Note: See TracTickets for help on using tickets.