|
35 | 35 | import os |
36 | 36 | import json |
37 | 37 | import shlex |
| 38 | +import ast |
| 39 | +import operator |
| 40 | + |
| 41 | + |
| 42 | +# Operators allowed when evaluating arithmetic from an untrusted linker script. |
| 43 | +_SAFE_OPS = { |
| 44 | + ast.Add: operator.add, ast.Sub: operator.sub, |
| 45 | + ast.Mult: operator.mul, ast.Div: operator.floordiv, |
| 46 | + ast.Mod: operator.mod, ast.LShift: operator.lshift, |
| 47 | + ast.RShift: operator.rshift, ast.BitOr: operator.or_, |
| 48 | + ast.BitAnd: operator.and_, ast.BitXor: operator.xor, |
| 49 | + ast.USub: operator.neg, ast.UAdd: operator.pos, |
| 50 | +} |
| 51 | + |
| 52 | + |
| 53 | +def safe_eval_int(expr): |
| 54 | + """Evaluate an integer arithmetic expression without executing code. |
| 55 | +
|
| 56 | + A crash bundle's linker.cmd is attacker-controllable, so its MEMORY |
| 57 | + expressions must never be passed to eval(). Only integer literals and |
| 58 | + basic arithmetic operators are accepted; anything else raises ValueError. |
| 59 | + """ |
| 60 | + def _eval(node): |
| 61 | + if isinstance(node, ast.Expression): |
| 62 | + return _eval(node.body) |
| 63 | + if isinstance(node, ast.Constant): |
| 64 | + if isinstance(node.value, int): |
| 65 | + return node.value |
| 66 | + raise ValueError("non-integer constant") |
| 67 | + if isinstance(node, ast.BinOp) and type(node.op) in _SAFE_OPS: |
| 68 | + return _SAFE_OPS[type(node.op)](_eval(node.left), _eval(node.right)) |
| 69 | + if isinstance(node, ast.UnaryOp) and type(node.op) in _SAFE_OPS: |
| 70 | + return _SAFE_OPS[type(node.op)](_eval(node.operand)) |
| 71 | + raise ValueError("unsupported expression") |
| 72 | + |
| 73 | + return _eval(ast.parse(expr, mode='eval')) |
38 | 74 |
|
39 | 75 | XTENSA_EXCCAUSE = { |
40 | 76 | 0: "No Error (or IllegalInstruction)", |
@@ -151,8 +187,8 @@ def parse_linker_cmd(filepath): |
151 | 187 | org_expr = m_org.group(1).strip() |
152 | 188 | len_expr = m_len.group(1).strip() |
153 | 189 | try: |
154 | | - org_val = eval(org_expr) |
155 | | - len_val = eval(len_expr) |
| 190 | + org_val = safe_eval_int(org_expr) |
| 191 | + len_val = safe_eval_int(len_expr) |
156 | 192 | # Ignore debug regions |
157 | 193 | if not (name.startswith('.debug') or name.startswith('.stab')): |
158 | 194 | regions.append({'name': name, 'start': org_val, 'end': org_val + len_val}) |
|
0 commit comments