【发布时间】:2012-02-29 01:20:55
【问题描述】:
如何保护我的变量免受此类攻击:
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()
【问题讨论】:
-
您为什么要这样做?为什么你关心其他程序员对你的课程做了什么?你负责让你的代码按照规范正常工作,如果另一个程序员想滥用它,那是他/她的问题,不是吗?
-
我怀疑你会找到一种防弹的方法来防止恶意用户的每一种可能的滥用。不如现在就放弃吧。
-
你今天很积极......这也是对以下问题的回答:python中是否存在私有变量和方法以及它们(不)存在的原因。
-
@DSM 我会测试你的“邪恶”;)
-
不值得。 “我在你的应用程序中入侵了你的课程并清除了我所有的数据”。是您按下手机上的静音按钮的地方,这样他们就不会听到您在想知道您是否可以得到报酬(很多)来解决它时大笑。
标签: python class dictionary private protected