Search code examples
pythonwindowsctypessecurezeromemory

SecureZeroMemory in Python Ctypes


I'm trying to translate the following line of C code into ctypes. Here's a snippet from the C program I'm trying to translate:

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

(Note that MIB_IF_ROW2 is a struct, defined in Netioapi.h)

Anyway, I can translate the first line fine in ctypes, assuming MIB_IF_ROW2 has already been defined as a ctypes struct:

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... ?

But when I get to the second line, I get stuck. I can't find anything in the docs or online with a ctypes equivalent for the function. What is the best way to go about this?


Solution

  • SecureZeroMemory will just fill the memory you pass it with zeroes. You should get the exact same result with ZeroMemory/memset or a plain loop in python. The thing that makes it "secure" is that it is not supposed to be optimized away by the compiler (when programming at a lower level like C/C++).

    Using it on memory you just malloc'ed is not its intended purpose (not harmful though), it is supposed to be used like this:

    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