r/TechNook • u/Ok_Yogurtcloset8372 • 1d ago
Can a web app safely run arbitrary user-submitted JavaScript without breaking its CSP?
These sites, including CodePen, JSFiddle and a number of browser developer playgrounds, allow users to compose and run any JavaScript within a browser window, but also prevent attackers from hijacking session cookies, stealing local storage, or cross-site scripting attacks against the parent site.
From the perspective of code isolation, what is their approach to isolating the execution? Do they need a web worker or server-side headless browser isolation to ensure that executing untrusted code on the client is done safely, or is it sufficient to simply run the user script from a completely new (or null) origin, strict sandboxing, and zero script permissions for the parent frame?
1
u/Laziness100 15h ago
Honestly, you got me curious how our university's bash shell learning ground works, as it works in basically the same way on the surface.
My educated guess for now is, they run it in a VM (likely a very lightweight, customizable linux distro) and compare the output of the script with output and state of the VM (ie. does the console output match precisely what is expected for specific testing data? Any errors? Leftover files? Did it finish in time? etc...). It might sound like overkill, but some sandboxing is certainly needed for user-submitted scripts, be it JS or Bash, as you will eventually get attempts to break in and there's no value in breaking into a VM that exists for 45 seconds at most.
1
u/ohkendruid 2m ago
There are sandbox options for sure.
To run on the server, Docker is a pretty good way. Docket containers are fast to start and to throw away, and they have very good isolati9n from the host machine.
I would guess sites like that tend to run the code in the user's browser. So, the site itself is going to be safe from the code. Anything code in a browser can do, the user could have already done, without even using a browser.
How about protection of the user, though? If the user copied the code from somewhere else and runs out, how are they safe from that code stealing info from their browser and generally causing havoc?
I do not know the state of the art, but there are sandboxes for that, too. Some of them were developed for running ads with JavaScript in a way that protects the user. One of them is called Caja ("box" in Spanish). That technology rewrites the JS before running it, in such a way that it can do what it wants if it behaves well, but where certain sensitive operations will be impossible for it.