Disabling content security policy of a Web page via a Chrome Extension

Viewed 5075

I'm creating a Chrome Extension which modifies a script served by the server (which I have no control over) to add new functionality to the website, and I had the following idea:

  1. Block the original script via WebRequest, webRequestBlocking.
  2. Send the url of the blocked script to a script injected into the page.
  3. GET this url from the page's script.
  4. Edit a part of the code (string).
  5. Eval the string.

(Another working way is to redirect it to a local modified script return { redirectUrl: chrome.extension.getURL("modified.js") };, inside the Chrome Extension folder, but then it's impossible to modify it on the fly, that's why I want to eval a modified script)

When I try to eval the string in the 5th step, it says: ...'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'nonce-DFX4zDtBDF32343LjE2DFKMs' 'self' https://website.com".

I've tried to use webRequest.onHeadersReceived to see if I could alter CSP headers (as some answers suggested: Edit Content Security Policy in onHeadersReceived), but there is no "content-security-policy" header.

I can see a Content Security Policy meta tag (I've omitted everything except 'script-src'):

<meta http-equiv="Content-Security-Policy" content="script-src 'nonce-DFX4zDtBDF32343LjE2DFKMs' 'self' https://website.com; base-uri 'none';">

From this answer (https://stackoverflow.com/a/27324485/10364842), Chrome Extensions cannot override CSP of Web pages. But someone replies: I know this is incredibly old, but I came across it while trying to inject Artoo.js into a page. The chrome extension does indeed allow you to modify the page you're looking at and let any content through.

Eval works in the content script, but I need to execute the script in the page's context, because it depends on the global scope.

I'm wondering if it's possible to alter CSP of a Web page through a Chrome Extension, or if there is any other way to accomplish this solely via a Chrome extension?

1 Answers

"Extensions have a content security policy applied to them by default. The default policy restricts the sources from which they can load and resources, and disallows potentially unsafe practices such as the use of eval(). See Default content security policy to learn more about the implications of this.

You can use the "content_security_policy" manifest key to loosen or tighten the default policy. This key is specified in just the same way as the Content-Security-Policy HTTP header. See Using Content Security Policy for a general description of CSP syntax." https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/content_security_policy

Related