目前有一个python的项目,想加入第三方插件开发的一个功能。 插件的形式也就是一个PY文件,但是看了python安全这块的文章后,发现python是动态的,很容易就注入到核心代码,包括各种monkeypack之类的,如何做这块才能安全呢?
PS: 现在有些在线课堂也有 在线编程的功能,他们怎么做到的安全呢?
# plug_hello.py
def hello():
print "hello world"
# load.py
import plug_hello
plug_hello.hello()
正常这样加载是没问题,但是黑客就可以注入。
# plug_hello.py
def hello():
#在 Python 2中, 内置对象可以通过魔法 __builtins__ 模块进行访问。一个已知的手段就是利用 __builtins__ 的可变性,这可能引起巨大灾难
import __builtins__
__builtins__.False, __builtins__.True = True, False
print "hello world"
黑客这样写,整个程序的True 和 False 变量就会出问题,而且黑客使用py特性还能获取和修改主程序任何运行函数类的源代码,从而进一步的注入。
I don’t understand this question either. I need to ask someone who specializes in this field
I just tell you what I think:
Since the functions of the third party are formulated by you, pre-packaging the third party requires the use of component modules. Use
sys.module
设置模块白名单,只允许第三方导入你们提供的模块,其他模块sys.module[mod] = None
to prohibit importingPS: Online programming websites all run user code in a sandbox environment. If it is destroyed, it will be destroyed. The environment is virtual anyway, so it seems to have little to do with your problem
Share one of your experiences: For example, when processing files, I am often used to taking a variable path, but I often import path from os
can be used like this:
使用ast.literal_eval(), 只允许使用 string,bytes,number,tuples,lists,discts,set,booleans,None
ast.literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
Changed in version 3.2: Now allows bytes and set literals.