成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python如何考慮代碼注入安全?

瀏覽:148日期:2022-09-20 08:34:37

問題描述

目前有一個(gè)python的項(xiàng)目,想加入第三方插件開發(fā)的一個(gè)功能。 插件的形式也就是一個(gè)PY文件,但是看了python安全這塊的文章后,發(fā)現(xiàn)python是動(dòng)態(tài)的,很容易就注入到核心代碼,包括各種monkeypack之類的,如何做這塊才能安全呢?

PS: 現(xiàn)在有些在線課堂也有 在線編程的功能,他們?cè)趺醋龅降陌踩兀?/p>

# plug_hello.pydef hello(): print 'hello world'

# load.pyimport plug_hello plug_hello.hello()

正常這樣加載是沒問題,但是黑客就可以注入。

# plug_hello.pydef hello(): #在 Python 2中, 內(nèi)置對(duì)象可以通過魔法 __builtins__ 模塊進(jìn)行訪問。一個(gè)已知的手段就是利用 __builtins__ 的可變性,這可能引起巨大災(zāi)難 import __builtins__ __builtins__.False, __builtins__.True = True, False print 'hello world'

黑客這樣寫,整個(gè)程序的True 和 False 變量就會(huì)出問題,而且黑客使用py特性還能獲取和修改主程序任何運(yùn)行函數(shù)類的源代碼,從而進(jìn)一步的注入。

問題解答

回答1:

這個(gè)問題我也不懂,需要問問專門做這方面的人

我只說說我的想法:

由于第三方的功能由你們制定,預(yù)先封裝好第三方需要用到組件模塊,利用sys.module設(shè)置模塊白名單,只允許第三方導(dǎo)入你們提供的模塊,其他模塊sys.module[mod] = None禁止導(dǎo)入

PS:在線編程網(wǎng)站都是在沙箱環(huán)境里運(yùn)行用戶代碼的,破壞便破壞了,反正環(huán)境是虛擬,貌似跟你這個(gè)問題關(guān)聯(lián)不大

回答2:

分享其中一個(gè)心得: 比如說, 文件處理時(shí), 經(jīng)常習(xí)慣取個(gè)變量path, 但又經(jīng)常from os import path

可以這么用:

import os.path# import os.path后, 使用時(shí), 需要完整輸入os.path# 相對(duì)于import os總模塊而言, import os.path能避免無(wú)用的引入path = os.path.join('/tmp', filename)回答3:

使用ast.literal_eval(), 只允許使用 string,bytes,number,tuples,lists,discts,set,booleans,None

ast.literal_eval(node_or_string)Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

Changed in version 3.2: Now allows bytes and set literals.

標(biāo)簽: Python 編程
相關(guān)文章: