Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute code that a user inputs into my ACE editor on my page

I am using ACE Editor as my text editor on my page and the user will type in it code.

  1. I am looking to execute code that has been entered by the user on or in the browser if possible. How do I get the input from the editor and utilize the Browsers V8 JavaScript compiler with it?

  2. I am then going to try to run it on a Node.js but first I have to learn Node :).

like image 542
inoabrian Avatar asked Mar 27 '14 21:03

inoabrian


People also ask

What is ace in coding?

An arbitrary code execution (ACE) stems from a flaw in software or hardware. A hacker spots that problem, and then they can use it to execute commands on a target device.


1 Answers

It's relatively simple to grab some user entered code and run it, with JavaScript. Essentially, you'll grab the code from ACE:

var code = editor.getValue();

Then use javascript to run it. At the simplest level you can just do:

eval(code);

However, you probably don't want to use eval(). Instead you might do something like:

// grabbed from https://stackoverflow.com/questions/6432984/adding-script-element-to-the-dom-and-have-the-javascript-run
var script = document.createElement('script');
try {
  script.appendChild(document.createTextNode(code));
  document.body.appendChild(script);
} catch (e) {
  script.text = code;
  document.body.appendChild(script);
}

This will work. However, it will still cause some problems, as then, the user code could affect your environment. In this scenario, it may not be terrible from a security perspective (unless the user can share their code), but it would be confusing. For that reason, you'll want to sandbox your code.

This answer explains sandboxing client side javascript, using window.postMessage, you could send javascript to the sandboxed iframe and have it be evaluated there.

If you wish to bring this server-side and execute Node code, you'll need to do sandboxing differently. On a server, sandboxing is much more of a concern, as the user gets to do a lot more with Javascript and could maliciously interact with your server. Luckily, there are a few sandboxes for Node that should help.

like image 87
Nick Q. Avatar answered Sep 28 '22 11:09

Nick Q.