- Notifications
You must be signed in to change notification settings - Fork20.6k
Description
jQuery should be able to load scripts via$.getScript
without causingunsafe-inline
CSP violations.
Look at the following test case:
index.html
<metahttp-equiv="Content-Security-Policy"content="default-src 'self'; script-src 'self' https://code.jquery.com 'sha256-DOU0/sVUxitk2MNb5zXL6o3XIe+ZQ5oKG5jmGDO9PmQ='"><scriptsrc="https://code.jquery.com/jquery-3.3.1.js"></script><inputid="btnJQuery"type="button"value="Load script via jQuery"/><inputid="btnScriptTag"type="button"value="Load script via script tag"/><script>console.log("start");$("#btnJQuery").on("click",function(){$.getScript("payload.js");});$("#btnScriptTag").on("click",function(){letscriptEl=document.createElement("script");scriptEl.onload=function(){console.log('onload',arguments);};scriptEl.onerror=function(){console.log('onerror',arguments);};scriptEl.src="payload.js";document.head.appendChild(scriptEl);});</script>
payload.js
console.log("OK");
If you click on theLoad script via jQuery
button the following error is shown in the browser's console (Chrome in this case):
jquery-3.3.1.js:111 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'https://code.jquery.com 'sha256-DOU0/sVUxitk2MNb5zXL6o3XIe+ZQ5oKG5jmGDO9PmQ='". Either the 'unsafe-inline' keyword, a hash ('sha256-oKrRnv4NSECe1z+2Q8HSC47J9uP6ALT0+UguOrbK7UU='), or a nonce ('nonce-...') is required to enable inline execution.
On the other hand if you click on theLoad script via script tag
button then the script is loaded without issues and the textOK
is shown in the console.
Note: I am reporting this issue, because third-party libraries use$.getScript()
and they consider this a jQuery issue (rightly) and won't fix this by their own because they expect the fix from jQuery.
For example see this issue:jackocnr/intl-tel-input#541
Security considerations
Using constructs which requireunsafe-inline
orunsafe-eval
are generally not recommended and the security community considers them as bad practice.
Mozilla MDN states the following aboutunsafe-inline
:
Disallowing inline styles and inline scripts is one of the biggest security wins CSP provides.
Google recommends the same in theirWeb Fundamentals guide
If you must have inline script and style, you can enable it by adding 'unsafe-inline' as an allowed source in a script-src or style-src directive. You can also use a nonce or a hash (see below), butyou really shouldn't.Banning inline script is the biggest security win CSP provides, and banning inline style likewise hardens your application.
you can enable them by adding 'unsafe-eval' as an allowed source in a script-src directive, butwe strongly discourage this.
So I hope you will consider changing the current behavior for the sake of a safer web (taking into account how widespread your library is).