pythonctypespydbg

Inside a pydbg exit_hook (callback) how can I convert a stack value to a matching Python type?


This is possibly more of a ctypes question than a pydbg question, but I still don't understand why the results are inconsistent in the way they are.

I have an exit_hook set on LoadLibraryA using pydbg and its utils.hook_container class like this:

def exit_LoadLibraryA(dbg, args, ret):
    libname = c_char_p(args[0])
    # or: libname = ctypes.cast(args[0], ctypes.c_char_p)
    print "LoadLibraryA(%s) -> %08X" % (str(libname), ret)
    return DBG_CONTINUE

unfortunately the output is inconsistent. While some of the values get converted to (and shown as) strings, some others get shown as numbers like this:

LoadLibraryA(c_char_p(2007516492)) -> 7C800000
LoadLibraryA(c_char_p(17426164)) -> 77DD0000
LoadLibraryA(c_char_p(17426164)) -> 76C30000
LoadLibraryA(c_char_p('UxTheme.dll')) -> 5AD70000
LoadLibraryA(c_char_p('IMM32.dll')) -> 76390000
LoadLibraryA(c_char_p('COMCTL32.dll')) -> 773D0000
LoadLibraryA(c_char_p('Secur32.dll')) -> 77FE0000
LoadLibraryA(c_char_p(1033757216)) -> 7C9C0000

what I would like is to reliably convert the char* (and later the wchar_t* of LoadLibraryW) to a Python string to output it.


Solution

  • IIUC, you want to read the string at the memory address args[0] which is an integer.

    In this case, you need the string_at (or wstring_at) function. However, if there is no valid NUL-terminated string at the specified memory address, a WindowsError will be raised which you may want to catch.