Fix calculator tool security vulnerability #506
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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
_OPSdictionary, 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:
_safe_globalsdictionary is created during initialization.mathmodule and safe built-in operations are included.'__builtins__': {}, access to dangerous functions such as__import__,exec,compile, and other potential attack vectors is fully prevented.Testing
The calculator has been tested with a wide range of inputs, including:
All legitimate mathematical expressions evaluate correctly, while potentially dangerous inputs are safely rejected without executing arbitrary code.
References
eval()security vulnerability pattern documented in CWE-94 (Code Injection)