• Hi there,
    I am trying to make my site more secure from XXS, and one way to do this is to add nonces to any inline Javascript.
    I came across this PHP snippet to be added to the functions.php on stackoverflow:

    add_action( 'run_custom_nonce_value', 'custom_nonce_value' );
    function custom_nonce_value () {
    
        $created_nonce = wp_create_nonce();
        define( 'NONCE_RANDVALUE', $created_nonce ); 
    
    }
    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;
    }

    Is there any way to apply this to all JS that is loaded inline, including any plugin you use?
    thx for any help on this.

    The page I need help with: [log in to see the link]

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    A variable declared in JS in the global scope is available to any other script. You can assign a value from PHP to such a variable with wp_localize_script()

    That said, simply providing a nonce does not enhance security by itself. It needs to be validated server side for it to have any meaning. If the app is not coded to do this already, supplying a nonce value isn’t going to help. Additionally, when a nonce is created in PHP, it is “seeded” with a value unique to the app. Its nonce is not usable by other apps which would use different seeds, so the concept of a global nonce for all JS is flawed and unworkable.

    If an app is vulnerable to XSS, short of rewriting it yourself, there’s little you can do to resolve the problem other than stop using the app.

    Thread Starter haddlyapis

    (@haddlyapis)

    Thx for you response. I have now understood nonces a little further myself and you are right, alone it does nothing but provide a “number only once”.
    Is there any way (and i say this naively), to get an “if” clause added to scripts, so that: if (JS is inline && site_uses_nonces_to_validate_inline_files_from_XXS()) { then get_nonce_and_add_it_to_inline_script(). }
    Whereby the site generates the e.g. meta data:
    Content-Security-Policy: default-src 'self'; script-src 'nonce-123456789'
    and then each inline script from any plugin gets added:
    <script type="text/javascript" 'nonce-123456789'>
    So to speak…..
    Then encourage developers to add this clause to their scripts embedded in .PHP files.
    (i hope this makes some sense to someone…).

    • This reply was modified 4 years, 3 months ago by haddlyapis.
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘add nonces to all inline JS for plugins’ is closed to new replies.