【问题标题】:SecureZeroMemory in Python CtypesPython Ctypes 中的 SecureZeroMemory
【发布时间】:2017-06-27 23:39:22
【问题描述】:

我正在尝试将以下 C 代码行转换为 ctypes。这是我要翻译的 C 程序的 sn-p:

pIfRow = (MIB_IF_ROW2 *) malloc(sizeof(MIB_IF_ROW2));
SecureZeroMemory((PVOID)pIfRow, sizeof(MIB_IF_ROW2));

(注意MIB_IF_ROW2是一个结构体,在Netioapi.h中定义)

无论如何,我可以在 ctypes 中很好地翻译第一行,假设 MIB_IF_ROW2 已经被定义为 ctypes 结构:

from ctypes import *

# Translate first line of C Code
buff = create_string_buffer(sizeof(MIB_IF_ROW2))
p_if_row = cast(buff, POINTER(MIB_IF_ROW2))

# Second Line... ?

但是当我到达第二行时,我被卡住了。我在文档或在线中找不到与该函数等效的 ctypes 的任何内容。解决此问题的最佳方法是什么?

【问题讨论】:

  • 在这种情况下,您似乎不太可能特别需要 SecureZeroMemory 函数。 ctypes.memset 应该也可以。
  • [Rtl]SecureZeroMemory 是在 winnt.h 中定义的内联函数。它不是由系统 DLL 导出的。您不需要它,因为 ctypes 会将它分配的内存归零。此外,这是一个固定大小的结构,因此无需将缓冲区转换为指针。只需将其实例化为 if_row = MIB_IF_ROW2()p_if_row = ctypes.pointer(if_row)

标签: python windows ctypes securezeromemory


【解决方案1】:

SecureZeroMemory 只会用零填充您传递给它的内存。您应该使用ZeroMemory/memset 或python 中的普通循环获得完全相同的结果。使其“安全”的原因在于它不应该被编译器优化掉(在 C/C++ 等较低级别进行编程时)。

在你刚刚 malloc'ed 的内存上使用它并不是它的预期目的(虽然无害),它应该像这样使用:

char password[100];
AskUserForPassword(password);
DoSomething(password);
SecureZeroMemory(password, sizeof(password)); // Make sure password is no longer visible in memory in case the application is paged out or creates a memory dump in a crash

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    相关资源
    最近更新 更多