Code Smell 245 - exec() and eval()
Tags: webdev, beginners, programming, python
Published: 2024-04-04 00:00:20

*A great door for hackers*

> TL;DR: Don't use metaprogramming. It is not that cool

# Problems

- Security

- Limited Control 

# Solutions

1. Use direct calls 

2. Wrap the execution in a primitive and controlled command

3. Sanitize it 

# Context

Developers employ the eval() and exec() functions to evaluate arbitrary expressions from strings.

They can be a powerful tool in certain contexts but come with several risks and problems, especially when used with untrusted input or where the code's behavior is not fully controlled or understood. 

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/234f3b1d3a82bfc9bba82d8bb0af642c)
```python
def calculate(mathOperand, firstArgument, secondArgument):
    return eval(f'{firstArgument} {mathOperand} {secondArgument}')

# Sample usage to multiply two numbers
result = calculate('*', 4, 6)

# Injection to remove all files
calculate('', "__import__('os').system('rm -rf *')",''))
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/c805ea4caee48b9ce7b37c2dcec0a594)
```python
def calculate(mathOperand, firstArgument, secondArgument):
    if mathOperand == '+':
        return firstArgument + secondArgument
    elif mathOperand == '-':
        return firstArgument - secondArgument
    elif mathOperand == '*':
        return firstArgument * secondArgument
    elif mathOperand == '/':
        if secondArgument != 0:
            return firstArgument / secondArgument
        else:
            return "Error: Division by zero"
    else:
        return "Error: Invalid operation - Do not hack!"
        
# This is a quick solution but another smell
# You should avoid this kind of switches and iterate to 
# a Polymorphic Hierarchy
```

# Detection

[X] Automatic 

You can search for eval() in the code

# Tags

- Metaprogramming

# Level

[x] Intermediate

# AI Assistants

Most AI Assistants avoid using eval() in their solutions. 

They also recognize it as a code smell and offer different options

# Conclusion

Avoid this metaprogramming solution by hardcoding all the possible scenarios and avoiding over-generalizations.

# Relations

{% post https://dev.to/mcsee/code-smell-207-dynamic-methods-4a1g %}

{% post https://dev.to/mcsee/code-smell-189-not-sanitized-input-853 %}

{% post https://dev.to/mcsee/code-smell-215-deserializing-object-vulnerability-3hbj %}

# More Info

{% post https://dev.to/mcsee/laziness-i-meta-programming-32a9 %}

# Disclaimer

Code Smells are my [opinion](https://dev.to/mcsee/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned-1n3a).

# Credits

Photo by [Yang](https://unsplash.com/@yangshuo) on [Unsplash](https://unsplash.com/photos/wall-with-red-gate-16Y4sHHe9xY)   
  
* * *

> When you actually sit down to write some code, you learn things that you didn’t get from thinking about them in modeling terms…there is a feedback process there that you can only really get at from executing some things and seeing what works.

_Martin Fowler_
  
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}