Home > Backend Development > Python Tutorial > How Secure Is Using Python\'s `eval()` with Untrusted Strings?

How Secure Is Using Python\'s `eval()` with Untrusted Strings?

Susan Sarandon
Release: 2024-11-27 01:36:10
Original
269 people have browsed it

How Secure Is Using Python's `eval()` with Untrusted Strings?

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:

  • Sanitize input to remove potentially harmful code.
  • Use a RestrictedExecutionEnvironment to limit the scope of code execution.
  • Transfer data using a secure serialization format that does not allow arbitrary code execution.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template