【发布时间】:2013-03-12 23:46:41
【问题描述】:
我正在尝试从内存中删除密码字符串like it is suggested in here。
我写了那个小sn-p:
import ctypes, sys
def zerome(string):
location = id(string) + 20
size = sys.getsizeof(string) - 20
#memset = ctypes.cdll.msvcrt.memset
# For Linux, use the following. Change the 6 to whatever it is on your computer.
print ctypes.string_at(location, size)
memset = ctypes.CDLL("libc.so.6").memset
memset(location, 0, size)
print "Clearing 0x%08x size %i bytes" % (location, size)
print ctypes.string_at(location, size)
a = "asdasd"
zerome(a)
奇怪的是,这段代码在 IPython 上运行良好,
[7] oz123@yenitiny:~ $ ipython a.py
Clearing 0x02275b84 size 23 bytes
但是使用 Python 会崩溃:
[8] oz123@yenitiny:~ $ python a.py
Segmentation fault
[9] oz123@yenitiny:~ $
任何想法为什么?
我在 Debian Wheezy 上使用 Python 2.7.3 进行了测试。
小更新...
代码适用于 CentOS 6.2 和 Python 2.6.6。 代码在使用 Python 2.6.8 的 Debian 上崩溃。 我试着思考为什么它可以在 CentOS 上运行,而不是在 Debian 上运行。唯一的理由, 有一点不同的是,我的 Debian 是 multiarch 和 CentOS 在我的带有 i686 CPU 的旧笔记本电脑上运行。
因此,我重新启动了我的 CentOS 笔记本电脑并在其上加载了 Debian Wheezy。 该代码适用于非多架构的 Debian Wheezy。 因此,我怀疑我在 Debian 上的配置有些问题......
【问题讨论】:
-
+20的这个 hack 真的适用于任何 CPython 吗?毕竟它甚至没有记录。您确定它实际上清除了不会崩溃的配置的正确值吗? -
您刚刚说过“我不确定这段代码是否符合我的要求,但没关系”。
-
当然,在托管环境中尝试擦除内存本身就是错误的事情,而且您似乎用错误的方式解决了错误的问题。