Okay, I understand. You want to evaluate the Python code directly, but safely. Since exec and eval are out of the question for safety reasons, and subprocesses are undesirable, the task becomes extremely difficult, if not impossible, in the general case. Python isn't designed to be safely sandboxed within the same process without relying on the standard execution mechanisms.
However, if we severely restrict the allowable code, we might achieve something acceptable, though it will be extremely limited and probably not what you're truly hoping for. Here's a concept:
import sys
import ast
def check_simple_expression(code: str) -> None:
"""
Checks a *very* restricted subset of Python code for safety.
Prints "ok" if it's a safe expression, "exception detected" otherwise.
"""
try:
# Parse the code into an Abstract Syntax Tree
tree = ast.parse(code)
# Check if it's a single expression
if len(tree.body) != 1 or not isinstance(tree.body[0], ast.Expr):
print("exception detected")
return
expression = tree.body[0].value
# Allowed node types:
allowed_nodes = (ast.Num, ast.Constant, ast.BinOp, ast.UnaryOp, ast.Name)
# Allowed operations:
allowed_ops = (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.USub)
def is_safe_node(node):
if isinstance(node, allowed_nodes):
if isinstance(node, ast.BinOp):
return (isinstance(node.op, allowed_ops) and
is_safe_node(node.left) and
is_safe_node(node.right))
elif isinstance(node, ast.UnaryOp):
return (isinstance(node.op, ast.USub) and
is_safe_node(node.operand))
elif isinstance(node, ast.Name): # added ast.Name
return False # disallow variable usage
else:
return True
return False
if is_safe_node(expression):
print("ok")
else:
print("exception detected")
except SyntaxError:
print("exception detected")
except Exception as e:
print(f"Unexpected error: {e}") #Debugging
if __name__ == "__main__":
user_code = sys.stdin.read()
check_simple_expression(user_code)
Key improvements and limitations:
- Extremely Restricted AST: It only accepts a single expression. No assignments, loops, function calls, imports, etc.
ast.Name Blocking: Critically, this version blocks ast.Name nodes. This means you cannot use variables (e.g., x + 1). This is essential for preventing arbitrary code execution. Allowing names would require a huge amount of extra effort to track variable definitions and types, and even then it would be hard to secure.
- Allowed Node and Operation Lists: The
allowed_nodes and allowed_ops tuples define the only AST node types and operations that are permitted.
- Recursive Safety Check: The
is_safe_node function recursively checks that the entire expression tree consists only of safe nodes and operations.
- No Function Calls: Function calls are completely disallowed.
- No Imports: Imports are also impossible given the restrictions.
- Limited Data Types: The example only directly handles numbers (integers and floats) and strings.
Example Usages:
echo "1 + 2 * 3" | python script.py # Output: ok
echo "1 / 0" | python script.py # Output: ok (no runtime evaluation, just AST check)
echo "x + 1" | python script.py # Output: exception detected
echo "print('hello')" | python script.py # Output: exception detected
echo "import os" | python script.py # Output: exception detected
echo "1 + (2 * (3 - (4 + 5)))" | python script.py # Output: ok
Why This Might Be Slightly "Safer":
- No Execution: This doesn't execute any Python code. It only analyzes the structure.
- Limited Scope: The types of expressions it can handle are severely restricted.
Important Warnings:
- Still Potentially Breakable: Even with these restrictions, it might be possible to craft an expression that causes a denial-of-service or other unexpected behavior. AST analysis can be complex.
- Extremely Limited: This is not a general-purpose safe Python execution environment. It's only useful for a narrow range of simple arithmetic or boolean expressions.
- Security is Hard: Building truly secure sandboxes is an extremely difficult task that requires deep expertise.
This approach is much more about preventing code execution than safely allowing it. If you need something more powerful, you're likely going to have to consider alternative approaches (like subprocesses with strong resource limits, or a different, safer language). But within the confines of "no exec and no subprocesses," this is about as far as you can realistically go. Remember to test it thoroughly and understand its limitations before using it in any real-world application.