forked from korcankaraokcu/PINCE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPINCE.py
2796 lines (2504 loc) · 139 KB
/
PINCE.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (C) 2016 Korcan Karaokçu <[email protected]>
Copyright (C) 2016 Çağrı Ulaş <[email protected]>
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 3 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, see <http://www.gnu.org/licenses/>.
"""
from PyQt5.QtGui import QIcon, QMovie, QPixmap, QCursor, QKeySequence, QColor
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem, QMessageBox, QDialog, QCheckBox, QWidget, \
QShortcut, QKeySequenceEdit, QTabWidget, QMenu, QFileDialog, QAbstractItemView, QToolTip, QTreeWidgetItem
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QSize, QByteArray, QSettings, QCoreApplication, QEvent, \
QItemSelectionModel, QTimer, QModelIndex
from time import sleep, time
import os
import pexpect
import sys
import traceback
from libPINCE import GuiUtils, SysUtils, GDB_Engine, type_defs
from GUI.MainWindow import Ui_MainWindow as MainWindow
from GUI.SelectProcess import Ui_MainWindow as ProcessWindow
from GUI.AddAddressManuallyDialog import Ui_Dialog as ManualAddressDialog
from GUI.LoadingDialog import Ui_Dialog as LoadingDialog
from GUI.DialogWithButtons import Ui_Dialog as DialogWithButtons
from GUI.SettingsDialog import Ui_Dialog as SettingsDialog
from GUI.ConsoleWidget import Ui_Form as ConsoleWidget
from GUI.AboutWidget import Ui_TabWidget as AboutWidget
# If you are going to change the name "Ui_MainWindow_MemoryView", review GUI/CustomLabels/RegisterLabel.py as well
from GUI.MemoryViewerWindow import Ui_MainWindow_MemoryView as MemoryViewWindow
from GUI.BookmarkWidget import Ui_Form as BookmarkWidget
from GUI.FloatRegisterWidget import Ui_TabWidget as FloatRegisterWidget
from GUI.StackTraceInfoWidget import Ui_Form as StackTraceInfoWidget
from GUI.BreakpointInfoWidget import Ui_TabWidget as BreakpointInfoWidget
from GUI.TrackWatchpointWidget import Ui_Form as TrackWatchpointWidget
from GUI.TrackBreakpointWidget import Ui_Form as TrackBreakpointWidget
from GUI.TraceInstructionsPromptDialog import Ui_Dialog as TraceInstructionsPromptDialog
from GUI.TraceInstructionsWaitWidget import Ui_Form as TraceInstructionsWaitWidget
from GUI.TraceInstructionsWindow import Ui_MainWindow as TraceInstructionsWindow
from GUI.FunctionsInfoWidget import Ui_Form as FunctionsInfoWidget
from GUI.HexEditDialog import Ui_Dialog as HexEditDialog
from GUI.CustomAbstractTableModels.HexModel import QHexModel
from GUI.CustomAbstractTableModels.AsciiModel import QAsciiModel
selfpid = os.getpid()
# settings
update_table = bool
table_update_interval = float
pause_hotkey = str
break_hotkey = str
continue_hotkey = str
code_injection_method = int
bring_disassemble_to_front = bool
instructions_per_scroll = int
gdb_path = str
# represents the index of columns in breakpoint table
BREAK_NUM_COL = 0
BREAK_ADDR_COL = 1
BREAK_TYPE_COL = 2
BREAK_SIZE_COL = 3
BREAK_ON_HIT_COL = 4
BREAK_COND_COL = 5
# row colours for disassemble qtablewidget
PC_COLOUR = Qt.blue
BOOKMARK_COLOUR = Qt.yellow
DEFAULT_COLOUR = Qt.white
BREAKPOINT_COLOUR = Qt.red
# represents the index of columns in address table
FROZEN_COL = 0 # Frozen
DESC_COL = 1 # Description
ADDR_COL = 2 # Address
TYPE_COL = 3 # Type
VALUE_COL = 4 # Value
# represents the index of columns in disassemble table
DISAS_ADDR_COL = 0
DISAS_BYTES_COL = 1
DISAS_OPCODES_COL = 2
DISAS_COMMENT_COL = 3
# represents the index of columns in floating point table
FLOAT_REGISTERS_NAME_COL = 0
FLOAT_REGISTERS_VALUE_COL = 1
# represents the index of columns in stacktrace table
STACKTRACE_RETURN_ADDRESS_COL = 0
STACKTRACE_FRAME_ADDRESS_COL = 1
# represents the index of columns in stack table
STACK_POINTER_ADDRESS_COL = 0
STACK_VALUE_COL = 1
STACK_INT_REPRESENTATION_COL = 2
STACK_FLOAT_REPRESENTATION_COL = 3
# represents row and column counts of Hex table
HEX_VIEW_COL_COUNT = 16
HEX_VIEW_ROW_COUNT = 42 # J-JUST A COINCIDENCE, I SWEAR!
# represents the index of columns in track watchpoint table(what accesses this address thingy)
TRACK_WATCHPOINT_COUNT_COL = 0
TRACK_WATCHPOINT_ADDR_COL = 1
# represents the index of columns in track breakpoint table(which addresses this instruction accesses thingy)
TRACK_BREAKPOINT_COUNT_COL = 0
TRACK_BREAKPOINT_ADDR_COL = 1
TRACK_BREAKPOINT_VALUE_COL = 2
TRACK_BREAKPOINT_SOURCE_COL = 3
# represents the index of columns in function info table
FUNCTIONS_INFO_ADDR_COL = 0
FUNCTIONS_INFO_SYMBOL_COL = 1
# From version 5.5 and onwards, PyQT calls qFatal() when an exception has been encountered
# So, we must override sys.excepthook to avoid calling of qFatal()
sys.excepthook = traceback.print_exception
# Checks if the inferior has been terminated
class AwaitProcessExit(QThread):
process_exited = pyqtSignal()
def run(self):
while True:
if GDB_Engine.currentpid is 0 or SysUtils.is_process_valid(GDB_Engine.currentpid):
pass
else:
self.process_exited.emit()
sleep(0.1)
# Await async output from gdb
class AwaitAsyncOutput(QThread):
async_output_ready = pyqtSignal()
def run(self):
while True:
with GDB_Engine.gdb_async_condition:
GDB_Engine.gdb_async_condition.wait()
self.async_output_ready.emit()
class CheckInferiorStatus(QThread):
process_stopped = pyqtSignal()
process_running = pyqtSignal()
def run(self):
while True:
with GDB_Engine.status_changed_condition:
GDB_Engine.status_changed_condition.wait()
if GDB_Engine.inferior_status is type_defs.INFERIOR_STATUS.INFERIOR_STOPPED:
self.process_stopped.emit()
else:
self.process_running.emit()
class UpdateAddressTableThread(QThread):
update_table_signal = pyqtSignal()
def run(self):
while True:
while not update_table:
sleep(0.1)
if GDB_Engine.inferior_status is type_defs.INFERIOR_STATUS.INFERIOR_STOPPED:
self.update_table_signal.emit()
sleep(table_update_interval)
# the mainwindow
class MainForm(QMainWindow, MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
GuiUtils.center(self)
self.tableWidget_addresstable.setColumnWidth(FROZEN_COL, 25)
self.tableWidget_addresstable.setColumnWidth(DESC_COL, 150)
self.tableWidget_addresstable.setColumnWidth(ADDR_COL, 150)
self.tableWidget_addresstable.setColumnWidth(TYPE_COL, 120)
QCoreApplication.setOrganizationName("PINCE")
QCoreApplication.setOrganizationDomain("github.com/korcankaraokcu/PINCE")
QCoreApplication.setApplicationName("PINCE")
self.settings = QSettings()
if not SysUtils.is_path_valid(self.settings.fileName()):
self.set_default_settings()
try:
self.apply_settings()
except Exception as e:
print("An exception occurred while trying to load settings, rolling back to the default configuration\n", e)
self.settings.clear()
self.set_default_settings()
try:
settings_version = self.settings.value("Misc/version", type=str)
except TypeError:
settings_version = None
if settings_version != "0.1.0":
self.settings.clear()
self.set_default_settings()
self.memory_view_window = MemoryViewWindowForm()
self.memory_view_window.address_added.connect(self.add_entry_to_addresstable)
self.await_exit_thread = AwaitProcessExit()
self.await_exit_thread.process_exited.connect(self.on_inferior_exit)
self.await_exit_thread.start()
self.check_status_thread = CheckInferiorStatus()
self.check_status_thread.process_stopped.connect(self.on_status_stopped)
self.check_status_thread.process_running.connect(self.on_status_running)
self.check_status_thread.process_stopped.connect(self.memory_view_window.process_stopped)
self.check_status_thread.process_running.connect(self.memory_view_window.process_running)
self.check_status_thread.start()
self.update_address_table_thread = UpdateAddressTableThread()
self.update_address_table_thread.update_table_signal.connect(self.update_address_table_manually)
self.update_address_table_thread.start()
self.shortcut_pause = QShortcut(QKeySequence(pause_hotkey), self)
self.shortcut_pause.activated.connect(self.pause_hotkey_pressed)
self.shortcut_pause.setContext(Qt.ApplicationShortcut)
self.shortcut_break = QShortcut(QKeySequence(break_hotkey), self)
self.shortcut_break.activated.connect(self.break_hotkey_pressed)
self.shortcut_break.setContext(Qt.ApplicationShortcut)
self.shortcut_continue = QShortcut(QKeySequence(continue_hotkey), self)
self.shortcut_continue.activated.connect(self.continue_hotkey_pressed)
self.shortcut_continue.setContext(Qt.ApplicationShortcut)
# Saving the original function because super() doesn't work when we override functions like this
self.tableWidget_addresstable.keyPressEvent_original = self.tableWidget_addresstable.keyPressEvent
self.tableWidget_addresstable.keyPressEvent = self.tableWidget_addresstable_keyPressEvent
self.tableWidget_addresstable.contextMenuEvent = self.tableWidget_addresstable_context_menu_event
self.processbutton.clicked.connect(self.processbutton_onclick)
self.pushButton_NewFirstScan.clicked.connect(self.newfirstscan_onclick)
self.pushButton_NextScan.clicked.connect(self.nextscan_onclick)
self.pushButton_Settings.clicked.connect(self.settingsbutton_onclick)
self.pushButton_Console.clicked.connect(self.consolebutton_onclick)
self.pushButton_Wiki.clicked.connect(self.wikibutton_onclick)
self.pushButton_About.clicked.connect(self.aboutbutton_onclick)
self.pushButton_AddAddressManually.clicked.connect(self.addaddressmanually_onclick)
self.pushButton_MemoryView.clicked.connect(self.memoryview_onlick)
self.pushButton_RefreshAdressTable.clicked.connect(self.update_address_table_manually)
self.pushButton_CleanAddressTable.clicked.connect(self.delete_address_table_contents)
self.tableWidget_addresstable.itemDoubleClicked.connect(self.on_address_table_double_click)
icons_directory = SysUtils.get_current_script_directory() + "/media/icons"
self.processbutton.setIcon(QIcon(QPixmap(icons_directory + "/monitor.png")))
self.pushButton_Open.setIcon(QIcon(QPixmap(icons_directory + "/folder.png")))
self.pushButton_Save.setIcon(QIcon(QPixmap(icons_directory + "/disk.png")))
self.pushButton_Settings.setIcon(QIcon(QPixmap(icons_directory + "/wrench.png")))
self.pushButton_CopyToAddressTable.setIcon(QIcon(QPixmap(icons_directory + "/arrow_down.png")))
self.pushButton_CleanAddressTable.setIcon(QIcon(QPixmap(icons_directory + "/bin_closed.png")))
self.pushButton_RefreshAdressTable.setIcon(QIcon(QPixmap(icons_directory + "/table_refresh.png")))
self.pushButton_Console.setIcon(QIcon(QPixmap(icons_directory + "/application_xp_terminal.png")))
self.pushButton_Wiki.setIcon(QIcon(QPixmap(icons_directory + "/book_open.png")))
self.pushButton_About.setIcon(QIcon(QPixmap(icons_directory + "/information.png")))
def set_default_settings(self):
self.settings.beginGroup("General")
self.settings.setValue("auto_update_address_table", False)
self.settings.setValue("address_table_update_interval", 0.5)
self.settings.endGroup()
self.settings.beginGroup("Hotkeys")
self.settings.setValue("pause", "F1")
self.settings.setValue("break", "F2")
self.settings.setValue("continue", "F3")
self.settings.endGroup()
self.settings.beginGroup("CodeInjection")
self.settings.setValue("code_injection_method", type_defs.INJECTION_METHOD.SIMPLE_DLOPEN_CALL)
self.settings.endGroup()
self.settings.beginGroup("Disassemble")
self.settings.setValue("bring_disassemble_to_front", False)
self.settings.setValue("instructions_per_scroll", 2)
self.settings.endGroup()
self.settings.beginGroup("Debug")
self.settings.setValue("gdb_path", type_defs.PATHS.GDB_PATH)
self.settings.endGroup()
self.settings.beginGroup("Misc")
self.settings.setValue("version", "0.1.0")
self.settings.endGroup()
self.apply_settings()
def apply_settings(self):
global update_table
global table_update_interval
global pause_hotkey
global break_hotkey
global continue_hotkey
global code_injection_method
global bring_disassemble_to_front
global instructions_per_scroll
global gdb_path
update_table = self.settings.value("General/auto_update_address_table", type=bool)
table_update_interval = self.settings.value("General/address_table_update_interval", type=float)
pause_hotkey = self.settings.value("Hotkeys/pause")
break_hotkey = self.settings.value("Hotkeys/break")
continue_hotkey = self.settings.value("Hotkeys/continue")
try:
self.shortcut_pause.setKey(QKeySequence(pause_hotkey))
except AttributeError:
pass
try:
self.shortcut_break.setKey(QKeySequence(break_hotkey))
except AttributeError:
pass
try:
self.shortcut_continue.setKey(QKeySequence(continue_hotkey))
except AttributeError:
pass
try:
self.memory_view_window.set_dynamic_debug_hotkeys()
except AttributeError:
pass
code_injection_method = self.settings.value("CodeInjection/code_injection_method", type=int)
bring_disassemble_to_front = self.settings.value("Disassemble/bring_disassemble_to_front", type=bool)
instructions_per_scroll = self.settings.value("Disassemble/instructions_per_scroll", type=int)
gdb_path = self.settings.value("Debug/gdb_path", type=str)
def pause_hotkey_pressed(self):
GDB_Engine.interrupt_inferior(type_defs.STOP_REASON.PAUSE)
def break_hotkey_pressed(self):
GDB_Engine.interrupt_inferior()
def continue_hotkey_pressed(self):
GDB_Engine.continue_inferior()
def tableWidget_addresstable_context_menu_event(self, event):
menu = QMenu()
browse_region = menu.addAction("Browse this memory region[B]")
disassemble = menu.addAction("Disassemble this address[D]")
menu.addSeparator()
delete_record = menu.addAction("Delete selected records[Del]")
menu.addSeparator()
what_writes = menu.addAction("Find out what writes to this address")
what_reads = menu.addAction("Find out what reads this address")
what_accesses = menu.addAction("Find out what accesses this address")
font_size = self.tableWidget_addresstable.font().pointSize()
menu.setStyleSheet("font-size: " + str(font_size) + "pt;")
action = menu.exec_(event.globalPos())
if action == browse_region:
self.browse_region_for_selected_row()
elif action == disassemble:
self.disassemble_selected_row()
elif action == delete_record:
self.delete_selected_records()
elif action == what_writes:
self.exec_track_watchpoint_widget(type_defs.WATCHPOINT_TYPE.WRITE_ONLY)
elif action == what_reads:
self.exec_track_watchpoint_widget(type_defs.WATCHPOINT_TYPE.READ_ONLY)
elif action == what_accesses:
self.exec_track_watchpoint_widget(type_defs.WATCHPOINT_TYPE.BOTH)
def exec_track_watchpoint_widget(self, watchpoint_type):
last_selected_row = self.tableWidget_addresstable.selectionModel().selectedRows()[-1].row()
address = self.tableWidget_addresstable.item(last_selected_row, ADDR_COL).text()
length = GuiUtils.text_to_valuetype(self.tableWidget_addresstable.item(last_selected_row, TYPE_COL).text())[1]
track_watchpoint_widget = TrackWatchpointWidgetForm(address, length, watchpoint_type, self)
track_watchpoint_widget.show()
def browse_region_for_selected_row(self):
last_selected_row = self.tableWidget_addresstable.selectionModel().selectedRows()[-1].row()
self.memory_view_window.hex_dump_address(
int(self.tableWidget_addresstable.item(last_selected_row, ADDR_COL).text(), 16))
self.memory_view_window.show()
self.memory_view_window.activateWindow()
def disassemble_selected_row(self):
last_selected_row = self.tableWidget_addresstable.selectionModel().selectedRows()[-1].row()
self.memory_view_window.disassemble_expression(
self.tableWidget_addresstable.item(last_selected_row, ADDR_COL).text(), append_to_travel_history=True)
self.memory_view_window.show()
self.memory_view_window.activateWindow()
def delete_selected_records(self):
selected_rows = self.tableWidget_addresstable.selectionModel().selectedRows()
while selected_rows:
selected_rows = self.tableWidget_addresstable.selectionModel().selectedRows()
if selected_rows:
first_selected_row = selected_rows[0].row()
self.tableWidget_addresstable.removeRow(first_selected_row)
def tableWidget_addresstable_keyPressEvent(self, e):
if e.key() == Qt.Key_Delete:
self.delete_selected_records()
elif e.key() == Qt.Key_B:
self.browse_region_for_selected_row()
elif e.key() == Qt.Key_D:
self.disassemble_selected_row()
elif e.key() == Qt.Key_R:
self.update_address_table_manually()
else:
self.tableWidget_addresstable.keyPressEvent_original(e)
def update_address_table_manually(self):
table_contents = []
row_count = self.tableWidget_addresstable.rowCount()
for row in range(row_count):
address = self.tableWidget_addresstable.item(row, ADDR_COL).text()
index, length, unicode, zero_terminate = GuiUtils.text_to_valuetype(
self.tableWidget_addresstable.item(row, TYPE_COL).text())
table_contents.append([address, index, length, unicode, zero_terminate])
new_table_contents = GDB_Engine.read_multiple_addresses(table_contents)
for row, item in enumerate(new_table_contents):
self.tableWidget_addresstable.setItem(row, VALUE_COL, QTableWidgetItem(str(item)))
# gets the information from the dialog then adds it to addresstable
def addaddressmanually_onclick(self):
manual_address_dialog = ManualAddressDialogForm()
if manual_address_dialog.exec_():
description, address, typeofaddress, length, unicode, zero_terminate = manual_address_dialog.get_values()
self.add_entry_to_addresstable(description=description, address=address, typeofaddress=typeofaddress,
length=length, unicode=unicode,
zero_terminate=zero_terminate)
def memoryview_onlick(self):
self.memory_view_window.showMaximized()
self.memory_view_window.activateWindow()
def wikibutton_onclick(self):
output = pexpect.run("who").decode("utf-8")
user_name = output.split()[0]
pexpect.run('sudo -u ' + user_name + ' python3 -m webbrowser "https://github.com/korcankaraokcu/PINCE/wiki"')
def aboutbutton_onclick(self):
self.about_widget = AboutWidgetForm()
self.about_widget.show()
def settingsbutton_onclick(self):
settings_dialog = SettingsDialogForm()
settings_dialog.reset_settings.connect(self.set_default_settings)
if settings_dialog.exec_():
self.apply_settings()
def consolebutton_onclick(self):
self.console_widget = ConsoleWidgetForm()
self.console_widget.show()
def newfirstscan_onclick(self):
print("Exception test")
x = 0 / 0
if self.pushButton_NewFirstScan.text() == "First Scan":
self.pushButton_NextScan.setEnabled(True)
self.pushButton_UndoScan.setEnabled(True)
self.pushButton_NewFirstScan.setText("New Scan")
return
if self.pushButton_NewFirstScan.text() == "New Scan":
self.pushButton_NextScan.setEnabled(False)
self.pushButton_UndoScan.setEnabled(False)
self.pushButton_NewFirstScan.setText("First Scan")
def nextscan_onclick(self):
# GDB_Engine.send_command('interrupt\nx _start\nc &') # test
GDB_Engine.send_command("x/100x _start")
# t = Thread(target=GDB_Engine.test) # test
# t2=Thread(target=test2)
# t.start()
# t2.start()
if self.tableWidget_valuesearchtable.rowCount() <= 0:
return
# shows the process select window
def processbutton_onclick(self):
self.processwindow = ProcessForm(self)
self.processwindow.show()
def delete_address_table_contents(self):
confirm_dialog = DialogWithButtonsForm(label_text="This will clear the contents of address table\nProceed?")
if confirm_dialog.exec_():
self.tableWidget_addresstable.setRowCount(0)
def on_inferior_exit(self):
self.on_status_running()
self.label_SelectedProcess.setText("No Process Selected")
def on_status_stopped(self):
self.label_SelectedProcess.setStyleSheet("color: red")
self.label_InferiorStatus.setText("[stopped]")
self.label_InferiorStatus.setVisible(True)
self.label_InferiorStatus.setStyleSheet("color: red")
self.update_address_table_manually()
def on_status_running(self):
self.label_SelectedProcess.setStyleSheet("")
self.label_InferiorStatus.setVisible(False)
# closes all windows on exit
def closeEvent(self, event):
if not GDB_Engine.currentpid == 0:
GDB_Engine.detach()
application = QApplication.instance()
application.closeAllWindows()
def add_entry_to_addresstable(self, description, address, typeofaddress, length=0, unicode=False,
zero_terminate=True):
frozen_checkbox = QCheckBox()
typeofaddress_text = GuiUtils.valuetype_to_text(typeofaddress, length, unicode, zero_terminate)
# this line lets us take symbols as parameters, pretty rad isn't it?
address_text = GDB_Engine.convert_symbol_to_address(address)
if address_text:
address = address_text
self.tableWidget_addresstable.setRowCount(self.tableWidget_addresstable.rowCount() + 1)
currentrow = self.tableWidget_addresstable.rowCount() - 1
value = GDB_Engine.read_single_address(address, typeofaddress, length, unicode, zero_terminate)
self.tableWidget_addresstable.setCellWidget(currentrow, FROZEN_COL, frozen_checkbox)
self.change_address_table_entries(row=currentrow, description=description, address=address,
typeofaddress=typeofaddress_text, value=str(value))
self.show() # In case of getting called from elsewhere
self.activateWindow()
def on_address_table_double_click(self, index):
current_row = index.row()
current_column = index.column()
if current_column is VALUE_COL:
value = self.tableWidget_addresstable.item(current_row, VALUE_COL).text()
value_index = GuiUtils.text_to_index(self.tableWidget_addresstable.item(current_row, TYPE_COL).text())
label_text = "Enter the new value"
if value_index == type_defs.VALUE_INDEX.INDEX_STRING:
label_text += "\nPINCE doesn't automatically insert a null terminated string at the end" \
"\nCopy-paste this character (\0) if you need to insert it at somewhere"
dialog = DialogWithButtonsForm(label_text=label_text, hide_line_edit=False,
line_edit_text=value, parse_string=True, value_index=value_index)
if dialog.exec_():
table_contents = []
value_text = dialog.get_values()
selected_rows = self.tableWidget_addresstable.selectionModel().selectedRows()
for item in selected_rows:
row = item.row()
address = self.tableWidget_addresstable.item(row, ADDR_COL).text()
value_type = self.tableWidget_addresstable.item(row, TYPE_COL).text()
value_index = GuiUtils.text_to_index(value_type)
if value_index == type_defs.VALUE_INDEX.INDEX_STRING or value_index == type_defs.VALUE_INDEX.INDEX_AOB:
unknown_type = SysUtils.parse_string(value_text, value_index)
if unknown_type is not None:
length = len(unknown_type)
self.tableWidget_addresstable.setItem(row, TYPE_COL, QTableWidgetItem(
GuiUtils.change_text_length(value_type, length)))
table_contents.append([address, value_index])
GDB_Engine.set_multiple_addresses(table_contents, value_text)
self.update_address_table_manually()
elif current_column is DESC_COL:
description = self.tableWidget_addresstable.item(current_row, DESC_COL).text()
dialog = DialogWithButtonsForm(label_text="Enter the new description", hide_line_edit=False,
line_edit_text=description)
if dialog.exec_():
description_text = dialog.get_values()
selected_rows = self.tableWidget_addresstable.selectionModel().selectedRows()
for item in selected_rows:
self.tableWidget_addresstable.setItem(item.row(), DESC_COL, QTableWidgetItem(description_text))
elif current_column is ADDR_COL or current_column is TYPE_COL:
description, address, value_type = self.read_address_table_entries(row=current_row)
index, length, unicode, zero_terminate = GuiUtils.text_to_valuetype(value_type)
manual_address_dialog = ManualAddressDialogForm(description=description, address=address, index=index,
length=length, unicode=unicode,
zero_terminate=zero_terminate)
if manual_address_dialog.exec_():
description, address, typeofaddress, length, unicode, zero_terminate = manual_address_dialog.get_values()
typeofaddress_text = GuiUtils.valuetype_to_text(value_index=typeofaddress, length=length,
is_unicode=unicode,
zero_terminate=zero_terminate)
address_text = GDB_Engine.convert_symbol_to_address(address)
if address_text:
address = address_text
value = GDB_Engine.read_single_address(address=address, value_index=typeofaddress,
length=length, is_unicode=unicode,
zero_terminate=zero_terminate)
self.change_address_table_entries(row=current_row, description=description, address=address,
typeofaddress=typeofaddress_text, value=str(value))
# Changes the column values of the given row
def change_address_table_entries(self, row, description="", address="", typeofaddress="", value=""):
self.tableWidget_addresstable.setItem(row, DESC_COL, QTableWidgetItem(description))
self.tableWidget_addresstable.setItem(row, ADDR_COL, QTableWidgetItem(address))
self.tableWidget_addresstable.setItem(row, TYPE_COL, QTableWidgetItem(typeofaddress))
self.tableWidget_addresstable.setItem(row, VALUE_COL, QTableWidgetItem(value))
# Returns the column values of the given row
def read_address_table_entries(self, row):
description = self.tableWidget_addresstable.item(row, DESC_COL).text()
address = self.tableWidget_addresstable.item(row, ADDR_COL).text()
value_type = self.tableWidget_addresstable.item(row, TYPE_COL).text()
return description, address, value_type
# process select window
class ProcessForm(QMainWindow, ProcessWindow):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setupUi(self)
GuiUtils.center_to_parent(self)
processlist = SysUtils.get_process_list()
self.refresh_process_table(self.processtable, processlist)
self.pushButton_Close.clicked.connect(self.pushbutton_close_onclick)
self.pushButton_Open.clicked.connect(self.pushbutton_open_onclick)
self.pushButton_CreateProcess.clicked.connect(self.pushbutton_createprocess_onclick)
self.lineEdit_searchprocess.textChanged.connect(self.generate_new_list)
self.processtable.itemDoubleClicked.connect(self.pushbutton_open_onclick)
# refreshes process list
def generate_new_list(self):
text = self.lineEdit_searchprocess.text()
processlist = SysUtils.search_in_processes_by_name(text)
self.refresh_process_table(self.processtable, processlist)
# closes the window whenever ESC key is pressed
def keyPressEvent(self, e):
if e.key() == Qt.Key_Escape:
self.close()
# lists currently working processes to table
def refresh_process_table(self, tablewidget, processlist):
tablewidget.setRowCount(0)
tablewidget.setRowCount(len(processlist))
for i, row in enumerate(processlist):
tablewidget.setItem(i, 0, QTableWidgetItem(str(row.pid)))
tablewidget.setItem(i, 1, QTableWidgetItem(row.username()))
tablewidget.setItem(i, 2, QTableWidgetItem(row.name()))
# self-explanatory
def pushbutton_close_onclick(self):
self.close()
# gets the pid out of the selection to attach
def pushbutton_open_onclick(self):
currentitem = self.processtable.item(self.processtable.currentIndex().row(), 0)
if currentitem is None:
QMessageBox.information(self, "Error", "Please select a process first")
else:
pid = int(currentitem.text())
if not SysUtils.is_process_valid(pid):
QMessageBox.information(self, "Error", "Selected process is not valid")
return
if pid == selfpid:
QMessageBox.information(self, "Error", "What the fuck are you trying to do?") # planned easter egg
return
if pid == GDB_Engine.currentpid:
QMessageBox.information(self, "Error", "You're debugging this process already")
return
tracedby = SysUtils.is_traced(pid)
if tracedby:
QMessageBox.information(self, "Error",
"That process is already being traced by " + tracedby + ", could not attach to the process")
return
self.setCursor(QCursor(Qt.WaitCursor))
print("processing")
result = GDB_Engine.can_attach(pid)
if not result:
print("done")
QMessageBox.information(self, "Error", "Permission denied, could not attach to the process")
return
if not GDB_Engine.currentpid == 0:
GDB_Engine.detach()
GDB_Engine.init_gdb(gdb_path)
GDB_Engine.attach(pid)
p = SysUtils.get_process_information(GDB_Engine.currentpid)
self.parent().label_SelectedProcess.setText(str(p.pid) + " - " + p.name())
self.enable_scan_gui()
readable_only, writeable, executable, readable = SysUtils.get_memory_regions_by_perms(
GDB_Engine.currentpid) # test
SysUtils.exclude_system_memory_regions(readable)
print(len(readable))
print("done")
self.close()
def pushbutton_createprocess_onclick(self):
file_path = QFileDialog.getOpenFileName(self, "Select the target binary")[0]
if file_path:
if not GDB_Engine.currentpid == 0:
GDB_Engine.detach()
arg_dialog = DialogWithButtonsForm(label_text="Enter the optional arguments", hide_line_edit=False)
if arg_dialog.exec_():
args = arg_dialog.get_values()
else:
args = ""
self.setCursor(QCursor(Qt.WaitCursor))
GDB_Engine.init_gdb(gdb_path)
GDB_Engine.create_process(file_path, args)
p = SysUtils.get_process_information(GDB_Engine.currentpid)
self.parent().label_SelectedProcess.setText(str(p.pid) + " - " + p.name())
self.enable_scan_gui()
self.close()
def enable_scan_gui(self):
self.parent().QWidget_Toolbox.setEnabled(True)
self.parent().pushButton_NextScan.setEnabled(False)
self.parent().pushButton_UndoScan.setEnabled(False)
# Add Address Manually Dialog
class ManualAddressDialogForm(QDialog, ManualAddressDialog):
def __init__(self, parent=None, description="No Description", address="0x",
index=type_defs.VALUE_INDEX.INDEX_4BYTES, length=10,
unicode=False,
zero_terminate=True):
super().__init__(parent=parent)
self.setupUi(self)
self.lineEdit_description.setText(description)
self.lineEdit_address.setText(address)
self.comboBox_ValueType.setCurrentIndex(index)
if self.comboBox_ValueType.currentIndex() is type_defs.VALUE_INDEX.INDEX_STRING:
self.label_length.show()
self.lineEdit_length.show()
try:
length = str(length)
except:
length = "10"
self.lineEdit_length.setText(length)
self.checkBox_Unicode.show()
self.checkBox_Unicode.setChecked(unicode)
self.checkBox_zeroterminate.show()
self.checkBox_zeroterminate.setChecked(zero_terminate)
elif self.comboBox_ValueType.currentIndex() is type_defs.VALUE_INDEX.INDEX_AOB:
self.label_length.show()
self.lineEdit_length.show()
try:
length = str(length)
except:
length = "10"
self.lineEdit_length.setText(length)
self.checkBox_Unicode.hide()
self.checkBox_zeroterminate.hide()
else:
self.label_length.hide()
self.lineEdit_length.hide()
self.checkBox_Unicode.hide()
self.checkBox_zeroterminate.hide()
self.comboBox_ValueType.currentIndexChanged.connect(self.valuetype_on_current_index_change)
self.lineEdit_length.textChanged.connect(self.update_value_of_address)
self.checkBox_Unicode.stateChanged.connect(self.update_value_of_address)
self.checkBox_zeroterminate.stateChanged.connect(self.update_value_of_address)
self.lineEdit_address.textChanged.connect(self.update_value_of_address)
self.label_valueofaddress.contextMenuEvent = self.label_valueofaddress_context_menu_event
self.update_value_of_address()
def label_valueofaddress_context_menu_event(self, event):
menu = QMenu()
refresh = menu.addAction("Refresh")
font_size = self.label_valueofaddress.font().pointSize()
menu.setStyleSheet("font-size: " + str(font_size) + "pt;")
action = menu.exec_(event.globalPos())
if action == refresh:
self.update_value_of_address()
def update_value_of_address(self):
address = self.lineEdit_address.text()
address_type = self.comboBox_ValueType.currentIndex()
if address_type is type_defs.VALUE_INDEX.INDEX_AOB:
length = self.lineEdit_length.text()
self.label_valueofaddress.setText(
GDB_Engine.read_single_address_by_expression(address, address_type, length))
elif address_type is type_defs.VALUE_INDEX.INDEX_STRING:
length = self.lineEdit_length.text()
is_unicode = self.checkBox_Unicode.isChecked()
is_zeroterminate = self.checkBox_zeroterminate.isChecked()
self.label_valueofaddress.setText(
GDB_Engine.read_single_address_by_expression(address, address_type, length, is_unicode,
is_zeroterminate))
else:
self.label_valueofaddress.setText(
GDB_Engine.read_single_address_by_expression(address, address_type))
def valuetype_on_current_index_change(self):
if self.comboBox_ValueType.currentIndex() is type_defs.VALUE_INDEX.INDEX_STRING:
self.label_length.show()
self.lineEdit_length.show()
self.checkBox_Unicode.show()
self.checkBox_zeroterminate.show()
elif self.comboBox_ValueType.currentIndex() is type_defs.VALUE_INDEX.INDEX_AOB:
self.label_length.show()
self.lineEdit_length.show()
self.checkBox_Unicode.hide()
self.checkBox_zeroterminate.hide()
else:
self.label_length.hide()
self.lineEdit_length.hide()
self.checkBox_Unicode.hide()
self.checkBox_zeroterminate.hide()
self.update_value_of_address()
def reject(self):
super(ManualAddressDialogForm, self).reject()
def accept(self):
if self.label_length.isVisible():
length = self.lineEdit_length.text()
try:
length = int(length)
except:
QMessageBox.information(self, "Error", "Length is not valid")
return
if length < 0:
QMessageBox.information(self, "Error", "Length cannot be smaller than 0")
return
super(ManualAddressDialogForm, self).accept()
def get_values(self):
description = self.lineEdit_description.text()
address = self.lineEdit_address.text()
length = self.lineEdit_length.text()
try:
length = int(length)
except:
length = 0
unicode = False
zero_terminate = False
if self.checkBox_Unicode.isChecked():
unicode = True
if self.checkBox_zeroterminate.isChecked():
zero_terminate = True
typeofaddress = self.comboBox_ValueType.currentIndex()
return description, address, typeofaddress, length, unicode, zero_terminate
class LoadingDialogForm(QDialog, LoadingDialog):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setupUi(self)
self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
if parent:
GuiUtils.center_to_parent(self)
self.keyPressEvent = QEvent.ignore
# Make use of this background_thread when you spawn a LoadingDialogForm
# Warning: overrided_func() can only return one value, so if your overridden function returns more than one
# value, refactor your overriden function to return only one object(convert tuple to list etc.)
# Check refresh_table method of FunctionsInfoWidgetForm for exemplary usage
self.background_thread = self.BackgroundThread()
self.background_thread.output_ready.connect(self.accept)
pince_directory = SysUtils.get_current_script_directory()
self.movie = QMovie(pince_directory + "/media/LoadingDialog/ajax-loader.gif", QByteArray())
self.label_Animated.setMovie(self.movie)
self.movie.setScaledSize(QSize(25, 25))
self.movie.setCacheMode(QMovie.CacheAll)
self.movie.setSpeed(100)
self.movie.start()
def exec_(self):
self.background_thread.start()
super(LoadingDialogForm, self).exec_()
class BackgroundThread(QThread):
output_ready = pyqtSignal(object)
def __init__(self):
super().__init__()
def run(self):
output = self.overrided_func()
self.output_ready.emit(output)
def overrided_func(self):
print("Override this function")
return 0
class DialogWithButtonsForm(QDialog, DialogWithButtons):
def __init__(self, parent=None, label_text="", hide_line_edit=True, line_edit_text="", parse_string=False,
value_index=type_defs.VALUE_INDEX.INDEX_4BYTES, align=Qt.AlignCenter):
super().__init__(parent=parent)
self.setupUi(self)
self.label.setAlignment(align)
self.parse_string = parse_string
self.value_index = value_index
label_text = str(label_text)
self.label.setText(label_text)
if hide_line_edit:
self.lineEdit.hide()
else:
line_edit_text = str(line_edit_text)
self.lineEdit.setText(line_edit_text)
def get_values(self):
line_edit_text = self.lineEdit.text()
return line_edit_text
def accept(self):
if self.parse_string:
string = self.lineEdit.text()
if SysUtils.parse_string(string, self.value_index) is None:
QMessageBox.information(self, "Error", "Can't parse the input")
return
super(DialogWithButtonsForm, self).accept()
class SettingsDialogForm(QDialog, SettingsDialog):
reset_settings = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent=parent)
self.setupUi(self)
# Yet another retarded hack, thanks to pyuic5 not supporting QKeySequenceEdit
self.keySequenceEdit = QKeySequenceEdit()
self.verticalLayout_Hotkey.addWidget(self.keySequenceEdit)
self.listWidget_Options.currentRowChanged.connect(self.change_display)
icons_directory = SysUtils.get_current_script_directory() + "/media/icons"
self.pushButton_GDBPath.setIcon(QIcon(QPixmap(icons_directory + "/folder.png")))
self.listWidget_Functions.currentRowChanged.connect(self.listWidget_Functions_current_row_changed)
self.keySequenceEdit.keySequenceChanged.connect(self.keySequenceEdit_key_sequence_changed)
self.pushButton_ClearHotkey.clicked.connect(self.pushButton_ClearHotkey_clicked)
self.pushButton_ResetSettings.clicked.connect(self.pushButton_ResetSettings_clicked)
self.pushButton_GDBPath.clicked.connect(self.pushButton_GDBPath_clicked)
self.checkBox_AutoUpdateAddressTable.stateChanged.connect(self.checkBox_AutoUpdateAddressTable_state_changed)
self.config_gui()
def accept(self):
try:
current_table_update_interval = float(self.lineEdit_UpdateInterval.text())
except:
QMessageBox.information(self, "Error", "Update interval must be a float")
return
try:
current_insturctions_shown = int(self.lineEdit_InstructionsPerScroll.text())
except:
QMessageBox.information(self, "Error", "Instruction count must be an integer")
return
if current_insturctions_shown < 1:
QMessageBox.information(self, "Error", "Instruction count cannot be lower than 1" +
"\nIt would be retarded anyways, wouldn't it?")
return
if current_table_update_interval < 0:
QMessageBox.information(self, "Error", "Update interval cannot be a negative number")
return
elif current_table_update_interval == 0:
# Easter egg #2
if not DialogWithButtonsForm(label_text="You are asking for it, aren't you?").exec_():
return
elif current_table_update_interval < 0.1:
if not DialogWithButtonsForm(label_text="Update interval should be bigger than 0.1 seconds" +
"\nSetting update interval less than 0.1 seconds may cause slowness" +
"\n\tProceed?").exec_():
return
self.settings.setValue("General/auto_update_address_table", self.checkBox_AutoUpdateAddressTable.isChecked())
self.settings.setValue("General/address_table_update_interval", current_table_update_interval)
self.settings.setValue("Hotkeys/pause", self.pause_hotkey)
self.settings.setValue("Hotkeys/break", self.break_hotkey)
self.settings.setValue("Hotkeys/continue", self.continue_hotkey)
if self.radioButton_SimpleDLopenCall.isChecked():
injection_method = type_defs.INJECTION_METHOD.SIMPLE_DLOPEN_CALL
elif self.radioButton_AdvancedInjection.isChecked():
injection_method = type_defs.INJECTION_METHOD.ADVANCED_INJECTION
self.settings.setValue("CodeInjection/code_injection_method", injection_method)
self.settings.setValue("Disassemble/bring_disassemble_to_front",
self.checkBox_BringDisassembleToFront.isChecked())
self.settings.setValue("Disassemble/instructions_per_scroll", current_insturctions_shown)
self.settings.setValue("Debug/gdb_path", self.lineEdit_GDBPath.text())
super(SettingsDialogForm, self).accept()
def config_gui(self):
self.settings = QSettings()
self.checkBox_AutoUpdateAddressTable.setChecked(
self.settings.value("General/auto_update_address_table", type=bool))
self.lineEdit_UpdateInterval.setText(
str(self.settings.value("General/address_table_update_interval", type=float)))
self.pause_hotkey = self.settings.value("Hotkeys/pause")
self.break_hotkey = self.settings.value("Hotkeys/break")
self.continue_hotkey = self.settings.value("Hotkeys/continue")
injection_method = self.settings.value("CodeInjection/code_injection_method", type=int)
if injection_method == type_defs.INJECTION_METHOD.SIMPLE_DLOPEN_CALL:
self.radioButton_SimpleDLopenCall.setChecked(True)
elif injection_method == type_defs.INJECTION_METHOD.ADVANCED_INJECTION:
self.radioButton_AdvancedInjection.setChecked(True)
self.checkBox_BringDisassembleToFront.setChecked(
self.settings.value("Disassemble/bring_disassemble_to_front", type=bool))
self.lineEdit_InstructionsPerScroll.setText(
str(self.settings.value("Disassemble/instructions_per_scroll", type=int)))
self.lineEdit_GDBPath.setText(str(self.settings.value("Debug/gdb_path", type=str)))
def change_display(self, index):
self.stackedWidget.setCurrentIndex(index)
def listWidget_Functions_current_row_changed(self, index):
if index is 0:
self.keySequenceEdit.setKeySequence(self.pause_hotkey)
elif index is 1:
self.keySequenceEdit.setKeySequence(self.break_hotkey)
elif index is 2:
self.keySequenceEdit.setKeySequence(self.continue_hotkey)
def keySequenceEdit_key_sequence_changed(self):
current_index = self.listWidget_Functions.currentIndex().row()
if current_index is 0:
self.pause_hotkey = self.keySequenceEdit.keySequence().toString()
if current_index is 1:
self.break_hotkey = self.keySequenceEdit.keySequence().toString()
elif current_index is 2:
self.continue_hotkey = self.keySequenceEdit.keySequence().toString()