Het extensiesysteem van Chrome hanteert een vrij strikt standaard Content Security Policy (CSP) . De beleidsbeperkingen zijn eenvoudig: scripts moeten uit de code worden gehaald en in aparte JavaScript-bestanden worden geplaatst, inline eventhandlers moeten worden omgezet naar het gebruik van addEventListener en eval() is uitgeschakeld.
We recognize, however, that a variety of libraries use eval() and eval -like constructs such as new Function() for performance optimization and ease of expression. Templating libraries are especially prone to this style of implementation. While some (like Angular.js ) support CSP out of the box, many popular frameworks haven't yet updated to a mechanism that is compatible with extensions' eval -less world. Removing support for that functionality has therefore proven more problematic than expected for developers.
Dit document introduceert sandboxing als een veilig mechanisme om deze bibliotheken in uw projecten op te nemen zonder de beveiliging in gevaar te brengen.
Waarom een sandbox?
eval is dangerous inside an extension because the code it executes has access to everything in the extension's high-permission environment. A slew of powerful browser.* APIs are available that could severely impact a user's security and privacy; simple data exfiltration is the least of our worries. The solution on offer is a sandbox in which eval can execute code without access either to the extension's data or the extension's high-value APIs. No data, no APIs, no problem.
We accomplish this by listing specific HTML files inside the extension package as being sandboxed. Whenever a sandboxed page is loaded, it will be moved to a unique origin , and will be denied access to browser.* APIs. If we load this sandboxed page into our extension via an iframe , we can pass it messages, let it act upon those messages in some way, and wait for it to pass us back a result. This simple messaging mechanism gives us everything we need to safely include eval -driven code in our extension's workflow.
Maak en gebruik een sandbox.
Als je meteen aan de slag wilt met coderen, download dan de sandbox-voorbeeldextensie en ga direct aan de slag . Het is een werkend voorbeeld van een kleine berichten-API, gebouwd bovenop de Handlebars -sjabloonbibliotheek, en het zou je alles moeten geven wat je nodig hebt om te beginnen. Voor degenen die wat meer uitleg willen, zullen we het voorbeeld hier samen doorlopen.
Lijst met bestanden in manifest
Elk bestand dat in een sandbox moet worden uitgevoerd, moet in het extensiemanifest worden opgenomen door een sandbox eigenschap toe te voegen. Dit is een cruciale stap die gemakkelijk vergeten kan worden, dus controleer goed of uw bestand in de sandbox in het manifest staat. In dit voorbeeld plaatsen we het bestand met de slimme naam "sandbox.html" in een sandbox. De vermelding in het manifest ziet er als volgt uit:
{
...,
"sandbox": {
"pages": ["sandbox.html"]
},
...
}
Laad het afgeschermde bestand.
In order to do something interesting with the sandboxed file, we need to load it in a context where it can be addressed by the extension's code. Here, sandbox.html has been loaded into an extension page using an iframe . The page's JavaScript file contains code that sends a message into the sandbox whenever the browser action is clicked by finding the iframe on the page, and calling postMessage() on its contentWindow . The message is an object containing three properties: context , templateName , and command . We'll dive in to context and command in a moment.
service-worker.js:
browser.action.onClicked.addListener(() => {
browser.tabs.create({
url: 'mainpage.html'
});
console.log('Opened a tab with a sandboxed page!');
});
extension-page.js:
let counter = 0;
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('reset').addEventListener('click', function () {
counter = 0;
document.querySelector('#result').innerHTML = '';
});
document.getElementById('sendMessage').addEventListener('click', function () {
counter++;
let message = {
command: 'render',
templateName: 'sample-template-' + counter,
context: { counter: counter }
};
document.getElementById('theFrame').contentWindow.postMessage(message, '*');
});
Doe iets gevaarlijks
Wanneer sandbox.html wordt geladen, laadt het de Handlebars-bibliotheek en maakt en compileert het een inline-sjabloon op de manier die Handlebars aanbeveelt:
extension-page.html:
<!DOCTYPE html>
<html>
<head>
<script src="mainpage.js"></script>
<link href="styles/main.css" rel="stylesheet" />
</head>
<body>
<div id="buttons">
<button id="sendMessage">Click me</button>
<button id="reset">Reset counter</button>
</div>
<div id="result"></div>
<iframe id="theFrame" src="sandbox.html" style="display: none"></iframe>
</body>
</html>
sandbox.html:
<script id="sample-template-1" type="text/x-handlebars-template">
<div class='entry'>
<h1>Hello</h1>
<p>This is a Handlebar template compiled inside a hidden sandboxed
iframe.</p>
<p>The counter parameter from postMessage() (outer frame) is:
</p>
</div>
</script>
<script id="sample-template-2" type="text/x-handlebars-template">
<div class='entry'>
<h1>Welcome back</h1>
<p>This is another Handlebar template compiled inside a hidden sandboxed
iframe.</p>
<p>The counter parameter from postMessage() (outer frame) is:
</p>
</div>
</script>
Dit werkt perfect! Hoewel Handlebars.compile uiteindelijk new Function gebruikt, werkt alles precies zoals verwacht en krijgen we een gecompileerde template in templates['hello'] .
Geef het resultaat terug
We'll make this template available for use by setting up a message listener that accepts commands from the extension page. We'll use the command passed in to determine what ought to be done (you could imagine doing more than simply rendering; perhaps creating templates? Perhaps managing them in some way?), and the context will be passed into the template directly for rendering. The rendered HTML will be passed back to the extension page so the extension can do something useful with it later on:
<script>
const templatesElements = document.querySelectorAll(
"script[type='text/x-handlebars-template']"
);
let templates = {},
source,
name;
// precompile all templates in this page
for (let i = 0; i < templatesElements.length; i++) {
source = templatesElements[i].innerHTML;
name = templatesElements[i].id;
templates[name] = Handlebars.compile(source);
}
// Set up message event handler:
window.addEventListener('message', function (event) {
const command = event.data.command;
const template = templates[event.data.templateName];
let result = 'invalid request';
// if we don't know the templateName requested, return an error message
if (template) {
switch (command) {
case 'render':
result = template(event.data.context);
break;
// you could even do dynamic compilation, by accepting a command
// to compile a new template instead of using static ones, for example:
// case 'new':
// template = Handlebars.compile(event.data.templateSource);
// result = template(event.data.context);
// break;
}
} else {
result = 'Unknown template: ' + event.data.templateName;
}
event.source.postMessage({ result: result }, event.origin);
});
</script>
Back in the extension page, we'll receive this message, and do something interesting with the html data we've been passed. In this case, we'll just echo it out via a notification , but it's entirely possible to use this HTML safely as part of the extension's UI. Inserting it via innerHTML doesn't pose a significant security risk as we trust the content which has been rendered within the sandbox.
This mechanism makes templating straightforward, but it of course isn't limited to templating. Any code that doesn't work out of the box under a strict Content Security Policy can be sandboxed; in fact, it's often useful to sandbox components of your extensions that would run correctly in order to restrict each piece of your program to the smallest set of privileges necessary for it to properly execute. The Writing Secure Web Apps and Chrome Extensions presentation from Google I/O 2012 gives some good examples of these technique in action, and is worth 56 minutes of your time.