#StackBounty: #php #plugin-development #functions #headers #nonce Reliable way to add nonce to HTTP Header in WordPress?

Bounty: 50

I am trying to implement CSP on my wordpress site.

Inspired by this question, https://stackoverflow.com/questions/50002041/adding-nonce-to-script-tag I tried to build a way to add nonces to my wordpress site.

add_action( 'run_custom_nonce_value', 'custom_nonce_value' );
function custom_nonce_value () {
    $created_nonce = wp_create_nonce();
    define( 'NONCE_RANDVALUE', $created_nonce ); 
}

This function was directly taken from the Stackoverflow link mentioned above.

It created Nonce Values using wp_create_nonce()

The major problem is that it creates a nonce but doesn’t update it. Refreshing my wordpress site still shows the same nonce.

could global $variable be better option instead of define?

Anyways, after that the below code is slightly modified and adds the nonce to headers using WP actions and adds nonce to all scripts that are registered.

add_filter( 'script_loader_tag', 'add_nonce_to_script', 10, 3 );
function add_nonce_to_script( $tag, $handle, $source ) {
    custom_nonce_value();
    $val_nonce = NONCE_RANDVALUE;
    $search = "type='text/javascript'";
    $replace = "type='text/javascript' nonce='".$val_nonce."' ";
    $subject = $tag;

    $output = str_replace($search, $replace, $subject);
    return $output;
}

function pagely_security_headers($headers) {
    custom_nonce_value();
    $val_nonce = NONCE_RANDVALUE;
    $headers['X-Content-Security-Policy'] = "default-src 'self'; script-src unsafe-hashes 'self' https://milyin.com 'nonce-" . $val_nonce . "' https:; object-src 'none';base-uri 'none';img-src https: data:;style-src 'self' 'unsafe-inline' https:;report-uri https://milyin.com/?csp=true";
    return $headers;

}
add_filter( 'wp_headers', 'pagely_security_headers' );


So, we need to solve 2 things.

1.) It does not update the value of nonce, refreshing page and opening new tab still use the same value of nonce, diluting the entire purpose of nonces.

2.) A better way to echo the nonce elsewhere as I want inline scripts not registered in WordPress to also have the nonce.

Also, I read CSP requires base64 nonces, are these nonces base64?


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.