Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
102 changes: 102 additions & 0 deletions bionetgen/core/utils/safe_expr.py
Original file line number Diff line number Diff line change
@@ -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
27 changes: 5 additions & 22 deletions bionetgen/modelapi/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down
14 changes: 3 additions & 11 deletions bionetgen/network/blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
86 changes: 86 additions & 0 deletions tests/test_safe_expr.py
Original file line number Diff line number Diff line change
@@ -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 = """<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level3" level="3" version="1">
<model id="toy">
<ListOfParameters>
<Parameter id="k1" type="Constant" value="1"
expr="{expr}"/>
</ListOfParameters>
</model>
</sbml>
"""


def _payload(marker):
# open(...).write(...) creates the marker file if the expression is ever evaluated.
return "open(&apos;{}&apos;, &apos;w&apos;).write(&apos;x&apos;) 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
Loading