|
| 1 | +# MIT License |
| 2 | + |
| 3 | +# Copyright (c) 2022 Yaroslav Polyakov |
| 4 | + |
| 5 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 6 | +# of this software and associated documentation files (the "Software"), to deal |
| 7 | +# in the Software without restriction, including without limitation the rights |
| 8 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 9 | +# copies of the Software, and to permit persons to whom the Software is |
| 10 | +# furnished to do so, subject to the following conditions: |
| 11 | + |
| 12 | +# The above copyright notice and this permission notice shall be included in all |
| 13 | +# copies or substantial portions of the Software. |
| 14 | + |
| 15 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 16 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 17 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 18 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 19 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 20 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 21 | +# SOFTWARE. |
| 22 | + |
| 23 | +"""Safe user-supplied python expression evaluation.""" |
| 24 | + |
| 25 | +import ast |
| 26 | +import dataclasses |
| 27 | + |
| 28 | +__version__ = '2.0.3' |
| 29 | + |
| 30 | + |
| 31 | +class EvalException(Exception): |
| 32 | + pass |
| 33 | + |
| 34 | + |
| 35 | +class ValidationException(EvalException): |
| 36 | + pass |
| 37 | + |
| 38 | + |
| 39 | +class CompilationException(EvalException): |
| 40 | + exc = None |
| 41 | + |
| 42 | + def __init__(self, exc): |
| 43 | + super().__init__(exc) |
| 44 | + self.exc = exc |
| 45 | + |
| 46 | + |
| 47 | +class ExecutionException(EvalException): |
| 48 | + exc = None |
| 49 | + |
| 50 | + def __init__(self, exc): |
| 51 | + super().__init__(exc) |
| 52 | + self.exc = exc |
| 53 | + |
| 54 | + |
| 55 | +@dataclasses.dataclass |
| 56 | +class EvalModel: |
| 57 | + """eval security model.""" |
| 58 | + |
| 59 | + nodes: list = dataclasses.field(default_factory=list) |
| 60 | + allowed_functions: list = dataclasses.field(default_factory=list) |
| 61 | + imported_functions: dict = dataclasses.field(default_factory=dict) |
| 62 | + attributes: list = dataclasses.field(default_factory=list) |
| 63 | + |
| 64 | + def clone(self): |
| 65 | + return EvalModel(**dataclasses.asdict(self)) |
| 66 | + |
| 67 | + |
| 68 | +class SafeAST(ast.NodeVisitor): |
| 69 | + """AST-tree walker class.""" |
| 70 | + |
| 71 | + def __init__(self, model: EvalModel): |
| 72 | + self.model = model |
| 73 | + |
| 74 | + def generic_visit(self, node): |
| 75 | + """Check node, raise exception if node is not in whitelist.""" |
| 76 | + if type(node).__name__ in self.model.nodes: |
| 77 | + |
| 78 | + if isinstance(node, ast.Attribute): |
| 79 | + if node.attr not in self.model.attributes: |
| 80 | + raise ValidationException( |
| 81 | + 'Attribute {aname} is not allowed'.format( |
| 82 | + aname=node.attr)) |
| 83 | + |
| 84 | + if isinstance(node, ast.Call): |
| 85 | + if isinstance(node.func, ast.Name): |
| 86 | + if node.func.id not in self.model.allowed_functions and \ |
| 87 | + node.func.id not in self.model.imported_functions: |
| 88 | + raise ValidationException( |
| 89 | + 'Call to function {fname}() is not allowed'.format( |
| 90 | + fname=node.func.id)) |
| 91 | + else: |
| 92 | + # Call to allowed function. good. No exception |
| 93 | + pass |
| 94 | + elif isinstance(node.func, ast.Attribute): |
| 95 | + pass |
| 96 | + # print("attr:", node.func.attr) |
| 97 | + else: |
| 98 | + raise ValidationException('Indirect function call') |
| 99 | + |
| 100 | + ast.NodeVisitor.generic_visit(self, node) |
| 101 | + else: |
| 102 | + raise ValidationException( |
| 103 | + 'Node type {optype!r} is not allowed. (whitelist it manually)'.format( |
| 104 | + optype=type(node).__name__)) |
| 105 | + |
| 106 | + |
| 107 | +base_eval_model = EvalModel( |
| 108 | + nodes=[ |
| 109 | + # 123, 'asdf' |
| 110 | + 'Num', 'Str', |
| 111 | + # any expression or constant |
| 112 | + 'Expression', 'Constant', |
| 113 | + # == ... |
| 114 | + 'Compare', 'Eq', 'NotEq', 'Gt', 'GtE', 'Lt', 'LtE', |
| 115 | + # variable name |
| 116 | + 'Name', 'Load', |
| 117 | + 'BinOp', |
| 118 | + 'Add', 'Sub', 'USub', |
| 119 | + 'Subscript', 'Index', # person['name'] |
| 120 | + 'BoolOp', 'And', 'Or', 'UnaryOp', 'Not', # True and True |
| 121 | + 'In', 'NotIn', # "aaa" in i['list'] |
| 122 | + 'IfExp', # for if expressions, like: expr1 if expr2 else expr3 |
| 123 | + 'NameConstant', # for True and False constants |
| 124 | + 'Div', 'Mod' |
| 125 | + ], |
| 126 | +) |
| 127 | + |
| 128 | + |
| 129 | +mult_eval_model = base_eval_model.clone() |
| 130 | +mult_eval_model.nodes.append('Mul') |
| 131 | + |
| 132 | + |
| 133 | +class Expr(): |
| 134 | + def __init__(self, expr, model=None, filename=None): |
| 135 | + |
| 136 | + self.expr = expr |
| 137 | + self.model = model or base_eval_model |
| 138 | + |
| 139 | + try: |
| 140 | + self.node = ast.parse(self.expr, '<usercode>', 'eval') |
| 141 | + except SyntaxError as e: |
| 142 | + raise CompilationException(e) |
| 143 | + |
| 144 | + v = SafeAST(model=self.model) |
| 145 | + v.visit(self.node) |
| 146 | + |
| 147 | + self.code = compile(self.node, filename or '<usercode>', 'eval') |
| 148 | + |
| 149 | + def safe_eval(self, ctx=None): |
| 150 | + |
| 151 | + try: |
| 152 | + result = eval(self.code, self.model.imported_functions, ctx) |
| 153 | + except Exception as e: |
| 154 | + raise ExecutionException(e) |
| 155 | + |
| 156 | + return result |
| 157 | + |
| 158 | + def __str__(self): |
| 159 | + return ('Expr(expr={expr!r})'.format(expr=self.expr)) |
0 commit comments