自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

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

網(wǎng)絡(luò)
本文對Python引入的一種格式化字符串的新型語法的安全漏洞進行了深入的分析,并提供了相應(yīng)的安全解決方案。

Python

前言

本文對Python引入的一種格式化字符串的新型語法的安全漏洞進行了深入的分析,并提供了相應(yīng)的安全解決方案。

當(dāng)我們對不可信的用戶輸入使用str.format的時候,將會帶來安全隱患——對于這個問題,其實我早就知道了,但是直到今天我才真正意識到它的嚴(yán)重性。因為攻擊者可以利用它來繞過Jinja2沙盒,這會造成嚴(yán)重的信息泄露問題。同時,我在本文最后部分為str.format提供了一個新的安全版本。

需要提醒的是,這是一個相當(dāng)嚴(yán)重的安全隱患,這里之所以撰文介紹,是因為大多數(shù)人很可能不知道它是多么容易被利用。

核心問題

從Python 2.6開始,Python受.NET啟發(fā)而引入了一種格式化字符串的新型語法。當(dāng)然,除了Python之外,Rust及其他一些編程語言也支持這種語法。借助于.format()方法,該語法可以應(yīng)用到字節(jié)和unicode字符串(在Python 3中,只能用于unicode字符串)上面,此外,它還能映射為更加具有可定制性的string.Formatter API。

該語法的一個特點是,人們可以通過它確定出字符串格式的位置和關(guān)鍵字參數(shù),并且隨時可以顯式對數(shù)據(jù)項重新排序。此外,它甚至可以訪問對象的屬性和數(shù)據(jù)項——這是導(dǎo)致這里的安全問題的根本原因。

總的來說,人們可以利用它來進行以下事情:

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

實質(zhì)上,任何能夠控制格式字符串的人都有可能訪問對象的各種內(nèi)部屬性。

問題出在哪里?

第一個問題是,如何控制格式字符串。可以從下列地方下手:

1.字符串文件中不可信的翻譯器。我們很可能通過它們得手,因為許多被翻譯成多種語言的應(yīng)用程序都會用到這種新式Python字符串格式化方法,但是并非所有人都會對輸入的所有字符串進行全面的審查。

2.用戶暴露的配置。 由于一些系統(tǒng)用戶可以對某些行為進行配置,而這些配置有可能以格式字符串的形式被暴露出來。需要特別提示的是,我就見過某些用戶可以通過Web應(yīng)用程序來配置通知郵件、日志消息格式或其他基本模板。

危險等級

如果只是向該格式字符串傳遞C解釋器對象的話,倒是不會有太大的危險,因為這樣的話,你最多會暴露一些整數(shù)類之類的東西。

然而,一旦Python對象被傳遞給這種格式字符串的話,那就麻煩了。這是因為,能夠從Python函數(shù)暴露的東西的數(shù)量是相當(dāng)驚人的。 下面是假想的Web應(yīng)用程序的情形,這種情況下能夠泄露密鑰:

  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,那么他們就能發(fā)現(xiàn)下面這樣的秘密字符串:

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

將格式化作沙箱化處理

那么,如果需要讓其他人提供格式化字符串,那該怎么辦呢? 其實,可以利用某些未公開的內(nèi)部機制來改變字符串格式化行為。

  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) 

現(xiàn)在,我們就可以使用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__ 

小結(jié)

在本文中,我們對Python引入的一種格式化字符串的新型語法的安全漏洞進行了深入的分析,并提供了相應(yīng)的安全解決方案,希望對讀者能夠有所幫助。

責(zé)任編輯:趙寧寧 來源: 安全客
相關(guān)推薦

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格式化字符串

2020-06-28 08:26:41

Python開發(fā)工具

2022-05-09 14:04:27

Python字符串格式化輸出

2024-03-06 08:41:14

Python字符串格式化工具

2023-08-26 20:21:58

字符KotlinJava

2010-09-13 15:06:40

sql server字

2023-08-21 10:28:00

字符串字符Python

2024-05-09 08:28:10

Python字符串百分號格式化

2024-12-09 08:10:00

Python字符串格式化

2022-03-28 10:56:11

Python字符串格式化

2010-09-14 14:32:02

sql server日

2009-09-02 15:56:49

C#格式化字符串

2011-08-22 10:59:42

SQL Server日期時間格式轉(zhuǎn)換字符串

2009-10-16 13:04:57

VB.NET字符串?dāng)?shù)組

2021-07-26 00:02:30

Python字符串列表

2022-05-18 11:35:17

Python字符串

2023-12-15 10:27:01

暴力匹配算法Python字符串
點贊
收藏

51CTO技術(shù)棧公眾號