Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible ways to do eval

Tags:

javascript

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?

like image 505
Estus Flask Avatar asked Jan 28 '23 03:01

Estus Flask


2 Answers

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
}));
*/
like image 96
T.J. Crowder Avatar answered Jan 31 '23 09:01

T.J. Crowder


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.

like image 21
Emeeus Avatar answered Jan 31 '23 07:01

Emeeus