3p1i4
3p1i4

Reputation: 51

Check if javascript source is using prohibited functions

I want to run user provided javascript on site, but before doing so, I need to (algorithmically) check if provided javascript source follows set of rules (e.g.not using eval() function, not using setTimeout()/setInterval() functions, etc.).

Nice thing in addition would be to check if source is valid. Tool for this could be anything, since executed server-side. Do you have any ideas what may be useful for this ?

edit: code will be executed in web worker environment

Upvotes: 0

Views: 134

Answers (3)

Brad
Brad

Reputation: 163438

It isn't possible to tell if a script is going to use a prohibited function by simply scanning through the source code. You have the change the environment the script executes in.

What you're doing is not a simple text search. JavaScript is a very dynamic language, and you could effectively call a "prohibited" function without having the name of that function in the source code at all!

window['e'+'v'+'a'+'l']

It also isn't possible to simply execute the script and track which functions are accessed, as you won't be able to hit all code paths.

To prohibit usage of specific functions, you must run the code in a sandbox where those functions do not exist.

Upvotes: 2

PleaseStand
PleaseStand

Reputation: 32112

If the JavaScript is running in a web browser, execute it on a page loaded from a separate domain ("exampleusercontent.com") in an iframe. Then use window.postMessage() to allow communication with the parent window (from "example.com"). This is more or less the way Facebook Apps work.

The untrusted JavaScript will, unfortunately, be able to do things such as redirecting the user to another Web site or hanging the user's browser; however, it should not be able to inject code into "example.com" or steal the user's "example.com" cookies.

For actually prohibiting certain functions in the way you are thinking of, Google Caja is an open-source compiler for sandboxing third-party JavaScript, although from time to time, someone has discovered a vulnerability in it.

Upvotes: 0

Michael Lorton
Michael Lorton

Reputation: 44406

If you are running it server side (on Node.js or Rhino or something like that), you have control of the global namespace. Take eval and setTimeout out of it.

Upvotes: 1

Related Questions