Vulnerability issues with Python eval() Function

Python3




def secret_function():
  return "Secret key is 1234"
 
def solve_expression():
  # expecting input expression
  # containing mathematical operations using x
  expression = input("Enter the function(in terms of x):")
   
  # variable to be used inside expression
  x = input("Enter the value of x:")
   
  # print result of expression evaluated
  print("result:", eval(expression))
   
solve_expression()


Our current version of solve_expression has a few vulnerabilities. The user can easily expose hidden values in the program or call a dangerous function, as eval will execute anything passed to it.

For example, if you input like this:

Enter the function(in terms of x):secret_function()
Enter the value of x:0

You will get the output:

result: Secret key is 1234

Also, consider the situation when you have imported the os module into your Python program. The os module provides a portable way to use operating system functionalities like reading or writing a file. A single command can delete all files in your system. Of course, in most cases (like desktop programs) the user can’t do any more than they could do by writing their own Python script, but in some applications (like web apps, kiosk computers), this could be a risk!

The solution is to restrict eval to only the functions and variables we want to make available.

eval in Python

Python eval() function parse the expression argument and evaluate it as a Python expression and runs Python expression (code) within the program.

Similar Reads

Python eval() Function Syntax

Syntax: eval(expression, globals=None, locals=None) Parameters: expression: String is parsed and evaluated as a Python expression globals [optional]: Dictionary to specify the available global methods and variables. locals [optional]: Another dictionary to specify the available local methods and variables. Return: Returns output of the expression....

eval() Function in Python Example

Python3 print(eval('1+2')) print(eval("sum([1, 2, 3, 4])"))...

Evaluating Expressions using Python’s eval()

...

Vulnerability issues with Python eval() Function

...

Making eval() safe

Evaluate Mathematical Expressions in Python...