The eval()
function in JavaScript takes a string as an argument and executes it as Javascript source code. Consider the following examples:
// This user input causes an infinite loop to run const user_input = "while(true) ;"; eval(user_input);
// This user input closes the application const user_input = "process.exit(0)"; eval(user_input);
The functions, setInterval()
, setTimeout()
, and new Function()
use eval()
in their implementations, and should be used with the same caution.
We might be able to mitigate this risk with npm
packages like safe-eval
and expression-eval
. Both allow us to limit which methods and properties are available to eval()
. Strings passed to safe-eval
must be an expression, not a statement. This prevents injected code from being executed. The code below, for example, will throw an error since it does not have access to the process
object.
// Using safeEval will throw an error const user_input = "process.exit(0)"; safeEval(user_input);
Take a look at their documentation for more examples!
Note: While packages like
safe-eval
may be safer than usingeval
, they may still contain vulnerabilities.
Best practices with eval
are:
- Avoid using it altogether!
- If you must use it, use a safer version, and only allow trusted, non-user input.
You should always do your own research when exploring packages to use in your applications.
Instructions
Run the provided web application with the terminal command node app.js
. You may need to refresh the integrated browser window afterward.
This web application takes a JavaScript expression and executes it using the eval
function. You are welcome to try any JavaScript statements. We recommend 2+2
, Date.now()
, console.log(process.env)
, or even process.exit(0)
.
Click Check Work to move on to the next checkpoint and make this application safer.
In app.js, import the default export from the safe-eval
package into safeEval
and click Check Work.
On line 19 in app.js, replace the instance of eval
with safeEval
and click Check Work.
Restart the application in the terminal using CTRL / CMD + C and running the node app.js
command again.
Congrats! You made our application a little safer from arbitrary code execution attacks. Feel free to try out the same commands as you did in the first checkpoint with this updated code.
Move on to the next exercise when ready!