15

我在与bytesPython3.2 相关的内存管理方面遇到了一些麻烦。在某些情况下,ob_sval缓冲区似乎包含我无法解释的内存。

对于特定的安全应用程序,我需要能够确保内存“归零”并在不再使用后尽快返回操作系统。由于重新编译 Python 并不是一个真正的选择,我正在编写一个可与​​ LD_PRELOAD一起使用的模块:

  • PyObject_Malloc通过用PyMem_MallocPyObject_ReallocwithPyMem_ReallocPyObject_Freewith替换来禁用内存池PyMem_Free(例如:如果你编译时不使用 ,你会得到什么WITH_PYMALLOC)。我真的不在乎内存是否被池化,但这似乎是最简单的方法。
  • 包装malloc, realloc, 等free以跟踪请求的内存量以及memset释放0的时间。

粗略一看,这种方法似乎效果很好:

>>> from ctypes import string_at
>>> from sys import getsizeof
>>> from binascii import hexlify
>>> a = b"Hello, World!"; addr = id(a); size = getsizeof(a)
>>> print(string_at(addr, size))
b'\x01\x00\x00\x00\xd4j\xb2x\r\x00\x00\x00<J\xf6\x0eHello, World!\x00'
>>> del a
>>> print(string_at(addr, size))
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x13\x00'

最后的错误\x13很奇怪,但不是来自我的原始值,所以起初我认为它没问题。我很快找到了一些不太好的例子:

>>> a = b'Superkaliphragilisticexpialidocious'; addr = id(a); size = getsizeof(a)
>>> print(string_at(addr, size))
b'\x01\x00\x00\x00\xd4j\xb2x#\x00\x00\x00\x9cb;\xc2Superkaliphragilisticexpialidocious\x00'
>>> del s
>>> print(string_at(addr, size))
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00))\n\x00\x00ous\x00'

这里最后三个字节ous, 幸存下来。

所以,我的问题:

对象的剩余字节是怎么回事bytes,为什么在del调用它们时它们不被删除?

我猜我的方法缺少类似于 a 的东西realloc,但我看不出那会是什么bytesobject.c

我试图量化垃圾收集后剩余的“剩余”字节数,它在某种程度上似乎是可预测的。

from collections import defaultdict
from ctypes import string_at
import gc
import os
from sys import getsizeof

def get_random_bytes(length=16):
    return os.urandom(length)

def test_different_bytes_lengths():
    rc = defaultdict(list)
    for ii in range(1, 101):
        while True:
            value = get_random_bytes(ii)
            if b'\x00' not in value:
                break
        check = [b for b in value]
        addr = id(value)
        size = getsizeof(value)
        del value
        gc.collect()
        garbage = string_at(addr, size)[16:-1]
        for jj in range(ii, 0, -1):
            if garbage.endswith(bytes(bytearray(check[-jj:]))):
                # for bytes of length ii, tail of length jj found
                rc[jj].append(ii)
                break
    return {k: len(v) for k, v in rc.items()}, dict(rc)

# The runs all look something like this (there is some variation):
# ({1: 2, 2: 2, 3: 81}, {1: [1, 13], 2: [2, 14], 3: [3, 4, 5, 6, 7, 8, 9, 10, 11, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 83, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]})
# That is:
#  - One byte left over twice (always when the original bytes object was of lengths 1 or 13, the first is likely because of the internal 'characters' list kept by Python)
#  - Two bytes left over twice (always when the original bytes object was of lengths 2 or 14)
#  - Three bytes left over in most other cases (the exact ones varies between runs but never has '12' in it)
# For added fun, if I replace the get_random_bytes call with one that returns an encoded string or random alphanumerics then results change slightly: lengths of 13 and 14 are now fully cleared too. My original test string was 13 bytes of encoded alphanumerics, of course!

编辑 1

我最初表示担心如果bytes对象在函数中使用它根本不会被清理:

>>> def hello_forever():
...     a = b"Hello, World!"; addr = id(a); size = getsizeof(a)
...     print(string_at(addr, size))
...     del a
...     print(string_at(addr, size))
...     gc.collect()
...     print(string_at(addr, size))
...     return addr, size
...
>>> addr, size = hello_forever()
b'\x02\x00\x00\x00\xd4J0x\r\x00\x00\x00<J\xf6\x0eHello, World!\x00'
b'\x01\x00\x00\x00\xd4J0x\r\x00\x00\x00<J\xf6\x0eHello, World!\x00'
b'\x01\x00\x00\x00\xd4J0x\r\x00\x00\x00<J\xf6\x0eHello, World!\x00'
>>> print(string_at(addr, size))
b'\x01\x00\x00\x00\xd4J0x\r\x00\x00\x00<J\xf6\x0eHello, World!\x00'

事实证明,这是我的要求未涵盖的人为问题。您可以查看对此问题的评论以获取详细信息,但问题来自hello_forever.__code__.co_consts元组将包含对Hello, World!即使 afteralocals.

在实际代码中,“安全”值将来自外部源,永远不会被硬编码,以后也不会像这样被删除。

编辑 2

我还对strings. 有人指出,它们也可能会遇到与bytes在函数中硬编码它们相同的问题(例如:我的测试代码的工件)。它们还有另外两个风险,我无法证明这是一个问题,但会继续调查:

  • 字符串实习是由 Python 在各个点完成的,以加快访问速度。这应该不是问题,因为当最后一个引用丢失时,应该删除实习字符串。如果它被证明是一个问题,它应该可以更换PyUnicode_InternInPlace,这样它就不会做任何事情。
  • Python 中的字符串和其他“原始”对象类型通常保留一个“空闲列表”,以便更快地为新对象获取内存。如果这被证明是一个问题,则可以替换*_dealloc中的方法。Objects/*.c

我还相信我看到了类实例没有正确归零的问题,但我现在认为这是我的错误。

谢谢

非常感谢@Dunes 和@Kevin 指出了混淆我最初问题的问题。这些问题已留在上面的“编辑”部分以供参考。

4

2 回答 2

4

事实证明,这个问题是我自己的代码中的一个绝对愚蠢的错误memset。在“接受”这个答案之前,我将联系@Calyth,他慷慨地为这个问题添加了赏金。

简而言之,malloc/free包装函数的工作方式如下:

  • 代码调用malloc请求N内存字节。
    • 包装器调用真正的函数但要求N+sizeof(size_t)字节。
    • 它写入N范围的开头并返回一个偏移量指针。
  • 代码使用偏移量指针,忽略了它附加到比请求稍大的内存块的事实。
  • 代码调用free要求返回内存并传入该偏移指针。
    • 包装器在偏移指针之前查找以获取最初请求的内存大小。
    • 它调用memset以确保所有内容都设置为零(库在没有优化的情况下编译,以防止编译器忽略memset)。
    • 只有这样它才会调用真正的函数。

我的错误是调用等价的memset(actual_pointer, 0, requested_size)而不是memset(actual_pointer, 0, actual_size)

我现在面临一个令人难以置信的问题,为什么不总是有“3”个剩余字节(我的单元测试验证我随机生成的字节对象都不包含任何空值)以及为什么字符串也不会有这个问题(确实Python 可能过度分配了字符串缓冲区的大小)。然而,这些都是另一天的问题。

所有这一切的结果是,确保字节和字符串在被垃圾收集后被设置为零是相对容易的!(有很多关于硬编码字符串、空闲列表等的警告,所以任何试图这样做的人都应该仔细阅读原始问题、问题的评论和这个“答案”。)

于 2015-03-02T22:12:12.483 回答
3

通常,您无法保证及时将内存清零甚至垃圾收集。有启发式方法,但是如果您担心安全性到这种程度,那可能还不够。

相反,您可以做的是直接处理可变类型,例如bytearray并将每个元素显式归零:

# Allocate (hopefully without copies)
bytestring = bytearray()
unbuffered_file.readinto(bytestring)

# Do stuff
function(bytestring)

# Zero memory
for i in range(len(bytestring)):
    bytestring[i] = 0

安全地使用它需要你只使用你知道不会制作临时副本的方法,这可能意味着你自己滚动。不过,这并不能防止某些缓存搞砸了。

zdan在另一个问题中给出了一个很好的建议:使用子进程来完成工作,一旦完成就用火杀死它。

于 2015-02-23T19:55:25.383 回答