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

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

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引入的一种格式化字符串的新型语法的安全漏洞进行了深入的分析,并提供了相应的安全解决方案,希望对读者能够有所帮助。

责任编辑:赵宁宁 来源: 安全客
相关推荐

2017-01-16 16:33:06

Python 字符串漏洞

2010-11-26 13:10:17

2016-10-17 09:07:11

漏洞字符串EIP劫持

2021-06-09 07:55:18

Python格式化字符串

2022-05-09 14:04:27

Python字符串格式化输出

2020-06-28 08:26:41

Python开发工具

2023-08-21 10:28:00

字符串字符Python

2024-03-06 08:41:14

Python字符串格式化工具

2022-03-28 10:56:11

Python字符串格式化

2010-09-13 15:06:40

sql server字

2023-08-26 20:21:58

字符KotlinJava

2011-08-22 10:59:42

SQL Server日期时间格式转换字符串

2022-05-18 11:35:17

Python字符串

2023-12-15 10:27:01

暴力匹配算法Python字符串

2009-09-02 15:56:49

C#格式化字符串

2010-09-14 14:32:02

sql server日

2009-10-16 13:04:57

VB.NET字符串数组

2010-03-31 19:15:25

Oracle函数

2010-02-01 16:46:07

C++格式化字符串

2009-09-03 18:05:04

ASP.NET字符串格
点赞
收藏

51CTO技术栈公众号