-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Safe eval #8936
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Safe eval #8936
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
a855124
Add safe_eval Function
ericspod 58e721e
Remove eval where possible
ericspod dd97330
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] f329f15
Fixes
ericspod 420d610
Minor fixes and renaming module to avoid alias test fail
ericspod 2f083a9
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 23f9b25
Type tweak
ericspod 1ca759d
Merge branch 'safe_eval' of github.com:ericspod/MONAI into safe_eval
ericspod 274c880
Type fix
ericspod 25d302b
Picky typing issue
ericspod 3982165
Merge branch 'dev' into safe_eval
ericspod 456d069
Update docs
ericspod b722325
Experiment with expression rewriting
ericspod d336f95
Minor fix [skip ci]
ericspod 95e2334
Minor tweak
ericspod dea9fa6
Fix
ericspod d020625
Merge branch 'dev' into safe_eval
ericspod File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| # Copyright (c) MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import ast | ||
| from collections.abc import Mapping, Sequence | ||
| from typing import Any | ||
|
|
||
| import numpy as np | ||
|
|
||
| __all__ = ["SAFE_TYPES", "safe_eval"] | ||
|
|
||
| # default set of safe AST node types | ||
| SAFE_TYPES: Sequence[type] = ( | ||
| ast.Expression, | ||
| ast.Name, | ||
| ast.Load, | ||
| ast.Constant, | ||
| ast.BinOp, | ||
| ast.UnaryOp, | ||
| ast.Add, | ||
| ast.Sub, | ||
| ast.Mult, | ||
| ast.Div, | ||
| ast.FloorDiv, | ||
| ast.Pow, | ||
| ast.Mod, | ||
| ast.USub, | ||
| ast.UAdd, | ||
| ) | ||
|
|
||
|
|
||
| class _RewriteConstNp(ast.NodeTransformer): | ||
| """Replaces int and float constants in the tree with those wrapped in Numpy types.""" | ||
|
|
||
| def __init__(self, int_type_str: str, float_type_str: str): | ||
| self.int_type_str = int_type_str | ||
| self.float_type_str = float_type_str | ||
|
|
||
| def visit_Constant(self, node): | ||
| if isinstance(node.value, (int, float)): | ||
| type_str = self.int_type_str if isinstance(node.value, int) else self.float_type_str | ||
| return ast.parse(f"{type_str}({node.value})") | ||
|
|
||
| return node | ||
|
|
||
|
|
||
| def safe_eval( | ||
| expr: str, | ||
| globals_vars: Mapping[str, Any] | None = None, | ||
| locals_vars: Mapping[str, object] | None = None, | ||
| allowed_types: Sequence[type] = SAFE_TYPES, | ||
| rewrite_np: bool = False, | ||
| int_type_str: str = "np.int32", | ||
| float_type_str: str = "np.float32", | ||
| ) -> Any: | ||
| """ | ||
| Evaluate the Python expression `expr` using `eval`, but only if it is a safe expression in that its parsed AST | ||
| contains nodes whose types are given in `allowed_types`. This ensures unsafe node types are excluded, if these | ||
| are present in the AST a ValueError is raised. The default set of such types in `SAFE_TYPES` ensures only | ||
| expressions with constants and names can be evaluated, so excludes attribute access, indexing, and calls. Code | ||
| injection is infeasible through such expressions, so this is a safe and secure way of evaluating simple expressions. | ||
|
|
||
| If `rewrite_np` is True, int and float constants in the given expression will be wrapped with Numpy types as given | ||
| by `int_type_str` and `float_type_str`. These are expected to be constructor names prefixed with `np.` as Numpy | ||
| will be present in the expression global variables under that name. The values can be changed to other types if | ||
| needed, such as "int64". One advantage of doing this is to avoid denial-of-service attacks by attempting to evaluate | ||
| an expressoini which is incredibly slow under native Python but fast (though potentially erroneous) under Numpy. | ||
|
|
||
| Args: | ||
| expr: expression to evaluate, this will be stripped before parsing to avoid indentation complaints | ||
| globals_vars: global variable mapping, this will be treated as read-only for this function, unlike `eval` | ||
|
ericspod marked this conversation as resolved.
|
||
| locals_vars: local variable mapping | ||
| allowed_types: sequence of allowed AST types which can be found in `expr` when parsed | ||
| rewrite_np: if True, wrap int or float literals in Numpy types | ||
| int_type_str: int Numpy wrapping type string | ||
| float_type_str: float Numpy wrapping type string | ||
|
|
||
| Raises: | ||
| ValueError: raised when any node in the AST parsed from `expr` has a type not in `allowed_types` | ||
|
|
||
| Returns: | ||
| The evaluated expression value, using `eval` with `globals_vars` and `locals_vars` | ||
| """ | ||
| parsed = ast.parse(expr.strip(), mode="eval") | ||
|
|
||
| # collect nodes in the AST which aren't permitted and unparse them for inclusion in the exception message | ||
| disallowed = [ast.unparse(n) for n in ast.walk(parsed) if not isinstance(n, tuple(allowed_types))] | ||
|
|
||
| if disallowed: | ||
| raise ValueError(f"Unsafe expression `{expr}` not evaluated, contains disallowed components: {disallowed}") | ||
|
|
||
| if rewrite_np: | ||
| parsed = _RewriteConstNp(int_type_str, float_type_str).visit(parsed) | ||
| locals_vars = {"np": np, **(locals_vars or {})} | ||
|
|
||
| return eval(expr, dict(globals_vars) if globals_vars else None, locals_vars) | ||
|
ericspod marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| # Copyright (c) MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import ast | ||
| import unittest | ||
|
|
||
| from parameterized import parameterized | ||
|
|
||
| from monai.utils import safe_eval | ||
|
|
||
| GOOD_EXPRS = [ | ||
| ("1+2", None, None, 3), | ||
| (" 1 + 2 ", None, None, 3), | ||
| ("1+2+x", {"x": 4}, None, 7), | ||
| ("1+2+x", None, {"x": 4}, 7), | ||
| ("1*2+x", {"x": 4}, None, 6), | ||
| ("(1+2)*3", None, None, 9), | ||
| ("foo+bar", {"foo": 1030}, {"bar": 204}, 1234), | ||
| ] | ||
|
|
||
| BAD_EXPRS = [("foo()",), ("foo.bar",), ("foo[123]",), ("(1,2)",), ("[3,4]",), ("int.__class__.__init__.__globals__",)] | ||
|
|
||
|
|
||
| class TestSafeEval(unittest.TestCase): | ||
| @parameterized.expand(GOOD_EXPRS) | ||
| def test_good_exprs(self, expr, globals_vars, locals_vars, expected): | ||
| """Test valid expressions with globals/locals evaluate to correct values.""" | ||
| result = safe_eval(expr, globals_vars, locals_vars) | ||
| self.assertEqual(result, expected) | ||
|
|
||
| @parameterized.expand(GOOD_EXPRS) | ||
| def test_good_exprs_np(self, expr, globals_vars, locals_vars, expected): | ||
| """Test valid expressions with globals/locals evaluate to correct values with Numpy wrapping.""" | ||
| result = safe_eval(expr, globals_vars, locals_vars, rewrite_np=True) | ||
| self.assertEqual(result, expected) | ||
|
|
||
| @parameterized.expand(BAD_EXPRS) | ||
| def test_bad_exprs(self, expr): | ||
| """Test bad expressions correctly raise ValueError.""" | ||
| with self.assertRaises(ValueError): | ||
| safe_eval(expr) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| safe_eval(expr, rewrite_np=True) | ||
|
|
||
| def test_allowed_types(self): | ||
| """Test restricting the allowed list of types.""" | ||
| allowed = [ast.Expression, ast.Constant, ast.BinOp, ast.Add] | ||
| result = safe_eval("1+2", allowed_types=allowed) | ||
| self.assertEqual(result, 3) | ||
|
|
||
| with self.assertRaises(ValueError): | ||
| safe_eval("1*2", allowed_types=allowed) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.