google-deepmind / google-deepmind/gemma

Replace unsafe eval() usage in Calculator tool

Open
#469 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
5.7k
Forks
1k
Avg merge
10h 33m
Merged PRs (30d)
2

Description

PR: [#470 ](https://github.com/google-deepmind/gemma/pull/470)

Problem:

The Calculator tool in gemma/gm/tools/_calculator.py uses eval() to evaluate mathematical expressions, which is a security risk. eval() can execute arbitrary Python code, making it vulnerable to code injection attacks.
Current code:

return eval(expression, _OPS) # pylint: disable=eval-used

Solution:
Replace eval() with a safe AST-based expression evaluator that:
Parses expressions using Python's ast module
Only allows safe AST node types (Expression, BinOp, UnaryOp, Constant, Name, Call)
Restricts function calls to operations defined in _OPS dictionary
Rejects unsafe operations (attribute access, imports, comprehensions, etc.)

Implementation:
Added _SafeEvaluator class that extends ast.NodeVisitor to safely traverse and evaluate AST nodes
Added _safe_eval() helper function for parsing and error handling
Updated Calculator.call() to use the safe evaluator instead of eval()
This maintains backward compatibility while removing the security vulnerability. All existing mathematical operations (+, -, , /, functions from _OPS) continue to work as before.

review PR for implementation details

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.