Python新型字符串格式漏洞分析

简介:

前言

本文对Python引入的一种格式化字符串的新型语法的安全漏洞进行了深入的分析,并提供了相应的安全解决方案。

当我们对不可信的用户输入使用str.format的时候,将会带来安全隐患——对于这个问题,其实我早就知道了,但是直到今天我才真正意识到它的严重性。因为攻击者可以利用它来绕过Jinja2沙盒,这会造成严重的信息泄露问题。同时,我在本文最后部分为str.format提供了一个新的安全版本。

需要提醒的是,这是一个相当严重的安全隐患,这里之所以撰文介绍,是因为大多数人很可能不知道它是多么容易被利用。

核心问题

从Python 2.6开始,Python受.NET启发而引入了一种格式化字符串的新型语法。当然,除了Python之外,Rust及其他一些编程语言也支持这种语法。借助于.format()方法,该语法可以应用到字节和unicode字符串(在Python 3中,只能用于unicode字符串)上面,此外,它还能映射为更加具有可定制性的string.Formatter API。

该语法的一个特点是,人们可以通过它确定出字符串格式的位置和关键字参数,并且随时可以显式对数据项重新排序。此外,它甚至可以访问对象的属性和数据项——这是导致这里的安全问题的根本原因。

总的来说,人们可以利用它来进行以下事情:

 
 
  1. >>> 'class of {0} is {0.__class__}'.format(42) 
  2. "class of 42 is <class 'int'>

实质上,任何能够控制格式字符串的人都有可能访问对象的各种内部属性。

问题出在哪里?

第一个问题是,如何控制格式字符串。可以从下列地方下手:

1.字符串文件中不可信的翻译器。我们很可能通过它们得手,因为许多被翻译成多种语言的应用程序都会用到这种新式Python字符串格式化方法,但是并非所有人都会对输入的所有字符串进行全面的审查。

2.用户暴露的配置。 由于一些系统用户可以对某些行为进行配置,而这些配置有可能以格式字符串的形式被暴露出来。需要特别提示的是,我就见过某些用户可以通过Web应用程序来配置通知邮件、日志消息格式或其他基本模板。

危险等级

如果只是向该格式字符串传递C解释器对象的话,倒是不会有太大的危险,因为这样的话,你最多会暴露一些整数类之类的东西。

然而,一旦Python对象被传递给这种格式字符串的话,那就麻烦了。这是因为,能够从Python函数暴露的东西的数量是相当惊人的。 下面是假想的Web应用程序的情形,这种情况下能够泄露密钥:

 
 
  1. CONFIG = { 
  2.     'SECRET_KEY': 'super secret key' 
  3.    
  4. class Event(object): 
  5.     def __init__(self, id, level, message): 
  6.         self.id = id 
  7.         self.level = level 
  8.         self.message = message 
  9.    
  10. def format_event(format_string, event): 
  11.     return format_string.format(eventevent=event) 

如果用户可以在这里注入format_string,那么他们就能发现下面这样的秘密字符串:

 
 
  1. {event.__init__.__globals__[CONFIG][SECRET_KEY]} 

将格式化作沙箱化处理

那么,如果需要让其他人提供格式化字符串,那该怎么办呢? 其实,可以利用某些未公开的内部机制来改变字符串格式化行为。

 
 
  1. from string import Formatter 
  2. from collections import Mapping 
  3.    
  4. class MagicFormatMapping(Mapping): 
  5.     """This class implements a dummy wrapper to fix a bug in the Python 
  6.     standard library for string formatting. 
  7.    
  8.     See http://bugs.python.org/issue13598 for information about why 
  9.     this is necessary. 
  10.     """ 
  11.    
  12.     def __init__(self, args, kwargs): 
  13.         self._args = args 
  14.         self._kwargs = kwargs 
  15.         self._last_index = 0 
  16.    
  17.     def __getitem__(self, key): 
  18.         if key == '': 
  19.             idx = self._last_index 
  20.             self._last_index += 1 
  21.             try: 
  22.                 return self._args[idx] 
  23.             except LookupError: 
  24.                 pass 
  25.             key = str(idx) 
  26.         return self._kwargs[key] 
  27.    
  28.     def __iter__(self): 
  29.         return iter(self._kwargs) 
  30.    
  31.     def __len__(self): 
  32.         return len(self._kwargs) 
  33.    
  34. # This is a necessary API but it's undocumented and moved around 
  35. # between Python releases 
  36. try: 
  37.     from _string import formatter_field_name_split 
  38. except ImportError: 
  39.     formatter_field_name_split = lambda \ 
  40.         x: x._formatter_field_name_split() 
  41.    
  42. class SafeFormatter(Formatter): 
  43.    
  44.     def get_field(self, field_name, args, kwargs): 
  45.         first, rest = formatter_field_name_split(field_name) 
  46.         obj = self.get_value(first, args, kwargs) 
  47.         for is_attr, i in rest: 
  48.             if is_attr: 
  49.                 obj = safe_getattr(obj, i) 
  50.             else: 
  51.                 objobj = obj[i] 
  52.         return obj, first 
  53.    
  54. def safe_getattr(obj, attr): 
  55.     # Expand the logic here.  For instance on 2.x you will also need 
  56.     # to disallow func_globals, on 3.x you will also need to hide 
  57.     # things like cr_frame and others.  So ideally have a list of 
  58.     # objects that are entirely unsafe to access. 
  59.     if attr[:1] == '_': 
  60.         raise AttributeError(attr) 
  61.     return getattr(obj, attr) 
  62.    
  63. def safe_format(_string, *args, **kwargs): 
  64.     formatter = SafeFormatter() 
  65.     kwargs = MagicFormatMapping(args, kwargs) 
  66.     return formatter.vformat(_string, args, kwargs) 

现在,我们就可以使用safe_format方法来替代str.format了:

 
 
  1. >>> '{0.__class__}'.format(42) 
  2. "<type 'int'>
  3. >>> safe_format('{0.__class__}', 42) 
  4. Traceback (most recent call last): 
  5.   File "<stdin>", line 1, in <module> 
  6. AttributeError: __class__ 

小结

在本文中,我们对Python引入的一种格式化字符串的新型语法的安全漏洞进行了深入的分析,并提供了相应的安全解决方案,希望对读者能够有所帮助。


作者:shan66

来源:51CTO

相关文章
|
4天前
|
Python
python学习-函数模块,数据结构,字符串和列表(下)
python学习-函数模块,数据结构,字符串和列表
25 0
|
2月前
|
数据处理 Python
Python中字符串、列表、字典常用的拼接方法有哪些?
Python中字符串、列表、字典常用的拼接方法有哪些?
56 1
|
4月前
2-Python字符串和列表
2-Python字符串和列表
15 0
|
10月前
|
数据采集 Python
如何从 Python 中的字符串列表中删除特殊字符?
如何从 Python 中的字符串列表中删除特殊字符?
237 0
|
5月前
|
存储 数据安全/隐私保护 索引
Python基础语法day02字符串详解和列表
今天是python基础语法入门第二天,大概总共会有四天左右。四天后就是对于python的numpy库的详细文章。那话不多说,我们开始。
|
8月前
|
存储 Python
【Python入门系列】第二篇、Python字符串、列表、元组、字典、集合的操作和常用方法
在Python中,字符串是由字符组成的,可以使用单引号或双引号来定义字符串。
114 0
|
9月前
|
存储 索引 Python
python基础知识-变量、字符串、列表
python基础知识-变量、字符串、列表
|
11月前
|
Python
Python 字符串str类型的方法(内建函数)分类举例列表
Python 字符串str类型的方法(内建函数)分类举例列表
64 0
|
索引 Python 容器
Python编程:容器总结-字符串、列表、元组、字典、集合
Python编程:容器总结-字符串、列表、元组、字典、集合
61 0
|
存储 SQL 算法
【Python刷题篇】Python从0到入门1|字符串、运算符、列表入门
本期是Python从0到入门1:字符串、运算符、列表入门,有不懂的地方可以评论进行讨论!
【Python刷题篇】Python从0到入门1|字符串、运算符、列表入门