Package vtrace :: Package platforms :: Module win32
[hide private]
[frames] | no frames]

Source Code for Module vtrace.platforms.win32

   1  """ 
   2  Win32 Platform Module 
   3  """ 
   4  # Copyright (C) 2007 Invisigoth - See LICENSE file for details 
   5  import os 
   6  import sys 
   7  import struct 
   8  import traceback 
   9  import platform 
  10   
  11  import PE 
  12   
  13  import vstruct 
  14  import vstruct.builder as vs_builder 
  15  import vstruct.defs.win32 as vs_win32 
  16  import vstruct.defs.windows as vs_windows 
  17   
  18  import vtrace 
  19  import vtrace.archs.i386 as v_i386 
  20  import vtrace.archs.amd64 as v_amd64 
  21  import vtrace.platforms.base as v_base 
  22   
  23  import envi 
  24  import envi.bits as e_bits 
  25  import envi.memory as e_mem 
  26  import envi.archs.i386 as e_i386 
  27  import envi.archs.amd64 as e_amd64 
  28  import envi.symstore.resolver as e_resolv 
  29  import envi.symstore.symcache as e_symcache 
  30   
  31  from ctypes import * 
  32  #from ctypes.wintypes import * 
  33   
  34  platdir = os.path.dirname(__file__) 
  35   
  36  kernel32 = None 
  37  dbghelp = None 
  38  psapi = None 
  39  ntdll = None 
  40  advapi32 = None 
  41   
  42  IsWow64Process = None 
  43   
  44  # Setup some ctypes helpers: 
  45  # NOTE: we don't use LPVOID because it can return None. 
  46  #       c_size_t is the designated platform word width int. 
  47  LPVOID = c_size_t 
  48  HANDLE  = LPVOID 
  49  SIZE_T  = LPVOID 
  50  QWORD   = c_ulonglong 
  51  DWORD   = c_ulong 
  52  WORD    = c_ushort 
  53  BOOL    = c_ulong 
  54  BYTE    = c_ubyte 
  55  NULL    = 0 
  56   
  57  INFINITE = 0xffffffff 
  58  EXCEPTION_MAXIMUM_PARAMETERS = 15 
  59   
  60  # Debug Event Types 
  61  EXCEPTION_DEBUG_EVENT       =1 
  62  CREATE_THREAD_DEBUG_EVENT   =2 
  63  CREATE_PROCESS_DEBUG_EVENT  =3 
  64  EXIT_THREAD_DEBUG_EVENT     =4 
  65  EXIT_PROCESS_DEBUG_EVENT    =5 
  66  LOAD_DLL_DEBUG_EVENT        =6 
  67  UNLOAD_DLL_DEBUG_EVENT      =7 
  68  OUTPUT_DEBUG_STRING_EVENT   =8 
  69  RIP_EVENT                   =9 
  70   
  71  # Symbol Flags 
  72  SYMFLAG_VALUEPRESENT     = 0x00000001 
  73  SYMFLAG_REGISTER         = 0x00000008 
  74  SYMFLAG_REGREL           = 0x00000010 
  75  SYMFLAG_FRAMEREL         = 0x00000020 
  76  SYMFLAG_PARAMETER        = 0x00000040 
  77  SYMFLAG_LOCAL            = 0x00000080 
  78  SYMFLAG_CONSTANT         = 0x00000100 
  79  SYMFLAG_EXPORT           = 0x00000200 
  80  SYMFLAG_FORWARDER        = 0x00000400 
  81  SYMFLAG_FUNCTION         = 0x00000800 
  82  SYMFLAG_VIRTUAL          = 0x00001000 
  83  SYMFLAG_THUNK            = 0x00002000 
  84  SYMFLAG_TLSREL           = 0x00004000 
  85   
  86  # Symbol Resolution Options 
  87  SYMOPT_CASE_INSENSITIVE         = 0x00000001 
  88  SYMOPT_UNDNAME                  = 0x00000002 
  89  SYMOPT_DEFERRED_LOADS           = 0x00000004 
  90  SYMOPT_NO_CPP                   = 0x00000008 
  91  SYMOPT_LOAD_LINES               = 0x00000010 
  92  SYMOPT_OMAP_FIND_NEAREST        = 0x00000020 
  93  SYMOPT_LOAD_ANYTHING            = 0x00000040 
  94  SYMOPT_IGNORE_CVREC             = 0x00000080 
  95  SYMOPT_NO_UNQUALIFIED_LOADS     = 0x00000100 
  96  SYMOPT_FAIL_CRITICAL_ERRORS     = 0x00000200 
  97  SYMOPT_EXACT_SYMBOLS            = 0x00000400 
  98  SYMOPT_ALLOW_ABSOLUTE_SYMBOLS   = 0x00000800 
  99  SYMOPT_IGNORE_NT_SYMPATH        = 0x00001000 
 100  SYMOPT_INCLUDE_32BIT_MODULES    = 0x00002000 
 101  SYMOPT_PUBLICS_ONLY             = 0x00004000 
 102  SYMOPT_NO_PUBLICS               = 0x00008000 
 103  SYMOPT_AUTO_PUBLICS             = 0x00010000 
 104  SYMOPT_NO_IMAGE_SEARCH          = 0x00020000 
 105  SYMOPT_SECURE                   = 0x00040000 
 106  SYMOPT_NO_PROMPTS               = 0x00080000 
 107  SYMOPT_OVERWRITE                = 0x00100000 
 108  SYMOPT_DEBUG                    = 0x80000000 
 109   
 110  # Exception Types 
 111  EXCEPTION_WAIT_0                     = 0x00000000L     
 112  EXCEPTION_ABANDONED_WAIT_0           = 0x00000080L     
 113  EXCEPTION_USER_APC                   = 0x000000C0L     
 114  EXCEPTION_TIMEOUT                    = 0x00000102L     
 115  EXCEPTION_PENDING                    = 0x00000103L     
 116  DBG_EXCEPTION_HANDLED             = 0x00010001L     
 117  DBG_CONTINUE                      = 0x00010002L     
 118  EXCEPTION_SEGMENT_NOTIFICATION       = 0x40000005L     
 119  DBG_TERMINATE_THREAD              = 0x40010003L     
 120  DBG_TERMINATE_PROCESS             = 0x40010004L     
 121  DBG_CONTROL_C                     = 0x40010005L     
 122  DBG_CONTROL_BREAK                 = 0x40010008L     
 123  DBG_COMMAND_EXCEPTION             = 0x40010009L     
 124  EXCEPTION_GUARD_PAGE_VIOLATION       = 0x80000001L     
 125  EXCEPTION_DATATYPE_MISALIGNMENT      = 0x80000002L     
 126  EXCEPTION_BREAKPOINT                 = 0x80000003L     
 127  EXCEPTION_SINGLE_STEP                = 0x80000004L     
 128  DBG_EXCEPTION_NOT_HANDLED         = 0x80010001L     
 129  STATUS_BUFFER_OVERFLOW               = 0x80000005L 
 130  STATUS_SUCCESS                       = 0x00000000L 
 131  STATUS_INFO_LENGTH_MISMATCH          = 0xC0000004L 
 132  EXCEPTION_ACCESS_VIOLATION           = 0xC0000005L     
 133  EXCEPTION_IN_PAGE_ERROR              = 0xC0000006L     
 134  EXCEPTION_INVALID_HANDLE             = 0xC0000008L     
 135  EXCEPTION_NO_MEMORY                  = 0xC0000017L     
 136  EXCEPTION_ILLEGAL_INSTRUCTION        = 0xC000001DL     
 137  EXCEPTION_NONCONTINUABLE_EXCEPTION   = 0xC0000025L     
 138  EXCEPTION_INVALID_DISPOSITION        = 0xC0000026L     
 139  EXCEPTION_ARRAY_BOUNDS_EXCEEDED      = 0xC000008CL     
 140  EXCEPTION_FLOAT_DENORMAL_OPERAND     = 0xC000008DL     
 141  EXCEPTION_FLOAT_DIVIDE_BY_ZERO       = 0xC000008EL     
 142  EXCEPTION_FLOAT_INEXACT_RESULT       = 0xC000008FL     
 143  EXCEPTION_FLOAT_INVALID_OPERATION    = 0xC0000090L     
 144  EXCEPTION_FLOAT_OVERFLOW             = 0xC0000091L     
 145  EXCEPTION_FLOAT_STACK_CHECK          = 0xC0000092L     
 146  EXCEPTION_FLOAT_UNDERFLOW            = 0xC0000093L     
 147  EXCEPTION_INTEGER_DIVIDE_BY_ZERO     = 0xC0000094L     
 148  EXCEPTION_INTEGER_OVERFLOW           = 0xC0000095L     
 149  EXCEPTION_PRIVILEGED_INSTRUCTION     = 0xC0000096L     
 150  EXCEPTION_STACK_OVERFLOW             = 0xC00000FDL     
 151  EXCEPTION_CONTROL_C_EXIT             = 0xC000013AL     
 152  EXCEPTION_FLOAT_MULTIPLE_FAULTS      = 0xC00002B4L     
 153  EXCEPTION_FLOAT_MULTIPLE_TRAPS       = 0xC00002B5L     
 154  EXCEPTION_REG_NAT_CONSUMPTION        = 0xC00002C9L     
 155   
 156  # Context Info 
 157  CONTEXT_i386    = 0x00010000    # this assumes that i386 and 
 158  CONTEXT_i486    = 0x00010000    # i486 have identical context records 
 159  CONTEXT_AMD64   = 0x00100000    # For amd x64... 
 160   
 161  CONTEXT_CONTROL         = 0x00000001L # SS:SP, CS:IP, FLAGS, BP 
 162  CONTEXT_INTEGER         = 0x00000002L # AX, BX, CX, DX, SI, DI 
 163  CONTEXT_SEGMENTS        = 0x00000004L # DS, ES, FS, GS 
 164  CONTEXT_FLOATING_POINT  = 0x00000008L # 387 state 
 165  CONTEXT_DEBUG_REGISTERS = 0x00000010L # DB 0-3,6,7 
 166  CONTEXT_EXTENDED_REGISTERS  = 0x00000020L # cpu specific extensions 
 167  CONTEXT_FULL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS) 
 168  CONTEXT_ALL = (CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_FLOATING_POINT | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS) 
 169   
 170   
 171  # Thread Permissions 
 172  THREAD_ALL_ACCESS = 0x001f03ff 
 173  PROCESS_ALL_ACCESS = 0x001f0fff 
 174   
 175  # Memory Permissions 
 176  PAGE_NOACCESS = 0x01 
 177  PAGE_READONLY = 0x02 
 178  PAGE_READWRITE = 0x04 
 179  PAGE_WRITECOPY = 0x08 
 180  PAGE_EXECUTE = 0x10 
 181  PAGE_EXECUTE_READ = 0x20 
 182  PAGE_EXECUTE_READWRITE = 0x40 
 183  PAGE_EXECUTE_WRITECOPY = 0x80 
 184  PAGE_GUARD = 0x100 
 185  PAGE_NOCACHE = 0x200 
 186  PAGE_WRITECOMBINE = 0x400 
 187   
 188  # Map win32 permissions to envi permissions 
 189  perm_lookup = { 
 190      PAGE_NOACCESS:0, 
 191      PAGE_READONLY:e_mem.MM_READ, 
 192      PAGE_READWRITE: e_mem.MM_READ | e_mem.MM_WRITE, 
 193      PAGE_WRITECOPY: e_mem.MM_READ | e_mem.MM_WRITE, 
 194      PAGE_EXECUTE: e_mem.MM_EXEC, 
 195      PAGE_EXECUTE_READ: e_mem.MM_EXEC | e_mem.MM_READ, 
 196      PAGE_EXECUTE_READWRITE: e_mem.MM_EXEC | e_mem.MM_READ | e_mem.MM_WRITE, 
 197      PAGE_EXECUTE_WRITECOPY: e_mem.MM_EXEC | e_mem.MM_READ | e_mem.MM_WRITE, 
 198  } 
 199   
 200  # To get win32 permssions from envi permissions 
 201  perm_rev_lookup = { 
 202      0:PAGE_NOACCESS, 
 203      e_mem.MM_READ:PAGE_READONLY, 
 204      e_mem.MM_READ|e_mem.MM_WRITE:PAGE_READWRITE, 
 205      e_mem.MM_EXEC:PAGE_EXECUTE, 
 206      e_mem.MM_EXEC|e_mem.MM_READ:PAGE_EXECUTE_READ, 
 207      e_mem.MM_EXEC|e_mem.MM_READ|e_mem.MM_WRITE:PAGE_EXECUTE_READWRITE, 
 208  } 
 209   
 210  # Memory States 
 211  MEM_COMMIT = 0x1000 
 212  MEM_FREE = 0x10000 
 213  MEM_RESERVE = 0x2000 
 214   
 215  # Memory Types 
 216  MEM_IMAGE = 0x1000000 
 217  MEM_MAPPED = 0x40000 
 218  MEM_PRIVATE = 0x20000 
 219   
 220  # Process Creation Flags 
 221  DEBUG_ONLY_THIS_PROCESS = 0x02 
 222   
 223  MAX_PATH=260 
224 225 -class MSR(Structure):
226 _fields_ = [ 227 ('msr', DWORD), 228 ('value', QWORD), 229 ]
230 231 # The enum of NtSystemDebugControl operations 232 SysDbgQueryModuleInformation = 0 233 SysDbgQueryTraceInformation = 1 234 SysDbgSetTracepoint = 2 235 SysDbgSetSpecialCall = 3 236 SysDbgClearSpecialCalls = 4 237 SysDbgQuerySpecialCalls = 5 238 SysDbgBreakPoint = 6 239 SysDbgQueryVersion = 7 240 SysDbgReadVirtual = 8 241 SysDbgWriteVirtual = 9 242 SysDbgReadPhysical = 10 243 SysDbgWritePhysical = 11 244 SysDbgReadControlSpace = 12 245 SysDbgWriteControlSpace = 13 246 SysDbgReadIoSpace = 14 247 SysDbgWriteIoSpace = 15 248 SysDbgReadMsr = 16 249 SysDbgWriteMsr = 17 250 SysDbgReadBusData = 18 251 SysDbgWriteBusData = 19 252 SysDbgCheckLowMemory = 20 253 SysDbgEnableKernelDebugger = 21 254 SysDbgDisableKernelDebugger = 22 255 SysDbgGetAutoKdEnable = 23 256 SysDbgSetAutoKdEnable = 24 257 SysDbgGetPrintBufferSize = 25 258 SysDbgSetPrintBufferSize = 26 259 SysDbgGetKdUmExceptionEnable = 27 260 SysDbgSetKdUmExceptionEnable = 28 261 SysDbgGetTriageDump = 29 262 SysDbgGetKdBlockEnable = 30 263 SysDbgSetKdBlockEnable = 31 264 SysDbgRegisterForUmBreakInfo = 32 265 SysDbgGetUmBreakPid = 33 266 SysDbgClearUmBreakPid = 34 267 SysDbgGetUmAttachPid = 35 268 SysDbgClearUmAttachPid = 36
269 270 -def wrmsr(msrid, value):
271 m = MSR() 272 m.msr = msrid 273 m.value = value 274 mptr = addressof(m) 275 x = ntdll.NtSystemDebugControl(SysDbgWriteMsr, mptr, sizeof(m), 0, 0, 0) 276 if x != 0: 277 raise vtrace.PlatformException('NtSystemDebugControl Failed: 0x%.8x' % kernel32.GetLastError()) 278 return 0
279
280 -def rdmsr(msrid):
281 m = MSR() 282 m.msr = msrid 283 m.value = 0 284 285 mptr = addressof(m) 286 msize = sizeof(m) 287 288 x = ntdll.NtSystemDebugControl(SysDbgReadMsr, mptr, msize, mptr, msize, 0) 289 if x != 0: 290 raise vtrace.PlatformException('NtSystemDebugControl Failed: 0x%.8x' % kernel32.GetLastError()) 291 return m.value
292 293 SC_MANAGER_ALL_ACCESS = 0xF003F 294 SC_MANAGER_CREATE_SERVICE = 0x0002 295 SC_MANAGER_CONNECT = 0x0001 296 SC_MANAGER_ENUMERATE_SERVICE = 0x0004 297 SC_MANAGER_LOCK = 0x0008 298 SC_MANAGER_MODIFY_BOOT_CONFIG = 0x0020 299 SC_MANAGER_QUERY_LOCK_STATUS = 0x0010 300 301 SC_ENUM_PROCESS_INFO = 0 302 303 SERVICE_WIN32 = 0x30 304 305 SERVICE_ACTIVE = 0x01 306 SERVICE_INNACTIVE = 0x02 307 SERVICE_STATE_ALL = 0x03
308 309 -class SERVICE_STATUS_PROCESS(Structure):
310 _fields_ = [ 311 ('dwServiceType', DWORD), 312 ('dwCurrentState', DWORD), 313 ('dwControlsAccepted', DWORD), 314 ('dwWin32ExitCode', DWORD), 315 ('dwServiceSpecificExitCode',DWORD), 316 ('dwCheckPoint', DWORD), 317 ('dwWaitHint', DWORD), 318 ('dwProcessId', DWORD), 319 ('dwServiceFlags', DWORD) 320 ]
321
322 -class ENUM_SERVICE_STATUS_PROCESS(Structure):
323 _fields_ = [ 324 ('lpServiceName', c_wchar_p), 325 ('lpDisplayName', c_wchar_p), 326 ('ServiceStatusProcess', SERVICE_STATUS_PROCESS), 327 ]
328
329 -class EXCEPTION_RECORD(Structure):
330 _fields_ = [ 331 ("ExceptionCode", DWORD), 332 ("ExceptionFlags", DWORD), 333 ("ExceptionRecord", LPVOID), 334 ("ExceptionAddress", LPVOID), 335 ("NumberParameters", c_ulong), 336 ("ExceptionInformation", LPVOID * EXCEPTION_MAXIMUM_PARAMETERS) 337 ]
338
339 -class EXCEPTION_DEBUG_INFO(Structure):
340 _fields_ = [ 341 ("ExceptionRecord", EXCEPTION_RECORD), 342 ("FirstChance", c_ulong) 343 ]
344
345 -class CREATE_THREAD_DEBUG_INFO(Structure):
346 _fields_ = [ 347 ("Thread", HANDLE), 348 ("ThreadLocalBase", LPVOID), 349 ("StartAddress", LPVOID) 350 ]
351
352 -class CREATE_PROCESS_DEBUG_INFO(Structure):
353 _fields_ = [ 354 ("File", HANDLE), 355 ("Process", HANDLE), 356 ("Thread", HANDLE), 357 ("BaseOfImage", LPVOID), 358 ("DebugInfoFileOffset", c_ulong), 359 ("DebugInfoSize", c_ulong), 360 ("ThreadLocalBase", LPVOID), 361 ("StartAddress", LPVOID), 362 ("ImageName", LPVOID), 363 ("Unicode", c_short), 364 ]
365
366 -class EXIT_THREAD_DEBUG_INFO(Structure):
367 _fields_ = [("ExitCode", c_ulong),]
368
369 -class EXIT_PROCESS_DEBUG_INFO(Structure):
370 _fields_ = [("ExitCode", c_ulong),]
371
372 -class LOAD_DLL_DEBUG_INFO(Structure):
373 _fields_ = [ 374 ("File", HANDLE), 375 ("BaseOfDll", LPVOID), 376 ("DebugInfoFileOffset", c_ulong), 377 ("DebugInfoSize", c_ulong), 378 ("ImageName", LPVOID), 379 ("Unicode", c_ushort), 380 ]
381 -class UNLOAD_DLL_DEBUG_INFO(Structure):
382 _fields_ = [ 383 ("BaseOfDll", LPVOID), 384 ]
385 -class OUTPUT_DEBUG_STRING_INFO(Structure):
386 _fields_ = [ 387 ("DebugStringData", LPVOID), 388 ("Unicode", c_ushort), 389 ("DebugStringLength", c_ushort), 390 ]
391 -class RIP_INFO(Structure):
392 _fields_ = [ 393 ("Error", c_ulong), 394 ("Type", c_ulong), 395 ]
396
397 -class DBG_EVENT_UNION(Union):
398 _fields_ = [ ("Exception",EXCEPTION_DEBUG_INFO), 399 ("CreateThread", CREATE_THREAD_DEBUG_INFO), 400 ("CreateProcessInfo", CREATE_PROCESS_DEBUG_INFO), 401 ("ExitThread", EXIT_THREAD_DEBUG_INFO), 402 ("ExitProcess", EXIT_PROCESS_DEBUG_INFO), 403 ("LoadDll", LOAD_DLL_DEBUG_INFO), 404 ("UnloadDll", UNLOAD_DLL_DEBUG_INFO), 405 ("DebugString", OUTPUT_DEBUG_STRING_INFO), 406 ("RipInfo", RIP_INFO)]
407
408 -class DEBUG_EVENT(Structure):
409 _fields_ = [ 410 ("DebugEventCode", c_ulong), 411 ("ProcessId", c_ulong), 412 ("ThreadId", c_ulong), 413 ("u", DBG_EVENT_UNION), 414 ]
415
416 -class FloatSavex86(Structure):
417 _fields_ = [("ControlWord", c_ulong), 418 ("StatusWord", c_ulong), 419 ("TagWord", c_ulong), 420 ("ErrorOffset", c_ulong), 421 ("ErrorSelector", c_ulong), 422 ("DataOffset", c_ulong), 423 ("DataSelector", c_ulong), 424 ("RegisterSave", c_byte*80), 425 ("Cr0NpxState", c_ulong), 426 ]
427
428 -class CONTEXTx64(Structure):
429 _fields_ = [ 430 431 ("P1Home",c_ulonglong), 432 ("P2Home",c_ulonglong), 433 ("P3Home",c_ulonglong), 434 ("P4Home",c_ulonglong), 435 ("P5Home",c_ulonglong), 436 ("P6Home",c_ulonglong), 437 438 ("ContextFlags", DWORD), 439 ("MxCsr",DWORD), 440 441 ("cs",WORD), 442 ("ds",WORD), 443 ("es",WORD), 444 ("fs", WORD), 445 ("gs",WORD), 446 ("ss",WORD), 447 ("eflags",DWORD), 448 449 ("debug0",c_ulonglong), 450 ("debug1",c_ulonglong), 451 ("debug2",c_ulonglong), 452 ("debug3",c_ulonglong), 453 ("debug6",c_ulonglong), 454 ("debug7",c_ulonglong), 455 456 ("rax",c_ulonglong), 457 ("rcx",c_ulonglong), 458 ("rdx",c_ulonglong), 459 ("rbx",c_ulonglong), 460 ("rsp",c_ulonglong), 461 ("rbp",c_ulonglong), 462 ("rsi",c_ulonglong), 463 ("rdi",c_ulonglong), 464 ("r8",c_ulonglong), 465 ("r9",c_ulonglong), 466 ("r10",c_ulonglong), 467 ("r11",c_ulonglong), 468 ("r12",c_ulonglong), 469 ("r13",c_ulonglong), 470 ("r14",c_ulonglong), 471 ("r15",c_ulonglong), 472 ("rip",c_ulonglong), 473 474 ("foo",c_ulonglong*200), 475 476 #union { 477 #XMM_SAVE_AREA32 FltSave, 478 #struct { 479 #M128A Header[2], 480 #M128A Legacy[8], 481 #M128A Xmm0, 482 #M128A Xmm1, 483 #M128A Xmm2, 484 #M128A Xmm3, 485 #M128A Xmm4, 486 #M128A Xmm5, 487 #M128A Xmm6, 488 #M128A Xmm7, 489 #M128A Xmm8, 490 #M128A Xmm9, 491 #M128A Xmm10, 492 #M128A Xmm11, 493 #M128A Xmm12, 494 #M128A Xmm13, 495 #M128A Xmm14, 496 #M128A Xmm15, 497 #}, 498 #}, 499 500 #M128A VectorRegister[26], 501 #(VectorControl,c_ulonglong), 502 503 #(DebugControl,c_ulonglong), 504 #(LastBranchToRip,c_ulonglong), 505 #(LastBranchFromRip,c_ulonglong), 506 #(LastExceptionToRip,c_ulonglong), 507 #(LastExceptionFromRip,c_ulonglong), 508 ] 509
510 - def regPostProcess(self):
511 pass
512
513 # Used for xmm registers 514 -class M128A(Structure):
515 _fields_ = [ 516 ('Low', c_ulonglong), 517 ('High', c_ulonglong), 518 ]
519
520 -class ExtendedXmmx86(Structure):
521 _fields_ = [ 522 ('Header', M128A * 2), 523 ('Legacy', M128A * 8), 524 ('_xmm0', M128A), 525 ('_xmm1', M128A), 526 ('_xmm2', M128A), 527 ('_xmm3', M128A), 528 ('_xmm4', M128A), 529 ('_xmm5', M128A), 530 ('_xmm6', M128A), 531 ('_xmm7', M128A), 532 ("Pad", c_byte * 224), 533 ]
534
535 -class CONTEXTx86(Structure):
536 _fields_ = [ ("ContextFlags", c_ulong), 537 ("debug0", c_ulong), 538 ("debug1", c_ulong), 539 ("debug2", c_ulong), 540 ("debug3", c_ulong), 541 ("debug6", c_ulong), 542 ("debug7", c_ulong), 543 ("FloatSave", FloatSavex86), 544 ("gs", c_ulong), 545 ("fs", c_ulong), 546 ("es", c_ulong), 547 ("ds", c_ulong), 548 ("edi", c_ulong), 549 ("esi", c_ulong), 550 ("ebx", c_ulong), 551 ("edx", c_ulong), 552 ("ecx", c_ulong), 553 ("eax", c_ulong), 554 ("ebp", c_ulong), 555 ("eip", c_ulong), 556 ("cs", c_ulong), 557 ("eflags", c_ulong), 558 ("esp", c_ulong), 559 ("ss", c_ulong), 560 561 #("Extension", c_byte * 512), 562 ('Extension', ExtendedXmmx86), 563 564 #M128A Header[2], 565 #M128A Legacy[8], 566 #M128A Xmm0, 567 #M128A Xmm1, 568 #M128A Xmm2, 569 #M128A Xmm3, 570 #M128A Xmm4, 571 #M128A Xmm5, 572 #M128A Xmm6, 573 #M128A Xmm7, 574 ] 575
576 - def regPostProcess(self):
577 self.xmm0 = (self.Extension._xmm0.High << 8) + self.Extension._xmm0.Low 578 self.xmm1 = (self.Extension._xmm1.High << 8) + self.Extension._xmm1.Low 579 self.xmm2 = (self.Extension._xmm2.High << 8) + self.Extension._xmm2.Low 580 self.xmm3 = (self.Extension._xmm3.High << 8) + self.Extension._xmm3.Low 581 self.xmm4 = (self.Extension._xmm4.High << 8) + self.Extension._xmm4.Low 582 self.xmm5 = (self.Extension._xmm5.High << 8) + self.Extension._xmm5.Low 583 self.xmm6 = (self.Extension._xmm6.High << 8) + self.Extension._xmm6.Low 584 self.xmm7 = (self.Extension._xmm7.High << 8) + self.Extension._xmm7.Low
585
586 -class MEMORY_BASIC_INFORMATION(Structure):
587 _fields_ = [ 588 ("BaseAddress", SIZE_T), 589 ("AllocationBase", SIZE_T), 590 ("AllocationProtect", DWORD), 591 ("RegionSize", SIZE_T), 592 ("State", DWORD), 593 ("Protect", DWORD), 594 ("Type", DWORD), 595 ]
596
597 -class STARTUPINFO(Structure):
598 """ 599 Passed into CreateProcess 600 """ 601 _fields_ = [ 602 ("db", c_ulong), 603 ("Reserved", c_char_p), 604 ("Desktop", c_char_p), 605 ("Title", c_char_p), 606 ("X", c_ulong), 607 ("Y", c_ulong), 608 ("XSize", c_ulong), 609 ("YSize", c_ulong), 610 ("XCountChars", c_ulong), 611 ("YCountChars", c_ulong), 612 ("FillAttribute", c_ulong), 613 ("Flags", c_ulong), 614 ("ShowWindow", c_ushort), 615 ("Reserved2", c_ushort), 616 ("Reserved3", LPVOID), 617 ("StdInput", c_ulong), 618 ("StdOutput", c_ulong), 619 ("StdError", c_ulong), 620 ]
621
622 -class PROCESS_INFORMATION(Structure):
623 _fields_ = [ 624 ("Process", HANDLE), 625 ("Thread", HANDLE), 626 ("ProcessId", c_ulong), 627 ("ThreadId", c_ulong), 628 ]
629
630 -class SYMBOL_INFO(Structure):
631 _fields_ = [ 632 ("SizeOfStruct", c_ulong), 633 ("TypeIndex", c_ulong), 634 ("Reserved1", c_ulonglong), 635 ("Reserved2", c_ulonglong), 636 ("Index", c_ulong), 637 ("Size", c_ulong), 638 ("ModBase", c_ulonglong), 639 ("Flags", c_ulong), 640 ("Value", c_ulonglong), 641 ("Address", c_ulonglong), 642 ("Register", c_ulong), 643 ("Scope", c_ulong), 644 ("Tag", c_ulong), 645 ("NameLen", c_ulong), 646 ("MaxNameLen", c_ulong), 647 ("Name", c_char * 2000), # MAX_SYM_NAME 648 ]
649
650 -class IMAGEHLP_MODULE64(Structure):
651 _fields_ = [ 652 ("SizeOfStruct", c_ulong), 653 ("BaseOfImage", c_ulonglong), 654 ("ImageSize", c_ulong), 655 ("TimeDateStamp", c_ulong), 656 ("CheckSum", c_ulong), 657 ("NumSyms", c_ulong), 658 ("SymType", c_ulong), 659 ("ModuleName", c_char*32), 660 ("ImageName", c_char*256), 661 ("LoadedImageName", c_char*256), 662 ("LoadedPdbName", c_char*256), 663 ("CvSig", c_ulong), 664 ("CvData", c_char*(MAX_PATH*3)), 665 ("PdbSig", c_ulong), 666 ("PdbSig70", c_char * 16), #GUID 667 ("PdbAge", c_ulong), 668 ("PdbUnmatched", c_ulong), 669 ("DbgUnmatched", c_ulong), 670 ("LineNumbers", c_ulong), 671 ("GlobalSymbols", c_ulong), 672 ("TypeInfo", c_ulong), 673 ]
674
675 -class IMAGEHLP_STACK_FRAME(Structure):
676 _fields_ = [ 677 ('InstructionOffset', QWORD), 678 ('ReturnOffset', QWORD), 679 ('FrameOffset', QWORD), 680 ('StackOffset', QWORD), 681 ('BackingStoreOffset', QWORD), 682 ('FuncTableEntry', QWORD), 683 ('Params', QWORD*4), 684 ('Reserved', QWORD*5), 685 ('Virtual', BOOL), 686 ('Reserved2', DWORD), 687 ]
688 689 IMAGE_DIRECTORY_ENTRY_EXPORT =0 # Export Directory 690 IMAGE_DIRECTORY_ENTRY_IMPORT =1 # Import Directory 691 IMAGE_DIRECTORY_ENTRY_RESOURCE =2 # Resource Directory 692 IMAGE_DIRECTORY_ENTRY_EXCEPTION =3 # Exception Directory 693 IMAGE_DIRECTORY_ENTRY_SECURITY =4 # Security Directory 694 IMAGE_DIRECTORY_ENTRY_BASERELOC =5 # Base Relocation Table 695 IMAGE_DIRECTORY_ENTRY_DEBUG =6 # Debug Directory 696 IMAGE_DIRECTORY_ENTRY_COPYRIGHT =7 # (X86 usage) 697 IMAGE_DIRECTORY_ENTRY_ARCHITECTURE =7 # Architecture Specific Data 698 IMAGE_DIRECTORY_ENTRY_GLOBALPTR =8 # RVA of GP 699 IMAGE_DIRECTORY_ENTRY_TLS =9 # TLS Directory 700 IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG =10 # Load Configuration Directory 701 IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT =11 # Bound Import Directory in headers 702 IMAGE_DIRECTORY_ENTRY_IAT =12 # Import Address Table 703 IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT =13 # Delay Load Import Descriptors 704 IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR =14 # COM Runtime descriptor 705 706 IMAGE_DEBUG_TYPE_UNKNOWN =0 707 IMAGE_DEBUG_TYPE_COFF =1 708 IMAGE_DEBUG_TYPE_CODEVIEW =2 709 IMAGE_DEBUG_TYPE_FPO =3 710 IMAGE_DEBUG_TYPE_MISC =4 711 IMAGE_DEBUG_TYPE_EXCEPTION =5 712 IMAGE_DEBUG_TYPE_FIXUP =6 713 IMAGE_DEBUG_TYPE_OMAP_TO_SRC =7 714 IMAGE_DEBUG_TYPE_OMAP_FROM_SRC =8 715 IMAGE_DEBUG_TYPE_BORLAND =9 716 IMAGE_DEBUG_TYPE_RESERVED10 =10 717 IMAGE_DEBUG_TYPE_CLSID =11 718 719 SSRVOPT_CALLBACK = 0x0001 720 SSRVOPT_DWORD = 0x0002 721 SSRVOPT_DWORDPTR = 0x0004 722 SSRVOPT_GUIDPTR = 0x0008 723 SSRVOPT_OLDGUIDPTR = 0x0010 724 SSRVOPT_UNATTENDED = 0x0020 725 SSRVOPT_NOCOPY = 0x0040 726 SSRVOPT_PARENTWIN = 0x0080 727 SSRVOPT_PARAMTYPE = 0x0100 728 SSRVOPT_SECURE = 0x0200 729 SSRVOPT_TRACE = 0x0400 730 SSRVOPT_SETCONTEXT = 0x0800 731 SSRVOPT_PROXY = 0x1000 732 SSRVOPT_DOWNSTREAM_STORE = 0x2000 733 734 TI_GET_SYMTAG = 0 735 TI_GET_SYMNAME = 1 736 TI_GET_LENGTH = 2 737 TI_GET_TYPE = 3 738 TI_GET_TYPEID = 4 739 TI_GET_BASETYPE = 5 740 TI_GET_ARRAYINDEXTYPEID = 6 741 TI_FINDCHILDREN = 7 742 TI_GET_DATAKIND = 8 743 TI_GET_ADDRESSOFFSET = 9 744 TI_GET_OFFSET = 10 745 TI_GET_VALUE = 11 746 TI_GET_COUNT = 12 747 TI_GET_CHILDRENCOUNT = 13 748 TI_GET_BITPOSITION = 14 749 TI_GET_VIRTUALBASECLASS = 15 750 TI_GET_VIRTUALTABLESHAPEID = 16 751 TI_GET_VIRTUALBASEPOINTEROFFSET = 17 752 TI_GET_CLASSPARENTID = 18 753 TI_GET_NESTED = 19 754 TI_GET_SYMINDEX = 20 755 TI_GET_LEXICALPARENT = 21 756 TI_GET_ADDRESS = 22 757 TI_GET_THISADJUST = 23 758 TI_GET_UDTKIND = 24 759 TI_IS_EQUIV_TO = 25 760 TI_GET_CALLING_CONVENTION = 26 761 762 SymTagNull = 0 763 SymTagExe = 1 764 SymTagCompiland = 2 765 SymTagCompilandDetails = 3 766 SymTagCompilandEnv = 4 767 SymTagFunction = 5 768 SymTagBlock = 6 769 SymTagData = 7 770 SymTagAnnotation = 8 771 SymTagLabel = 9 772 SymTagPublicSymbol = 10 773 SymTagUDT = 11 774 SymTagEnum = 12 775 SymTagFunctionType = 13 776 SymTagPointerType = 14 777 SymTagArrayType = 15 778 SymTagBaseType = 16 779 SymTagTypedef = 17 780 SymTagBaseClass = 18 781 SymTagFriend = 19 782 SymTagFunctionArgType = 20 783 SymTagFuncDebugStart = 21 784 SymTagFuncDebugEnd = 22 785 SymTagUsingNamespace = 23 786 SymTagVTableShape = 24 787 SymTagVTable = 25 788 SymTagCustom = 26 789 SymTagThunk = 27 790 SymTagCustomType = 28 791 SymTagManagedType = 29 792 SymTagDimension = 30 793 SymTagMax = 31
794 795 -class IMAGE_DEBUG_DIRECTORY(Structure):
796 _fields_ = [ 797 ("Characteristics", c_ulong), 798 ("TimeDateStamp", c_ulong), 799 ("MajorVersion", c_ushort), 800 ("MinorVersion", c_ushort), 801 ("Type", c_ulong), 802 ("SizeOfData", c_ulong), 803 ("AddressOfRawData", c_ulong), 804 ("PointerToRawData", c_ulong), 805 ]
806 807 NT_LIST_HANDLES = 16 808 809 ACCESS_MASK = DWORD
810 -class SYSTEM_HANDLE(Structure):
811 _fields_ = [ 812 ('ProcessID' , c_ulong), 813 ('HandleType' , c_byte), 814 ('Flags' , c_byte), 815 ('HandleNumber' , c_ushort), 816 ('KernelAddress' , LPVOID), 817 ('GrantedAccess' , ACCESS_MASK), 818 ]
819 PSYSTEM_HANDLE = POINTER(SYSTEM_HANDLE) 820 821 # OBJECT_INFORMATION_CLASS 822 ObjectBasicInformation = 0 823 ObjectNameInformation = 1 824 ObjectTypeInformation = 2 825 ObjectAllTypesInformation = 3 826 ObjectHandleInformation = 4 827 828 # ProcessInformationClass 829 ProcessBasicInformation = 0 # Get pointer to PEB 830 ProcessDebugPort = 7 # Get DWORD_PTR to debug port number 831 ProcessWow64Information = 26 # Get WOW64 status 832 # FIXME may be more reliable to use this! \|/ 833 ProcessImageFileName = 27 # Get a UNICODE_STRING of the filename 834 ProcessExecuteFlags = 34 # Get DWORD of execute status (including DEP) (bug: your process only)
835 836 -class UNICODE_STRING(Structure):
837 _fields_ = ( 838 ("Length",c_ushort), 839 ("MaximumLength", c_ushort), 840 ("Buffer", c_wchar_p) 841 )
842 PUNICODE_STRING = POINTER(UNICODE_STRING)
843 844 -class OBJECT_TYPE_INFORMATION(Structure):
845 _fields_ = ( 846 ("String",UNICODE_STRING), 847 ("reserved", c_uint * 22) 848 )
849 850 object_type_map = { 851 "File":vtrace.FD_FILE, 852 "Directory":vtrace.FD_FILE, 853 "Event":vtrace.FD_EVENT, 854 "KeyedEvent":vtrace.FD_EVENT, 855 "Mutant":vtrace.FD_LOCK, 856 "Semaphore":vtrace.FD_LOCK, 857 "Key":vtrace.FD_REGKEY, 858 "Port":vtrace.FD_UNKNOWN, 859 "Section":vtrace.FD_UNKNOWN, 860 "IoCompletion":vtrace.FD_UNKNOWN, 861 "Desktop":vtrace.FD_UNKNOWN, 862 "WindowStation":vtrace.FD_UNKNOWN, 863 }
864 865 -class LUID(Structure):
866 _fields_ = ( 867 ("LowPart", c_ulong), 868 ("HighPart", c_ulong) 869 )
870
871 -class TOKEN_PRIVILEGES(Structure):
872 # This isn't really universal, more just for one priv use 873 _fields_ = ( 874 ("PrivilegeCount", c_ulong), # Always one 875 ("Privilege", LUID), 876 ("PrivilegeAttribute", c_ulong) 877 )
878 879 # All platforms must be able to import this module (for exceptions etc..) 880 # (do this stuff *after* we define some types...) 881 if sys.platform == "win32": 882 883 kernel32 = windll.kernel32 884 # We need to inform some of the APIs about their args 885 kernel32.OpenProcess.argtypes = [DWORD, BOOL, DWORD] 886 kernel32.OpenProcess.restype = HANDLE 887 kernel32.CreateProcessA.argtypes = [LPVOID, c_char_p, LPVOID, LPVOID, c_uint, DWORD, LPVOID, LPVOID, LPVOID, LPVOID] 888 kernel32.ReadProcessMemory.argtypes = [HANDLE, LPVOID, LPVOID, SIZE_T, LPVOID] 889 kernel32.WriteProcessMemory.argtypes = [HANDLE, LPVOID, c_char_p, SIZE_T, LPVOID] 890 kernel32.GetThreadContext.argtypes = [HANDLE, LPVOID] 891 kernel32.SetThreadContext.argtypes = [HANDLE, LPVOID] 892 kernel32.CreateRemoteThread.argtypes = [HANDLE, LPVOID, SIZE_T, LPVOID, LPVOID, DWORD, LPVOID] 893 kernel32.SuspendThread.argtypes = [HANDLE,] 894 kernel32.ResumeThread.argtypes = [HANDLE,] 895 kernel32.VirtualQueryEx.argtypes = [HANDLE, LPVOID, LPVOID, SIZE_T] 896 kernel32.DebugBreakProcess.argtypes = [HANDLE,] 897 kernel32.CloseHandle.argtypes = [HANDLE,] 898 kernel32.GetLogicalDriveStringsA.argtypes = [DWORD, LPVOID] 899 kernel32.TerminateProcess.argtypes = [HANDLE, DWORD] 900 kernel32.VirtualProtectEx.argtypes = [HANDLE, LPVOID, SIZE_T, DWORD, LPVOID] 901 kernel32.VirtualAllocEx.argtypes = [HANDLE, LPVOID, SIZE_T, DWORD, DWORD] 902 kernel32.VirtualAllocEx.restype = c_void_p 903 kernel32.VirtualFreeEx.argtypes = [HANDLE, LPVOID, SIZE_T, DWORD] 904 kernel32.DuplicateHandle.argtypes = [HANDLE, HANDLE, HANDLE, LPVOID, DWORD, DWORD, DWORD] 905 kernel32.SetEvent.argtypes = [HANDLE, ] 906 kernel32.FormatMessageW.argtypes = [DWORD, LPVOID, DWORD, DWORD, LPVOID, DWORD, LPVOID] 907 908 IsWow64Process = getattr(kernel32, 'IsWow64Process', None) 909 if IsWow64Process != None: 910 IsWow64Process.argtypes = [HANDLE, LPVOID] 911 912 913 914 psapi = windll.psapi 915 psapi.GetModuleFileNameExW.argtypes = [HANDLE, HANDLE, LPVOID, DWORD] 916 psapi.GetMappedFileNameW.argtypes = [HANDLE, LPVOID, LPVOID, DWORD] 917 918 ntdll = windll.ntdll 919 ntdll.NtQuerySystemInformation.argtypes = [DWORD, LPVOID, DWORD, LPVOID] 920 ntdll.NtQueryObject.argtypes = [HANDLE, DWORD, c_void_p, DWORD, LPVOID] 921 ntdll.NtQueryObject.restype = c_ulong 922 ntdll.NtQueryInformationProcess.argtypes = [HANDLE, DWORD, c_void_p, DWORD, LPVOID] 923 ntdll.NtSystemDebugControl.restype = SIZE_T 924 925 926 try: 927 928 SYMCALLBACK = WINFUNCTYPE(BOOL, POINTER(SYMBOL_INFO), c_ulong, LPVOID) 929 PDBCALLBACK = WINFUNCTYPE(BOOL, c_char_p, LPVOID) 930 931 arch_name = envi.getCurrentArch() 932 symsrv = windll.LoadLibrary(os.path.join(platdir, "windll", arch_name, "symsrv.dll")) 933 dbghelp = windll.LoadLibrary(os.path.join(platdir, "windll", arch_name, "dbghelp.dll")) 934 dbghelp.SymInitialize.argtypes = [HANDLE, c_char_p, BOOL] 935 dbghelp.SymInitialize.restype = BOOL 936 dbghelp.SymSetOptions.argtypes = [DWORD] 937 dbghelp.SymSetOptions.restype = DWORD 938 dbghelp.SymCleanup.argtypes = [HANDLE] 939 dbghelp.SymCleanup.restype = BOOL 940 dbghelp.SymLoadModule64.argtypes = [HANDLE, HANDLE, c_char_p, c_char_p, QWORD, DWORD] 941 dbghelp.SymLoadModule64.restype = QWORD 942 dbghelp.SymGetModuleInfo64.argtypes = [HANDLE, QWORD, POINTER(IMAGEHLP_MODULE64)] 943 dbghelp.SymSetContext.restype = BOOL 944 dbghelp.SymSetContext.argtypes = [ HANDLE, POINTER(IMAGEHLP_STACK_FRAME), LPVOID ] 945 dbghelp.SymGetModuleInfo64.restype = BOOL 946 dbghelp.SymEnumSymbols.argtypes = [HANDLE, QWORD, c_char_p, SYMCALLBACK, LPVOID] 947 dbghelp.SymEnumSymbols.restype = BOOL 948 dbghelp.SymEnumTypes.argtypes = [HANDLE, QWORD, SYMCALLBACK, LPVOID] 949 dbghelp.SymEnumTypes.restype = BOOL 950 dbghelp.SymGetTypeInfo.argtypes = [HANDLE, QWORD, DWORD, DWORD, c_void_p] 951 dbghelp.SymGetTypeInfo.restype = BOOL 952 dbghelp.SymFromAddr.argtypes = [HANDLE, QWORD, POINTER(QWORD), POINTER(SYMBOL_INFO) ] 953 954 except Exception, e: 955 print "WARNING: Failed to import dbghelp/symsrv: %s" % e 956 957 advapi32 = windll.advapi32 958 advapi32.LookupPrivilegeValueA.argtypes = [LPVOID, c_char_p, LPVOID] 959 advapi32.OpenProcessToken.argtypes = [HANDLE, DWORD, HANDLE] 960 advapi32.AdjustTokenPrivileges.argtypes = [HANDLE, DWORD, LPVOID, DWORD, LPVOID, LPVOID] 961 advapi32.OpenSCManagerA.argtypes = [ LPVOID, LPVOID, DWORD ] 962 advapi32.OpenSCManagerA.restype = HANDLE 963 advapi32.EnumServicesStatusExW.argtypes = [ HANDLE, 964 LPVOID, 965 DWORD, 966 DWORD, 967 LPVOID, 968 DWORD, 969 LPVOID, 970 LPVOID, 971 LPVOID, 972 LPVOID ] 973 advapi32.EnumServicesStatusExW.restype = BOOL 974 advapi32.CloseServiceHandle.argtypes = [ HANDLE, ] 975 advapi32.CloseServiceHandle.restype = BOOL 976 advapi32.GetTokenInformation.argtypes = [HANDLE, DWORD, LPVOID, DWORD, LPVOID] 977 advapi32.GetTokenInformation.restype = BOOL
978 979 -def getFormatMessage(err, isNtStatusCode):
980 ''' 981 Given an error code look up via win32 FormatMessage API. 982 ''' 983 if isNtStatusCode: 984 dwFlags = 0x1800 985 dwSource = windll.ntdll._handle 986 else: 987 dwFlags = 0x1000 988 dwSource = NULL 989 990 dwMessageId = err 991 dwLanguageId = 0 992 dwSize = 512 993 lpBuffer = create_unicode_buffer(dwSize) 994 vaList = NULL 995 ret = kernel32.FormatMessageW( dwFlags, 996 dwSource, 997 dwMessageId, 998 dwLanguageId, 999 addressof(lpBuffer), 1000 dwSize, 1001 vaList) 1002 if not ret: 1003 return None 1004 1005 return lpBuffer.value
1006
1007 -def getServicesList():
1008 ''' 1009 Get a list of (pid, servicename, displayname) tuples for the 1010 currently running services. 1011 ''' 1012 1013 ret = [] 1014 scmh = advapi32.OpenSCManagerA(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE) 1015 1016 try: 1017 dwSvcSize = DWORD(0) 1018 dwSvcCount = DWORD(0) 1019 1020 advapi32.EnumServicesStatusExW( scmh, 1021 SC_ENUM_PROCESS_INFO, 1022 SERVICE_WIN32, 1023 SERVICE_ACTIVE, 1024 NULL, 1025 0, 1026 addressof(dwSvcSize), 1027 addressof(dwSvcCount), 1028 NULL, 1029 NULL) 1030 1031 buf = create_string_buffer(dwSvcSize.value) 1032 1033 #print 'NEEDED',dwSvcSize 1034 #print 'COUNT',dwSvcCount 1035 1036 advapi32.EnumServicesStatusExW( scmh, 1037 SC_ENUM_PROCESS_INFO, 1038 SERVICE_WIN32, 1039 SERVICE_ACTIVE, 1040 addressof(buf), 1041 dwSvcSize.value, 1042 addressof(dwSvcSize), 1043 addressof(dwSvcCount), 1044 NULL, 1045 NULL) 1046 1047 #p = POINTER(ENUM_SERVICE_STATUS_PROCESS)(addressof(buf)) 1048 p = cast(buf, POINTER(ENUM_SERVICE_STATUS_PROCESS)) 1049 1050 for i in xrange(dwSvcCount.value): 1051 pid = p[i].ServiceStatusProcess.dwProcessId 1052 name = p[i].lpServiceName 1053 descr = p[i].lpDisplayName 1054 ret.append((pid, name, descr)) 1055 1056 finally: 1057 advapi32.CloseServiceHandle(scmh) 1058 1059 return ret
1060 1061 x = ''' 1062 BOOL WINAPI EnumServicesStatusEx( 1063 __in SC_HANDLE hSCManager, 1064 __in SC_ENUM_TYPE InfoLevel, 1065 __in DWORD dwServiceType, 1066 __in DWORD dwServiceState, 1067 __out_opt LPBYTE lpServices, 1068 __in DWORD cbBufSize, 1069 __out LPDWORD pcbBytesNeeded, 1070 __out LPDWORD lpServicesReturned, 1071 __inout_opt LPDWORD lpResumeHandle, 1072 __in_opt LPCTSTR pszGroupName 1073 ); 1074 ''' 1075 1076 SE_PRIVILEGE_ENABLED = 0x00000002 1077 TOKEN_ADJUST_PRIVILEGES = 0x00000020 1078 TOKEN_QUERY = 0x00000008 1079 dbgprivdone = False 1080 1081 # TOKEN_INFORMATION_CLASS 1082 TokenUser = 1 1083 TokenGroups = 2 1084 TokenPrivileges = 3 1085 TokenOwner = 4 1086 TokenPrimaryGroup = 5 1087 TokenDefaultDacl = 6 1088 TokenSource = 7 1089 TokenType = 8 1090 TokenImpersonationLevel = 9 1091 TokenStatistics = 10 1092 TokenRestrictedSids = 11 1093 TokenSessionId = 12 1094 TokenGroupsAndPrivileges = 13 1095 TokenSessionReference = 14 1096 TokenSandBoxInert = 15 1097 TokenAuditPolicy = 16 1098 TokenOrigin = 17 1099 TokenElevationType = 18 1100 TokenLinkedToken = 19 1101 TokenElevation = 20 1102 TokenHasRestrictions = 21 1103 TokenAccessInformation = 22 1104 TokenVirtualizationAllowed = 23 1105 TokenVirtualizationEnabled = 24 1106 TokenIntegrityLevel = 25 1107 TokenUIAccess = 26 1108 TokenMandatoryPolicy = 27 1109 TokenLogonSid = 28 1110 MaxTokenInfoClass = 29 1111 1112 # TOKEN_ELEVATION_TYPE 1113 TokenElevationTypeDefault = 1 1114 TokenElevationTypeFull = 2 1115 TokenElevationTypeLimited = 3
1116 1117 -def getTokenElevationType(handle=-1):
1118 1119 token = HANDLE(0) 1120 etype = DWORD(0) 1121 outsize = DWORD(0) 1122 if not advapi32.OpenProcessToken(handle, TOKEN_QUERY, addressof(token)): 1123 raise Exception('Invalid Process Handle: %d' % handle) 1124 1125 advapi32.GetTokenInformation(token, TokenElevationType, addressof(etype), 4, addressof(outsize)) 1126 1127 return etype.value
1128 1129 if __name__ == '__main__': 1130 print getTokenElevationType()
1131 1132 -def getDebugPrivileges():
1133 tokprivs = TOKEN_PRIVILEGES() 1134 dbgluid = LUID() 1135 token = HANDLE(0) 1136 1137 if not advapi32.LookupPrivilegeValueA(0, "seDebugPrivilege", addressof(dbgluid)): 1138 print "LookupPrivilegeValue Failed: %d" % kernel32.GetLastError() 1139 return False 1140 1141 if not advapi32.OpenProcessToken(-1, TOKEN_ADJUST_PRIVILEGES, addressof(token)): 1142 print "kernel32.OpenProcessToken Failed: %d" % kernel32.GetLastError() 1143 return False 1144 1145 tokprivs.PrivilegeCount = 1 1146 tokprivs.Privilege = dbgluid 1147 tokprivs.PrivilegeAttribute = SE_PRIVILEGE_ENABLED 1148 1149 if not advapi32.AdjustTokenPrivileges(token, 0, addressof(tokprivs), 0, 0, 0): 1150 kernel32.CloseHandle(token) 1151 print "AdjustTokenPrivileges Failed: %d" % kernel32.GetLastError() 1152 return False 1153 1154 kernel32.CloseHandle(token)
1155
1156 -def buildSystemHandleInformation(count):
1157 """ 1158 Dynamically build the structure definition for the 1159 handle info list. 1160 """ 1161 class SYSTEM_HANDLE_INFORMATION(Structure): 1162 _fields_ = [ ('Count', c_ulong), ('Handles', SYSTEM_HANDLE * count), ]
1163 return SYSTEM_HANDLE_INFORMATION() 1164
1165 -def buildFindChildrenParams(count):
1166 class TI_FINDCHILDREN_PARAMS(Structure): 1167 _fields_ = [ ('Count', c_ulong), ('Start', c_ulong), ("Children",c_ulong * count),]
1168 tif = TI_FINDCHILDREN_PARAMS() 1169 tif.Count = count 1170 return tif 1171
1172 -def raiseWin32Error(name):
1173 raise vtrace.PlatformException("Win32 Error %s failed: %s" % (name,kernel32.GetLastError()))
1174
1175 -def GetModuleFileNameEx(phandle, mhandle):
1176 1177 buf = create_unicode_buffer(1024) 1178 psapi.GetModuleFileNameExW(phandle, mhandle, addressof(buf), 1024) 1179 return buf.value
1180 1181 av_einfo_perms = [e_mem.MM_READ, e_mem.MM_WRITE, None, None, None, None, None, None, e_mem.MM_EXEC]
1182 1183 -class WindowsMixin:
1184 1185 """ 1186 A mixin to handle all non-arch specific win32 stuff. 1187 """ 1188
1189 - def __init__(self):
1190 1191 self.casesens = False 1192 1193 self.phandle = None 1194 self.thandles = {} 1195 self.win32threads = {} 1196 self.dosdevs = [] 1197 self.flushcache = False 1198 self.faultaddr = None 1199 global dbgprivdone 1200 if not dbgprivdone: 1201 dbgprivdone = getDebugPrivileges() 1202 1203 self._is_wow64 = False # 64 bit trace uses this... 1204 self._step_suspends = set() # Threads we have suspended for single stepping 1205 1206 # Skip the attach event and plow through to the first 1207 # injected breakpoint (cause libs are loaded by then) 1208 self.enableAutoContinue(vtrace.NOTIFY_ATTACH) 1209 1210 self.setupDosDeviceMaps() 1211 1212 # Setup our binary format meta 1213 self.setMeta('Format','pe') 1214 1215 # Setup some win32_ver info in metadata 1216 rel,ver,csd,ptype = platform.win32_ver() 1217 self.setMeta("WindowsRelease",rel) 1218 self.setMeta("WindowsVersion", ver) 1219 self.setMeta("WindowsCsd", csd) 1220 self.setMeta("WindowsProcessorType", ptype) 1221 1222 # Setup modes which only apply to windows systems 1223 self.initMode('BlockStep', False, 'Single step to branch entry points') 1224 1225 # If possible, get a default set of struct definitions 1226 # for ntdll... 1227 nt = vs_windows.getCurrentDef('ntdll') 1228 if nt != None: 1229 self.vsbuilder.addVStructNamespace('ntdll', nt) 1230 1231 # Either way, add the fallback "win32" namespace 1232 self.vsbuilder.addVStructNamespace('win32', vs_win32) 1233 1234 # We need thread proxying for a few calls... 1235 self.fireTracerThread()
1236
1237 - def platformGetFds(self):
1238 ret = [] 1239 hinfo = self.getHandles() 1240 for x in range(hinfo.Count): 1241 if hinfo.Handles[x].ProcessID != self.pid: 1242 continue 1243 1244 hand = hinfo.Handles[x].HandleNumber 1245 myhand = self.dupHandle(hand) 1246 typestr = self.getHandleInfo(myhand, ObjectTypeInformation) 1247 htype = object_type_map.get(typestr, vtrace.FD_UNKNOWN) 1248 1249 # prevent hanging when accessing special named pipes 1250 if hinfo.Handles[x].GrantedAccess == 0x0012019f: 1251 namestr = 'unknown, special named pipe with access mask 0x0012019f' 1252 ret.append( (hand, htype, "%s: %s" % (typestr, namestr)) ) 1253 return ret 1254 1255 wait = False 1256 if typestr == "File": 1257 wait = True 1258 namestr = self.getHandleInfo(myhand, ObjectNameInformation, wait=wait) 1259 kernel32.CloseHandle(myhand) 1260 ret.append( (hand, htype, "%s: %s" % (typestr, namestr)) ) 1261 return ret
1262
1263 - def _winJitEvent(self, handle):
1264 kernel32.SetEvent(handle)
1265
1266 - def dupHandle(self, handle):
1267 """ 1268 Duplicate the handle (who's id is in the currently attached 1269 target process) and return our own copy. 1270 """ 1271 hret = c_uint(0) 1272 kernel32.DuplicateHandle(self.phandle, handle, 1273 kernel32.GetCurrentProcess(), addressof(hret), 1274 0, False, 2) # DUPLICATE_SAME_ACCESS 1275 return hret.value
1276
1277 - def getHandleInfo(self, handle, itype=ObjectTypeInformation, wait=False):
1278 returnLength = c_ulong(0) 1279 objInfo = create_string_buffer(100) 1280 1281 retval = ntdll.NtQueryObject(handle, 1282 itype, 1283 objInfo, 1284 sizeof(objInfo), 1285 addressof(returnLength) 1286 ) 1287 1288 if (retval == STATUS_INFO_LENGTH_MISMATCH or 1289 retval == STATUS_BUFFER_OVERFLOW): 1290 1291 objInfo = create_string_buffer(returnLength.value) 1292 retval = ntdll.NtQueryObject(handle, 1293 itype, 1294 objInfo, 1295 sizeof(objInfo), 1296 addressof(returnLength) 1297 ) 1298 1299 if retval != 0: 1300 return 'Error 0x%.8x' % (e_bits.unsigned(retval, self.psize)) 1301 1302 uString = cast(objInfo, PUNICODE_STRING).contents 1303 1304 return uString.Buffer
1305
1306 - def getHandles(self):
1307 1308 hinfo = buildSystemHandleInformation(1) 1309 hsize = c_ulong(sizeof(hinfo)) 1310 1311 ntdll.NtQuerySystemInformation(NT_LIST_HANDLES, addressof(hinfo), hsize, addressof(hsize)) 1312 1313 count = (hsize.value-4) / sizeof(SYSTEM_HANDLE) 1314 hinfo = buildSystemHandleInformation(count) 1315 hsize = c_ulong(sizeof(hinfo)) 1316 1317 ntdll.NtQuerySystemInformation(NT_LIST_HANDLES, addressof(hinfo), hsize, 0) 1318 1319 return hinfo
1320 1321
1322 - def setupDosDeviceMaps(self):
1323 self.dosdevs = [] 1324 dname = (c_char * 512)() 1325 size = kernel32.GetLogicalDriveStringsA(512, addressof(dname)) 1326 devs = dname.raw[:size-1].split("\x00") 1327 for dev in devs: 1328 dosname = "%s:" % dev[0] 1329 kernel32.QueryDosDeviceA("%s:" % dev[0], pointer(dname), 512) 1330 self.dosdevs.append( (dosname, dname.value) )
1331
1332 - def platformKill(self):
1333 kernel32.TerminateProcess(self.phandle, 0)
1334 1335 @v_base.threadwrap
1336 - def platformExec(self, cmdline):
1337 sinfo = STARTUPINFO() 1338 pinfo = PROCESS_INFORMATION() 1339 if not kernel32.CreateProcessA(0, cmdline, 0, 0, 0, 1340 DEBUG_ONLY_THIS_PROCESS, 0, 0, addressof(sinfo), addressof(pinfo)): 1341 raise Exception("CreateProcess failed!") 1342 1343 # When launching an app, we're guaranteed to get a breakpoint 1344 # Unless we want to fail checkBreakpoints, we'll need to set ShouldBreak 1345 self.setMeta('ShouldBreak', True) 1346 1347 kernel32.CloseHandle(pinfo.Process) 1348 kernel32.CloseHandle(pinfo.Thread) 1349 1350 return pinfo.ProcessId
1351
1352 - def platformInjectSo(self, filename):
1353 tid = c_uint32() 1354 x = self.parseExpression('kernel32.LoadLibraryA') 1355 memaddr = self.allocateMemory(4096) 1356 self.writeMemory(memaddr, '%s\x00' % filename) 1357 t = kernel32.CreateRemoteThread(self.phandle, 0, 0, x, memaddr, 0, addressof(tid)) 1358 self.joinThread(tid.value) 1359 kernel32.CloseHandle(t) 1360 kernel32.VirtualFreeEx(self.phandle, memaddr, 0, 0x8000) # MEM_RELEASE 0x8000 MEM_DECOMMIT 0x4000
1361 1362 @v_base.threadwrap
1363 - def platformAttach(self, pid):
1364 if not kernel32.DebugActiveProcess(pid): 1365 raiseWin32Error("DebugActiveProcess")
1366 1367 @v_base.threadwrap
1368 - def platformDetach(self):
1369 # Do the crazy "can't supress exceptions from detach" dance. 1370 if ((not self.exited) and 1371 self.getCurrentBreakpoint() != None): 1372 self._clearBreakpoints() 1373 self.platformContinue() 1374 self.platformSendBreak() 1375 self.platformWait() 1376 if not kernel32.DebugActiveProcessStop(self.pid): 1377 raiseWin32Error("DebugActiveProcessStop") 1378 kernel32.CloseHandle(self.phandle) 1379 self.phandle = None
1380
1381 - def platformProtectMemory(self, va, size, perms):
1382 pret = c_uint(0) 1383 pval = perm_rev_lookup.get(perms, PAGE_EXECUTE_READWRITE) 1384 ret = kernel32.VirtualProtectEx(self.phandle, va, size, pval, addressof(pret)) 1385 if ret == 0: 1386 raiseWin32Error("kernel32.VirtualProtectEx")
1387
1388 - def platformAllocateMemory(self, size, perms=e_mem.MM_RWX, suggestaddr=0):
1389 pval = perm_rev_lookup.get(perms, PAGE_EXECUTE_READWRITE) 1390 ret = kernel32.VirtualAllocEx(self.phandle, 1391 suggestaddr, size, MEM_COMMIT, pval) 1392 if ret == 0: 1393 raiseWin32Error("kernel32.VirtualAllocEx") 1394 return ret
1395
1396 - def platformReadMemory(self, address, size):
1397 btype = c_char * size 1398 buf = btype() 1399 ret = c_ulong(0) 1400 if not kernel32.ReadProcessMemory(self.phandle, address, addressof(buf), size, addressof(ret)): 1401 raiseWin32Error("kernel32.ReadProcessMemory %s" % hex(address)) 1402 return buf.raw
1403 1404 @v_base.threadwrap
1405 - def platformContinue(self):
1406 1407 # If there is anything in _step_suspends, un-suspend them 1408 for thrid in self._step_suspends: 1409 kernel32.ResumeThread(thrid) 1410 1411 self._step_suspends.clear() 1412 1413 self._continueDebugEvent()
1414
1415 - def _continueDebugEvent(self):
1416 1417 magic = DBG_CONTINUE 1418 1419 if self.getCurrentSignal() != None: 1420 magic = DBG_EXCEPTION_NOT_HANDLED 1421 1422 if self.flushcache: 1423 self.flushcache = False 1424 kernel32.FlushInstructionCache(self.phandle, 0, 0) 1425 1426 if not kernel32.ContinueDebugEvent(self.pid, self.getMeta("StoppedThreadId"), magic): 1427 raiseWin32Error("ContinueDebugEvent")
1428 1429 @v_base.threadwrap
1430 - def platformStepi(self):
1431 # We have some flag fields broken out as meta regs 1432 self.setRegisterByName("TF", 1) 1433 if self.getMode('BlockStep'): 1434 wrmsr(e_i386.MSR_DEBUGCTL, e_i386.MSR_DEBUGCTL_BTF) 1435 1436 self._syncRegs() 1437 1438 # For single step, suspend all the threads except the current 1439 for thrid in self.getThreads().keys(): 1440 1441 # If this thread is the "current thread" don't suspend it 1442 if thrid == self.getCurrentThread(): 1443 # If it was suspended because of stepping another thread 1444 # resume it. 1445 if thrid in self._step_suspends: 1446 kernel32.ResumeThread(thrid) 1447 continue 1448 1449 # Check for "already suspended" 1450 if self.sus_threads.get( thrid ): 1451 continue 1452 1453 # Check if we're returning in a step loop 1454 if thrid in self._step_suspends: 1455 continue 1456 1457 # Call suspend thread directly for speed 1458 kernel32.SuspendThread(thrid) 1459 self._step_suspends.add( thrid ) 1460 1461 self._continueDebugEvent()
1462
1463 - def platformWriteMemory(self, address, buf):
1464 ret = c_ulong(0) 1465 if not kernel32.WriteProcessMemory(self.phandle, address, buf, len(buf), addressof(ret)): 1466 raiseWin32Error("kernel32.WriteProcessMemory") 1467 # If we wrote memory, flush the instruction cache... 1468 self.flushcache = True 1469 return ret.value
1470
1471 - def platformSendBreak(self):
1472 #FIXME make this support windows 2000 1473 if not kernel32.DebugBreakProcess(self.phandle): 1474 raiseWin32Error("kernel32.DebugBreakProcess")
1475
1476 - def platformPs(self):
1477 ret = [] 1478 pcount = 1024 1479 pids = (c_int * pcount)() 1480 needed = c_int(0) 1481 hmodule = HANDLE() 1482 1483 psapi.EnumProcesses(addressof(pids), 4*pcount, addressof(needed)) 1484 if needed.value > pcount: 1485 # If the array was too small, lets up the size to needed + 128 1486 pcount = needed.value + 128 1487 pids = (c_int * pcount)() 1488 psapi.EnumProcesses(addressof(pids), 4*pcount, addressof(needed)) 1489 1490 for i in range(needed.value/4): 1491 fname = (c_wchar * 512)() 1492 phandle = kernel32.OpenProcess(PROCESS_ALL_ACCESS, 0, pids[i]) 1493 if not phandle: # If we get 0, we failed to open it (perms) 1494 continue 1495 psapi.EnumProcessModules(phandle, addressof(hmodule), 4, addressof(needed)) 1496 psapi.GetModuleBaseNameW(phandle, hmodule, fname, 512) 1497 ret.append( (pids[i], fname.value)) 1498 kernel32.CloseHandle(phandle) 1499 kernel32.CloseHandle(hmodule) 1500 return ret
1501 1502 @v_base.threadwrap
1503 - def platformWait(self):
1504 event = DEBUG_EVENT() 1505 if not kernel32.WaitForDebugEvent(addressof(event), INFINITE): 1506 raiseWin32Error("WaitForDebugEvent") 1507 return event
1508
1509 - def platformGetMemFault(self):
1510 return self.faultaddr,self.faultperm
1511
1512 - def platformProcessEvent(self, event):
1513 1514 self.faultaddr = None 1515 self.faultperm = None 1516 1517 if event.ProcessId != self.pid: 1518 raise Exception("event.ProcessId != self.pid (%d != %d)" % 1519 (event.ProcessId,self.pid)) 1520 1521 ThreadId = event.ThreadId 1522 eventdict = {} # Each handler fills this in 1523 self.setMeta("Win32Event", eventdict) 1524 self.setMeta("StoppedThreadId", ThreadId) 1525 self.setMeta("ThreadId", ThreadId) 1526 1527 if event.DebugEventCode == CREATE_PROCESS_DEBUG_EVENT: 1528 self.phandle = event.u.CreateProcessInfo.Process 1529 baseaddr = event.u.CreateProcessInfo.BaseOfImage 1530 ImageName = GetModuleFileNameEx(self.phandle, 0) 1531 if not ImageName: 1532 # If it fails, fall back on getMappedFileName 1533 ImageName = self.getMappedFileName(baseaddr) 1534 self.setMeta("ExeName", ImageName) 1535 1536 teb = event.u.CreateProcessInfo.ThreadLocalBase 1537 self.win32threads[ThreadId] = teb 1538 self.thandles[ThreadId] = event.u.CreateProcessInfo.Thread 1539 1540 tobj = self.getStruct("ntdll.TEB", teb) 1541 if tobj != None: 1542 peb = tobj.ProcessEnvironmentBlock 1543 self.setMeta("PEB", peb) 1544 self.setVariable("peb", peb) 1545 1546 eventdict["ImageName"] = ImageName 1547 eventdict["StartAddress"] = event.u.CreateProcessInfo.StartAddress 1548 eventdict["ThreadLocalBase"] = teb 1549 1550 self._is_wow64 = False 1551 if IsWow64Process != None: 1552 b = BOOL() 1553 IsWow64Process(self.phandle, addressof(b)) 1554 if b.value: 1555 self._is_wow64 = True 1556 1557 self.setMeta('IsWow64', self._is_wow64) 1558 1559 self.fireNotifiers(vtrace.NOTIFY_ATTACH) 1560 self.addLibraryBase(ImageName, baseaddr) 1561 1562 elif event.DebugEventCode == CREATE_THREAD_DEBUG_EVENT: 1563 self.thandles[ThreadId] = event.u.CreateThread.Thread 1564 teb = event.u.CreateThread.ThreadLocalBase 1565 startaddr = event.u.CreateThread.StartAddress 1566 # Setup the event dictionary for notifiers 1567 eventdict["ThreadLocalBase"] = teb 1568 eventdict["StartAddress"] = startaddr 1569 self.win32threads[ThreadId] = teb 1570 self.fireNotifiers(vtrace.NOTIFY_CREATE_THREAD) 1571 1572 elif event.DebugEventCode == EXCEPTION_DEBUG_EVENT: 1573 excode = event.u.Exception.ExceptionRecord.ExceptionCode 1574 exflags = event.u.Exception.ExceptionRecord.ExceptionFlags 1575 exaddr = event.u.Exception.ExceptionRecord.ExceptionAddress 1576 exparam = event.u.Exception.ExceptionRecord.NumberParameters 1577 firstChance = event.u.Exception.FirstChance 1578 1579 plist = [] 1580 for i in range(exparam): 1581 plist.append(long(event.u.Exception.ExceptionRecord.ExceptionInformation[i])) 1582 1583 eventdict["ExceptionCode"] = excode 1584 eventdict["ExceptionFlags"] = exflags 1585 eventdict["ExceptionAddress"] = exaddr 1586 eventdict["NumberParameters"] = exparam 1587 eventdict["FirstChance"] = bool(firstChance) 1588 eventdict["ExceptionInformation"] = plist 1589 1590 if firstChance: 1591 1592 if excode == EXCEPTION_BREAKPOINT: 1593 1594 if not self.checkBreakpoints(): 1595 # On first attach, all the library load 1596 # events occur, then we hit a CC. So, 1597 # if we don't find a breakpoint, notify 1598 # break anyay.... 1599 self.fireNotifiers(vtrace.NOTIFY_BREAK) 1600 1601 elif excode == EXCEPTION_SINGLE_STEP: 1602 1603 if not self.checkWatchpoints(): 1604 self._fireStep() 1605 1606 else: 1607 if excode == 0xc0000005: 1608 self.faultaddr = plist[1] 1609 self.faultperm = av_einfo_perms[plist[0]] 1610 1611 # First we check for PageWatchpoint faults 1612 if not self.checkPageWatchpoints(): 1613 self._fireSignal(excode, siginfo=plist) 1614 1615 else: 1616 self._fireSignal(excode, siginfo=plist) 1617 1618 elif event.DebugEventCode == EXIT_PROCESS_DEBUG_EVENT: 1619 ecode = event.u.ExitProcess.ExitCode 1620 eventdict["ExitCode"] = ecode 1621 self._fireExit(ecode) 1622 self.platformDetach() 1623 1624 elif event.DebugEventCode == EXIT_THREAD_DEBUG_EVENT: 1625 self.win32threads.pop(ThreadId, None) 1626 ecode = event.u.ExitThread.ExitCode 1627 eventdict["ExitCode"] = ecode 1628 self._fireExitThread(ThreadId, ecode) 1629 1630 elif event.DebugEventCode == LOAD_DLL_DEBUG_EVENT: 1631 baseaddr = event.u.LoadDll.BaseOfDll 1632 ImageName = GetModuleFileNameEx(self.phandle, baseaddr) 1633 if not ImageName: 1634 # If it fails, fall back on getMappedFileName 1635 ImageName = self.getMappedFileName(baseaddr) 1636 self.addLibraryBase(ImageName, baseaddr) 1637 kernel32.CloseHandle(event.u.LoadDll.File) 1638 1639 elif event.DebugEventCode == UNLOAD_DLL_DEBUG_EVENT: 1640 baseaddr = event.u.UnloadDll.BaseOfDll 1641 eventdict["BaseOfDll"] = baseaddr 1642 self.delLibraryBase(baseaddr) 1643 1644 elif event.DebugEventCode == OUTPUT_DEBUG_STRING_EVENT: 1645 # Gotta have a way to continue these... 1646 d = event.u.DebugString 1647 sdata = d.DebugStringData 1648 ssize = d.DebugStringLength 1649 1650 # FIXME possibly make a gofast option that 1651 # doesn't get the string 1652 mem = self.readMemory(sdata, ssize) 1653 if d.Unicode: 1654 mem = mem.decode("utf-16-le") 1655 eventdict["DebugString"] = mem 1656 self.fireNotifiers(vtrace.NOTIFY_DEBUG_PRINT) 1657 1658 else: 1659 print "Currently unhandled event",code
1660 1661 # NOTE: Not everbody falls through to here 1662 1663
1664 - def getMappedFileName(self, address):
1665 self.requireAttached() 1666 fname = (c_wchar * 512)() 1667 x = psapi.GetMappedFileNameW(self.phandle, address, addressof(fname), 512) 1668 if not x: 1669 return "" 1670 name = fname.value 1671 for dosname, devname in self.dosdevs: 1672 if name.startswith(devname): 1673 return name.replace(devname, dosname) 1674 return name
1675
1676 - def platformGetMaps(self):
1677 ret = [] 1678 base = 0 1679 1680 mbi = MEMORY_BASIC_INFORMATION() 1681 1682 while kernel32.VirtualQueryEx(self.phandle, base, addressof(mbi), sizeof(mbi)) > 0: 1683 if mbi.State == MEM_COMMIT: 1684 prot = mbi.Protect & 0xff 1685 perm = perm_lookup.get(prot, 0) 1686 base = mbi.BaseAddress 1687 mname = self.getMappedFileName(base) 1688 # If it fails, fall back on getmodulefilename 1689 if mname == "": 1690 mname = GetModuleFileNameEx(self.phandle, base) 1691 ret.append( (base, mbi.RegionSize, perm, mname) ) 1692 1693 base += mbi.RegionSize 1694 1695 return ret
1696
1697 - def platformGetThreads(self):
1698 return self.win32threads
1699
1700 - def platformSuspendThread(self, thrid):
1701 if kernel32.SuspendThread(thrid) == 0xffffffff: 1702 raiseWin32Error()
1703
1704 - def platformResumeThread(self, thrid):
1705 if kernel32.ResumeThread(thrid) == 0xffffffff: 1706 raiseWin32Error()
1707
1708 - def platformParseBinary(self, filename, baseaddr, normname):
1709 pe = PE.peFromMemoryObject(self, baseaddr) 1710 ep = pe.IMAGE_NT_HEADERS.OptionalHeader.AddressOfEntryPoint 1711 self.addSymbol(e_resolv.Symbol('__entry', baseaddr+ep, 0, normname)) 1712 symhash = e_symcache.symCacheHashFromPe(pe) 1713 1714 if self.symcache: 1715 symcache = self.symcache.getCacheSyms(symhash) 1716 if symcache != None: 1717 self.impSymCache( symcache, symfname=normname, baseaddr=baseaddr) 1718 return 1719 1720 symcache = None 1721 # Check if we can use the real lib to parse... 1722 if dbghelp != None and os.path.isfile(filename): 1723 symcache = self.parseWithDbgHelp(filename, baseaddr, normname) 1724 1725 # If it's *still* none, fall back on PE 1726 if symcache == None: 1727 symcache = [ (rva, 0, name, 0) for (rva,ord,name) in pe.getExports() ] 1728 1729 self.impSymCache( symcache, symfname=normname, baseaddr=baseaddr) 1730 1731 if self.symcache: 1732 self.symcache.setCacheSyms(symhash, symcache)
1733
1734 - def parseWithDbgHelp(self, filename, baseaddr, normname):
1735 funcflags = (SYMFLAG_FUNCTION | SYMFLAG_EXPORT) 1736 1737 sympath = self.getMeta('NtSymbolPath') 1738 parser = Win32SymbolParser(self.phandle, filename, baseaddr, sympath=sympath) 1739 parser.parse() 1740 parser.loadStructsIntoTrace(self, normname) 1741 return parser.getCacheSyms()
1742 1743 @v_base.threadwrap
1744 - def platformGetRegCtx(self, threadid):
1745 ctx = self.archGetRegCtx() 1746 c = self._winGetRegStruct() 1747 1748 thandle = self.thandles.get(threadid, None) 1749 if not thandle: 1750 raise Exception("Getting registers for unknown thread") 1751 1752 if not kernel32.GetThreadContext(thandle, addressof(c)): 1753 raiseWin32Error("kernel32.GetThreadContext") 1754 1755 c.regPostProcess() 1756 1757 ctx._rctx_Import(c) 1758 return ctx
1759 1760 @v_base.threadwrap
1761 - def platformSetRegCtx(self, threadid, ctx):
1762 1763 c = self._winGetRegStruct() 1764 1765 thandle = self.thandles.get(threadid, None) 1766 if not thandle: 1767 raise Exception("Getting registers for unknown thread: %d" % threadid) 1768 1769 if not kernel32.GetThreadContext(thandle, addressof(c)): 1770 raiseWin32Error("kernel32.GetThreadContext (tid: %d)" % threadid) 1771 1772 ctx._rctx_Export(c) 1773 1774 if not kernel32.SetThreadContext(thandle, addressof(c)): 1775 raiseWin32Error("kernel32.SetThreadContext (tid: %d)" % threadid)
1776
1777 - def _getSvcList(self):
1778 ''' 1779 Expose the getServicesList via the trace for remote... 1780 ''' 1781 return getServicesList()
1782
1783 - def _getFormatMessage(self, err, isNtStatusCode):
1784 ''' 1785 Expose the getFormatMessage via the trace for remote... 1786 ''' 1787 return getFormatMessage(err, isNtStatusCode)
1788
1789 - def _getUacStatus(self):
1790 return getTokenElevationType(self.phandle)
1791
1792 # NOTE: The order of the constructors vs inheritance is very important... 1793 1794 -class Windowsi386Trace( 1795 vtrace.Trace, 1796 WindowsMixin, 1797 v_i386.i386Mixin, 1798 v_base.TracerBase, 1799 ):
1800
1801 - def __init__(self):
1802 vtrace.Trace.__init__(self) 1803 v_base.TracerBase.__init__(self) 1804 v_i386.i386Mixin.__init__(self) 1805 WindowsMixin.__init__(self)
1806
1807 - def _winGetRegStruct(self):
1808 c = CONTEXTx86() 1809 c.ContextFlags = (CONTEXT_i386 | 1810 CONTEXT_FULL | 1811 CONTEXT_DEBUG_REGISTERS | 1812 CONTEXT_EXTENDED_REGISTERS) 1813 return c
1814
1815 -class WindowsAmd64Trace( 1816 vtrace.Trace, 1817 WindowsMixin, 1818 v_amd64.Amd64Mixin, 1819 v_base.TracerBase, 1820 ):
1821
1822 - def __init__(self):