helmetjs / csp Goto Github PK
View Code? Open in Web Editor NEWThe source for this module has moved to the Helmet repository.
Home Page: https://github.com/helmetjs/helmet/
License: MIT License
The source for this module has moved to the Helmet repository.
Home Page: https://github.com/helmetjs/helmet/
License: MIT License
Chrome 40 introduces support for CSP level 2: https://w3c.github.io/webappsec/specs/content-security-policy/#changes-from-level-1
We'll do this after helmet-crossdomain has been in the wild for awhile. We'll likely change a few things here and there before we're ready to publish the rest of the middlewares.
Hi,
Thank you for this wonderful project.
I got one problem that I can't figure out. External links (<a href="http://google.com target="_blank">Google</a>
) doesn't work with Chrome and Safari, but works on Firefox. What have I done wrong in my config?
app.use(helmet.contentSecurityPolicy({
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
sandbox: ['allow-forms', 'allow-scripts', 'allow-same-origin'],
// reportUri: '/report-violation',
reportOnly: false, // set to true if you only want to report errors
setAllHeaders: false, // set to true if you want to set all headers
disableAndroid: false, // set to true if you want to disable Android (browsers can vary and be buggy)
safari5: false // set to true if you want to force buggy CSP in Safari 5
}));
See https://www.w3.org/TR/mixed-content/.
This might also require a change in the DefinitelyTyped TypeScript definition files for Helmet. This isn't technically part of this module but is probably easy to fix and worth doing.
This should be invalid:
csp({
directives: {
'script-src': ['example.com'],
scriptSrc: ['example.com']
}
})
This is a breaking change, so we'll need to do it in Helmet 4.
Not sure what's your policy is, but manifest-src
is in Editor's Draft stage and browsers already implement it.
I don't mind setting loose: true
, just wanted to bring this up.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/manifest-src
The transformDirectivesForBrowser
method accesses browser.name
which in turn is read from the user-agent
request header. If that header is missing (as it was in my end-to-end tests), CSP crashes with TypeError: Cannot read property 'name' of undefined
.
Using this directive only the self rule gets applied and inline styles still get caught by the browser.
styleSrc: ["'self'", "'unsafe-inline'"],
I want to protect the resources of non-response by the CSP 403
see https://w3c.github.io/webappsec/specs/content-security-policy/#csp-request-header
I know it posts. I have it setup as follows:
reportUri: '/csp',
handle it:
// Report csp violations
app.post('/csp', bodyParser.json(), bodyParser.urlencoded({ extended: false }), function (req, res) {
// Just log it to see if this is working
if (req.body) {
debug('CSP Violation: ' + JSON.stringify(req.body));
debug('CSP Violation: ' + req.body);
} else {
debug('CSP: testing only!');
}
res.end();
});
my:app CSP: {} +4s
my:app CSP: [object Object] +0ms
I can't figure out why I can't get some type of message or route from the post. Help?
Thanks!
EDIT: I have tried both:
When using a service worker, CSP currently can not be configured without using the loose
-option.
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/worker-src
This module is reading the config.json
file without its extension, which means in some module bundlers it will break.
Since this is a widely used module, I feel we should be explicit about requiring a file that's not JavaScript, to avoid any bundling errors.
This means changing the require for the config to require('./lib/config.json')
.
Thoughts?
it's in csp2 and mozilla's observer is using it to judge the security of sites
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/base-uri
Instead of:
assert(foo === undefined);
Do:
assert.equal(foo, undefined);
I have some content that's dynamic (server-side values that are unique per request, like geoIP's country code). I am currently using unsafe-inline
in helmet, but how can I specify a per-request nonce or hash?
All the docs I've read on helmet so far use a static policy, which won't work with nonce's and won't for hashes of dynamic content.
Hi added the CSP Module on my ExpressJS application and a security scan found this:
I do not know, it depends on csp ?
This page contains an error/warning message that may disclose sensitive information.The message can also contain the location of the file that produced the unhandled exception.
Output:
HTTP Header input Host was set to 12345'"\'\");|]*%00{%0d%0a<%00>%bf%27'💩
Pattern found: Internal Server Error
------------------------------------------
JSON input csp-report.blocked-uri was set to
12345'"\'\");|]*%00{%0d%0a<%00>%bf%27'💩
Pattern found: SyntaxError: Unexpected token
/report-violation
------------------------------------------
JSON input csp-report.document-uri was set to
12345'"\'\");|]*%00{%0d%0a<%00>%bf%27'💩
Pattern found: SyntaxError: Unexpected token
/report-violation
------------------------------------------
JSON input csp-report.original-policy was set to
12345'"\'\");|]*%00{%0d%0a<%00>%bf%27'💩
Pattern found: SyntaxError: Unexpected token
/report-violation
------------------------------------------
JSON input csp-report.referrer was set to
12345'"\'\");|]*%00{%0d%0a<%00>%bf%27'💩
Pattern found: SyntaxError: Unexpected token
/report-violation
------------------------------------------
JSON input csp-report.violated-directive was set to
12345'"\'\");|]*%00{%0d%0a<%00>%bf%27'💩
Pattern found: SyntaxError: Unexpected token
/report-violation
------------------------------------------
JSON input csp-report.line-number was set to
12345'"\'\");|]*%00{%0d%0a<%00>%bf%27'💩
Pattern found: SyntaxError: Unexpected token
/report-violation
------------------------------------------
JSON input csp-report.source-file was set to
12345'"\'\");|]*%00{%0d%0a<%00>%bf%27'💩
Pattern found: SyntaxError: Unexpected token
/report-violation
This is useful in an upcoming branch (see other issues); not needed now.
Following helmetjs/helmet#82, I created a simple app to easily reproduce the problem : https://github.com/jsebfranck/helmet-csp-example. It is a simple express app with an html view where I try to use a Javascript alert.
Without helmet-csp, it works fine on my device (Samsung Galaxy Tab 2, native Android Browser 4.0). But as soon as I add scriptSrc to self, it doesn't work anymore.
Hello. I read from Gitter that it'd be better if I opened up an issue on Github, so here I go.
The way I've set up helmet/csp currently:
import csp from 'helmet-csp';
app.use(csp({
directives: {
defaultSrc: [`'self'`],
scriptSrc: [`'self'`, `'unsafe-inline'`, `*.google-analytics.com/`],
styleSrc: [`'self'`, `'unsafe-inline'`],
frameSrc: [`'self'`, `*.youtube.com/`, `*.vimeo.com/`],
childSrc: [`'self'`, `*.youtube.com/`, `*.vimeo.com/`],
objectSrc: [`'self'`, `*.youtube.com/`, `*.vimeo.com/`],
imgSrc: [`*.amazonaws.com`, `data:`, `'self'`],
connectSrc: [`'self'`],
upgradeInsecureRequests: true
}
}));
And then the errors I get with it lead me to believe most of these directives haven't registered properly:
Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-S87yxoMcr9T7U+ZcUvvvkw7U6Ja2xsYbceNLyApPIr0='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.
Refused to load the image 'http://localhost:8080/favicon.ico' because it violates the following Content Security Policy directive: "img-src data: amazonaws.com".
Refused to load the script 'https://localhost:8080/dist/build.js' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
it throws an error on console at the moment.
Some like to keep the console less noisy and clean so that any exception csp or otherwise is made obvious.
We found this problem when testing Firefox Accounts with Firefox for Android (Fennec) and Firefox OS.
There are rules in place to convert connectSrc to xhrSrc for Firefox Desktop < 24, but not Firefox OS or Fennec.
Firefox OS 1.x and and Fennec < 25 both require the conversion of connectSrc to xhrSrc.
For ease of reuse, I'd like to define my csp options in a JSON config file and import them in when the application starts, but this is throwing csp violations:
var csp = require('helmet-csp');
app.use(csp({ defaultSrc: config.csp.defaultSrc });
I believe the issue lies in
>var test = { key: ["'value1'", "value1"] };
{ key: [ '\'value1\'', 'value1' ] }
I'm not sure if I'm missing something simple or not, but I can't seem to find away around this.
See helmetjs/helmet#95.
GitHub wrote a great post about CSP which we should link to in the readme.
I noticed that only in iOS Chrome, handler is truthy in the transformDirectivesForBrowser.js while mac, windows, and android returns false.
the truthy handler sets the connectSrc:["'self'"] for iOS Chrome if the directive.connectSrc is falsy or appends "'self'" if the the directives.connectSrc doesn't contain "'self'".
I was hoping that the defaultSrc would be the policy string, however in iOS Chrome, adding explicit connect-src to self is causing the web sockets domains to be ignored.
I understand that I can just add each wss domain manually, however, would this be something to address or is this a non issue?
Thanks!
The upgrade to 3 is breaking our tests because frame-src
is seen as invalid.
Would it be possible to relax this to a warning so that frame-src
continues to work, or only flag it as invalid if a child-src
directive isn't configured? Or another option?
Ideally we don't want to use loose: true
.
We still specific frame-src since child-src
was only implemented in FF45 [1] , we supply both frame-src
and child-src
to provide maximum compatibility.
[1] https://developer.mozilla.org/en-US/Firefox/Releases/45#Security
See https://www.w3.org/TR/CSP/#directive-report-to and https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP#Browser_compatibility.
Originally reported in helmet#156.
I am running an express app with following dependencies:
"dependencies": {
"body-parser": "~1.12.0",
"cookie-parser": "~1.3.4",
"debug": "~2.1.1",
"express": "~4.12.2",
"helmet": "^0.15.0",
"helmet-csp": "^0.3.0",
"jade": "~1.9.2",
"morgan": "~1.5.1",
"serve-favicon": "~2.2.0"
}
Was the example "Handling CSP violations" running on older versions of Express and/or body-parser, because it is not working for me? bodyParser does not recognize application/csp-report
as valid Content-Type for bodyParser.json(). I had to add the following to make it work:
app.use(bodyParser.json({
type: ['json', 'application/csp-report']
}));
Thanks to @oroce for that Gist: https://gist.github.com/oroce/361d1abda643d1b6a95d
We're currently running with setAllHeaders: true
because we'd like to cache the responses, which you can't do if we're dynamically setting headers based on user agent.
Since the nonstandard versions of the CSP header are supported by browsers that are falling out of use, it would be awesome to provide an option to disable dynamic headers completely, and just use the standard one.
Came across https://github.com/3rd-Eden/useragent, which claims to be fast. We should evaluate it and see whether it's good for this module.
up vote
0
down vote
favorite
I meet a surprising problem. If i don't enable my CSP config, no problem, everything works fine. But when I activate CSP, internal links work normally, but external not. On my website, (for example here, https://www.matosmaison.fr/avis/perceuses-visseuses/ryobi-rpd1200k) I have links to amazon, zanox and other similar. These links doesn't work when using CSP.
What is for you my mistake in this config ?
"defaultSrc": [
"'self'",
"www.matosmaison.fr",
"cdn.matosmaison.fr",
"www.google-analytics.com",
"images-na.ssl-images-amazon.com",
"youtube.com",
"www.youtube.com",
"googleads.g.doubleclick.net"
],
"scriptSrc": [
"'self'",
"www.matosmaison.fr",
"cdn.matosmaison.fr",
"www.google-analytics.com",
"images-na.ssl-images-amazon.com",
"youtube.com",
"www.youtube.com",
"googleads.g.doubleclick.net"
],
"styleSrc": [
"'self'",
"www.matosmaison.fr",
"cdn.matosmaison.fr",
"www.google-analytics.com",
"images-na.ssl-images-amazon.com",
"youtube.com",
"www.youtube.com",
"googleads.g.doubleclick.net",
"'unsafe-inline'"
],
"fontSrc": [
"'self'",
"www.matosmaison.fr",
"cdn.matosmaison.fr",
"www.google-analytics.com",
"images-na.ssl-images-amazon.com",
"youtube.com",
"www.youtube.com",
"googleads.g.doubleclick.net",
"'unsafe-inline'"
],
"imgSrc": [
"'self'",
"www.matosmaison.fr",
"cdn.matosmaison.fr",
"www.google-analytics.com",
"images-na.ssl-images-amazon.com",
"youtube.com",
"www.youtube.com",
"googleads.g.doubleclick.net",
"data:"
],
"sandbox": ["allow-forms", "allow-scripts", "allow-same-origin", "allow-top-navigation"],
"reportUri": "/report-violation",
"objectSrc": []
I have tried with adding amazon, zanox and the others but no changes, it doesn't work.
Thanks in advance !
We have a config for production that turns on upgrade-insecure-requests
, however for the development conf (which overrides the prod config) we want to turn off upgrade-insecure-requests
since the local dev is running on http. Unfortunately if the upgrade-insecure-requests
key is there with any falsey value the header is still sent.
Here's a basic test-case:
const csp = require('helmet-csp');
const Express = require('express');
var request = require('supertest');
const app = new Express();
app.use(csp({
directives: {
// header is still sent with undefined / false etc.
upgradeInsecureRequests: undefined,
}
}));
app.use(function (req, res) {
res.end('Hello world!')
})
request(app)
.get('/')
.expect(200)
.expect(function(res) {
console.log(res.headers);
})
.end(function(err, res) {
if (err) throw err;
});
The output is:
{ 'x-powered-by': 'Express',
'content-security-policy': 'upgrade-insecure-requests',
'x-content-security-policy': 'upgrade-insecure-requests',
'x-webkit-csp': 'upgrade-insecure-requests',
date: 'Wed, 11 May 2016 17:27:21 GMT',
connection: 'close',
'content-length': '12' }
I'd expect a falsey value to result in the directive not being included in the CSP headers.
I noticed a bug when using browser sync
and helmet-csp
where I end up having HTTP headers like this one:
I am not sure in which module the error is so I will start here :)
I wrote a minimal test case and instructions to reproduce in a gist.
Hey guys, awesome lib. Love it!
I heavily rely on 'unsafe-inline' and 'unsafe-eval'. For Firefox 4 to 22 you replace those with 'inline-script' and 'eval-script'. I tested that on Firefox 20 for Mac and found out that you must not replace those strings in this version. Only the original ones work in this browser.
It even states:
CSP WARN: Failed to parse unrecognized source 'inline-script'
CSP WARN: Failed to parse unrecognized source 'eval-script'
How did you test which strings to use in which browser? Did you perhaps test Firefox on Windows which behaves differently? A test on all browsers with SauceLabs would be ideal. I could help if you want.
my configuration:
...
workerSrc: [
"'self'",
'data:',
'blob:'
]
...
getting error:
Refused to create a worker from 'blob:https://mydomain.com/xx' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'worker-src' was not explicitly set, so 'default-src' is used as a fallback.
helmet 3.6.0
helmet-csp 2.4.0
Hi, I've encountered a strange issue with reportOnly enabled - over time the headers have multiple "-Report-Only"s appended to the end - to the point where the header name can be thousands of Kb in length (causing other problems). Instead of Content-Security-Policy-Report-Only I'm getting Content-Security-Policy-Report-Only-Report-Only-Report-Only-Report-Only-Report-Only-Report-Only-Report-Only-Report-Only-Report-Only...
Update - this only occurs if shouldBrowserSniff is false, although may also occur if setAllHeaders is enabled
It would be great to know exactly what API changes were made from 0.3 to 1.0.1. I wasn't able to deduce that from a general glance at the API.
Something like this might be cool:
app.use(helmet.csp.sslOnly());
app.use(helmet.csp.socialMedia());
I'd love some way to add these to policies, rather than overwrite them. Ideas?
I made report-uri
required if you're using a report-only
policy.
But, to quote @mfinifter:
I believe there is value in allowing a report-only policy with no
report-uri
. For example, imagine I don't yet have a reporting endpoint set up, but I want to get started on CSP as soon as possible. I put a report-only policy on the application, and ask the web developers to report any CSP errors they notice in the console during development. I can't do this with helmet today.
I think this is a legitimate use case, but I want to protect developers from accidentally doing the wrong thing. You could also do this by setting any report-uri
and watching things 404, though that's an imperfect workaround.
This would be a breaking change.
What do people think?
See https://www.w3.org/TR/referrer-policy/.
This is not relevant for the 1.x version.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.