Code Smell 245 — Exec() and Eval()

Written by mcsee | Published 2024/04/04
Tech Story Tags: programming | technology | clean-code | software-engineering | refactoring | refactor-legacy-code | pyhton | computer-science

TLDRDon't use metaprogramming. It is not that cool. via the TL;DR App

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

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

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

  • Automatic

You can search for eval() in the code

Tags

  • Metaprogramming

Level

  • 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

Code Smell 207 - Dynamic Methods

Code Smell 189 - Not Sanitized Input

Code Smell 215 - Deserializing Object Vulnerability

More Info

https://hackernoon.com/laziness-chapter-i-meta-programming-6s4l300e?embedable=true

Disclaimer

Code Smells are my opinion.

Credits

Photo by Yang on Unsplash


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

https://hackernoon.com/400-thought-provoking-software-engineering-quotes?embedable=true


This article is part of the CodeSmell Series.

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-i-xqz3evd?embedable=true


Written by mcsee | I’m senior software engineer specialized in declarative designs and S.O.L.I.D. and Agile lover.
Published by HackerNoon on 2024/04/04