Reputation: 1818
i m trying to create a small system where developers can write some code and that can be run by any other user.
if that code runs in some other user's session then it will privacy concerns as session data can be stolen
i could sandbox the code using an iframe but every pieace of code can have their own session data which again demands infinite iframes so i ll have to setup subdomains for each of the iframe
here is one way that i think which can suffice all the purposes
((window, document) => {
// malicious code
console.log(window, document)
})({}, {})
if i scope the code this way and give them a way to access only their data.
does this have any threats ?
all types of opinoins and tweaks are welcomed . please help
Upvotes: 0
Views: 84
Reputation: 3647
((window, document, globalThis) => {
'use strict';
// malicious code
console.log(window, document, globalThis); // null, null, null
(async () => {
await new Promise(r => setTimeout(function() {
window = this;
document = this.document;
globalThis = this;
r();
}, 1));
console.log(window, document, globalThis);
})()
})(null, null, null)
Is already enough to fill the vars again with the original values.
There are several other ways to get the original window. You could create an iframe-element with src="about:blank"
, append it to the DOM and access the iframe.contentWindow.parent
property. Which will be the original window
again.
((window) => { // in case document is not null'd
let iframe = document.createElement("iframe");
iframe.src = "about:blank";
document.body.append(iframe);
console.log(iframe.contentWindow.parent == globalThis);
})(null)
And if you block to much, nothing would be possible anymore.
You could also make use of workers. They are not allowed to access the DOM and/or Cookies/Storage.
Upvotes: 2
Reputation: 1073968
here is one way that i think which can suffice all the purposes
No, that's not remotely sufficient. I suggest reading up on the Content Security Policy.
You don't need infinite subdomains, but you do need a domain dedicated to just this user-provided code. Then put the code in an iframe
with sandbox options. For instance, here's the iframe
that Stack overflow's Stack Snippets use:
<iframe
id="snpte-box-edit-result"
name="071f00d0-f927-46e0-a9c5-872b42751f46"
sandbox="allow-forms allow-modals allow-scripts"
class="snippet-box-edit snippet-box-result"
frameborder="0"
></iframe>
That's served from https://stacksnippets.net
, not stackoverflow.com
.
The key bits there are:
sandbox
attribute activating the content security policy (CSP) and passlisting only the things Snippets should allow (forms, modals, and scripts). Everything else is blocked by default.(I think serving it via HTTPS is also important. It's best practice in any case.)
Doing that does not guarantee that malicious code won't run (you are, after all, explicitly allowing it to run). But it tries to restrict the things the malicious code can do.
Upvotes: 4