Security Implications of Python's eval() with Untrusted Strings
When evaluating untrusted Python strings using eval(), several security risks arise:
1. eval(string, {"f": Foo()}, {})
This is unsafe. Through a Foo instance, one can access built-ins like "os" and "sys," potentially compromising the system.
2. eval(string, {}, {})
This is also unsafe. Even without explicitly passing a dictionary, built-ins like "len" and "list" can be used to reach other unsafe APIs.
3. Disallowing Built-ins
There is no straightforward way to entirely prevent the presence of built-ins in the eval() context. Patches to the Python interpreter would be necessary.
Additional Risks:
Malicious strings like "[0] * 100000000" can lead to resource exhaustion. Executing arbitrary expressions can compromise user data and system security.
Alternative Approaches:
Instead of using eval(), consider other methods for handling untrusted data. For example:
The above is the detailed content of How Secure Is Using Python\'s `eval()` with Untrusted Strings?. For more information, please follow other related articles on the PHP Chinese website!