python - 如何保护 python 类变量免受邪恶程序员的侵害?

标签 python class dictionary private protected

如何保护我的变量免受此类攻击:

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()  

最佳答案

我觉得这个问题的动机很深。私有(private)变量不是为了让邪恶的“黑客”远离。他们与安全无关。他们在那里促进良好的编程实践,如 maintaining low coupling .

如果“邪恶的程序员”可以访问您的源代码,他或她就可以为所欲为。将变量称为“私有(private)”不会改变这一点。如果说邪恶的程序员试图破坏你在另一个系统上执行的程序......调用一个变量“私有(private)”对你没有好处。它不会改变程序在内存中的存储和操作方式。它只是强制执行(以一种不必要的复杂方式 IMO)separation of concerns .

此外,值得注意的是,在正常情况下,您不必经历所有这些恶作剧......

MyClass.__dict__ = {}
MyClass.__dict__.__setitem__('_MyClass__protectedVariable','...but it is not')

...分配给 protected 变量。您甚至不必覆盖 __dict__。你可以这样做:

MyClass._MyClass__protectedVariable = '...but it is not'

因为它真的不是。 protected ,我的意思是。名称修改的主要目的是防止namespace collisions .如果您只想要一个“私有(private)”属性,只需在它前面加上一个下划线即可。期望您的用户尊重惯例,并期望无论您做什么,滥用者都会打破它。

关于python - 如何保护 python 类变量免受邪恶程序员的侵害?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9179225/

相关文章:

python - 无法将输入翻译成字典

c# - 为什么 ExpandoObject 比 Dictionary 慢很多?

python - 类型错误 : Field 'classroom' expected a number but got (4, )

python - numba @jit 比纯 python 慢?

javascript - 如何显示所选类Jquery的内容

c++ - 通过赋值初始化类对象

c++ - 如何在 C++ 中从映射创建倒排索引到映射?

python - 使用 `gevent.event.Event` 实现多监听器通知的更好模式?

python - python中的链式调用父初始化器

vba - 将 Type 更改为 Class 会导致 ByRef 参数执行 ByVal