File size: 584 Bytes
8651b0d
 
 
b64e0d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8651b0d
 
 
 
 
 
 
b64e0d2
8651b0d
 
 
b64e0d2
8651b0d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import ast

SAFE_NODES = (
    ast.Module,
    ast.Assign,
    ast.Expr,
    ast.Call,
    ast.Name,
    ast.Load,
    ast.Constant,
    ast.BinOp,
    ast.Add,
    ast.Sub,
    ast.Mult,
    ast.Div,
    ast.Return,
    ast.FunctionDef,
    ast.arguments
)

def safe_execute(code):
    tree = ast.parse(code)

    for node in ast.walk(tree):
        if not isinstance(node, SAFE_NODES):
            raise ValueError(f"Unsafe code detected: {type(node).__name__}")

    local_env = {}
    exec(compile(tree, "<sandbox>", "exec"), {"__builtins__": {}}, local_env)

    return local_env