diff --git a/bionetgen/core/utils/safe_expr.py b/bionetgen/core/utils/safe_expr.py new file mode 100644 index 00000000..e4ef3488 --- /dev/null +++ b/bionetgen/core/utils/safe_expr.py @@ -0,0 +1,102 @@ +"""Fold constant parameter expressions to numbers without evaluating untrusted code. + +``sympy.sympify`` on a string ends in Python ``eval``, so it must never see text taken +from a model file as is. ``fold_numeric`` first checks the expression with ``ast`` and +passes it to SymPy only if it is plain arithmetic on numbers, names and a short list of +math functions. Anything else is returned unchanged, as text. +""" + +import ast + +# Math functions that may appear in BNGL parameter expressions. +_ALLOWED_FUNCS = frozenset( + { + "exp", + "ln", + "log", + "log10", + "log2", + "sqrt", + "abs", + "Abs", + "sin", + "cos", + "tan", + "asin", + "acos", + "atan", + "sinh", + "cosh", + "tanh", + "asinh", + "acosh", + "atanh", + "min", + "max", + "Min", + "Max", + "rint", + "floor", + "ceiling", + } +) +_ALLOWED_BINOPS = (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Pow, ast.BitXor) +_ALLOWED_UNARYOPS = (ast.UAdd, ast.USub) +# Longest expression we hand to SymPy; real parameter expressions are far shorter. +_MAX_LENGTH = 1000 + + +def _is_safe(node) -> bool: + if isinstance(node, ast.Expression): + return _is_safe(node.body) + if isinstance(node, ast.Constant): + return isinstance(node.value, (int, float)) and not isinstance(node.value, bool) + if isinstance(node, ast.Name): + return not node.id.startswith("_") + if isinstance(node, ast.BinOp): + return ( + isinstance(node.op, _ALLOWED_BINOPS) + and _is_safe(node.left) + and _is_safe(node.right) + ) + if isinstance(node, ast.UnaryOp): + return isinstance(node.op, _ALLOWED_UNARYOPS) and _is_safe(node.operand) + if isinstance(node, ast.Call): + return ( + isinstance(node.func, ast.Name) + and node.func.id in _ALLOWED_FUNCS + and not node.keywords + and all(_is_safe(arg) for arg in node.args) + ) + return False + + +def is_safe_expression(text) -> bool: + """True if ``text`` is plain arithmetic that may be passed to ``sympy.sympify``.""" + if not isinstance(text, str) or len(text) > _MAX_LENGTH: + return False + try: + tree = ast.parse(text.strip(), mode="eval") + except (SyntaxError, ValueError): + return False + return _is_safe(tree) + + +def fold_numeric(text): + """Return ``text`` as a numeric string if it is a constant expression, else unchanged. + + BNGL writes powers as ``^``; SymPy reads ``^`` as a power, as before this check. + """ + if not is_safe_expression(text): + return text + try: + import sympy + + sval = sympy.sympify(text) + if sval.is_Number: + return str(float(sval)) + if sval.is_constant(): + return str(float(sval.evalf())) + except Exception: + pass + return text diff --git a/bionetgen/modelapi/blocks.py b/bionetgen/modelapi/blocks.py index a410bc3b..0c2175a4 100644 --- a/bionetgen/modelapi/blocks.py +++ b/bionetgen/modelapi/blocks.py @@ -3,6 +3,7 @@ except ImportError: from collections import OrderedDict from bionetgen.core.utils.logging import BNGLogger +from bionetgen.core.utils.safe_expr import fold_numeric from .structs import Parameter, Compartment, Observable from .structs import MoleculeType, Species, Function from .structs import Rule, Action @@ -185,17 +186,8 @@ def add_item(self, item_tpl) -> None: f"Item must be an iterable of length 2 (name, value), got {type(item_tpl)}" ) - try: - import sympy - - if hasattr(value, "value") and isinstance(value.value, str): - sval = sympy.sympify(value.value) - if sval.is_Number: - value.value = str(float(sval)) - elif sval.is_constant(): - value.value = str(float(sval.evalf())) - except Exception: - pass + if hasattr(value, "value") and isinstance(value.value, str): + value.value = fold_numeric(value.value) # allow for empty addition, uses index if name is None: name = len(self.items) @@ -260,17 +252,8 @@ def add_item(self, item_tpl) -> None: except (ValueError, TypeError): pass else: - try: - import sympy - - if hasattr(value, "value") and isinstance(value.value, str): - sval = sympy.sympify(value.value) - if sval.is_Number: - value.value = str(float(sval)) - elif sval.is_constant(): - value.value = str(float(sval.evalf())) - except Exception: - pass + if hasattr(value, "value") and isinstance(value.value, str): + value.value = fold_numeric(value.value) super().add_item(item_tpl) def __setattr__(self, name, value) -> None: diff --git a/bionetgen/network/blocks.py b/bionetgen/network/blocks.py index 985f697b..f4231099 100644 --- a/bionetgen/network/blocks.py +++ b/bionetgen/network/blocks.py @@ -3,6 +3,7 @@ except ImportError: from collections import OrderedDict from bionetgen.core.utils.logging import BNGLogger +from bionetgen.core.utils.safe_expr import fold_numeric from .structs import NetworkParameter, NetworkCompartment, NetworkGroup from .structs import NetworkSpecies, NetworkFunction, NetworkReaction from .structs import NetworkEnergyPattern, NetworkPopulationMap @@ -176,17 +177,8 @@ def __init__(self) -> None: def add_item(self, item_tpl) -> None: name, value = item_tpl - try: - import sympy - - if hasattr(value, "value") and isinstance(value.value, str): - sval = sympy.sympify(value.value) - if sval.is_Number: - value.value = str(float(sval)) - elif sval.is_constant(): - value.value = str(float(sval.evalf())) - except Exception: - pass + if hasattr(value, "value") and isinstance(value.value, str): + value.value = fold_numeric(value.value) super().add_item((name, value)) def __setattr__(self, name, value) -> None: diff --git a/tests/test_safe_expr.py b/tests/test_safe_expr.py new file mode 100644 index 00000000..f1a94308 --- /dev/null +++ b/tests/test_safe_expr.py @@ -0,0 +1,86 @@ +"""Parameter expressions from model files must not be evaluated as Python (issue #118).""" + +import pytest + +import bionetgen +from bionetgen.core.utils.safe_expr import fold_numeric, is_safe_expression + +POC_XML = """ + + + + + + + +""" + + +def _payload(marker): + # open(...).write(...) creates the marker file if the expression is ever evaluated. + return "open('{}', 'w').write('x') or 1".format( + marker + ) + + +def test_xml_parameter_expression_is_not_executed(tmp_path): + marker = tmp_path / "executed.txt" + model_file = tmp_path / "evil_model.xml" + model_file.write_text(POC_XML.format(expr=_payload(marker))) + + model = bionetgen.bngmodel(str(model_file)) + + assert not marker.exists() + assert model.model_name == "toy" + + +def test_import_payload_is_not_executed(tmp_path): + marker = tmp_path / "executed.txt" + expr = "__import__('os').system('touch {}') or 1".format(marker) + assert fold_numeric(expr) == expr + assert not marker.exists() + + +def test_xml_constant_expression_still_folds(tmp_path): + model_file = tmp_path / "ok_model.xml" + model_file.write_text(POC_XML.format(expr="2*3")) + model = bionetgen.bngmodel(str(model_file)) + assert float(model.parameters.k1.value) == 6.0 + + +@pytest.mark.parametrize( + "text, expected", + [ + ("2*3", "6.0"), + ("2^3", "8.0"), + ("1e-3", "0.001"), + ("-(4+2)/3", "-2.0"), + ("exp(0)", "1.0"), + ("sqrt(16)", "4.0"), + ("k1*2", "k1*2"), + ("NA*V", "NA*V"), + ], +) +def test_fold_numeric_arithmetic(text, expected): + assert fold_numeric(text) == expected + + +@pytest.mark.parametrize( + "text", + [ + "__import__('os').system('id')", + "open('x', 'w')", + "().__class__.__bases__", + "exp.__globals__", + "[1, 2]", + "lambda: 1", + "_hidden + 1", + "exp(x=1)", + "'a string'", + "1" * 2000, + ], +) +def test_unsafe_or_non_arithmetic_is_left_as_text(text): + assert not is_safe_expression(text) + assert fold_numeric(text) == text