Skip to content

Conversation

@markknoffler
Copy link

Summary

This PR enhances the security of the Calculator tool by implementing a hardened eval() environment that prevents remote code execution vulnerabilities.


Problem

The current implementation uses eval(expression, _OPS) with a limited set of mathematical operations. However, this approach is vulnerable to code injection attacks (CWE-94) because the restricted namespace can still be bypassed through various Python introspection techniques.

Even with a limited _OPS dictionary, an attacker could potentially access built-in functions through object introspection, method resolution order manipulation, or other Python internals, leading to arbitrary code execution.

The vulnerability exists because the second parameter to eval() only restricts the global namespace but does not completely isolate the execution environment. Python’s dynamic nature allows access to dangerous built-ins through various indirect paths, making this a critical security concern for any system that processes untrusted mathematical expressions.


Solution

This PR implements a comprehensive, security-hardened approach by explicitly setting __builtins__ to an empty dictionary, effectively blocking all built-in functions at their source.

The solution introduces several layers of defense:

  • A _safe_globals dictionary is created during initialization.
  • Only explicitly whitelisted mathematical functions from the math module and safe built-in operations are included.
  • By setting '__builtins__': {}, access to dangerous functions such as __import__, exec, compile, and other potential attack vectors is fully prevented.
  • The safe environment supports an expanded set of mathematical operations, including trigonometric functions, logarithmic functions, and mathematical constants, while maintaining strict isolation from system-level functionality.

Testing

The calculator has been tested with a wide range of inputs, including:

  • Basic arithmetic expressions
  • Advanced mathematical functions
  • Malicious payloads attempting code injection

All legitimate mathematical expressions evaluate correctly, while potentially dangerous inputs are safely rejected without executing arbitrary code.


References

Replace unsafe eval() usage with restricted environment to prevent
arbitrary code execution. Uses __init__ method to create safe_globals
that only allows mathematical functions and constants.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant