How to allow https://* in csp? - javascript

So I am using CSP for my website, but I am running into an issue when it comes to my img-src header, I am using NodeJS, and Express to program my website, in which this website is for my Discord Bot, and well I am wanting to take the time to revamp the website, but now I am stuck.
======
So, I am using the following code for my headers:
app.use(
helmet.contentSecurityPolicy({
directives: {
// eslint-disable-next-line no-irregular-whitespace
...helmet.contentSecurityPolicy.getDefaultDirectives(),
'default-src': ['\'unsafe-inline\'', '\'self\'', '\'https://*\'', '\'http://*\''],
'script-src': ['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', '*'],
'img-src': ['\'self\'', '\'https://*\'', '\'http://*\''],
},
})
);
====
And the error I get (For both Default and Img):
Couldn't Parse unknown Host: https://*
Couldn't Parse unknown Host: http://*
Content Security Policy: Couldn’t parse invalid host 'https://*'
Content Security Policy: Couldn’t parse invalid host 'http://*'
====
Thank you in advance for the help.
If anyone would like to check out the website for any sort of Idea of what I am trying to do, the link is https://therpbot.xyz/, and I am trying to get image links from discord.

If you want to allow https without specifying a domain, then just use "https" without the colon, slashes or star, like this:
Content-Security-Policy: "default-src https:; script-src https; img-src https"
[edit]: for default-src, include the colon...

Hosts like 'https://*' are really invalid, because host-sources should not be a single quoted.
Remove one pair single quotes around '\'https://*\'', '\'http://*\'':
app.use(
helmet.contentSecurityPolicy({
directives: {
// eslint-disable-next-line no-irregular-whitespace
...helmet.contentSecurityPolicy.getDefaultDirectives(),
'default-src': ['\'unsafe-inline\'', '\'self\'', 'https://*', 'http://*'],
'script-src': ['\'self\'', '\'unsafe-inline\'', '\'unsafe-eval\'', '*'],
'img-src': ['\'self\'', 'https://*', 'http://*'],
},
})
);

Related

can I use both 'unsafe-inline' and 'unsafe-eval' in the same script-scr or do I need to add a new script-scr?

I am working with the gatsby-plugin-csp and want to understand if it is possible to add two keywords both 'unsafe-inline' and 'unsafe-eval' in the same script-scr and make them work? Or do I need to create two different script-scr? There are a few sources that I must use and some them of need eval() and others inline scripts.
Can I do this?
// In your gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-csp`,
options: {
disableOnDev: true,
reportOnly: false, // Changes header to Content-Security-Policy-Report-Only for csp testing purposes
mergeScriptHashes: true, // you can disable scripts sha256 hashes
mergeStyleHashes: true, // you can disable styles sha256 hashes
mergeDefaultDirectives: true,
directives: {
"script-src": "'self' 'unsafe-inline' 'unsafe-eval' www.example.com",
"style-src": "'self' 'unsafe-inline'",
"img-src": "'self' data: www.google-analytics.com"
// you can add your directives or override defaults
}
}
}
]
};
Or should I do this?
// In your gatsby-config.js
module.exports = {
plugins: [
{
resolve: `gatsby-plugin-csp`,
options: {
disableOnDev: true,
reportOnly: false, // Changes header to Content-Security-Policy-Report-Only for csp testing purposes
mergeScriptHashes: true, // you can disable scripts sha256 hashes
mergeStyleHashes: true, // you can disable styles sha256 hashes
mergeDefaultDirectives: true,
directives: {
"script-src": "'self' 'unsafe-inline' www.example.com",
"script-src": "'self' 'unsafe-eval' www.example.com",
"style-src": "'self' 'unsafe-inline'",
"img-src": "'self' data: www.google-analytics.com"
// you can add your directives or override defaults
}
}
}
]
};
I have tried using the first option with both 'unsafe-inline' and 'unsafe-eval' in this case half of them give errors like Refused to load the script 'http://embed.example.com/next/embed.js' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval'
I also get this error Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.google-analytics.com https://www.googletagmanager.com
When I change the order of the keywords putting 'unsafe-eval' then 'unsafe-inline' I still get errors refusing to run other scripts.
You could have two CSPs defined, but not the same directive twice in one policy. If you define multiple policies, your content still needs to pass all policies, adding another one can only make it stricter.
Your first script-src is "'self' 'unsafe-inline' 'unsafe-eval' www.example.com", which allows anything from the same server (same host, same port and same or safer scheme), inline scripts, eval (new Function(), setInterval(), setTimeout() and eval()) and scripts from www.example.com.
Your first error is caused by script from embed.example.com, which is blocked by your policy which only allows 'self' and www.example.com. You can add embed.example.com or replace www.example.com with *.example.com.
The second error is likely related to inline event attributes (like onclick, onload etc), click on the link in the error message to see the violating code. You generally need to rewrite them using event handlers. You might be able to allow them with additional efforts in CSP level 3, but I don't think there is full browser compatibility yet.

Content Security Policy error while loading a script

i am trying to render a chart in my app using Pug as seen below:
block content
h2 Question statistics
.col-lg-12
script(src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js")
.chart-container
canvas#myChart2
script.
var ctx = document.getElementById("myChart2").getContext('2d');
ctx.canvas.parentNode.style.width = '50%'
var idata = [1]
var ilabel = [2]
var myChart = new Chart(ctx, { /* ... etc */
This was loaded just fine before a week or so but today when i tried to access this feature the chart would not render.
The error in my console is this:
Refused to load the script
'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js'
because it violates the following Content Security Policy directive:
"script-src 'self'". Note that 'script-src-elem' was not explicitly
set, so 'script-src' is used as a fallback.
and
Refused to execute inline script because it violates the following
Content Security Policy directive: "script-src 'self'". Either the
'unsafe-inline' keyword, a hash
('sha256-AklvVxShqs4WBi3vUz7qSiPkes2rSVGoNyoZXYVnSA8='), or a nonce
('nonce-...') is required to enable inline execution.
This is the first time i am seeing this error and i don't know how to solve it. Any ideas?
As turned out in comments, here's the line of code that broke it all:
app.use(helmet());
Helmet is a really neat module designed to let you protect your server from the most common attack vectors without worrying much about details. Alas, as any good security tool, it operates in 'paranoid mode' by default. Here's what this small line is actually equivalent to:
app.use(helmet.contentSecurityPolicy());
app.use(helmet.dnsPrefetchControl());
app.use(helmet.expectCt());
app.use(helmet.frameguard());
app.use(helmet.hidePoweredBy());
app.use(helmet.hsts());
app.use(helmet.ieNoOpen());
app.use(helmet.noSniff());
app.use(helmet.permittedCrossDomainPolicies());
app.use(helmet.referrerPolicy());
app.use(helmet.xssFilter());
Yep, a lot of stuff. The one that messed up your setup is the first item of this list. Here's the default values sent as Content-Security-Policy header values by that line:
default-src 'self';
base-uri 'self';
block-all-mixed-content;
font-src 'self' https: data:;
frame-ancestors 'self';
img-src 'self' data:;
object-src 'none';
script-src 'self';
script-src-attr 'none';
style-src 'self' https: 'unsafe-inline';
upgrade-insecure-requests
Once again, that makes sense, as Helmet doesn't know anything about external entities you're using - and your level of trust to those. It's you who are responsible for providing this data, either by adding hash info or by listing the trusted sources in the configuration. For example:
helmet.contentSecurityPolicy({
useDefaults: false,
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "example.com"], // scripts from example.com are now trusted
objectSrc: ["'none'"],
upgradeInsecureRequests: [],
},
})
You can configure each module individually, or add this configuration into helmet directly:
app.use(
helmet({
contentSecurityPolicy: {
useDefaults: false,
directives: { ... }
},
})
);

Why is my resource getting blocked even though I allowed it specifically in the CSP declaration?

Hi all hoping you can help but I don't know if you can. Having checked other questions about the CSP blocking, they all recommend to specifically allow your resource in the headers (or if you're using helmet, in a CSP declaration object) and now that I've now done that I still relentlessly get the same issue.
Here is my declaration via Helmet
app.use(helmet());
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: [
"'self'",
'https://*.mapbox.com',
'https://*.stripe.com',
'blob',
],
baseUri: ["'self'"],
fontSrc: ["'self'", 'https:', 'data:'],
scriptSrc: ["'self'", 'https://*.cloudflare.com'],
imgSrc: ["'self'", 'https://www.gstatic.com'],
scriptSrc: [
"'self'",
'https://*.stripe.com',
'https://cdnjs.cloudflare.com',
'https://api.mapbox.com',
'https://js.stripe.com',
'blob',
],
frameSrc: ["'self'", 'https://*.stripe.com'],
objectSrc: ["'none'"],
styleSrc: ["'self'", 'https:', "'unsafe-inline'"],
upgradeInsecureRequests: [],
},
})
);
And then these are the errors:
web_worker.js:9 Refused to create a worker from 'blob:http://127.0.0.1:8000/a115d817-1a59-46c1-97e5-355513ade597' because it violates the following Content Security Policy directive: "script-src 'self' https://*.stripe.com https://cdnjs.cloudflare.com https://api.mapbox.com https://js.stripe.com blob". Note that 'worker-src' was not explicitly set, so 'script-src' is used as a fallback.
Another one here:
Refused to load the image 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=' because it violates the following Content Security Policy directive: "img-src 'self' https://www.gstatic.com".
Console warnings show that:
You miss a colon in blob: scheme.
You need to specify data: in the img-src directive.

Google App Engine CORS “Error parsing ./app.yaml: Unknown url handler type”

I'm trying to apply CORS to one of my app engines, but I'm encountering an error. I've tried looking at the recommendations for other answers (spacing) but it still errors:
app.yaml
runtime: nodejs10
env_variables:
NODE_ENV: production
CLOUD_SQL_CONNECTION_NAME: domain-name-server:australia-southeast1:db_name
handlers:
- url: /.*
http_headers:
Access-Control-Allow-Origin: https://domain_name-fixed.appspot.com/
Errors
ERROR: (gcloud.app.deploy) An error occurred while parsing file: [/home/project/domain_name-server/app.yaml]
Unknown url handler type.
<URLMap
secure=default
static_files=None
application_readable=None
auth_fail_action=redirect
require_matching_file=None
static_dir=None
redirect_http_response_code=None
http_headers={u'Access-Control-Allow-Origin': 'https://domain_name-fixed.appspot.com/'}
url=/.*
script=None
upload=None
api_endpoint=None
expiration=None
position=None
login=optional
mime_type=None
>
in "/home/project/domain_name-server/app.yaml", line 10, column 73
nodejs cors settings
let cors = require("cors")
let origin =
[
"http://localhost:8080",
`http://${ip.address()}:8080`,
"http://localhost:4000",
`http://${ip.address()}:4000`,
"https://domain_name-fixed.appspot.com/"
]
app.use(cors({
origin,
credentials: true
}))
You can only set HTTP headers for static files. You need to do the CORS part in nodejs code.

Meteor BrowserPolicy enable 'blob:' origins

I have enabled Content Security Policy meteor package meteor/browser-policy-common
Now I'm getting this error from ostrio:files related to CSP
Refused to create a worker from
'blob:http://localhost:3000/ef628f55-736b-4b36-a32d-b1056adfaa8c'
because it violates the following Content Security Policy directive:
"default-src 'self' http://fonts.googleapis.com
https://fonts.googleapis.com http://fonts.gstatic.com
https://fonts.gstatic.com http://code.ionicframework.com
https://code.ionicframework.com". Note that 'worker-src' was not
explicitly set, so 'default-src' is used as a fallback.
My actual browser-policy-common config looks like this
import { BrowserPolicy } from 'meteor/browser-policy-common';
// e.g., BrowserPolicy.content.allowOriginForAll( 's3.amazonaws.com' );
// BrowserPolicy.content.allowFontOrigin("data:");
BrowserPolicy.framing.disallow();
BrowserPolicy.content.disallowInlineScripts();
BrowserPolicy.content.disallowEval();
BrowserPolicy.content.allowInlineStyles();
BrowserPolicy.content.allowFontDataUrl();
const trusted = [
'fonts.googleapis.com',
'fonts.gstatic.com',
'code.ionicframework.com',
];
_.each(trusted, (origin) => {
BrowserPolicy.content.allowOriginForAll(origin);
});
Can you tell me which config should I change to allow ostrio:files blob:http://localhost:3000/... to work?
Thanks a lot!
To allow blob: origins, you can add this:
BrowserPolicy.content.allowOriginForAll('blob:');
Meteor doesn’t provide a mechanism for more specifically allowing blob: just for worker-src.

Categories