[wp-trac] [WordPress Trac] #39941: Allow using Content-Security-Policy without unsafe-inline

WordPress Trac noreply at wordpress.org
Wed Apr 24 23:35:47 UTC 2024


#39941: Allow using Content-Security-Policy without unsafe-inline
-------------------------------------------------+-------------------------
 Reporter:  tomdxw                               |       Owner:
                                                 |  adamsilverstein
     Type:  enhancement                          |      Status:  closed
 Priority:  normal                               |   Milestone:  5.7
Component:  Security                             |     Version:  4.8
 Severity:  normal                               |  Resolution:  fixed
 Keywords:  has-patch has-unit-tests commit      |     Focuses:  javascript
  has-dev-note                                   |
-------------------------------------------------+-------------------------

Comment (by amanandhishoe):

 So inside the loop where I create hashes for inline scripts, check if each
 inline script is malicious or not and only create hashes for those which
 are not. Something like this:


 {{{
 $page_html = preg_replace_callback(
         '#<script.*?>(.*?)<\/script>#s',
         function ( $matches ) use ( &$hashes_a ) {
                 $script_content = $matches[1]; // Extract the content
 between the script tags.

                 // Only create hashes for scripts that are not malicious.
                 if ( !is_script_malicious( $script_content ) ){
                         // phpcs:ignore
                         $hash       = base64_encode( hash( 'sha256',
 $script_content, true ) ); // Compute the SHA-256 hash and encode it in
 Base64.
                         $hashes_a[] = "'sha256-" . $hash . "'"; // Add the
 hash to the list with the 'sha256-' prefix.
                 }
                 return $matches[0]; // Return the original script tag
 unmodified.
         },
         $page_html
 );
 }}}


 Then the trick is what to include in the is_script_malicious() function to
 determine if a script is malicious or not. Maybe something like this?

 {{{
 $dangerous_functions = ['eval(', 'base64_decode(', 'exec(', 'system('];

 // Check for dangerous functions in the script content.
 foreach ($dangerous_functions as $function) {
         if (strpos($script_content, $function) !== false) {
                 return true; // Malicious script detected
         }
 }
 }}}

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/39941#comment:119>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list