Estus Flask
Estus Flask

Reputation: 223054

Possible ways to do eval

The ones that I'm aware of are eval, Function and setTimeout. Even though setImmediate reference doesn't mention that it can be called with string argument, I assume it will work the same way as setTimeoutin this regard.

What are the possible ways (including non-standard ones) to evaluate the code from a string in browsers?

Upvotes: 4

Views: 114

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1075417

On browsers, the only ones I know are:

  • eval
  • The Function constructor
  • setTimeout and related (setInterval, non-standard setImmediate)
  • Creating a script element, setting its text content, and appending it to the document (either via DOM methods, or using document.write or similar)
  • Using the javascript: pseudo-protocol on links and such (and then either clicking them artifically or inviting the user to do so)
    • Bookmarklets are a special case of this one
  • DOM0 event handlers (and then either triggering them artificially or inviting the user to do so) (nice one GOTO 0)

Live:

eval("console.log('eval');");
(0,eval)("console.log('indirect eval');");

new Function("console.log('Function constructor');")();

setTimeout("console.log('setTimeout and such');", 0);

var script = document.createElement("script");
script.textContent = "console.log('script element');";
document.body.appendChild(script);

var link = document.createElement("a");
link.href = "javascript:console.log('javascript: pseudo-protocol');";
document.body.appendChild(link);
link.click();

var div = document.createElement("div");
div.setAttribute("onclick", "console.log('DOM0 event handler');");
document.body.appendChild(div);
div.click();
/* Or to be long-winded
div.dispatchEvent(new MouseEvent("click", {
  view: window,
  bubbles: true,
  cancelable: true
}));
*/

Upvotes: 5

Emeeus
Emeeus

Reputation: 5260

non-standard one using immediate execution

<h1>

</h1>
<script></script>

$("script").html("(function(){$('h1').html('wow');})()");

There is also a non-standard way not mentioned so far here that is using wkhtmltopdf, in this way wkhtmltopdf myjscode.html all.pdf where myjscode.html is generated with fopen/cat or something taking string as argument. When pdf is executed, javascript is executed (https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/js_api_reference.pdf), also javascript is executed server side (yes). This could seems non relevant but it has big implications on security. If we're going do a pdf based in part on user inputs with wkhtmltopdf we have this problem to keep in mind.

Upvotes: 2

GOTO 0
GOTO 0

Reputation: 47881

In addition to the methods mentioned in the other answers, in a browser you could do:

document.write('<script>doSomething()</script>');
const script = document.createElement('script');
script.src = 'data:text/javascript,' + encodeURIComponent('doSomething()');
document.body.appendChild(script);

Upvotes: 1

Related Questions