forked from OpenRCE/pydbg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pydbg.py
3644 lines (2679 loc) · 148 KB
/
pydbg.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!c:\python\python.exe
#
# PyDBG
# Copyright (C) 2006 Pedram Amini <[email protected]>
#
# $Id: pydbg.py 253 2011-01-24 19:13:57Z my.name.is.sober $
#
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
'''
@author: Pedram Amini
@license: GNU General Public License 2.0 or later
@contact: [email protected]
@organization: www.openrce.org
'''
import os.path
import sys
import copy
import signal
import struct
import pydasm
import socket
from my_ctypes import *
from defines import *
from windows_h import *
# macos compatability.
try:
kernel32 = windll.kernel32
advapi32 = windll.advapi32
ntdll = windll.ntdll
iphlpapi = windll.iphlpapi
except:
kernel32 = CDLL(os.path.join(os.path.dirname(__file__), "libmacdll.dylib"))
advapi32 = kernel32
from breakpoint import *
from hardware_breakpoint import *
from memory_breakpoint import *
from memory_snapshot_block import *
from memory_snapshot_context import *
from pdx import *
from system_dll import *
class pydbg:
'''
This class implements standard low leven functionality including:
- The load() / attach() routines.
- The main debug event loop.
- Convenience wrappers for commonly used Windows API.
- Single step toggling routine.
- Win32 error handler wrapped around PDX.
- Base exception / event handler routines which are meant to be overridden.
Higher level functionality is also implemented including:
- Register manipulation.
- Soft (INT 3) breakpoints.
- Memory breakpoints (page permissions).
- Hardware breakpoints.
- Exception / event handling call backs.
- Pydasm (libdasm) disassembly wrapper.
- Process memory snapshotting and restoring.
- Endian manipulation routines.
- Debugger hiding.
- Function resolution.
- "Intelligent" memory derefencing.
- Stack/SEH unwinding.
- Etc...
'''
STRING_EXPLORATON_BUF_SIZE = 256
STRING_EXPLORATION_MIN_LENGTH = 2
####################################################################################################################
def __init__ (self, ff=True, cs=False):
'''
Set the default attributes. See the source if you want to modify the default creation values.
@type ff: Boolean
@param ff: (Optional, Def=True) Flag controlling whether or not pydbg attaches to forked processes
@type cs: Boolean
@param cs: (Optional, Def=False) Flag controlling whether or not pydbg is in client/server (socket) mode
'''
# private variables, internal use only:
self._restore_breakpoint = None # breakpoint to restore
self._guarded_pages = set() # specific pages we set PAGE_GUARD on
self._guards_active = True # flag specifying whether or not guard pages are active
self.page_size = 0 # memory page size (dynamically resolved at run-time)
self.pid = 0 # debuggee's process id
self.h_process = None # debuggee's process handle
self.h_thread = None # handle to current debuggee thread
self.debugger_active = True # flag controlling the main debugger event handling loop
self.follow_forks = ff # flag controlling whether or not pydbg attaches to forked processes
self.client_server = cs # flag controlling whether or not pydbg is in client/server mode
self.callbacks = {} # exception callback handler dictionary
self.system_dlls = [] # list of loaded system dlls
self.dirty = False # flag specifying that the memory space of the debuggee was modified
self.system_break = None # the address at which initial and forced breakpoints occur at
self.peb = None # process environment block address
self.tebs = {} # dictionary of thread IDs to thread environment block addresses
# internal variables specific to the last triggered exception.
self.context = None # thread context of offending thread
self.dbg = None # DEBUG_EVENT
self.exception_address = None # from dbg.u.Exception.ExceptionRecord.ExceptionAddress
self.write_violation = None # from dbg.u.Exception.ExceptionRecord.ExceptionInformation[0]
self.violation_address = None # from dbg.u.Exception.ExceptionRecord.ExceptionInformation[1]
self.exception_code = None # from dbg.u.Exception.ExceptionRecord.ExceptionCode
self.breakpoints = {} # internal breakpoint dictionary, keyed by address
self.memory_breakpoints = {} # internal memory breakpoint dictionary, keyed by base address
self.hardware_breakpoints = {} # internal hardware breakpoint array, indexed by slot (0-3 inclusive)
self.memory_snapshot_blocks = [] # list of memory blocks at time of memory snapshot
self.memory_snapshot_contexts = [] # list of threads contexts at time of memory snapshot
self.first_breakpoint = True # this flag gets disabled once the windows initial break is handled
self.memory_breakpoint_hit = 0 # address of hit memory breakpoint or zero on miss
# designates whether or not the violation was in reaction to a memory
# breakpoint hit or other unrelated event.
self.hardware_breakpoint_hit = None # hardware breakpoint on hit or None on miss
# designates whether or not the single step event was in reaction to
# a hardware breakpoint hit or other unrelated event.
self.instruction = None # pydasm instruction object, propagated by self.disasm()
self.mnemonic = None # pydasm decoded instruction mnemonic, propagated by self.disasm()
self.op1 = None # pydasm decoded 1st operand, propagated by self.disasm()
self.op2 = None # pydasm decoded 2nd operand, propagated by self.disasm()
self.op3 = None # pydasm decoded 3rd operand, propagated by self.disasm()
# control debug/error logging.
self._log = lambda msg: None #sys.stderr.write("PDBG_LOG> " + msg + "\n")
self._err = lambda msg: sys.stderr.write("PDBG_ERR> " + msg + "\n")
# determine the system page size.
system_info = SYSTEM_INFO()
kernel32.GetSystemInfo(byref(system_info))
self.page_size = system_info.dwPageSize
# determine the system DbgBreakPoint address. this is the address at which initial and forced breaks happen.
# XXX - need to look into fixing this for pydbg client/server.
self.system_break = self.func_resolve("ntdll.dll", "DbgBreakPoint")
self._log("system page size is %d" % self.page_size)
####################################################################################################################
def addr_to_dll (self, address):
'''
Return the system DLL that contains the address specified.
@type address: DWORD
@param address: Address to search system DLL ranges for
@rtype: system_dll
@return: System DLL that contains the address specified or None if not found.
'''
for dll in self.system_dlls:
if dll.base < address < dll.base + dll.size:
return dll
return None
####################################################################################################################
def addr_to_module (self, address):
'''
Return the MODULEENTRY32 structure for the module that contains the address specified.
@type address: DWORD
@param address: Address to search loaded module ranges for
@rtype: MODULEENTRY32
@return: MODULEENTRY32 strucutre that contains the address specified or None if not found.
'''
found = None
for module in self.iterate_modules():
if module.modBaseAddr < address < module.modBaseAddr + module.modBaseSize:
# we have to make a copy of the 'module' since it is an iterator and will be blown away.
# the reason we can't "break" out of the loop is because there will be a handle leak.
# and we can't use enumerate_modules() because we need the entire module structure.
# so there...
found = copy.copy(module)
return found
####################################################################################################################
def attach (self, pid):
'''
Attach to the specified process by PID. Saves a process handle in self.h_process and prevents debuggee from
exiting on debugger quit.
@type pid: Integer
@param pid: Process ID to attach to
@raise pdx: An exception is raised on failure.
@rtype: pydbg
@return: Self
'''
self._log("attaching to pid %d" % pid)
# obtain necessary debug privileges.
self.get_debug_privileges()
self.pid = pid
self.open_process(pid)
self.debug_active_process(pid)
# allow detaching on systems that support it.
try:
self.debug_set_process_kill_on_exit(False)
except:
pass
# enumerate the TEBs and add them to the internal dictionary.
for thread_id in self.enumerate_threads():
thread_handle = self.open_thread(thread_id)
thread_context = self.get_thread_context(thread_handle)
selector_entry = LDT_ENTRY()
if not kernel32.GetThreadSelectorEntry(thread_handle, thread_context.SegFs, byref(selector_entry)):
self.win32_error("GetThreadSelectorEntry()")
self.close_handle(thread_handle)
teb = selector_entry.BaseLow
teb += (selector_entry.HighWord.Bits.BaseMid << 16) + (selector_entry.HighWord.Bits.BaseHi << 24)
# add this TEB to the internal dictionary.
self.tebs[thread_id] = teb
# if the PEB has not been set yet, do so now.
if not self.peb:
self.peb = self.read_process_memory(teb + 0x30, 4)
self.peb = struct.unpack("<L", self.peb)[0]
return self.ret_self()
####################################################################################################################
def bp_del (self, address):
'''
Removes the breakpoint from target address.
@see: bp_set(), bp_del_all(), bp_is_ours()
@type address: DWORD or List
@param address: Address or list of addresses to remove breakpoint from
@raise pdx: An exception is raised on failure.
@rtype: pydbg
@return: Self
'''
# if a list of addresses to remove breakpoints from was supplied.
if type(address) is list:
# pass each lone address to ourself.
for addr in address:
self.bp_del(addr)
return self.ret_self()
self._log("bp_del(0x%08x)" % address)
# ensure a breakpoint exists at the target address.
if self.breakpoints.has_key(address):
# restore the original byte.
self.write_process_memory(address, self.breakpoints[address].original_byte)
self.set_attr("dirty", True)
# remove the breakpoint from the internal list.
del self.breakpoints[address]
return self.ret_self()
####################################################################################################################
def bp_del_all (self):
'''
Removes all breakpoints from the debuggee.
@see: bp_set(), bp_del(), bp_is_ours()
@raise pdx: An exception is raised on failure.
@rtype: pydbg
@return: Self
'''
self._log("bp_del_all()")
for bp in self.breakpoints.keys():
self.bp_del(bp)
return self.ret_self()
####################################################################################################################
def bp_del_hw (self, address=None, slot=None):
'''
Removes the hardware breakpoint from the specified address or slot. Either an address or a slot must be
specified, but not both.
@see: bp_set_hw(), bp_del_hw_all()
@type address: DWORD
@param address: (Optional) Address to remove hardware breakpoint from.
@type slot: Integer (0 through 3)
@param slot: (Optional)
@raise pdx: An exception is raised on failure.
@rtype: pydbg
@return: Self
'''
if address == slot == None:
raise pdx("hw bp address or slot # must be specified.")
if not address and slot not in xrange(4):
raise pdx("invalid hw bp slot: %d. valid range is 0 through 3" % slot)
# de-activate the hardware breakpoint for all active threads.
for thread_id in self.enumerate_threads():
context = self.get_thread_context(thread_id=thread_id)
if address:
if context.Dr0 == address: slot = 0
elif context.Dr1 == address: slot = 1
elif context.Dr2 == address: slot = 2
elif context.Dr3 == address: slot = 3
# mark slot as inactive.
# bits 0, 2, 4, 6 for local (L0 - L3)
# bits 1, 3, 5, 7 for global (L0 - L3)
context.Dr7 &= ~(1 << (slot * 2))
# remove address from the specified slot.
if slot == 0: context.Dr0 = 0x00000000
elif slot == 1: context.Dr1 = 0x00000000
elif slot == 2: context.Dr2 = 0x00000000
elif slot == 3: context.Dr3 = 0x00000000
# remove the condition (RW0 - RW3) field from the appropriate slot (bits 16/17, 20/21, 24,25, 28/29)
context.Dr7 &= ~(3 << ((slot * 4) + 16))
# remove the length (LEN0-LEN3) field from the appropriate slot (bits 18/19, 22/23, 26/27, 30/31)
context.Dr7 &= ~(3 << ((slot * 4) + 18))
# set the thread context.
self.set_thread_context(context, thread_id=thread_id)
# remove the breakpoint from the internal list.
del self.hardware_breakpoints[slot]
return self.ret_self()
####################################################################################################################
def bp_del_hw_all (self):
'''
Removes all hardware breakpoints from the debuggee.
@see: bp_set_hw(), bp_del_hw()
@raise pdx: An exception is raised on failure.
@rtype: pydbg
@return: Self
'''
if self.hardware_breakpoints.has_key(0): self.bp_del_hw(slot=0)
if self.hardware_breakpoints.has_key(1): self.bp_del_hw(slot=1)
if self.hardware_breakpoints.has_key(2): self.bp_del_hw(slot=2)
if self.hardware_breakpoints.has_key(3): self.bp_del_hw(slot=3)
return self.ret_self()
####################################################################################################################
def bp_del_mem (self, address):
'''
Removes the memory breakpoint from target address.
@see: bp_del_mem_all(), bp_set_mem(), bp_is_ours_mem()
@type address: DWORD
@param address: Address or list of addresses to remove memory breakpoint from
@raise pdx: An exception is raised on failure.
@rtype: pydbg
@return: Self
'''
self._log("bp_del_mem(0x%08x)" % address)
# ensure a memory breakpoint exists at the target address.
if self.memory_breakpoints.has_key(address):
size = self.memory_breakpoints[address].size
mbi = self.memory_breakpoints[address].mbi
# remove the memory breakpoint from our internal list.
del self.memory_breakpoints[address]
# page-aligned target memory range.
start = mbi.BaseAddress
end = address + size # non page-aligned range end
end = end + self.page_size - (end % self.page_size) # page-aligned range end
# for each page in the target range, restore the original page permissions if no other breakpoint exists.
for page in range(start, end, self.page_size):
other_bp_found = False
for mem_bp in self.memory_breakpoints.values():
if page <= mem_bp.address < page + self.page_size:
other_bp_found = True
break
if page <= mem_bp.address + size < page + self.page_size:
other_bp_found = True
break
if not other_bp_found:
try:
self.virtual_protect(page, 1, mbi.Protect & ~PAGE_GUARD)
# remove the page from the set of tracked GUARD pages.
self._guarded_pages.remove(mbi.BaseAddress)
except:
pass
return self.ret_self()
####################################################################################################################
def bp_del_mem_all (self):
'''
Removes all memory breakpoints from the debuggee.
@see: bp_del_mem(), bp_set_mem(), bp_is_ours_mem()
@raise pdx: An exception is raised on failure.
@rtype: pydbg
@return: Self
'''
self._log("bp_del_mem_all()")
for address in self.memory_breakpoints.keys():
self.bp_del_mem(address)
return self.ret_self()
####################################################################################################################
def bp_is_ours (self, address_to_check):
'''
Determine if a breakpoint address belongs to us.
@see: bp_set(), bp_del(), bp_del_all()
@type address_to_check: DWORD
@param address_to_check: Address to check if we have set a breakpoint at
@rtype: Bool
@return: True if breakpoint in question is ours, False otherwise
'''
if self.breakpoints.has_key(address_to_check):
return True
return False
####################################################################################################################
def bp_is_ours_mem (self, address_to_check):
'''
Determines if the specified address falls within the range of one of our memory breakpoints. When handling
potential memory breakpoint exceptions it is mandatory to check the offending address with this routine as
memory breakpoints are implemented by changing page permissions and the referenced address may very well exist
within the same page as a memory breakpoint but not within the actual range of the buffer we wish to break on.
@see: bp_set_mem(), bp_del_mem(), bp_del_mem_all()
@type address_to_check: DWORD
@param address_to_check: Address to check if we have set a breakpoint on
@rtype: Mixed
@return: The starting address of the buffer our breakpoint triggered on or False if address falls outside range.
'''
for address in self.memory_breakpoints:
size = self.memory_breakpoints[address].size
if address_to_check >= address and address_to_check <= address + size:
return address
return False
####################################################################################################################
def bp_set (self, address, description="", restore=True, handler=None):
'''
Sets a breakpoint at the designated address. Register an EXCEPTION_BREAKPOINT callback handler to catch
breakpoint events. If a list of addresses is submitted to this routine then the entire list of new breakpoints
get the same description and restore. The optional "handler" parameter can be used to identify a function to
specifically handle the specified bp, as opposed to the generic bp callback handler. The prototype of the
callback routines is::
func (pydbg)
return DBG_CONTINUE # or other continue status
@see: bp_is_ours(), bp_del(), bp_del_all()
@type address: DWORD or List
@param address: Address or list of addresses to set breakpoint at
@type description: String
@param description: (Optional) Description to associate with this breakpoint
@type restore: Bool
@param restore: (Optional, def=True) Flag controlling whether or not to restore the breakpoint
@type handler: Function Pointer
@param handler: (Optional, def=None) Optional handler to call for this bp instead of the default handler
@raise pdx: An exception is raised on failure.
@rtype: pydbg
@return: Self
'''
# if a list of addresses to set breakpoints on from was supplied
if type(address) is list:
# pass each lone address to ourself (each one gets the same description / restore flag).
for addr in address:
self.bp_set(addr, description, restore, handler)
return self.ret_self()
self._log("bp_set(0x%08x)" % address)
# ensure a breakpoint doesn't already exist at the target address.
if not self.breakpoints.has_key(address):
try:
# save the original byte at the requested breakpoint address.
original_byte = self.read_process_memory(address, 1)
# write an int3 into the target process space.
self.write_process_memory(address, "\xCC")
self.set_attr("dirty", True)
# add the breakpoint to the internal list.
self.breakpoints[address] = breakpoint(address, original_byte, description, restore, handler)
except:
raise pdx("Failed setting breakpoint at %08x" % address)
return self.ret_self()
####################################################################################################################
def bp_set_hw (self, address, length, condition, description="", restore=True, handler=None):
'''
Sets a hardware breakpoint at the designated address. Register an EXCEPTION_SINGLE_STEP callback handler to
catch hardware breakpoint events. Setting hardware breakpoints requires the internal h_thread handle be set.
This means that you can not set one outside the context of an debug event handler. If you want to set a hardware
breakpoint as soon as you attach to or load a process, do so in the first chance breakpoint handler.
For more information regarding the Intel x86 debug registers and hardware breakpoints see::
http://pdos.csail.mit.edu/6.828/2005/readings/ia32/IA32-3.pdf
Section 15.2
Alternatively, you can register a custom handler to handle hits on the specific hw breakpoint slot.
*Warning: Setting hardware breakpoints during the first system breakpoint will be removed upon process
continue. A better approach is to set a software breakpoint that when hit will set your hardware breakpoints.
@note: Hardware breakpoints are handled globally throughout the entire process and not a single specific thread.
@see: bp_del_hw(), bp_del_hw_all()
@type address: DWORD
@param address: Address to set hardware breakpoint at
@type length: Integer (1, 2 or 4)
@param length: Size of hardware breakpoint in bytes (byte, word or dword)
@type condition: Integer (HW_ACCESS, HW_WRITE, HW_EXECUTE)
@param condition: Condition to set the hardware breakpoint to activate on
@type description: String
@param description: (Optional) Description of breakpoint
@type restore: Boolean
@param restore: (Optional, def=True) Flag controlling whether or not to restore the breakpoint
@type handler: Function Pointer
@param handler: (Optional, def=None) Optional handler to call for this bp instead of the default handler
@raise pdx: An exception is raised on failure.
@rtype: pydbg
@return: Self
'''
self._log("bp_set_hw(%08x, %d, %s)" % (address, length, condition))
# instantiate a new hardware breakpoint object for the new bp to create.
hw_bp = hardware_breakpoint(address, length, condition, description, restore, handler=handler)
if length not in (1, 2, 4):
raise pdx("invalid hw breakpoint length: %d." % length)
# length -= 1 because the following codes are used for determining length:
# 00 - 1 byte length
# 01 - 2 byte length
# 10 - undefined
# 11 - 4 byte length
length -= 1
# condition table:
# 00 - break on instruction execution only
# 01 - break on data writes only
# 10 - undefined
# 11 - break on data reads or writes but not instruction fetches
if condition not in (HW_ACCESS, HW_EXECUTE, HW_WRITE):
raise pdx("invalid hw breakpoint condition: %d" % condition)
# check for any available hardware breakpoint slots. there doesn't appear to be any difference between local
# and global as far as we are concerned on windows.
#
# bits 0, 2, 4, 6 for local (L0 - L3)
# bits 1, 3, 5, 7 for global (G0 - G3)
#
# we could programatically search for an open slot in a given thread context with the following code:
#
# available = None
# for slot in xrange(4):
# if context.Dr7 & (1 << (slot * 2)) == 0:
# available = slot
# break
#
# but since we are doing global hardware breakpoints, we rely on ourself for tracking open slots.
if not self.hardware_breakpoints.has_key(0):
available = 0
elif not self.hardware_breakpoints.has_key(1):
available = 1
elif not self.hardware_breakpoints.has_key(2):
available = 2
elif not self.hardware_breakpoints.has_key(3):
available = 3
else:
raise pdx("no hw breakpoint slots available.")
# activate the hardware breakpoint for all active threads.
for thread_id in self.enumerate_threads():
context = self.get_thread_context(thread_id=thread_id)
# mark available debug register as active (L0 - L3).
context.Dr7 |= 1 << (available * 2)
# save our breakpoint address to the available hw bp slot.
if available == 0: context.Dr0 = address
elif available == 1: context.Dr1 = address
elif available == 2: context.Dr2 = address
elif available == 3: context.Dr3 = address
# set the condition (RW0 - RW3) field for the appropriate slot (bits 16/17, 20/21, 24,25, 28/29)
context.Dr7 |= condition << ((available * 4) + 16)
# set the length (LEN0-LEN3) field for the appropriate slot (bits 18/19, 22/23, 26/27, 30/31)
context.Dr7 |= length << ((available * 4) + 18)
# set the thread context.
self.set_thread_context(context, thread_id=thread_id)
# update the internal hardware breakpoint array at the used slot index.
hw_bp.slot = available
self.hardware_breakpoints[available] = hw_bp
return self.ret_self()
####################################################################################################################
def bp_set_mem (self, address, size, description="", handler=None):
'''
Sets a memory breakpoint at the target address. This is implemented by changing the permissions of the page
containing the address to PAGE_GUARD. To catch memory breakpoints you have to register the EXCEPTION_GUARD_PAGE
callback. Within the callback handler check the internal pydbg variable self.memory_breakpoint_hit to
determine if the violation was a result of a direct memory breakpoint hit or some unrelated event.
Alternatively, you can register a custom handler to handle the memory breakpoint. Memory breakpoints are
automatically restored via the internal single step handler. To remove a memory breakpoint, you must explicitly
call bp_del_mem().
@see: bp_is_ours_mem(), bp_del_mem(), bp_del_mem_all()
@type address: DWORD
@param address: Starting address of the buffer to break on
@type size: Integer
@param size: Size of the buffer to break on
@type description: String
@param description: (Optional) Description to associate with this breakpoint
@type handler: Function Pointer
@param handler: (Optional, def=None) Optional handler to call for this bp instead of the default handler
@raise pdx: An exception is raised on failure.
@rtype: pydbg
@return: Self
'''
self._log("bp_set_mem() buffer range is %08x - %08x" % (address, address + size))
# ensure the target address doesn't already sit in a memory breakpoint range:
if self.bp_is_ours_mem(address):
self._log("a memory breakpoint spanning %08x already exists" % address)
return self.ret_self()
# determine the base address of the page containing the starting point of our buffer.
try:
mbi = self.virtual_query(address)
except:
raise pdx("bp_set_mem(): failed querying address: %08x" % address)
self._log("buffer starting at %08x sits on page starting at %08x" % (address, mbi.BaseAddress))
# individually change the page permissions for each page our buffer spans.
# why do we individually set the page permissions of each page as opposed to a range of pages? because empirical
# testing shows that when you set a PAGE_GUARD on a range of pages, if any of those pages are accessed, then
# the PAGE_GUARD attribute is dropped for the entire range of pages that was originally modified. this is
# undesirable for our purposes when it comes to the ease of restoring hit memory breakpoints.
current_page = mbi.BaseAddress
while current_page <= address + size:
self._log("changing page permissions on %08x" % current_page)
# keep track of explicitly guarded pages, to differentiate from pages guarded by the debuggee / OS.
self._guarded_pages.add(current_page)
self.virtual_protect(current_page, 1, mbi.Protect | PAGE_GUARD)
current_page += self.page_size
# add the breakpoint to the internal list.
self.memory_breakpoints[address] = memory_breakpoint(address, size, mbi, description, handler)
return self.ret_self()
####################################################################################################################
def close_handle (self, handle):
'''
Convenience wraper around kernel32.CloseHandle()
@type handle: Handle
@param handle: Handle to close
@rtype: Bool
@return: Return value from CloseHandle().
'''
return kernel32.CloseHandle(handle)
####################################################################################################################
def dbg_print_all_debug_registers (self):
'''
*** DEBUG ROUTINE ***
This is a debugging routine that was used when debugging hardware breakpoints. It was too useful to be removed
from the release code.
'''
# ensure we have an up to date context for the current thread.
context = self.get_thread_context(self.h_thread)
print "eip = %08x" % context.Eip
print "Dr0 = %08x" % context.Dr0
print "Dr1 = %08x" % context.Dr1
print "Dr2 = %08x" % context.Dr2
print "Dr3 = %08x" % context.Dr3
print "Dr7 = %s" % self.to_binary(context.Dr7)
print " 10987654321098765432109876543210"
print " 332222222222111111111"
####################################################################################################################
def dbg_print_all_guarded_pages (self):
'''
*** DEBUG ROUTINE ***
This is a debugging routine that was used when debugging memory breakpoints. It was too useful to be removed
from the release code.
'''
cursor = 0
# scan through the entire memory range.
while cursor < 0xFFFFFFFF:
try:
mbi = self.virtual_query(cursor)
except:
break
if mbi.Protect & PAGE_GUARD:
address = mbi.BaseAddress
print "PAGE GUARD on %08x" % mbi.BaseAddress
while 1:
address += self.page_size
tmp_mbi = self.virtual_query(address)
if not tmp_mbi.Protect & PAGE_GUARD:
break
print "PAGE GUARD on %08x" % address
cursor += mbi.RegionSize
####################################################################################################################
def debug_active_process (self, pid):
'''
Convenience wrapper around GetLastError() and FormatMessage(). Returns the error code and formatted message
associated with the last error. You probably do not want to call this directly, rather look at attach().
@type pid: Integer
@param pid: Process ID to attach to
@raise pdx: An exception is raised on failure.
'''
if not kernel32.DebugActiveProcess(pid):
raise pdx("DebugActiveProcess(%d)" % pid, True)
####################################################################################################################
def debug_event_iteration (self):
'''
Check for and process a debug event.
'''
continue_status = DBG_CONTINUE
dbg = DEBUG_EVENT()
# wait for a debug event.
if kernel32.WaitForDebugEvent(byref(dbg), 100):
# grab various information with regards to the current exception.
self.h_thread = self.open_thread(dbg.dwThreadId)
self.context = self.get_thread_context(self.h_thread)
self.dbg = dbg
self.exception_address = dbg.u.Exception.ExceptionRecord.ExceptionAddress
self.write_violation = dbg.u.Exception.ExceptionRecord.ExceptionInformation[0]
self.violation_address = dbg.u.Exception.ExceptionRecord.ExceptionInformation[1]
self.exception_code = dbg.u.Exception.ExceptionRecord.ExceptionCode
if dbg.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT:
continue_status = self.event_handler_create_process()
elif dbg.dwDebugEventCode == CREATE_THREAD_DEBUG_EVENT:
continue_status = self.event_handler_create_thread()
elif dbg.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT:
continue_status = self.event_handler_exit_process()
elif dbg.dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT:
continue_status = self.event_handler_exit_thread()
elif dbg.dwDebugEventCode == LOAD_DLL_DEBUG_EVENT:
continue_status = self.event_handler_load_dll()
elif dbg.dwDebugEventCode == UNLOAD_DLL_DEBUG_EVENT:
continue_status = self.event_handler_unload_dll()
# an exception was caught.
elif dbg.dwDebugEventCode == EXCEPTION_DEBUG_EVENT:
ec = dbg.u.Exception.ExceptionRecord.ExceptionCode
self._log("debug_event_loop() exception: %08x" % ec)
# call the internal handler for the exception event that just occured.
if ec == EXCEPTION_ACCESS_VIOLATION:
continue_status = self.exception_handler_access_violation()
elif ec == EXCEPTION_BREAKPOINT:
continue_status = self.exception_handler_breakpoint()
elif ec == EXCEPTION_GUARD_PAGE:
continue_status = self.exception_handler_guard_page()
elif ec == EXCEPTION_SINGLE_STEP:
continue_status = self.exception_handler_single_step()
# generic callback support.
elif self.callbacks.has_key(ec):
continue_status = self.callbacks[ec](self)
# unhandled exception.
else:
self._log("TID:%04x caused an unhandled exception (%08x) at %08x" % (self.dbg.dwThreadId, ec, self.exception_address))
continue_status = DBG_EXCEPTION_NOT_HANDLED
# if the memory space of the debuggee was tainted, flush the instruction cache.
# from MSDN: Applications should call FlushInstructionCache if they generate or modify code in memory.
# The CPU cannot detect the change, and may execute the old code it cached.
if self.dirty:
kernel32.FlushInstructionCache(self.h_process, 0, 0)
# close the opened thread handle and resume executing the thread that triggered the debug event.
self.close_handle(self.h_thread)
kernel32.ContinueDebugEvent(dbg.dwProcessId, dbg.dwThreadId, continue_status)
####################################################################################################################
def debug_event_loop (self):
'''
Enter the infinite debug event handling loop. This is the main loop of the debugger and is responsible for
catching debug events and exceptions and dispatching them appropriately. This routine will check for and call
the USER_CALLBACK_DEBUG_EVENT callback on each loop iteration. run() is an alias for this routine.
@see: run()
@raise pdx: An exception is raised on any exceptional conditions, such as debugger being interrupted or
debuggee quiting.
'''
while self.debugger_active:
# don't let the user interrupt us in the midst of handling a debug event.
try:
def_sigint_handler = None
def_sigint_handler = signal.signal(signal.SIGINT, self.sigint_handler)
except:
pass
# if a user callback was specified, call it.
if self.callbacks.has_key(USER_CALLBACK_DEBUG_EVENT):
# user callbacks do not / should not access debugger or contextual information.
self.dbg = self.context = None
self.callbacks[USER_CALLBACK_DEBUG_EVENT](self)
# iterate through a debug event.
self.debug_event_iteration()
# resume keyboard interruptability.
if def_sigint_handler:
signal.signal(signal.SIGINT, def_sigint_handler)
# close the global process handle.
self.close_handle(self.h_process)
####################################################################################################################
def debug_set_process_kill_on_exit (self, kill_on_exit):
'''
Convenience wrapper around DebugSetProcessKillOnExit().
@type kill_on_exit: Bool
@param kill_on_exit: True to kill the process on debugger exit, False to let debuggee continue running.
@raise pdx: An exception is raised on failure.
'''
if not kernel32.DebugSetProcessKillOnExit(kill_on_exit):
raise pdx("DebugActiveProcess(%s)" % kill_on_exit, True)
####################################################################################################################
def detach (self):
'''
Detach from debuggee.
@raise pdx: An exception is raised on failure.
@rtype: pydbg
@return: Self
'''
self._log("detaching from debuggee")
# remove all software, memory and hardware breakpoints.
self.bp_del_all()
self.bp_del_mem_all()
self.bp_del_hw_all()
# try to detach from the target process if the API is available on the current platform.
kernel32.DebugActiveProcessStop(self.pid)
self.set_debugger_active(False)
return self.ret_self()
####################################################################################################################
def disasm (self, address):
'''
Pydasm disassemble utility function wrapper. Stores the pydasm decoded instruction in self.instruction.
@type address: DWORD
@param address: Address to disassemble at
@rtype: String
@return: Disassembled string.