|
| 1 | +# Copyright (c) MONAI Consortium |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import ast |
| 15 | +from collections.abc import Mapping, Sequence |
| 16 | +from typing import Any |
| 17 | + |
| 18 | +import numpy as np |
| 19 | + |
| 20 | +__all__ = ["SAFE_TYPES", "safe_eval"] |
| 21 | + |
| 22 | +# default set of safe AST node types |
| 23 | +SAFE_TYPES: Sequence[type] = ( |
| 24 | + ast.Expression, |
| 25 | + ast.Name, |
| 26 | + ast.Load, |
| 27 | + ast.Constant, |
| 28 | + ast.BinOp, |
| 29 | + ast.UnaryOp, |
| 30 | + ast.Add, |
| 31 | + ast.Sub, |
| 32 | + ast.Mult, |
| 33 | + ast.Div, |
| 34 | + ast.FloorDiv, |
| 35 | + ast.Pow, |
| 36 | + ast.Mod, |
| 37 | + ast.USub, |
| 38 | + ast.UAdd, |
| 39 | +) |
| 40 | + |
| 41 | + |
| 42 | +class _RewriteConstNp(ast.NodeTransformer): |
| 43 | + """Replaces int and float constants in the tree with those wrapped in Numpy types.""" |
| 44 | + |
| 45 | + def __init__(self, int_type_str: str, float_type_str: str): |
| 46 | + self.int_type_str = int_type_str |
| 47 | + self.float_type_str = float_type_str |
| 48 | + |
| 49 | + def visit_Constant(self, node): |
| 50 | + if isinstance(node.value, (int, float)): |
| 51 | + type_str = self.int_type_str if isinstance(node.value, int) else self.float_type_str |
| 52 | + return ast.parse(f"{type_str}({node.value})") |
| 53 | + |
| 54 | + return node |
| 55 | + |
| 56 | + |
| 57 | +def safe_eval( |
| 58 | + expr: str, |
| 59 | + globals_vars: Mapping[str, Any] | None = None, |
| 60 | + locals_vars: Mapping[str, object] | None = None, |
| 61 | + allowed_types: Sequence[type] = SAFE_TYPES, |
| 62 | + rewrite_np: bool = False, |
| 63 | + int_type_str: str = "np.int32", |
| 64 | + float_type_str: str = "np.float32", |
| 65 | +) -> Any: |
| 66 | + """ |
| 67 | + Evaluate the Python expression `expr` using `eval`, but only if it is a safe expression in that its parsed AST |
| 68 | + contains nodes whose types are given in `allowed_types`. This ensures unsafe node types are excluded, if these |
| 69 | + are present in the AST a ValueError is raised. The default set of such types in `SAFE_TYPES` ensures only |
| 70 | + expressions with constants and names can be evaluated, so excludes attribute access, indexing, and calls. Code |
| 71 | + injection is infeasible through such expressions, so this is a safe and secure way of evaluating simple expressions. |
| 72 | +
|
| 73 | + If `rewrite_np` is True, int and float constants in the given expression will be wrapped with Numpy types as given |
| 74 | + by `int_type_str` and `float_type_str`. These are expected to be constructor names prefixed with `np.` as Numpy |
| 75 | + will be present in the expression global variables under that name. The values can be changed to other types if |
| 76 | + needed, such as "int64". One advantage of doing this is to avoid denial-of-service attacks by attempting to evaluate |
| 77 | + an expressoini which is incredibly slow under native Python but fast (though potentially erroneous) under Numpy. |
| 78 | +
|
| 79 | + Args: |
| 80 | + expr: expression to evaluate, this will be stripped before parsing to avoid indentation complaints |
| 81 | + globals_vars: global variable mapping, this will be treated as read-only for this function, unlike `eval` |
| 82 | + locals_vars: local variable mapping |
| 83 | + allowed_types: sequence of allowed AST types which can be found in `expr` when parsed |
| 84 | + rewrite_np: if True, wrap int or float literals in Numpy types |
| 85 | + int_type_str: int Numpy wrapping type string |
| 86 | + float_type_str: float Numpy wrapping type string |
| 87 | +
|
| 88 | + Raises: |
| 89 | + ValueError: raised when any node in the AST parsed from `expr` has a type not in `allowed_types` |
| 90 | +
|
| 91 | + Returns: |
| 92 | + The evaluated expression value, using `eval` with `globals_vars` and `locals_vars` |
| 93 | + """ |
| 94 | + parsed = ast.parse(expr.strip(), mode="eval") |
| 95 | + |
| 96 | + # collect nodes in the AST which aren't permitted and unparse them for inclusion in the exception message |
| 97 | + disallowed = [ast.unparse(n) for n in ast.walk(parsed) if not isinstance(n, tuple(allowed_types))] |
| 98 | + |
| 99 | + if disallowed: |
| 100 | + raise ValueError(f"Unsafe expression `{expr}` not evaluated, contains disallowed components: {disallowed}") |
| 101 | + |
| 102 | + if rewrite_np: |
| 103 | + parsed = _RewriteConstNp(int_type_str, float_type_str).visit(parsed) |
| 104 | + locals_vars = {"np": np, **(locals_vars or {})} |
| 105 | + |
| 106 | + return eval(expr, dict(globals_vars) if globals_vars else None, locals_vars) |
0 commit comments