Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: mv2 firefox csp header #27770

Open
wants to merge 25 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions app/scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import {
// TODO: Remove restricted import
// eslint-disable-next-line import/no-restricted-paths
import { getCurrentChainId } from '../../ui/selectors';
import { addNonceToCsp } from '../../shared/modules/add-nonce-to-csp';
import migrations from './migrations';
import Migrator from './lib/migrator';
import ExtensionPlatform from './platforms/extension';
Expand Down Expand Up @@ -327,6 +328,27 @@ function maybeDetectPhishing(theController) {
);
}

/**
* Overrides the Content-Security-Policy Header, acting as a workaround for an MV2 Firefox Bug.
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
*/
function overrideContentSecurityPolicyHeader() {
browser.webRequest.onHeadersReceived.addListener(
({ responseHeaders }) => {
for (const header of responseHeaders) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might want to check some additional properties before overriding the CSP headers, as there is no reason to modify the headers if we aren't going to end up injecting inpage.js.

For example, we only every try injecting the inpage provider when our function shouldInjectProvider returns true. We can't use shouldInjectProvider as is here in the background script, because shouldInjectProvider uses the page's document and window in its checks, but we could use parts of it (with a little refactoring).

If suffixCheck and blockedDomainCheck could be refactored to take a URL as a param, instead of relying on window.location as they do now, we could use these existing functions to further limit when we might modify the CSP headers.

if (header.name.toLowerCase() === 'content-security-policy') {
header.value = addNonceToCsp(
header.value,
btoa(browser.runtime.getURL('/')),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: you could precompute this once outside the listener callback and reuse the value; browser.runtime.getURL('/') is unique per install (on FireFox).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: a comment about how browser.runtime.getURL('/') is unique per install would be useful for people reading this code in the future.

);
}
}
return { responseHeaders };
},
{ urls: ['http://*/*', 'https://*/*'] },
['blocking', 'responseHeaders'],
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
);
}

// These are set after initialization
let connectRemote;
let connectExternalExtension;
Expand Down Expand Up @@ -473,6 +495,10 @@ async function initialize() {

if (!isManifestV3) {
await loadPhishingWarningPage();
const { name } = await browser.runtime.getBrowserInfo();
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
if (name === PLATFORM_FIREFOX) {
overrideContentSecurityPolicyHeader();
}
}
await sendReadyMessageToTabs();
log.info('MetaMask initialization complete.');
Expand Down
2 changes: 1 addition & 1 deletion development/build/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ function getBuildName({
function makeSelfInjecting(filePath) {
const fileContents = readFileSync(filePath, 'utf8');
const textContent = JSON.stringify(fileContents);
const js = `{let d=document,s=d.createElement('script');s.textContent=${textContent};d.documentElement.appendChild(s).remove();}`;
const js = `{let d=document,s=d.createElement('script');s.textContent=${textContent};s.nonce=btoa(browser.runtime.getURL('/'));d.documentElement.appendChild(s).remove();}`;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might need to be (globalThis.browser||chrome).runtime.getURL('/'), as chrome doesn't user the global browser property.

writeFileSync(filePath, js, 'utf8');
}

Expand Down
4 changes: 2 additions & 2 deletions development/webpack/test/plugins.SelfInjectPlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ describe('SelfInjectPlugin', () => {
// reference the `sourceMappingURL`
assert.strictEqual(
newSource,
`{let d=document,s=d.createElement('script');s.textContent="${source}\\n//# sourceMappingURL=${filename}.map"+\`\\n//# sourceURL=\${(globalThis.browser||chrome).runtime.getURL("${filename}")};\`;d.documentElement.appendChild(s).remove()}`,
`{let d=document,s=d.createElement('script');s.textContent="${source}\\n//# sourceMappingURL=${filename}.map"+\`\\n//# sourceURL=\${(globalThis.browser||chrome).runtime.getURL("${filename}")};\`;s.nonce=btoa(browser.runtime.getURL('/'));d.documentElement.appendChild(s).remove()}`,
);
} else {
// the new source should NOT reference the new sourcemap, since it's
Expand All @@ -66,7 +66,7 @@ describe('SelfInjectPlugin', () => {
// console.
assert.strictEqual(
newSource,
`{let d=document,s=d.createElement('script');s.textContent="console.log(3);"+\`\\n//# sourceURL=\${(globalThis.browser||chrome).runtime.getURL("${filename}")};\`;d.documentElement.appendChild(s).remove()}`,
`{let d=document,s=d.createElement('script');s.textContent="console.log(3);"+\`\\n//# sourceURL=\${(globalThis.browser||chrome).runtime.getURL("${filename}")};\`;s.nonce=btoa(browser.runtime.getURL('/'));d.documentElement.appendChild(s).remove()}`,
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ export class SelfInjectPlugin {
`\`\\n//# sourceURL=\${${this.options.sourceUrlExpression(file)}};\``,
);
newSource.add(`;`);
newSource.add(`s.nonce=btoa(browser.runtime.getURL('/'));`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the SelfInjectPlugin's options should be extended to accept a nonceExpression option, similar to its existing sourceURLExpression option, that defaults to the string "(globalThis.browser||chrome).runtime.getURL('/')".

So this line here would become something like:

newSource.add(`s.nonce=${this.options.nonceExpression(file)}`);

// add and immediately remove the script to avoid modifying the DOM.
newSource.add(`d.documentElement.appendChild(s).remove()`);
newSource.add(`}`);
Expand Down
77 changes: 77 additions & 0 deletions shared/modules/add-nonce-to-csp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { addNonceToCsp } from './add-nonce-to-csp';

describe('addNonceToCsp', () => {
it('empty string', () => {
const input = '';
const expected = '';
const output = addNonceToCsp(input, 'test');
expect(output).toBe(expected);
});

it('one empty directive', () => {
const input = 'script-src';
const expected = `script-src 'nonce-test'`;
const output = addNonceToCsp(input, 'test');
expect(output).toBe(expected);
});

it('one directive, one value', () => {
const input = 'script-src default.example';
const expected = `script-src default.example 'nonce-test'`;
const output = addNonceToCsp(input, 'test');
expect(output).toBe(expected);
});

it('one directive, two values', () => {
const input = "script-src 'self' default.example";
const expected = `script-src 'self' default.example 'nonce-test'`;
const output = addNonceToCsp(input, 'test');
expect(output).toBe(expected);
});

it('multiple directives', () => {
const input =
"default-src 'self'; script-src 'unsafe-eval' scripts.example; object-src; style-src styles.example";
const expected = `default-src 'self'; script-src 'unsafe-eval' scripts.example 'nonce-test'; object-src; style-src styles.example`;
const output = addNonceToCsp(input, 'test');
expect(output).toBe(expected);
});

it('non-ASCII directives', () => {
const input = 'script-src default.example;\u0080;style-src style.example';
const expected = `script-src default.example 'nonce-test';\u0080;style-src style.example`;
const output = addNonceToCsp(input, 'test');
expect(output).toBe(expected);
});

it('uppercase directive names', () => {
const input = 'SCRIPT-SRC DEFAULT.EXAMPLE';
const expected = `SCRIPT-SRC DEFAULT.EXAMPLE 'nonce-test'`;
const output = addNonceToCsp(input, 'test');
expect(output).toBe(expected);
});

it('duplicate directive names', () => {
const input =
'default-src default.example; script-src script.example; script-src script.example';
const expected = `default-src default.example; script-src script.example 'nonce-test'; script-src script.example`;
const output = addNonceToCsp(input, 'test');
expect(output).toBe(expected);
});

it('nonce value contains script-src', () => {
const input =
"default-src 'self' 'nonce-script-src'; script-src 'self' https://example.com";
const expected = `default-src 'self' 'nonce-script-src'; script-src 'self' https://example.com 'nonce-test'`;
const output = addNonceToCsp(input, 'test');
expect(output).toBe(expected);
});

it('url value contains script-src', () => {
const input =
"default-src 'self' https://script-src.com; script-src 'self' https://example.com";
const expected = `default-src 'self' https://script-src.com; script-src 'self' https://example.com 'nonce-test'`;
const output = addNonceToCsp(input, 'test');
expect(output).toBe(expected);
});
});
13 changes: 13 additions & 0 deletions shared/modules/add-nonce-to-csp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Adds a nonce value to the script-src directive of the Content-Security-Policy Header.
*
* @param header - the Content-Security-Policy Header
* @param nonce - the nonce value to add
* @returns the Content-Security-Policy Header with the nonce value added
*/
export const addNonceToCsp = (header: string, nonce: string) => {
return header.replace(
/(^|;[\t\n\f\r ]*)script-src([^;]*)/iu,
itsyoboieltr marked this conversation as resolved.
Show resolved Hide resolved
(match) => `${match} 'nonce-${nonce}'`,
);
};