+ 2

Why is eval() "unsafe" to use in JavaScript?

I saw some people said it is "unsafe" to use and should avoid from it, is it true and why is that??

27th Dec 2024, 4:13 PM
☕︎︎AstroParrot✦
☕︎︎AstroParrot✦ - avatar
4 Respostas
+ 9
Generally speaking eval() allows you to execute arbitrary JavaScript code within your application. This opens a significant security vulnerability. If your application receives input from untrusted sources (like raw_user_input, external APIs, etc.), attackers can inject malicious code into that input. When eval() executes this input, it can: • Steal sensitive data • Modify application behavior • Cause Denial of Service (DoS)
27th Dec 2024, 5:22 PM
BroFar
BroFar - avatar
+ 5
BroFar thanks a lot!
27th Dec 2024, 5:25 PM
☕︎︎AstroParrot✦
☕︎︎AstroParrot✦ - avatar
+ 3
I made a web application recently where I used eval(), an I realized that I had to disable the input field after I published it here on SL, because I found out, that I could execute the alert() popup box. It was a Calculator. The alternative is to rewrite it without using eval(), but I think it's safe now, since the users only can use the buttons for input, and not raw input from the keyboard, and it doesn't makes API requests either. BroFar What is your opinion about that?
27th Dec 2024, 7:51 PM
Jan
Jan - avatar
+ 3
Jan the more you can avoid using eval(), the better. While restricting input through buttons is a good start, it's crucial to implement robust safeguards. Encapsulate your calculation logic within a well-defined function and rigorously validate all input within that function. Double- and even triple-check that input from buttons adheres to strict rules and only allows expected values. Remember, even seemingly minor vulnerabilities can be exploited. Instead of relying on eval(), consider alternative approaches like using a mathematical library or constructing functions dynamically using new Function() with careful consideration for security implications.
27th Dec 2024, 8:18 PM
BroFar
BroFar - avatar