content security policy blocking inline execution - javascript

I am working on a project in Django, where I am using a javascript from an external payment provider. Upon calling their script, they will insert a payment form embedded in my page.
The documentation on how to integrate with their service is found here. Specifically I am following step 3 and 4.
A snippet of my html is as below. Upon calling my javascript the payment form from checkout.js will be rendered as an iframe in the checkout-container-div element
<div id="checkout-container-div"> </div>
<script src="https://test.checkout.dibspayment.eu/v1/checkout.js?v=1"></script>
In my javascript, I first call my backend to get the paymentId. Then using the obtained paymentId, I am calling the external checkout.js with const checkout = new Dibs.Checkout(checkoutOptions); in order to render the payment form
document.getElementById("paymentButton").addEventListener("click", function() {
//Collect all the fields value and send it to the server
console.log("pay button clicked")
$.ajax({
url : "localDeliveryPayment",
type : "get",
success: function(response) {
if (response['paymentIdCreation'] == true) {
console.log(response);
const checkoutOptions = {
checkoutKey: response['checkoutKey'], // Replace!
paymentId: response['paymentId'],
containerId: "checkout-container-div",
};
const checkout = new Dibs.Checkout(checkoutOptions);
checkout.on('payment-completed', function (response) {
window.location = 'completed.html';
});
}
}
})
})
From Google Chrome's console I get the following error related to test.checkout.dibspayment.eu/:1
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'sha256-NzNw/hrx7wC5UKemwLm4mwVnoDVfHDuSpmZAeKCQaqY=' 'sha256-aKaLBqGLMQ35mP/i/QmpW+s6QnrN3dNb78G9ndv1bC0=' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='". Either the 'unsafe-inline' keyword, a hash ('sha256-1XgMsIi6szxMi7JX5ZCg4KWReddGOu15C+cKuzlVaf4='), or a nonce ('nonce-...') is required to enable inline execution.
Also I see this error related to checkout.api.ts:126 POST
POST https://test.checkout.dibspayment.eu/api/v1/frontendlogs net::ERR_ABORTED 401 (Unauthorized)
There are some other errors as well that I think is related to content being blocked. I have tried to add the below meta tag to the head in my html base template.
<meta http-equiv="Content-Security-Policy"
content = "script-src 'self'
cdnjs.cloudflare.com
code.jquery.com
cdn.jsdelivr.net
stackpath.bootstrapcdn.com
test.checkout.dibspayment.eu;">
Still I got the error test.checkout.dibspayment.eu/:1
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'sha256-NzNw/hrx7wC5UKemwLm4mwVnoDVfHDuSpmZAeKCQaqY=' 'sha256-aKaLBqGLMQ35mP/i/QmpW+s6QnrN3dNb78G9ndv1bC0=' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='". Either the 'unsafe-inline' keyword, a hash ('sha256-1XgMsIi6szxMi7JX5ZCg4KWReddGOu15C+cKuzlVaf4='), or a nonce ('nonce-...') is required to enable inline execution.
Also I tried with 'unsafe-inline' keyword in the Content-Security-Policy meta tag, but still got the same error. I have read several places that CSP is blocking for inline code execution and now is really confused if the issue at all is related to inline code execution from the external javascript, or if this error is related to something else?

The solution to this problem on integration of NETS payment service when running in Django turned out not to be fully related to content security protocol. The error I posed originally is related to CSP, but I never managed to solve it. When I used the payment demo webshop I see the same error on my browser as during my own test. The checkout was successful, therefore I figured out that the error is not only related to CSP. It turned out that adding
django_referrer_policy.middleware.ReferrerPolicyMiddleware'
to the middleware in my settings.py and followed by adding
REFERRER_POLICY = 'strict-origin'
in settings.py solved the problem.

Related

Content Security Policy violation on external Js Script

sorry for bad description. I have an app that works fine on localhost and test server. On the machine that has connection to test server when I try to access the app via server's IP and port I can access the app too. But with a rerouting that points to my apps test server IP and port I get below 2 errors in a script that I use from a different host. Test server doesn't has outside connection allowed but related script host has been allowed. I have tried adding CSP headers to ISS but it didn't work. How can I resolve this issue or how can I get more details about it. Any help would appreciated. Thank you.
1st error:
Refused to create a worker from
'blob:https://redirecteddomain.com/04891805-36bb-45f7-a4e9-7cb58f25a3bf'
because it violates the following Content Security Policy directive:
"default-src https: data: 'unsafe-inline' 'unsafe-eval'". Note that
'worker-src' was not explicitly set, so 'default-src' is used as a
fallback.
2nd error:
Uncaught DOMException: Failed to construct 'Worker': Access to the
script at
'blob:https://redirecteddomain.com/04891805-36bb-45f7-a4e9-7cb58f25a3bf'
is denied by the document's Content Security Policy.
Script that got the error:
<script src="https://scriptsource.com/script.php?lang=en"></script>
Due to privacy issues domain names are replaced.
Update: So I have tried to download and use the script locally and there were couple of API calls in the javascript file and it gave the same error again.
Update-2: I have checked through the script file and found the lines that are causing the issue, I have added "default-src 'self' 'unsafe-inline'; worker-src blob:;" meta header but still get the same error
const e=window.URL||window.webkitURL,n=new
Blob(['importScripts("'+Dt.faceworker+"?v="+t.replace(/\./g,"")+'");'],
{type:"application/javascript"}),o=e.createObjectURL(n);
Wt=new Worker(o)
The CSP on your page doesn't allow "blob:". Adding another CSP in a meta tag can only impose restrictions, it can't change the other CSP that is likely there and served in a response header. You will likely need to modify the original CSP adding blob: to default-src or worker-src.

Electron Confusion about Security

Ok, im just lost. I opened an electron start app and added one simple code, to console log on button press. The function is in a file renderer.js and in being called in in my index.html. Why when I press the button
I get this message ....
Refused to execute inline event handler because it violates the following Content
Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a
hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
Why would I not be allowed to execute something inline? An external source seems more vulnerable. Can anyone clear this up for me please?
Content Security Policy is using to avoid XSS based attacks in browser.In electron the background is running in a chrome engine, so the code is actullay running in a chromium browser.This browser is prone to all security issues that a browser is having
What is Content-Security-Policy?
Content-Security-Policy is the name of a HTTP response header that modern browsers use to enhance the security of the document (or web page). The Content-Security-Policy header allows you to restrict how resources such as JavaScript, CSS, or pretty much anything that the browser loads.
you can add the following code at the top of HTML to avoid the content security issue. this new header will allow the inline code to execute
<meta http-equiv="Content-Security-Policy" content="script-src 'self';">
What this meta tag will do ?
Allows
With the above CSP policy, the following are allowed to load and execute in the browser:
<!-- allowed by 'self' -->
<script src="/js/some-file.js"></script>
<!-- allowed by https://js.example.com -->
<script src="https://js.example.com/file.js"></script>
Blocks
The Example Policy above will block the following from loading or executing in the browser:
<script src="https://attacker.example.com/file.js"></script>

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source

I added the following to a web page:
<script type="text/javascript">
window.addEventListener("load", function () {
window.location = "https://localhost:5002";
});
</script>
When I run the application I get the following error:
Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "default-src 'self'"
When I remove the script I do not get the error anymore.
Any idea why this happens?
Your current CSP setting is:
"default-src 'self'"
which means that you can only execute your code from your root URL (localhost:5000).
You can try to extend this policy to the other URL you are using:
"default-src 'self' https://localhost:5002"
The CSP setting location depends on your web server. In case of Apache, this is set in file '.htaccess'.
P.S: 'unsafe-eval' doesn't seem to be related to the listener you are adding, but you can try the above change anyway.
For other people that might come across something similar: developing a plugin for an electron app i got this error when i was trying to load it. The solution was to just change the mode to "production" in webpack.config.js.

It is possible to override/remove page Content Security Policy through the external script?

I'm write an external script for a single web page and i need to make one POST JSON request to another resource through this script.
However, when i do, it throws CSP error: "Refused to connect to <URL> because it violates the following Content Security Policy directive: "connect-src 'self'".
I looked into the web page and see meta tag which contain a Content-Security-Policy with CSP content. However, i tried manually add my <URL> to CSP connect-src content, but it is still not working.
Questions:
can i change CSP through the external script? How?
maybe any workaround for this?
The error message is saying the setting that needs to be changed:
it violates the following Content Security Policy directive: "connect-src 'self'"
So you need to set the 'connect-src' directive to something other than 'self', which might have been set by default.
You said you tried to add the URL that you're trying to connect to. That is not quite right - you need to add just the host part, rather than any of the path.
So the connect-src part of the CSP header should look like:
connect-src 'self' https://*.example.com
If you update your question with what you tried, if it still isn't working, the exact error could be diagnosed.

Browser is blocking my jquery

So I'm not sure why but I get an error message from Chrome.
Error message:
Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-TakXxMuCq+J+ccgIY6WUXR+xy3/BdgRbqG7Y1mNRWJQ='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
jQuery:
<script type="text/javascript">
$( document ).ready(function() {
$.ajax({
type:'GET',
url:'http://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/?appid=440&count=3&maxlength=300&format=json'
success: function(data){
console.log('success',data);
}
});
});
</script>
Sorry if this is a duplicate question.
I just had a hard time finding the answer to my problem.
But can someone explain why I am getting the error message that I am getting?
I want to give some extra information, so that you may understand my situation.
I was writing an app in HTML.
All the files used in the HTML other then the JSON are all from my machine.
I did not run them from any server including xampp. I simply double clicked my HTML file.
Are you writing a Chrome extension? It's not immediately clear from your question, but that's where I would expect to find this error message.
Inline script tags are not executed by extensions. The Google Content Security Policy pages state:
Inline JavaScript will not be executed. This restriction bans both
inline <script> blocks and inline event handlers (e.g. <button
onclick="...">).
The first restriction wipes out a huge class of cross-site scripting
attacks by making it impossible for you to accidentally execute script
provided by a malicious third-party. It does, however, require you to
write your code with a clean separation between content and behavior
(which you should of course do anyway, right?).
There is a way to relax this policy though
As of Chrome 46, inline scripts can be whitelisted by specifying the
base64-encoded hash of the source code in the policy. This hash must
be prefixed by the used hash algorithm (sha256, sha384 or sha512). See
Hash usage for <script> elements for an example.

Categories