Giter VIP home page Giter VIP logo

winappdbg's Introduction

What is WinAppDbg?

The WinAppDbg python module allows developers to quickly code instrumentation scripts in Python under a Windows environment.

It uses ctypes to wrap many Win32 API calls related to debugging, and provides an object-oriented abstraction layer to manipulate threads, libraries and processes, attach your script as a debugger, trace execution, hook API calls, handle events in your debugee and set breakpoints of different kinds (code, hardware and memory). Additionally it has no native code at all, making it easier to maintain or modify than other debuggers on Windows.

The intended audience are QA engineers and software security auditors wishing to test / fuzz Windows applications with quickly coded Python scripts, as well as malware analysts and researchers wishing to instrument and test Windows binaries. Several ready to use utilities are shipped and can be used for this purposes.

Current features also include disassembling x86/x64 native code, debugging multiple processes simultaneously and produce a detailed log of application crashes, useful for fuzzing and automated testing.

Where can I find WinAppDbg?

winappdbg's People

Contributors

aidanhs avatar axelboesenach avatar bkp-romain avatar elvanderb avatar flowztul avatar gand3lf avatar gogibanchan avatar hardik05 avatar holzhaus avatar japp-0xlabs avatar mariovilas avatar mivanchev avatar newuser54 avatar popof avatar sieutruc avatar talsaiag avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

winappdbg's Issues

need to redefine some functions related to window DC

The winappdbg win32 api wrapper defines GetDC, GetWindowDC and ReleaseDC functions as ctypes.windll.gdi32.GetDC. The functions are not exported in gdi32 but in user32. Seems to be need change to ctypes.windll.user32.GetDC. Tested on Windows 10 x64. Thanks MarioVilas.

Example 14 in the tutorial no longer works

Hi,

"Example #14: watching a buffer" from http://winappdbg.readthedocs.io/en/latest/Debugging.html doesn't work as expected. Entry/Leave callbacks are correctly called when "ReadFile" is called, however, the read buffer is not watched (the access callback is never called).

I modified the script to print the return value of watch_buffer. It always returns None:

C:\winappdbg> python 14_watch_buffer.py notepad.exe

[... open a file in notepad...]

ReadFile:
        Handle a14
        Expected bytes: 1024

ReadFile:
        Status: SUCCESS
        Read bytes: 1024
        watch_buffer returned 'None'

My setup:

C:\winappdbg> ver
Microsoft Windows [Version 10.0.14393]

C:\winappdbg> python
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32

C:\winappdbg> pip show winappdbg
Name: winappdbg
Version: 1.6
Summary: Windows application debugging engine
Home-page: http://winappdbg.readthedocs.io/en/latest/
Author: Mario Vilas
Author-email: [email protected]
License: UNKNOWN
Location: c:\python27\lib\site-packages
Requires:

Catching Exception for 64 Bit Process

Hi,
Wanted to know if we catch Access Violation Exception for 64 bit process as the same way we do for 32 bit processes ?

def AVHandler(event): #self
	code = event.get_event_code()	
	if event.get_event_code() == win32.EXCEPTION_DEBUG_EVENT and event.is_last_chance():
		print event.get_event_code()
		print 'Crashed'

Above code seems missing some crashes for me.

Any help suggestion will be appreciated!

TIA,

Shared memory writes break debugged process

Under certain conditions (active shared memory, for example), modifying a shared memory map with PAGE_WRITECOPY can have adverse effects on the target process.

In the Process class exists the following:

  hProcess = self.get_handle( win32.PROCESS_VM_WRITE |
                                    win32.PROCESS_VM_OPERATION |
                                    win32.PROCESS_QUERY_INFORMATION )
        mbi = self.mquery(lpBaseAddress)
        if not mbi.has_content():
            raise ctypes.WinError(win32.ERROR_INVALID_ADDRESS)
        if mbi.is_image() or mbi.is_mapped():
            prot = win32.PAGE_WRITECOPY
        elif mbi.is_writeable():
            prot = None
        elif mbi.is_executable():
            prot = win32.PAGE_EXECUTE_READWRITE
        else:
            prot = win32.PAGE_READWRITE
        if prot is not None:

In my case, I'm debugging a process that communicates with another via a shared memory section (via CreateFileMappingW with INVALID_HANDLE_VALUE and MapViewOfFile). When I attempt to write to this shared section, poke_dword will first attempt to detect the page protections and, if it's an image or mapped, mprotect it with PAGE_WRITECOPY, even if the section is writable. This causes the parent process to lock up and/or crash.

A couple things are unclear to me:

  1. Why mprotect a shared memory section PAGE_WRITECOPY if it's writable?
  2. Why check a mapped section's protection if it's writable?
  3. Why would this cause other processes sharing/accessing the section to crash/freeze?

I was able to fix this by simply switching the order of the checks:

if mbi.is_writeable():
    prot = None
elif mbi.is_image() or mbi.is_mapped():
    prot = win32.PAGE_WRITECOPY
elif mbi.is_executable():
    prot = win32.PAGE_EXECUTE_READWRITE
else:
    prot = win32.PAGE_READWRITE

I haven't fully debugged the root cause, but I do think the PAGE_WRITECOPY is at fault here. I'm also not sure what implications my fix may have under other scenarios.

Debug class has no method disable_thread_breakpoints

Debug class appears to be missing disable_thread_breakpoints method, which results in warning messages being printed when calling debug.stop().

Is it necessary to call disable_thread_breakpoints(tid) after previously calling disable_process_breakpoints (debug.py, line 1011)?

Stack argument order is wrong on amd64

For 64-bit Windows, the first four arguments are passed in registers, the rest is passed via the stack (https://msdn.microsoft.com/en-us/library/zthk2dkh.aspx). winappdbg (most recent master branch) seems to parse the stack arguments in the wrong order (also versions 1.5 and 1.6 are affected, I think). I will propose a pull request with a fix.

Note that this only affects breakpoints/hooks for functions with more than 4 arguments, for example the Windows API function RegQueryValueExW(). A minimal test case could use the following C code with a Hook on RegQueryValueExW() and the arguments data and datalen contain erroneous values (unless the fix is applied):

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    HKEY CH;
    BYTE* data;
    DWORD datalen;
    datalen = 100;
    DWORD vtype;

    data = malloc(100);
    printf("data    @0x%016x\n", data);
    printf("datalen @0x%016x\n", datalen);

    if(RegOpenKeyW(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", &CH) != 0)
    {
        printf("Error - RegOpenKey\n");
        system("PAUSE");
        return -1;
    }
    if(RegQueryValueExW(CH, L"VBoxTray", NULL, &vtype, data, &datalen) != 0)
    {
        printf("Error - RegQueryValueExW\n");
        system("PAUSE");
        return -1;
    }
    printf("data=%s\n", data);
    RegCloseKey(CH);
    return 0;
}

api hooking error: hook ExtTextOutW in gdi32.dll and return unreadable codes

I am using winappdbg to hook ExtTextOutW function in gdi32.dll, the code is blow:

# BOOL ExtTextOut(HDC hdc, int X, int Y, UINT fuOptions, CONST RECT *lprc, LPCTSTR lpString, UINT cbCount, CONST INT *lpDx);
class MyEventHandler(EventHandler):
    # Here we set which API calls we want to intercept.
    apiHooks = {

        # Hooks for the kernel32 library.
        'gdi32.dll': [

            #  Function            Parameters
            # HDC hdc, int X, int Y, UINT fuOptions, CONST RECT * lprc, LPCTSTR lpString, UINT cbCount, CONST INT * lpDx
            ('ExtTextOutW', (HDC, c_int, c_int, UINT, RECT, LPCWSTR, UINT,INT)),
        ],
    }

# HDC hdc, int X, int Y, UINT fuOptions, CONST RECT *lprc, LPCTSTR lpString, UINT cbCount, CONST INT *lpDx
    def pre_ExtTextOutW(self, event, ra, hdc, X, Y, fuOptions, lprc, lpString, cbCount, lpDx):

        self.__print_pre_textout(event, lpString, "ExtTextOutW")

    def post_ExtTextOutW(self, event, retval):
        self.__print_post_textout(event, retval, "ExtTextOutW")


    def __print_pre_textout(self, event, string, tag):
        tid = event.get_tid()
        print  "%d: pre_textout %s: %s" % (tid, tag, string)



    def __print_post_textout(self, event, retval, tag):
        tid = event.get_tid()
        if retval:
            print "%d: post_textout Success %s: %x" % (tid, tag, retval)
        else:
            print "%d: post_textout Failed! %s" % (tid, tag)



def simple_debugger(argv):
    # Instance a Debug object, passing it the MyEventHandler instance.
    with Debug(MyEventHandler(), bKillOnExit=True) as debug:
        # Start a new process for debugging.
        debug.execv(argv)

        # Wait for the debugee to finish.
        debug.loop()


# When invoked from the command line,
# the first argument is an executable file,
# and the remaining arguments are passed to the newly created process.
if __name__ == "__main__":
    program_to_debug = "c:\\windows\\system32\\notepad.exe"

    sys.argv.append(program_to_debug)
    simple_debugger(sys.argv[1:])

There are two type errors:
The first likes this :

File "D:\ProgramData\Anaconda2\lib\site-packages\winappdbg\breakpoint.py", line 1197, in call
13660: pre_textout ExtTextOutW:
params = self._get_function_arguments(aProcess, aThread)
File "D:\ProgramData\Anaconda2\lib\site-packages\winappdbg\breakpoint.py", line 1453, in _get_function_arguments
offset = win32.sizeof(win32.LPVOID))
File "D:\ProgramData\Anaconda2\lib\site-packages\winappdbg\thread.py", line 1481, in read_stack_structure
for (name, type) in stackData.fields ])
ValueError: invalid string pointer 0xA6011B1F

warnings.warn(msg, BreakpointCallbackWarning)

the second likes this:

13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW: 筀̶彟̀蛠̶蚠̶��
13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW: čďČĖĄČĉăęďēĆćĆĄȊĕČȊĔĆđЄċČ̓ĄČđĔĄčȎ
13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW:
13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW: čďČĖĄČĉăęďēĆćĆĄȊĕČȊĔĆđЄċČ̓ĄČđĔĄčȎ
13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW: 琠扡敬✠猥㨧渠潣畬湭渠浡摥✠猥‧獩瀠敲敳瑮.
13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW: ǖ
13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW: 琠扡敬✠猥㨧渠潣畬湭渠浡摥✠猥‧獩瀠敲敳瑮.
13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW: ǖ
13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW: 琠扡敬✠猥㨧渠潣畬湭渠浡摥✠猥‧獩瀠敲敳瑮.
13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW: ǖ
13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW: 琠扡敬✠猥㨧渠潣畬湭渠浡摥✠猥‧獩瀠敲敳瑮.
13660: post_textout Success ExtTextOutW: 1
13660: pre_textout ExtTextOutW: ǖ

Is there something wrong?

Thread.get_linear_address could also take a numeric selector

I'm currently doing some x86 disassembly and I stumped upon a situation related to the jump instruction involving a segment (selector) given through a non-symbolic value, i.e. jmp 0x47:0xff00. With WinAppDbg, calculating the address through get_linear_address requires a symbolic name for the segment register which is then immediately converted to a numeric value before being passed on to GetThreadSelectorEntry. It would be therefore useful to be able to specify a numeric value directly. I would submit a patch about it.

WinAppDbg cannot debug Metro apps in Windows 10

Reason yet unknown.

D:\tools>python pdebug.py --follow calc.exe
WinAppDbg Version 1.6 console debugger
by Mario Vilas (mvilas at gmail.com)

Spawned process (1136)
Started process 1136 at 0x00007ff602d717e0
Started thread 7016 at calc!start
Loaded module (00007FF602D70000) C:\Windows\System32\calc.exe
Loaded module (00007FFEB6490000) C:\Windows\System32\ntdll.dll
Loaded module (00007FFEB3950000) C:\Windows\System32\kernel32.dll
Loaded module (00007FFEB2860000) C:\Windows\System32\KernelBase.dll
Loaded module (00007FFEB48E0000) C:\Windows\System32\shell32.dll
Loaded module (00007FFEB3A10000) C:\Windows\System32\msvcrt.dll
Started thread 7672 at ntdll!RtlReleaseSRWLockExclusive+0x40
Loaded module (00007FFEB37D0000) C:\Windows\System32\cfgmgr32.dll
Loaded module (00007FFEB3820000) C:\Windows\System32\ucrtbase.dll
Loaded module (00007FFEB4820000) C:\Windows\System32\SHCore.dll
Started thread 4436 at ntdll!RtlReleaseSRWLockExclusive+0x40
Loaded module (00007FFEB3FE0000) C:\Windows\System32\rpcrt4.dll
Loaded module (00007FFEB4390000) C:\Windows\System32\combase.dll
Loaded module (00007FFEB3300000) C:\Windows\System32\bcryptprimitives.dll
Loaded module (00007FFEB2AE0000) C:\Windows\System32\windows.storage.dll
Loaded module (00007FFEB3B20000) C:\Windows\System32\advapi32.dll
Loaded module (00007FFEB6330000) C:\Windows\System32\sechost.dll
Loaded module (00007FFEB4330000) C:\Windows\System32\shlwapi.dll
Loaded module (00007FFEB6300000) C:\Windows\System32\gdi32.dll
Loaded module (00007FFEB3380000) C:\Windows\System32\gdi32full.dll
Loaded module (00007FFEB3540000) C:\Windows\System32\msvcp_win.dll
Loaded module (00007FFEB5D20000) C:\Windows\System32\user32.dll
Loaded module (00007FFEB3520000) C:\Windows\System32\win32u.dll
Loaded module (00007FFEB2800000) C:\Windows\System32\kernel.appcore.dll
Loaded module (00007FFEB2840000) C:\Windows\System32\profapi.dll
Loaded module (00007FFEB27B0000) C:\Windows\System32\powrprof.dll
Loaded module (00007FFEB27A0000) C:\Windows\System32\fltLib.dll

Breakpoint (80000003) at address 00007FFEB655CE5C (first chance)

rax=0000000000000000 rbx=0000000000000010 rcx=00007ffeb652a354
rdx=0000000000000000 rsi=00007ffeb65b40f0 rdi=00007ffeb65b47a0
rip=00007ffeb655ce5d rsp=000000c0ffb1f070 rbp=0000000000000000
 r8=000000c0ffb1f068  r9=0000000000000000 r10=0000000000000000
r11=0000000000000246 r12=0000000000000040 r13=0000000000000000
r14=000000c0ffc1b000 r15=0000021102fe0000
iopl=0         no up ei pl zr na pe nc
cs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246
ntdll!LdrInitShimEngineDynamic+0x34d:
00007FFEB655CE5D: eb00 jmp ntdll!ldrinitshimenginedynamic+0x34f
1136:7016> continue
Started thread 7068 at ntdll!RtlReleaseSRWLockExclusive+0x40
Loaded module (00007FFEB4300000) C:\Windows\System32\imm32.dll
Started thread 2484 at shcore!Ordinal172+0xa60
Loaded module (00007FFEB46C0000) C:\Windows\System32\ole32.dll
Loaded module (00007FFEB0CE0000) C:\Windows\System32\uxtheme.dll
Loaded module (00007FFEAF270000) C:\Windows\System32\propsys.dll
Loaded module (00007FFEB6390000) C:\Windows\System32\oleaut32.dll
Loaded module (00007FFEB4110000) C:\Windows\System32\clbcatq.dll
Started thread 6760 at combase!CoRegisterPSClsid+0x3c0
Started thread 1848 at ntdll!RtlReleaseSRWLockExclusive+0x40
Loaded module (00007FFEAE280000) C:\Windows\System32\OneCoreUAPCommonProxyStub.dll
Loaded module (00007FFEAA400000) C:\Windows\System32\urlmon.dll
Loaded module (00007FFEA86E0000) C:\Windows\System32\iertutil.dll
Loaded module (00007FFEB2190000) C:\Windows\System32\cryptbase.dll
Loaded module (00007FFE7C3C0000) C:\Windows\System32\ieframe.dll
Loaded module (00007FFEA86C0000) C:\Windows\System32\netapi32.dll
Loaded module (00007FFEAD540000) C:\Windows\System32\version.dll
Loaded module (00007FFEAC710000) C:\Windows\System32\wkscli.dll
Loaded module (00007FFEB22A0000) C:\Windows\System32\bcrypt.dll
Loaded module (00007FFEB1D80000) C:\Windows\System32\netutils.dll
Loaded module (00007FFEA2440000) C:\Windows\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.17134.112_none_fb3f961b30681c12\comctl32.dll
Loaded module (00007FFEA1CD0000) C:\Windows\System32\msIso.dll
Loaded module (00007FFE9CC40000) C:\Windows\System32\edputil.dll
Loaded module (00007FFEAD060000) C:\Windows\System32\secur32.dll
Loaded module (00007FFEB26D0000) C:\Windows\System32\sspicli.dll
Loaded module (00007FFE950F0000) C:\Windows\System32\mlang.dll
Loaded module (00007FFEA1E50000) C:\Windows\System32\wininet.dll
Loaded module (00007FFEA23F0000) C:\Windows\System32\Windows.UI.AppDefaults.dll
Loaded module (00007FFEACD20000) C:\Windows\System32\policymanager.dll
Loaded module (00007FFEB01C0000) C:\Windows\System32\msvcp110_win.dll
Loaded module (00007FFEB0B20000) C:\Windows\System32\apphelp.dll
Loaded module (00007FFE9B470000) C:\Windows\System32\twinui.dll
Loaded module (00007FFEAEA40000) C:\Windows\System32\WinTypes.dll
Loaded module (00007FFEB0F30000) C:\Windows\System32\dwmapi.dll
Loaded module (00007FFE9FC40000) C:\Windows\System32\twinui.appcore.dll
Loaded module (00007FFEAEB90000) C:\Windows\System32\CoreUIComponents.dll
Loaded module (00007FFEB1890000) C:\Windows\System32\ntmarta.dll
Loaded module (00007FFEB0860000) C:\Windows\System32\CoreMessaging.dll
Loaded module (0000021104E30000) C:\Windows\System32\CoreMessaging.dll
Unloaded module (0000021104E30000) C:\Windows\System32\CoreMessaging.dll
Loaded module (00007FFEA8350000) C:\Windows\System32\MrmCoreR.dll
Loaded module (00007FFEA7EE0000) C:\Windows\System32\BCP47mrm.dll
Loaded module (00007FFEA7F30000) C:\Windows\System32\Windows.UI.dll
Loaded module (00007FFEA78D0000) C:\Windows\System32\TextInputFramework.dll
Loaded module (00007FFEA7850000) C:\Windows\System32\InputHost.dll
Unloaded module (00007FFEB0F30000) C:\Windows\System32\dwmapi.dll
Unloaded module (00007FFE9B470000) C:\Windows\System32\twinui.dll
Unloaded module (00007FFEA86C0000) C:\Windows\System32\netapi32.dll
Unloaded module (00007FFEAD540000) C:\Windows\System32\version.dll
Unloaded module (00007FFEAC710000) C:\Windows\System32\wkscli.dll
Unloaded module (00007FFEB1D80000) C:\Windows\System32\netutils.dll
Unloaded module (00007FFE7C3C0000) C:\Windows\System32\ieframe.dll
Thread 1848 terminated, exit code 0
Thread 7068 terminated, exit code 0
Thread 4436 terminated, exit code 0
Thread 7672 terminated, exit code 0
Thread 6760 terminated, exit code 0
Thread 2484 terminated, exit code 0
Process 1136 terminated, exit code 0
> q

D:\tools>

Missing write_string function

There's a read_string function available for the Process object, but no write_string. Is there a technical reason for this or just an oversight (or alternative)?

GitHub / SourceForge Confusion

Hi,I noticed that the "old" SourceForge page is still up, and also used for some stuff such as documentation and downloads. However, the download links for version 1.6 in the README on GitHub do not work for me at the moment, SourceForge complains that it cannot find the files. Would it be possible to upload the 1.6 Release Installers to GitHub as well, and maybe also move the documentation to over? This may reduce some confusion for new users that try to get the latest version and documentation.

no unicode write for process write

def unicode_to_str(string):
    hex_s = binascii.hexlify(string)
    return ('00'.join(wrap(hex_s, 2)) + '000000').decode('hex')

I write a code for unicode to str and work fine. like process.write(addr, unicode_to_str('string' or u'unicode'))

should check lpBuffer in WriteProcessMemory ,like this:

    if isinstance(lpBuffer, (unicode,)):
        nSize                   = len(lpBuffer) * 2
        lpBuffer                = ctypes.create_unicode_buffer(lpBuffer)
   else:
       # old

and modify process.poke for len change

Re-implement the strings() feature

A user has asked me privately to bring back the strings() method to automatically dump all ASCII strings from a process memory. I am documenting it here so I don't forget later. :)

Thread.get_linear_address doesn't take into account the segment's granularity

Thread.get_linear_address is currently (almost) guaranteed to cause an exception due to an address too large. The reason is that the limit calculation must take into account the granularity of the segment. As state here & here the granularity is either in bytes or pages. Now, the Microsoft docs are not explicit on that, but the granularity affects the calculation of the segment's limit, see for instance the ReactOS source (Line 164).

As a side note, my fix for #55 forgot to address the formatting of the error's text for the case where no segment is given. Might be a good idea to do it here...

ArgumentError: argument 1: <type 'exceptions.TypeError'>: wrong type

Hi there,
I'd like to hook SHUnicodeToAnsi from ShLwApi.dll DLL using this code

        if module.match_name("ShLwApi.dll"):
            pid = event.get_pid()
            address = module.resolve("SHUnicodeToAnsi")
            signature = (LPCWSTR, LPWSTR, INT)
            event.debug.hook_function(pid, address, SHUnicodeToAnsi, signature=signature)

but I'm getting this error

C:\Python27\lib\site-packages\winappdbg\event.py:1853: EventCallbackWarning: Event handler pre-callback <__main__.MyEventHandler object at 0x02B14C10> raised an exception: Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\winappdbg\event.py", line 1848, in dispatch
    returnValue = self.__eventHandler(event)
  File "C:\Python27\lib\site-packages\winappdbg\event.py", line 1465, in __call__
    return method(event)
  File "C:/Users/vvvaa/PycharmProjects/zipper1/main.py", line 44, in load_dll
    event.debug.hook_function(pid, address, SHUnicodeToAnsi, signature=signature)
  File "C:\Python27\lib\site-packages\winappdbg\breakpoint.py", line 4047, in hook_function
    hookObj = Hook(preCB, postCB, paramCount, signature, arch)
  File "C:\Python27\lib\site-packages\winappdbg\breakpoint.py", line 1048, in __new__
    return _Hook_i386(*argv, **argd)
  File "C:\Python27\lib\site-packages\winappdbg\breakpoint.py", line 1138, in __init__
    self._signature = self._calc_signature(signature)
  File "C:\Python27\lib\site-packages\winappdbg\breakpoint.py", line 1440, in _calc_signature
    self._cast_signature_pointers_to_void(signature)
  File "C:\Python27\lib\site-packages\winappdbg\breakpoint.py", line 1152, in _cast_signature_pointers_to_void
    signature[i] = cast(t, c_void_p)
  File "C:\Python27\lib\ctypes\__init__.py", line 503, in cast
    return _cast(obj, obj, typ)
ArgumentError: argument 1: <type 'exceptions.TypeError'>: wrong type

  warnings.warn(msg, EventCallbackWarning)

I saw that SHUnicodeToAnsi function has 3 arguments

; int __stdcall SHUnicodeToUnicode(LPCWSTR pwzSrc, LPWSTR pwzDst, int cwchBuf)
pwzSrc= dword ptr  4
pwzDst= dword ptr  8
cwchBuf= dword ptr  0Ch

Could you help me what I'm doing wrong?

*I know this is a question not issue, I'm sorry

there is no i386 disassembler engine for i386 code

i wanna see disassemble code if i get a crash.

so i've written code like this

eip = event.get_thread().get_pc()
code = event.get_thread().disassemble_around(eip)
crashdump.dump_code(code, eip)

but I received these logs

C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address E06D7363: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address 96170000: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address DE961700: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address 93052000: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address 9C199305: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address F79C1993: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address 800A0CF7: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address B1800A0C: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address EDB1800A: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address A3350F00: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address A3353A77: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address 94000000: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address F7940000: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address A0000000: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address ECA00000: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\process.py:2029: UserWarning: Error read
ing process 324 address DBECA000: Invalid access to memory location.
warnings.warn(msg)
C:\Python27\lib\site-packages\winappdbg\crash.py:618: CrashWarning: Cannot disas
semble, reason: No disassembler engine available for i386 code.
CrashWarning)

Debug 64 bit process

Hey!

Just wanted to ask if we can debug 64 bit process using winappdbg?

Traceback (most recent call last): File "main.py", line 161, in <module> start() File "main.py", line 158, in start proc = debug.execv( [r"C:\Users\aaaa\Desktop\wscript.exe",file.js] ) File "c:\python27\lib\site-packages\winappdbg\debug.py", line 356, in execv return self.execl(lpCmdLine, **kwargs) File "c:\python27\lib\site-packages\winappdbg\debug.py", line 499, in execl aProcess = self.system.start_process(lpCmdLine, **kwargs) File "c:\python27\lib\site-packages\winappdbg\process.py", line 4189, in start_process lpStartupInfo = lpStartupInfo) File "c:\python27\lib\site-packages\winappdbg\win32\defines.py", line 279, in __call__ return fn(*argv, **argd) File "c:\python27\lib\site-packages\winappdbg\win32\kernel32.py", line 3848, in CreateProcessA _CreateProcessA(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation)) File "c:\python27\lib\site-packages\winappdbg\win32\defines.py", line 156, in RaiseIfZero raise ctypes.WinError() WindowsError: [Error 50] The request is not supported.

CreateProcessA failed with error 50 - ERROR_NOT_SUPPORTED

When trying to call debug.execv(..) I get error 50 - ERROR_NOT_SUPPORTED:
File "C:\Python27\lib\site-packages\winappdbg\debug.py", line 356, in execv return self.execl(lpCmdLine, **kwargs) File "C:\Python27\lib\site-packages\winappdbg\debug.py", line 499, in execl aProcess = self.system.start_process(lpCmdLine, **kwargs) File "C:\Python27\lib\site-packages\winappdbg\process.py", line 4258, in start_process lpStartupInfo = lpStartupInfo) File "C:\Python27\lib\site-packages\winappdbg\win32\defines.py", line 279, in __call__ return fn(*argv, **argd) File "C:\Python27\lib\site-packages\winappdbg\win32\kernel32.py", line 3892, in CreateProcessA _CreateProcessA(lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bool(bInheritHandles), dwCreationFlags, lpEnvironment, lpCurrentDirectory, byref(lpStartupInfo), byref(lpProcessInformation)) File "C:\Python27\lib\site-packages\winappdbg\win32\defines.py", line 156, in RaiseIfZero raise ctypes.WinError() WindowsError: [Error 50] The request is not supported.

I think that's because I'm trying to debug 64-bit from 32-bit

Error attaching to suspended process

Hi Marito!
I'm trying to start a suspended process and attaching to it after the creation, but an error occurs when the attach method (in debug.py) calls scan_modules (the error occurs calling CreateTool32Snapshot function). I've work around it commenting lines call functions scan_modules and scan_threads, but would be great if you can add an option to call, or not, scan_modules (and scan_threads).

Message error is the following:


Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python27\Lib\threading.py", line 530, in __bootstrap_inner
    self.run()
  File "C:\Python27\Lib\threading.py", line 483, in run
    self.__target(*self.__args, **self.__kwargs)
  File "reporte_marito.py", line 37, in _run
    aProcess = debug.attach( dwProcessId )
  File "c:\Python27\lib\site-packages\winappdbg\debug.py", line 269, in attach
    aProcess.scan_modules()
  File "c:\Python27\lib\site-packages\winappdbg\module.py", line 1059, in scan_m
odules
    dwProcessId) as hSnapshot:
  File "c:\Python27\lib\site-packages\winappdbg\win32\kernel32.py", line 4239, i
n CreateToolhelp32Snapshot
    raise ctypes.WinError()
WindowsError: [Error 299] Only part of a ReadProcessMemory or WriteProcessMemory
 request was completed.

This is the POC to reproduce the issue:


import winappdbg
from winappdbg import EventHandler, HexDump, Disassembler
import time
from multiprocessing import Queue
import win32process
from threading import Thread
import struct

class DebuggingParams:
    Q_FROM_PARENT = None
    Q_TO_PARENT = None

class DebuggingSession:
    def __init__(self, parent_to_child, child_to_parent):
        DebuggingParams.Q_FROM_PARENT = parent_to_child
        DebuggingParams.Q_TO_PARENT = child_to_parent
        
    def run(self):
        # this function will create an thread to start and kill the acro process
        t = Thread(target=self._run)
        t.start()

    def _run(self):
               
        # Instance a Debug object.
        debug = winappdbg.Debug()
        try:
            from_parent = DebuggingParams.Q_FROM_PARENT
            to_parent = DebuggingParams.Q_TO_PARENT
            
            #wait for event start process
            dwProcessId = from_parent.get(block=True)
            
            # Attach to a running process.
            print "[-] Attaching to process"
            aProcess = debug.attach( dwProcessId )
            
            #send attach ok! to parent
            to_parent.put(True)
            
            # Make sure the debugees die if the debugger dies unexpectedly
            debug.system.set_kill_on_exit_mode(True)
            
            #wait resume thread!
            from_parent.get(block=True)
            
            # Wait for the debugee to finish.
            print "[-] Running Process"
            debug.loop()

        # Stop the debugger.
        finally:
            debug.stop()
            to_parent.put(True)

parent_to_child = Queue()
child_to_parent = Queue()

#create processs
commandLine = "C:\Windows\System32\calc.exe"
si = win32process.STARTUPINFO()
flags = win32process.CREATE_SUSPENDED

print "[*] Creating Debugging session"
ds = DebuggingSession(parent_to_child, child_to_parent)
ds.run()

print "[*] Creating Process"
(_handle, _thandle, _pid, i2) = win32process.CreateProcess(None, commandLine, None, None, 0, flags, None, '.', si)

#waiting creation
time.sleep(0.2)

#send pid
parent_to_child.put(_pid)

#wait for attach
child_to_parent.get(block=True)

print "[*] Resuming Thread"
win32process.ResumeThread(_thandle)

#thread resumed
parent_to_child.put(True)

#wait process finish
child_to_parent.get(block=True)

process.read_string() Error: character "a" will be extract as "D", and so on

Hi,Mario Vilas:
Thanks a lot for your rapidlly response! I understand that the string is really a pointer which should be used to "extract" the real string from the process. But when I use process.read_string(), I found another problem appears: character "a" will be extract as "D", "b" will be extract as "E", "1" will be extract as "x14",and so on.
I use your code in "WinAppDbg Documentation Release 1.4",only change peek() to read_string() :

#------------------------------------------------------------------------------
# BOOL TextOut(
# __in HDC hdc,
# __in int nXStart,
# __in int nYStart,
# __in LPCTSTR lpString,
# __in int cbString
# );
def TextOutA(event, ra, hdc, nXStart, nYStart, lpString, cbString):
    log_ansi(event, "TextOutA", lpString, cbString)
def TextOutW(event, ra, hdc, nXStart, nYStart, lpString, cbString):
    log_wide(event, "TextOutW", lpString, cbString)
# BOOL ExtTextOut(
# __in HDC hdc,
# __in int X,
# __in int Y,
# __in UINT fuOptions,
# __in const RECT * lprc,
# __in LPCTSTR lpString,
# __in UINT cbCount,
# __in const INT * lpDx
# );
def ExtTextOutA(event, ra, hdc, X, Y, fuOptions, lprc, lpString, cbCount, lpDx):
    log_ansi(event, "ExtTextOutA", lpString, cbCount)
def ExtTextOutW(event, ra, hdc, X, Y, fuOptions, lprc, lpString, cbCount, lpDx):
    log_wide(event, "ExtTextOutW", lpString, cbCount)
# typedef struct _POLYTEXT {
# int x;
# int y;
# UINT n;
# LPCTSTR lpstr;
# UINT uiFlags;
# RECT rcl;
# int * pdx;
# } POLYTEXT,* PPOLYTEXT;
class POLYTEXT(Structure):
    _fields_ = [
    ('x', c_int),
    ('y', c_int),
    ('n', c_uint),
    ('lpstr', c_void_p),
    ('uiFlags', c_uint),
    ('rcl', c_uint*4),
    ('pdx', POINTER(c_int)),
    ]
# BOOL PolyTextOut(
# __in HDC hdc,
# __in const POLYTEXT * pptxt,
# __in int cStrings
# );

def PolyTextOutA(event, ra, hdc, pptxt, cStrings):
    process = event.get_process()
    sizeof_polytext = sizeof(POLYTEXT)
    while cStrings:
        txt = process.read_structure(pptxt, POLYTEXT)
        log_ansi(event, "PolyTextOutA", txt.lpstr, txt.n)
        pptxt = pptxt + sizeof_polytext
        cStrings = cStrings - 1

def PolyTextOutW(event, ra, hdc, pptxt, cStrings):
    process = event.get_process()
    sizeof_polytext = sizeof(POLYTEXT)
    while cStrings:
        txt = process.read_structure(pptxt, POLYTEXT)
        log_wide(event, "PolyTextOutW", txt.lpstr, txt.n)
        pptxt = pptxt + sizeof_polytext
        cStrings = cStrings - 1
#------------------------------------------------------------------------------
def log_ansi(event, fn, lpString, nCount):
    if lpString and nCount:
        if c_int(nCount).value == -1:
            lpString = event.get_process().read_string(lpString, fUnicode = False)
        else:
            lpString = event.get_process().read_string(lpString, nCount)
        print (DebugLog.log_text("%s( %r );" % (fn, lpString)))
def log_wide(event, fn, lpString, nCount):
    if lpString and nCount:
        if c_int(nCount).value == -1:
            lpString = event.get_process().read_string(lpString, fUnicode = True)
        else:
            # lpString = event.get_process().peek(lpString, nCount * 2)
            # lpString = unicode(lpString, 'U16', 'strict')

            lpString=event.get_process().read_string(lpString, nCount,fUnicode = True)


        print (DebugLog.log_text("%s( %r );" % (fn, lpString)))

class MyEventHandler( EventHandler ):
    def load_dll(self, event):
        pid = event.get_pid()
        module = event.get_module()
        if module.match_name("gdi32.dll"):
            event.debug.hook_function(pid, module.resolve("TextOutA"), TextOutA, paramCount = 5)
            event.debug.hook_function(pid, module.resolve("TextOutW"), TextOutW, paramCount = 5)
            event.debug.hook_function(pid, module.resolve("ExtTextOutA"), ExtTextOutA, paramCount = 8)
            event.debug.hook_function(pid, module.resolve("ExtTextOutW"), ExtTextOutW, paramCount = 8)
            event.debug.hook_function(pid, module.resolve("PolyTextOutA"), PolyTextOutA, paramCount = 2)
            event.debug.hook_function(pid, module.resolve("PolyTextOutW"), PolyTextOutW, paramCount = 2)
def simple_debugger(argv):
    print (DebugLog.log_text("Trace started on %s" % argv[0]))
    debug = Debug(MyEventHandler())
    try:
        debug.execv(argv)
        debug.loop()
    finally:
        debug.stop()
    print (DebugLog.log_text("Trace stopped on %s" % argv[0]))

if __name__=="__main__":
    program_to_debug="c:\\windows\\system32\\notepad.exe"

    sys.argv.append(program_to_debug)
    simple_debugger(sys.argv[1:])

Can you help me to figure it out where I was wrong! Thanks!

                                Alex Liang

snap_screen_20170623101854

TypeError: object of type '_ctypes.PyCSimpleType' has no len()

I get the following error when trying to run/hook API for LoadLibraryA/W per the example code provided in 09_api_hook.py. Here is the following error.

C:\code\bad_rtf>c:\code\Anaconda\python.exe py_hookz.py "c:\Program Files (x86)
Microsoft Office\Office15\WINWORD.EXE"
c:\code\Anaconda\lib\site-packages\sqlalchemy\sql\base.py:291: SAWarning: Can't
validate argument 'drizzle_engine'; can't locate any SQLAlchemy dialect named 'd
rizzle'
(k, dialect_name))
c:\code\Anaconda\lib\site-packages\winappdbg\debug.py:502: MixedBitsWarning: Mix
ture of 32 and 64 bits is considered experimental. Use at your own risk!
warnings.warn(msg, MixedBitsWarning)
c:\code\Anaconda\lib\site-packages\winappdbg\event.py:1855: EventCallbackWarning
: Event handler pre-callback <main.MyEventHandler object at 0x0000000002E740
B8> raised an exception: Traceback (most recent call last):
File "c:\code\Anaconda\lib\site-packages\winappdbg\event.py", line 1850, in di
spatch
returnValue = self.eventHandler(event)
File "c:\code\Anaconda\lib\site-packages\winappdbg\event.py", line 1461, in __
call

self.hook_dll(event)
File "c:\code\Anaconda\lib\site-packages\winappdbg\event.py", line 1436, in __
hook_dll
hook_api_stub.hook(debug, pid)
File "c:\code\Anaconda\lib\site-packages\winappdbg\breakpoint.py", line 1724,
in hook
aProcess.get_arch() )
File "c:\code\Anaconda\lib\site-packages\winappdbg\breakpoint.py", line 1044,
in __new

return _Hook_i386(_argv, *_argd)
File "c:\code\Anaconda\lib\site-packages\winappdbg\breakpoint.py", line 1134,
in init
self._signature = self._calc_signature(signature)
File "c:\code\Anaconda\lib\site-packages\winappdbg\breakpoint.py", line 1436,
in _calc_signature
self._cast_signature_pointers_to_void(signature)
File "c:\code\Anaconda\lib\site-packages\winappdbg\breakpoint.py", line 1144,
in _cast_signature_pointers_to_void
for i in xrange(len(signature)):
TypeError: object of type '_ctypes.PyCSimpleType' has no len()

warnings.warn(msg, EventCallbackWarning)

Running the following Python distribution.

C:\code\bad_rtf>c:\code\Anaconda\python.exe
Python 2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 16:44:52) [MSC v.
1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org

exit()

This may be a byproduct of 'mixed bits mode' as warned at the script start. The attatched script is here.

Py_hookz.py
http://paste2.org/KaL7cdGF

SHELLEXECUTEINFOA, SHELLEXECUTEINFOW

Hello, thanks for your great work, and it seems that you forgot to split SHELLEXECUTEINFO and LPSHELLEXECUTEINFO to A/W types, which defined in shell32.py: line 176, 201, so that ShellExecuteExA & ShellExecuteExW can't work fine.

Hooks cleared

In some cases, kernel32.dll is unloaded but actually the reference count of that module still greater than zero but apis hooked are cleared.

Can't seem to handle crash when using COM

Hi all,
I'm building my own fuzzer and I'm using winappdbg alongside COM functionalities to make it all work.
the code works something like that:

`
while not q.empty():
launchWord(wordFile, refFile, q)
def launchWord(wordFile, refFile, queue):
fail_count = 0
word = win32com.client.DispatchEx("word.Application")
cmd = ["WINWORD.EXE", fileArgument]
debug = Debug(AccessViolationHandlerWINAPPDBG, bKillOnExit = True )
proc = debug.execv(cmd)
debug.loop()

while (fail_count < 10 and fail_count >= 0):
        try:
            if (word.Selection.Fields.Update() == 0): #update document fields
                queue.task_done()
       except:
           fail_count += 1

def AccessViolationHandlerWINAPPDBG(event):
code = event.get_event_code()
print event
if event.get_event_code() == win32.EXCEPTION_DEBUG_EVENT and event.is_last_chance():
print 'Crash detected'
`

Basically it executes Word with a given file and update it's fields via COM Fields.Update() method.
Everything works fine, printing every event that happens, but fails to handle the crash.
I first thought that it had something to do with the COM operations but now I'm not so sure..

I simply want it to detect the Word crash and act accordingly.
Any ideas?

Access denied when attaching to process

Hi! Thank you very much for your library, we're using it in PyDev.Debugger and PyCharm for attaching to process: https://github.com/fabioz/PyDev.Debugger/tree/master/pydevd_attach_to_process

One of our users reported this exception (https://youtrack.jetbrains.com/issue/PY-29932):

Attaching to a process with PID=15044
C:\virtualenvs\weboptions\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pydev\pydevd_attach_to_process\attach_pydevd.py" --port 54765 --pid 15044
Traceback (most recent call last):
  File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pydev\pydevd_attach_to_process\attach_pydevd.py", line 64, in <module>
    main(process_command_line(sys.argv[1:]))
  File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pydev\pydevd_attach_to_process\attach_pydevd.py", line 61, in main
    setup['pid'], python_code, connect_debugger_tracing=True, show_debug_info=show_debug_info_on_target_process)
  File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pydev\pydevd_attach_to_process\add_code_to_python_process.py", line 395, in run_python_code_windows
    thread, _thread_address = process.inject_code(code, 0)
  File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pydev\pydevd_attach_to_process\winappdbg\process.py", line 3576, in inject_code
    bSuspended = False)
  File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pydev\pydevd_attach_to_process\winappdbg\thread.py", line 1916, in start_thread
    hProcess, 0, 0, lpStartAddress, lpParameter, dwCreationFlags)
  File "C:\Program Files\JetBrains\PyCharm 2018.1.1\helpers\pydev\pydevd_attach_to_process\winappdbg\win32\kernel32.py", line 3796, in CreateRemoteThread
    raise ctypes.WinError()
PermissionError: [WinError 5] Zugriff verweigert

Could you please help us to understand reasons of the problem? Does it happen, because user doesn't have enough permissions? He reported that running the same code as administrator didn't fix the problem.
Thank you!

Getting Stack Trace with Microsoft Symbols

Hi,

I would like to know if I can configure winappdbg with MS symbol server so that in an app crash detail report I get stack trace with actual MS symbol ?

crash = Crash(event)
crash.fetch_extra_data(event)
details = crash.fullReport(bShowNotes=True)

Thanks in Advance,

search_hexa does not work correctly

The search_hexa, and search_bytes sometimes don't return the correct offset. For example:

pattern = "D8 E0 AF 5C 2F 10"
for address, match in process.search_hexa(pattern):
    read = process.read(address, len(pattern.split(" ")))
    print("memory at address", " ".join(["{:02X}".format(ord(_)) for _ in read]))
    print("search pattern", pattern)
    print("found match", " ".join(["{:02X}".format(ord(_)) for _ in match]))

might return:

('memory at address', '87 A0 00 00 00 8B')
('search pattern', 'D8 E0 AF 5C 2F 10')
('found match', 'D8 E0 AF 5C 2F 10')

The match is correct, but reading the process memory at the returned address shows that the address is wrong. The returned address isn't always false, in many cases the address is correct.

.NET CLR exception filtering?

Winappdbg is a great tool!

I have a couple of questions:

1. Any way to filter the type/text of a CLR Exception?

Currently I can filter a .NET CLR exception (inside an event handler) by using:

if (code == win32.EXCEPTION_DEBUG_EVENT and event.get_exception_code() == 0xE0434352):

, but I cannot figure out how to "dig" inside the .NET exception (similar to !PrintException or !pe with the SOS.dll in WinDbg) to filter further on its text/type/etc.

2. Any way to generate a WinDbg/Visual Studio compatible .dmp full memory dump file (similar to .dump /ma in WinDbg, for example)?

I know I can use crash.fetch_extra_data( event, takeMemorySnapshot = 2 ) , but I am not sure how to convert the result to a .dmp file.

Any pointers will be greatly appreciated.

anomaly api_hook signature

I'm using the following code to print the argument passed to the Sleep function.

#!/bin/env python
# -*- coding: utf-8 -*-

from winappdbg import Debug, EventHandler
from winappdbg.win32 import PVOID, DWORD, HANDLE

class MyEventHandler( EventHandler ):

    apiHooks = {

        "kernel32.dll": [
            ("Sleep", (DWORD, )),
        ],
    }

    def pre_Sleep(self, event, ra, dwMilliseconds):
        proc = event.get_process()
        proc.suspend()
        print "%d" % (ra>>32)  # This print the value passed to the Sleep function!
        print dwMilliseconds
        proc.resume()


def simple_debugger( argv ):
    with Debug( MyEventHandler(), bKillOnExit

        debug.attach( int(argv[0]) )
        debug.loop()

if __name__ == "__main__":
    import sys
    simple_debugger( sys.argv[1:] )

I would ask why does the "ra" parameter contain the value passed to the Sleep function? The dwMilliseconds contains a strange garbage value...

Capstone disassembler not working as expected

Simple single step event:

class Stepper(EventHandler):
	def create_process(self, event):
		event.debug.start_tracing(event.get_tid())

	def single_step(self, event):
		try:
			thread = event.get_thread()
			code = thread.disassemble_current()
			print code
		except Exception, e:
			print e
		raw_input()

When run with Capstone installed (3.0.4 for Python 2.7), I was receiving this exception:

  File "C:\Python27\lib\site-packages\winappdbg\event.py", line 1848, in dispatc
h
    returnValue = self.__eventHandler(event)
  File "C:\Python27\lib\site-packages\winappdbg\event.py", line 1465, in __call_
_
    return method(event)
  File "ruzz.py", line 14, in single_step
    code = thread.disassemble_current()
  File "C:\Python27\lib\site-packages\winappdbg\thread.py", line 1718, in disass
emble_current
    return self.disassemble_instruction( self.get_pc() )
  File "C:\Python27\lib\site-packages\winappdbg\thread.py", line 1704, in disass
emble_instruction
    return aProcess.disassemble(lpAddress, 15)[0]
  File "C:\Python27\lib\site-packages\winappdbg\process.py", line 564, in disass
emble
    disasm = self.disassemble_string(lpAddress, data)
  File "C:\Python27\lib\site-packages\winappdbg\process.py", line 543, in disass
emble_string
    return disasm.decode(lpAddress, code)
  File "C:\Python27\lib\site-packages\winappdbg\disasm.py", line 575, in decode
    mnemonic = instr.mnemonic
  File "C:\Python27\lib\site-packages\capstone\__init__.py", line 541, in __geta
ttr__
    raise CsError(CS_ERR_DETAIL)
CsError: Details are unavailable (CS_ERR_DETAIL)

This is occurring in __getattr__ when attempting to access an instruction's mnemonic:

 def __getattr__(self, name):
        if not self._cs._detail:
            raise CsError(CS_ERR_DETAIL)

I had assumed this had something to do with using capstone.cs_disasm_quick disabling disassembly details by default. I patched the decode function to instead use the standard Cs object and this seems to fix it, but I'm not sure what sort of implications this might have.

Since it appears your Capstone engine only cares about the instruction size/mnemonic/op_str, you could use disasm_lite instead of disasm, which should speed things up to cs_disasm_quick levels.

According to the Python bindings code, using the Cs object is more efficient, so it may be something to do anyway.

stack trace is too simple

And I test in IE, when crashed my IE, and I wanted to get the stacktrace by crash.fullReport(), but the info is too simple, not the deep 16.

Stack trace:
Frame            Origin
0000007647653960 000000000000007E (0x7e)

Can I get the stack trace like k in windbg by setting something in winappdbg? thx.

WinAppDbg shuts down before programm finishes

When I tried to debug a programm, the debugger closes before the process ends. I dont know if i'm using it the right way but I think so :). I use Windows 10 and python 2.7 (64 Bit). In the shown case, the calculator app was still running when exit_process event happened. I guess this shouldn't be the case so I reported this.

Here's the poc. It also works with any other app than calc.exe

`# -*- coding: utf-8 -*-

from winappdbg import *


cmd = [b"calc"]


class handler(EventHandler):

	def load_dll(self, event):
		print("A dll has been loaded: %s" % event.get_filename())

	def create_process(self, event):
		print("A new process was created: PID %i" % event.get_process_handle().get_pid())

	def exit_process(self, event):
		print("exit_process")

	def create_thread(self, event):
		print("create_thread")

	def exit_thread(self, event):
		print("exit_thread")

	def unload_dll(self, event):
		print("unload_dll")

	def exception(self, event):
		print("exception")

	def output_string(self, event):
		print("output_string")


debug = Debug(handler())

proc = debug.execv(cmd)
print("Process PID %i" % proc.get_pid())

debug.loop()

The output of the cmd is

Process PID 365364
A new process was created: PID 365364
A dll has been loaded: C:\Windows\System32\ntdll.dll
A dll has been loaded: C:\Windows\System32\kernel32.dll
A dll has been loaded: C:\Windows\System32\KernelBase.dll
A dll has been loaded: C:\Windows\System32\shell32.dll
A dll has been loaded: C:\Windows\System32\ucrtbase.dll
create_thread
A dll has been loaded: C:\Windows\System32\cfgmgr32.dll
A dll has been loaded: C:\Windows\System32\SHCore.dll
A dll has been loaded: C:\Windows\System32\msvcrt.dll
A dll has been loaded: C:\Windows\System32\rpcrt4.dll
A dll has been loaded: C:\Windows\System32\combase.dll
A dll has been loaded: C:\Windows\System32\bcryptprimitives.dll
create_thread
A dll has been loaded: C:\Windows\System32\windows.storage.dll
A dll has been loaded: C:\Windows\System32\msvcp_win.dll
A dll has been loaded: C:\Windows\System32\sechost.dll
A dll has been loaded: C:\Windows\System32\advapi32.dll
A dll has been loaded: C:\Windows\System32\profapi.dll
A dll has been loaded: C:\Windows\System32\powrprof.dll
A dll has been loaded: C:\Windows\System32\umpdc.dll
A dll has been loaded: C:\Windows\System32\shlwapi.dll
A dll has been loaded: C:\Windows\System32\gdi32.dll
A dll has been loaded: C:\Windows\System32\win32u.dll
A dll has been loaded: C:\Windows\System32\gdi32full.dll
A dll has been loaded: C:\Windows\System32\user32.dll
A dll has been loaded: C:\Windows\System32\kernel.appcore.dll
create_thread
A dll has been loaded: C:\Windows\System32\cryptsp.dll
exception
A dll has been loaded: C:\Windows\System32\imm32.dll
create_thread
A dll has been loaded: C:\Windows\System32\ole32.dll
A dll has been loaded: C:\Windows\System32\uxtheme.dll
A dll has been loaded: C:\Windows\System32\propsys.dll
A dll has been loaded: C:\Windows\System32\oleaut32.dll
A dll has been loaded: C:\Windows\System32\urlmon.dll
A dll has been loaded: C:\Windows\System32\iertutil.dll
A dll has been loaded: C:\Windows\System32\cryptbase.dll
A dll has been loaded: C:\Windows\System32\clbcatq.dll
output_string
output_string
A dll has been loaded: C:\Windows\System32\ieframe.dll
A dll has been loaded: C:\Windows\System32\userenv.dll
A dll has been loaded: C:\Windows\System32\version.dll
A dll has been loaded: C:\Windows\System32\winhttp.dll
A dll has been loaded: C:\Windows\System32\netapi32.dll
A dll has been loaded: C:\Windows\System32\wkscli.dll
A dll has been loaded: C:\Windows\System32\bcrypt.dll
A dll has been loaded: C:\Windows\System32\netutils.dll
A dll has been loaded: C:\Windows\WinSxS\amd64_microsoft.windows.common-controls_6595b64144ccf1df_6.0.18362.1440_none_9e7dbfb9e45e8e67\comctl32.dll
create_thread
create_thread
create_thread
create_thread
A dll has been loaded: C:\Windows\System32\Windows.StateRepositoryPS.dll
A dll has been loaded: C:\Windows\System32\WinTypes.dll
A dll has been loaded: C:\Windows\System32\edputil.dll
A dll has been loaded: C:\Windows\System32\secur32.dll
A dll has been loaded: C:\Windows\System32\sspicli.dll
A dll has been loaded: C:\Windows\System32\mlang.dll
A dll has been loaded: C:\Windows\System32\wininet.dll
A dll has been loaded: C:\Windows\System32\Windows.UI.AppDefaults.dll
A dll has been loaded: C:\Windows\System32\policymanager.dll
A dll has been loaded: C:\Windows\System32\msvcp110_win.dll
A dll has been loaded: C:\Windows\System32\apphelp.dll
A dll has been loaded: C:\Windows\System32\twinui.dll
A dll has been loaded: C:\Windows\System32\dwmapi.dll
A dll has been loaded: C:\Windows\System32\pdh.dll
A dll has been loaded: C:\Windows\System32\DXCore.dll
A dll has been loaded: C:\Windows\System32\twinui.appcore.dll
A dll has been loaded: C:\Windows\System32\OneCoreUAPCommonProxyStub.dll
A dll has been loaded: C:\Windows\System32\execmodelproxy.dll
A dll has been loaded: C:\Windows\System32\MrmCoreR.dll
A dll has been loaded: C:\Windows\System32\Windows.StateRepositoryCore.dll
A dll has been loaded: C:\Windows\System32\AppXDeploymentClient.dll
A dll has been loaded: C:\Windows\System32\StateRepository.Core.dll
A dll has been loaded: C:\Windows\System32\FirewallAPI.dll
A dll has been loaded: C:\Windows\System32\dnsapi.dll
A dll has been loaded: C:\Windows\System32\ws2_32.dll
A dll has been loaded: C:\Windows\System32\nsi.dll
A dll has been loaded: C:\Windows\System32\IPHLPAPI.DLL
A dll has been loaded: C:\Windows\System32\fwbase.dll
unload_dll
unload_dll
unload_dll
unload_dll
unload_dll
unload_dll
unload_dll
unload_dll
A dll has been loaded: C:\Windows\System32\BCP47mrm.dll
A dll has been loaded: C:\Windows\System32\Windows.UI.dll
A dll has been loaded: C:\Windows\System32\InputHost.dll
A dll has been loaded: C:\Windows\System32\TextInputFramework.dll
A dll has been loaded: C:\Windows\System32\CoreUIComponents.dll
A dll has been loaded: C:\Windows\System32\CoreMessaging.dll
A dll has been loaded: C:\Windows\System32\ntmarta.dll
exit_thread
exit_thread
exit_thread
exit_thread
exit_thread
exit_thread
exit_thread
exit_thread
exit_process

The debugee is still going on here.

Issue with null termination on command line arguments

There is an issue iv'e encountered in at least one location in the win32 api.

In kernel32.py line 3857:
using max(MAX_PATH, len(lpCommandLine)) will create a string without a null terminator
this creates invalid command lines since the command line will contain heap garbage appended to it
using max(MAX_PATH, len(lpCommandLine+1)) should fix the issue here.

the same happenes in lines 3900 (using +2 should fix the issue here, i think)

Debugged applications may crash randomly after calling Debug.stop()

The title pretty much describes the problem. I am debugging various 32 bit applications using the Debug class. Before calling Debug.next() I check a threading.Event in my debugging loop to see if the debugger should detach. If the event is set, Debug.stop() is called. The debugger quits nicely, but often the debugged application crashes (showing the windows dialog "<foo.exe> has stopped working").
The exception codes I saw were either 0x80000003 or 0x80000004.
Is that a general issue when debugging windows applications or is it possibly a bug?

How to write hex data?

when I use process.write function. the second param only affect string words.
I want to write hex data such as "00 10 33"

sql code is broken

when importing the winappdbg.sql module I get an crash:

    __all__ = ['CrashDAO']
    
    import sqlite3
    import datetime
    import warnings
    
    from sqlalchemy import create_engine, Column, ForeignKey, Sequence
    from sqlalchemy.engine.url import URL
    from sqlalchemy.ext.compiler import compiles
    from sqlalchemy.ext.declarative import declarative_base
>   from sqlalchemy.interfaces import PoolListener
E   ImportError: No module named interfaces

I installed the winappdbg version from current head, running on python 2.7 and sqlalchemy is present (SQLAlchemy==1.4.13)

Reference documentation link is only available intermittently

The reference documentation listed in the programming guide hyperlinks(!) to nicely generated docs that're unfortunately hosted on a site with either the most underfunded or the worst admins ever. As a result, the reference documentation's availability is based on whether or not they're able to win at their job. However, according to @sfnet_ops on twitter, their present issue has been re-occurring for quite a bit now and thus hopefulness is at a loss.

The bad link is located here: https://github.com/MarioVilas/winappdbg/blob/master/doc/source/ProgrammingGuide.rst

Which points to http://winappdbg.sourceforge.net/doc/latest/reference/ instead of a locally created winappdbg reference.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.