如何保護我的變量免受此類攻擊:以上如何從邪惡的程序員保護python類變量?
MyClass.__dict__ = {}
MyClass.__dict__.__setitem__('_MyClass__protectedVariable','...but it is not')
改變可變字典之後,它是孩子的發揮改變所有的變量。上限對於這項工作至關重要。如果你的字典的__setitem__
像下面那樣調整過,以上不起作用)。
我想強制用戶使用我的方法setProtectedVariable(value)
來更改變量,但我似乎在Python 2.7中找不到這樣做的方法。有任何想法嗎?
我也很欣賞,如果你從下面的代碼中找到其他類似的漏洞(我注意到我應該添加文件名和行號到我的inspect.stack
檢查myDict.__setitem__
)。
這是我到目前爲止已經試過:
import inspect
class ProtectionTest:
__myPrivate = 0
def __init__(self):
md = myDict()
setattr(self,'__dict__', md)
def __setattr__(self, name, val):
if name == '__myPrivate':
print "failed setattr attempt: __myPrivate"
pass
elif name == '_ProtectionTest__myPrivate':
print "failed setattr attempt: _ProtectionTest__myPrivate"
pass
elif name == '__dict__':
print "failed setattr attempt: __dict__"
pass
else:
self.__dict__[name] = val
def getMyPrivate(self):
return self.__myPrivate
def setMyPrivate(self, myPrivate):
#self.__dict__['_ProtectionTest__stack'] = inspect.stack()[0][1:]
self.__dict__['_ProtectionTest__myPrivate'] = -myPrivate
class myDict(dict):
def __init__(self):
dict.__init__(self)
def __setitem__(self, key, value):
if inspect.stack()[1][3] == 'setMyPrivate':
dict.__setitem__(self,key,value)
else:
print "failed dict attempt"
pass
pt = ProtectionTest()
print "trying to change... (success: 1): "
pt.__myPrivate = 1
print pt.getMyPrivate(), '\n'
print "trying to change... (success: 2): "
pt._ProtectionTest__myPrivate = 2
print pt.getMyPrivate() , '\n'
print "trying to change... (success: 3): "
pt.__dict__['_ProtectionTest__myPrivate'] = 3
print pt.getMyPrivate() , '\n'
print "trying to change the function (success: 4): "
def setMyPrivate(self, myPrivate):
self.__dict__['_ProtectionTest__myPrivate'] = 4
pt.setMyPrivate = setMyPrivate
pt.setMyPrivate(0)
print pt.getMyPrivate(), '\n'
print "trying to change the dict (success: 5): "
pt.__dict__ = {}
pt.__dict__.__setitem__('_ProtectionTest__myPrivate',5)
print pt.getMyPrivate(), '\n'
print "Still working (correct output = -input = -100): "
pt.setMyPrivate(100)
print pt.getMyPrivate()
你爲什麼要這麼做?你爲什麼關心另一個程序員在你的課堂上做什麼?如果另一位程序員想濫用這個問題,你負責讓你的代碼按照規範正常工作,不是嗎? – 2012-02-07 15:47:06
我懷疑你會發現一個防彈的方法來防止惡意用戶的任何可能的濫用。你現在不妨放棄。 – NPE 2012-02-07 15:47:47
你今天很積極......這也是對這個問題的回答:是否存在python中的私有變量和方法以及它們爲什麼存在。 – Juha 2012-02-07 15:52:54