markwylde / workerbox

A secure sandbox to execute untrusted user JavaScript, in a web browser, without any risk to your own domain/site/page.
https://workerbox.net
MIT License
123 stars 3 forks source link

Callbacks and security #23

Closed strogonoff closed 1 year ago

strogonoff commented 1 year ago

Hi and thanks for an interesting project!

Curious about the setCallback example in the README; wouldn’t calling fn() in host context be insecure? If the plugin can pass an arbitrary function, when it’s executed wouldn’t it be able to gain access to host context?

strogonoff commented 1 year ago

I mean this example:

let callback;
const scope = {
  name: 'Mark',
  getMessage: () => 'Have a great day!',
  setCallback: fn => {
    // You can store arguments, objects, arrays and returned values
    // outside of the scope of your main app, and then call them
    // from anywhere, so long as the worker is not destroyed.
    callback = fn;
  }
};

setInterval(() => {
  if (callback) {
    // This will communicate with the workerbox transparently.
    callback();
  }
});

Notably, the example doesn’t actually use setCallback() within the evaluated plugin side, so there is no further explanation…

markwylde commented 1 year ago

Hey @strogonoff, sorry for any confusion in the documentation. I'll try to explain the security of the setCallback example more clearly.

In workerbox, communication between the host window and the workerbox is done through JSON messages sent back and forth between the two. When you call setCallback, a unique ID is generated and stored in memory on both the host and the workerbox. This ID is used to reference the stored function.

When you later call the "callback" function in the host window, it doesn't directly execute the function. Instead, it sends a message to the workerbox, instructing it to execute the function associated with the unique ID (e.g., "run callback with ID XXX").

As a result, the actual execution of the untrusted code takes place within the sandboxed workerbox, keeping your main application secure. Additionally, if you were to destroy the workerbox instance, the callback function would no longer work, as the function's reference is tied to the unique ID within that particular workerbox.

strogonoff commented 1 year ago

Thanks for the explanation!