Contact Form 7 and CSP / Content Security Policy
-
Hi,
first of all let me thank you for your great plugin which really is a huge help for us on many websites! ??For security reasons, we are forced to use a strict CSP (content security policy) on a new website where “unsafe-inline” or “unsafe-eval” is no longer possible/allowed. (Just to mention it, not allowing unsafe inline code execution is very reasonable and will probably be introduced by more and more websites and hosters).
Unfortunately, CF7 together with the reCaptcha addon are creating inline code, which causes a lot of console errors (due to the CSP settings) and therefore also leads to the reCaptcha not being displayed and the form not working.
We already saw this ticket: https://www.ads-software.com/support/topic/csp-and-unsafe-inline/ but unfortunately there doesn’t seem to be a solution yet.
We are creating a nonce to be used together with the CSP rule, so that’s what our CSP rule for script-src looks like:
script-src 'self' 'nonce-" . $_SESSION['script-nonce'] . "'
For all scripts that are embedded by WordPress, we add this nonce in functions.php to make them work, which works just fine:
add_filter( 'script_loader_tag', 'add_nonce_to_script', 10, 3 ); function add_nonce_to_script( $tag, $handle, $source ) { $search = "type='text/javascript'"; $replace = "type='text/javascript' nonce='".$_SESSION['script-nonce']."' "; $subject = $tag; $output = str_replace($search, $replace, $subject); return $output; }
This way, for example also your plugin’s script is being loaded using the nonce and therefore being validated:
<script nonce='ot353ENqk7DMURbcOQIseNdynRQWckKbBYsO6qN2/1E=' src='https://OURDOMAIN/wp-content/plugins/contact-form-7/includes/js/scripts.js'></script>
The only issue we are having is with the inline <script> tags generated by your plugin and/or the reCaptcha addon. So stuff like that:
<script >var wpcf7 = {"apiSettings":{"root":"https:\/\/OURDOMAIN\/wp-json\/contact-form-7\/v1","namespace":"contact-form-7\/v1"}};</script>
In my opinion, it would be very easy to get this to work as well if we could apply a similar filter so we could add the nonce to the inline <script> tags as well, so the filtered output should be something like that:
<script nonce='ot353ENqk7DMURbcOQIseNdynRQWckKbBYsO6qN2/1E='>var wpcf7 = {"apiSettings":{"root":"https:\/\/OURDOMAIN\/wp-json\/contact-form-7\/v1","namespace":"contact-form-7\/v1"}};</script>
Is there any filter existing that we could use for this, or would it be possible for you to add such a filter to your plugin? This would be a great help and I’m pretty sure we wouldn’t be the only ones to benefit from this.
Thank you very much in advance!
- The topic ‘Contact Form 7 and CSP / Content Security Policy’ is closed to new replies.