Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

DaNeil C
DaNeil C

Posted on

     

The Evil JavaScript eval()

So you need to handle some user input

The Evil eval()

eval() is a global function in JavaScript that evaluates a string of code and executes it. Theeval() function is fast and "invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parentheses to avoid tripping on an ambiguity in JavaScript’s syntax.

var myObject = eval(‘(‘ + myJSONtext + ‘)’);
” (6)

Below is a simple string of "a + b" and you can see that theeval() function does the math for it and will output "4". It's pretty handy if you need to evaluate some code on the fly.

var a = 2; var b = 2;console.log(eval('a + b'));// output: 4
Enter fullscreen modeExit fullscreen mode

Where is eval() used?

Because data received from a web server is always a string theeval() function is commonly used to convert the strings received from a web server into a JSON object.

var str = '({"firstName":"John","lastName":"Smith"})';var obj = eval(str);obj.firstName; // John
Enter fullscreen modeExit fullscreen mode

What is a JSON object?

In case you don't already know, JavaScript Object Notation (JSON) is a file format, and data interchange format, that uses human-readable text to store and transmit data objects, consisting of key/value pairs and array data types, to make it easier for machines to parse and generate.

Why is the eval() function evil?

The JavaScripteval() function is great because it doesn't differentiate between a JavaScript expression, variable, statement, or sequence of statements.... but this is also why it is evil as it will also execute any code it's passed with the privileges of the sender.

foo = 2;eval('foo = foo + 2;alert(foo);');
Enter fullscreen modeExit fullscreen mode

Because theeval() function doesn't care what it's evaluating it becomes dangerous if you useeval() on a string that could be modified by a malicious user. This runs the risk of running malicious code on the user's machine with the permissions of your webpage/extension.
Theeval() function is also evil because any third-party code can see the scope in whicheval() was invoked, which can lead to possible attacks. (4)

If your website uses theeval() function to display user names from an input box display the name in an alert box or search the database for the user's name, this could be leveraged to display files on the server the malicious user shouldn't have access to.

Say your function that handles usernames might look like:

var str = '({"firstName":"John","lastName":"Smith"})';var obj = eval(str);eval('alert("Welcome Back: " + obj.firstName.);');Output: John
Enter fullscreen modeExit fullscreen mode

A malicious user could not put in their name but instead puts/etc/passwd, a file or other sensitive files could be displayed instead of their name.

var str = '({"firstName":"fs.readFileSync('cat /etc/passwd')+''","lastName":"Smith"})';
var obj = eval(str);
eval('alert("Welcome Back: " + obj.firstName.);');

Output: tom:x:1000:1000:Vivek Gite:/home/vivek:/bin/bash

Enter fullscreen modeExit fullscreen mode




Fear not! There is an alternative, json.parse()

Though botheval() andjson.parse() can take a JSON string and then transform it into a JavaScript object,json.parse() is safer to use because theeval() function will execute js wherejson.parse() will only process valid JSON string representations into a JavaScript value or JSON object.json.parse() will throw an error if invalid JSON strings are passed to it.

const myPets = {
dog: 0,
cat: 2,
koala: "I wish",
total: 2
};

console.log(JSON.stringify(myPets));
// result: {"dog":0,"cat":2,"koala":"I wish","count":2}

console.log(JSON.parse(JSON.stringify(myPets)));
// result: Object {dog: 0, cat: 2, koala: "I wish", count: 2}

Enter fullscreen modeExit fullscreen mode




Stay Safe

Remember, the use ofJSON.parse() is the best choice if the data being processed is coming from an untrusted source, but it is not the only thing that needs to be done to protect against untrusted data. Don't forget to use safe parameterized interfaces with strong typing and to always validate/sanitize and encode untrusted input.


Happy Hacking

Resources:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
  2. https://en.wikipedia.org/wiki/JSON
  3. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON
  4. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
  5. https://www.geeksforgeeks.org/converting-json-text-to-javascript-object/
  6. http://www.json.org/js.html
Please Note: that I am still learning and if something that I have stated is incorrect please let me know. I would love to learn more about what I may not understand fully.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I write to better educate myself as I go through CTFs and Bug Bounties. If anything I have written is incorrect, please let me know and send me a link to an article to read to better educate myself.
  • Location
    Seattle
  • Education
    Information Technology BA and Software Engineering Bootcamp Grad
  • Work
    Security Engineer/Researcher Performing Responsible Disclosure
  • Joined

More fromDaNeil C

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp