2

I found some answers, but very old one and I wondered how can it be done?

I've seen that eval() function isn't safe:

Alternate for eval() to execute auto-generated JS code from the server

So what are my options in order to run a javascript code in isolated secured way?

Dorki
  • 1,021
  • 2
  • 8
  • 23
  • https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string look at here – Alp Eren Gül May 30 '20 at 21:02
  • If it was totally isolated, you wouldn't need to run it. What is the problem you are trying to solve? – Bergi May 30 '20 at 21:02
  • @Bergi I want to build an app that allow you to share code and execute it. – Dorki May 30 '20 at 21:03
  • 3
    @Dorki Users running code that is shared by other users is inherently unsafe. Don't do that. If you take a look at how all the code sharing platforms work (including things like StackSnippets): they serve the code on a separate domain and sandbox it in an iframe protected by the SOP. – Bergi May 30 '20 at 21:04
  • Why not load external JS files with xmlhttprequest? You should also have some sort of backend filter that makes sure no unsafe functions or libraries are used. – hewiefreeman May 30 '20 at 21:04
  • @Bergi stackoverflow's website has the feature to execute javascript code, maybe something related to iframe or isolated environment? – Dorki May 30 '20 at 21:05
  • @hewiefreeman Is there a well-known library that does that already? – Dorki May 30 '20 at 21:06
  • @Dorki Ah, I was still editing my comment :-) Yes, they use iframes. They do not "run code from a string". – Bergi May 30 '20 at 21:08
  • @Bergi ohhh, that's a bit cleared some fuzzy about how it works, so the question is whether using the same domain could also be secured? I mean, I could make my backend to send the string ( that should be convereted to code ) to an new url, but couldn't it be bypass or hacked with any js code? – Dorki May 30 '20 at 21:12
  • 1
    See https://stackoverflow.com/q/10653809/1048572 https://stackoverflow.com/q/22506026/1048572 https://stackoverflow.com/q/195149/1048572 https://stackoverflow.com/q/2986908/1048572 https://stackoverflow.com/q/5044608/1048572 – Bergi May 30 '20 at 21:15

1 Answers1

-1

(as pointed out, this answer is outdated and the proposed solution could be easily broken).

Currently, draft for secure ecmascript has not been approved/implemented yet. One hack that has decent browser support (proxy is es6 feature) is using proxies and with to create a sandbox.

You just have to write a proxy which returns null for every requested key except for some safe functions. with would ask the proxy every time a var outside eval is required (for example, window) and so, provide null instead of the real var.

Check this website for a tutorial: code sandbox

Luca Fabbian
  • 194
  • 6