Skip to content

Commit

Permalink
Use Blob URLs to reliably inject scriptlets
Browse files Browse the repository at this point in the history
Related issue:
- uBlockOrigin/uBlock-issues#235

Fixed as suggested by <https://github.com/evilpie>, to safely
bypass a page's own CSP.
  • Loading branch information
gorhill committed Dec 11, 2022
1 parent 1b63d65 commit 0971025
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 14 deletions.
11 changes: 8 additions & 3 deletions src/js/contentscript.js
Expand Up @@ -465,16 +465,21 @@ vAPI.SafeAnimationFrame = class {

vAPI.injectScriptlet = function(doc, text) {
if ( !doc ) { return; }
let script;
let script, url;
try {
const blob = new self.Blob([ text ], { type: 'text/javascript' });
url = self.URL.createObjectURL(blob);
script = doc.createElement('script');
script.appendChild(doc.createTextNode(text));
script.src = url;
(doc.head || doc.documentElement || doc).appendChild(script);
} catch (ex) {
}
if ( script ) {
script.remove();
script.textContent = '';
script.src = '';
}
if ( url ) {
self.URL.revokeObjectURL(url);
}
};

Expand Down
4 changes: 2 additions & 2 deletions src/js/redirect-engine.js
Expand Up @@ -35,7 +35,7 @@ import {
const extToMimeMap = new Map([
[ 'gif', 'image/gif' ],
[ 'html', 'text/html' ],
[ 'js', 'application/javascript' ],
[ 'js', 'text/javascript' ],
[ 'mp3', 'audio/mp3' ],
[ 'mp4', 'video/mp4' ],
[ 'png', 'image/png' ],
Expand All @@ -46,7 +46,7 @@ const extToMimeMap = new Map([
const typeToMimeMap = new Map([
[ 'main_frame', 'text/html' ],
[ 'other', 'text/plain' ],
[ 'script', 'application/javascript' ],
[ 'script', 'text/javascript' ],
[ 'stylesheet', 'text/css' ],
[ 'sub_frame', 'text/html' ],
[ 'xmlhttprequest', 'text/plain' ],
Expand Down
21 changes: 12 additions & 9 deletions src/js/scriptlet-filtering.js
Expand Up @@ -97,19 +97,25 @@ const contentscriptCode = (( ) => {
) {
return;
}
let script;
let script, url;
try {
script = doc.createElement('script');
script.appendChild(doc.createTextNode(
decodeURIComponent(scriptlets))
const blob = new self.Blob(
[ decodeURIComponent(scriptlets) ],
{ type: 'text/javascript' }
);
url = self.URL.createObjectURL(blob);
script = doc.createElement('script');
script.src = url;
(doc.head || doc.documentElement).appendChild(script);
self.uBO_scriptletsInjected = true;
} catch (ex) {
}
if ( script ) {
script.remove();
script.textContent = '';
script.src = '';
}
if ( url ) {
self.URL.revokeObjectURL(url);
}
if ( typeof self.uBO_scriptletsInjected === 'boolean' ) { return 0; }
}.toString(),
Expand Down Expand Up @@ -177,10 +183,7 @@ const lookupScriptlet = function(rawToken, reng, toInject) {
} else {
token = `${token}.js`;
}
content = reng.resourceContentFromName(
token,
'application/javascript'
);
content = reng.resourceContentFromName(token, 'text/javascript');
if ( !content ) { return; }
if ( args ) {
content = patchScriptlet(content, args);
Expand Down

0 comments on commit 0971025

Please sign in to comment.