pwnlib.util.safeeval — Safe evaluation of python code

pwnlib.util.safeeval.const(expression) → value[source]

Safe Python constant evaluation

Evaluates a string that contains an expression describing a Python constant. Strings that are not valid Python expressions or that contain other code besides the constant raise ValueError.

>>> const("10")
10
>>> const("[1,2, (3,4), {'foo':'bar'}]")
[1, 2, (3, 4), {'foo': 'bar'}]
>>> const("[1]+[2]")
Traceback (most recent call last):
...
ValueError: opcode BINARY_ADD not allowed
Traceback (most recent call last):
...
ValueError: opcode BINARY_ADD not allowed
pwnlib.util.safeeval.expr(expression) → value[source]

Safe Python expression evaluation

Evaluates a string that contains an expression that only uses Python constants. This can be used to e.g. evaluate a numerical expression from an untrusted source.

>>> expr("1+2")
3
>>> expr("[1,2]*2")
[1, 2, 1, 2]
>>> expr("__import__('sys').modules")
Traceback (most recent call last):
...
ValueError: opcode LOAD_NAME not allowed
Traceback (most recent call last):
...
ValueError: opcode LOAD_NAME not allowed
pwnlib.util.safeeval.test_expr(expr, allowed_codes) → codeobj[source]

Test that the expression contains only the listed opcodes. If the expression is valid and contains only allowed codes, return the compiled code object. Otherwise raise a ValueError