I have tried every possible solution I can think of to generate a nonce and pass it to the CSP and all inline scripts with the nonce variable. I have read many articles and they all are very vague on how to do this. I have successfully generated the nonce and it is generating a unique hex string on page load. However, I can't seem to figure out how to pass that generated nonce to the CSP or the script tags effectively. This is what it looks like in the routes.js file:
router.route('/')
.all(checkAuthentication)
.get( (req, res, next) => {
cspNonce = crypto.randomBytes(16).toString('hex');
next();
console.log("Nonce is" + cspNonce);
// PREVENT PAGE CACHING
res.setHeader('Cache-Control', 'private, max-age=0, no-cache, no-store, must-revalidate');
res.setHeader('Expires', '-1');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Vary', '*');
res.setHeader('Strict-Transport-Security', "max-age=31536000; includeSubDomains; preload");
res.setHeader('X-Content-Type-Options', "nosniff");
res.setHeader("Content-Security-Policy", "script-src 'nonce-${cspNonce}' http://localhost:* https://code.jquery.com/jquery-2.1.4.js https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js https://www.google-analytics.com/analytics.js https://www.googletagmanager.com https://vimeo.com https://player.vimeo.com/api/player.js https://use.fontawesome.com/0202fc905b.js https://cdn.fontawesome.com/js/stats.js https://use.fontawesome.com/webfontloader/1.6.24/webfontloader.js https://code.jquery.com/jquery-latest.min.js https://code.jquery.com/jquery-latest.min.js https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.0/TweenMax.min.js https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.0/TimelineMax.min.js https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/ScrollMagic.min.js https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/plugins/animation.gsap.js https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.5/plugins/jquery.ScrollMagic.js img-src: https://www.googletagmanager.com");
res.render('survey_views/survey_container', {host_mode: process.env.HOST_MODE});
})
Also, when I try to console log the ‘cspNonce’ variable elsewhere in the app it is showing up undefined. I am calling this nonce above in Router.js and I need to call it in head.ejs file which is a few levels up in the structure.
I need to figure out how to get this generated nonce to pass into the CSP and be able to call it in other files where I am trying to have inline-scripts run. If anyone has any insight on what might be going wrong here, it would be very helpful.
Thanks in advance.
I write it to res.locals (res.locals.cspNonce in my case) and both the CSP function and the script renderer reads it from there.
I would also suggest to replace hex with base64 as it is more compact.