-
Notifications
You must be signed in to change notification settings - Fork 35
/
idacyber.py
1324 lines (1085 loc) · 49.5 KB
/
idacyber.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
import os
import sys
from random import randrange
from math import floor
from PyQt5.QtWidgets import (QWidget, QCheckBox, QLabel, QComboBox, QSizePolicy,
QVBoxLayout, QHBoxLayout)
from PyQt5.QtGui import QPainter, QColor, QFont, QImage, qRgb, QPainterPath
from PyQt5.QtCore import Qt, QObject, pyqtSignal, QRect, QPoint
import ida_kernwin
import ida_diskio
import ida_bytes
import ida_segment
import ida_idaapi
import ida_ida
from ida_pro import IDA_SDK_VERSION
__author__ = 'Dennis Elser'
BANNER = """
.___ .______ .______ ._______ ____ ____._______ ._______.______
: __|:_ _ \ : \ :_. ___\\ \_/ /: __ / : .____/: __ \
| : || | || . || : |/\ \___ ___/ | |> \ | : _/\ | \____|
| || . | || : || / \ | | | |> \| / \| : \
| ||. ____/ |___| ||. _____/ |___| |_______/|_.: __/| |___\
|___| :/ |___| :/ :/ |___|
https://github.com/patois/IDACyber
"""
PLUGIN_HELP = """
.-~========================= [IDACyber: Controls] ==========================~-.
. .
Function | Mouse (+Keyboard) | Keyboard
~~~~~~~~~~~~~~~~~~~~~~+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+~~~~~~~~~~~~~~~~~~~
| |
Vertical panning | LMB, Wheel | page: Page up/down
| | 8px: Up/Down
| | 1px: Shift-Up/Down
Horizontal panning | Shift+LMB, Shift+Wheel |
Change width | LMB+h (8px), LMB+x (1px), |
| Wheel+h (8px), Wheel+x (1px) |
Zoom | Ctrl+LMB, Ctrl+Wheel | Ctrl+'-', Ctrl+'+'
Goto address | Doubleclick | g
Next filter | | n
Previous filter | | b
Data: Off/Ascii/Hex | | d
Data: composition | | t
Toggle sync | | s
Help: Controls | | Ctrl+F1
Help: Current filter | | Ctrl+F2
Close help | | Escape
* *
'-~=========================================================================~-'
"""
FILTER_HELP = """
.-~========================= [IDACyber: Filter] ============================~-.
-= %s =-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
%s
'-~=========================================================================~-'
"""
# TODO:
# * refactor
# * colorfilter: improve arrows/pointers
# * optimizations
# * load filters using "require"
# * add grid?
# * use builtin Qt routines for scaling etc?
# * store current settings in netnode?
# * review signal handlers
# * implement feature that generates a graph of all memory content/current
# idb using the current color filter which is then saved/exported to disk
# * implement color filter: dbghook, memory read/write tracing
# * implement color filter: apply recorded trace log to graph
# * implement color filter: colorize instructions/instruction groups
# * implement color filter: Entropy visualization
# I believe this is Windows-only?
FONT_DEFAULT = "Consolas"
HL_COLOR = ida_kernwin.CK_EXTRA3
HIGHLIGHTED_ITEM = None
class ColorFilter():
"""every new color filters must inherit this class"""
name = None
highlight_cursor = True
help = None
width = 16
sync = True
lock_width = False
lock_sync = False
show_address_range = True
zoom = 10
link_pixel = True
support_selection = False
disable_data = False
def __init__(self, pw=None):
pass
"""called when filter is selected in list"""
def on_activate(self, idx):
pass
"""called on deselection of filter (or when plugin closes)"""
def on_deactivate(self):
pass
"""handles mouse click events"""
def on_mb_click(self, event, addr, size, mouse_offs):
pass
"""called whenever a new frame is about to be drawn"""
def on_process_buffer(self, buffers, addr, size, mouse_offs):
return []
"""called before tooltip is shown"""
def on_get_tooltip(self, addr, size, mouse_offs):
return None
"""called after on_process_buffer
returns annotations and arrows/pointers"""
def on_get_annotations(self, addr, size, mouse_offs):
return None
# -----------------------------------------------------------------------
def is_ida_version(min_ver_required):
return IDA_SDK_VERSION >= min_ver_required
# -----------------------------------------------------------------------
def highlight_item(ea):
global HIGHLIGHTED_ITEM
HIGHLIGHTED_ITEM = ea
# -----------------------------------------------------------------------
def unhighlight_item():
global HIGHLIGHTED_ITEM
HIGHLIGHTED_ITEM = None
# -----------------------------------------------------------------------
class UIHook(ida_kernwin.UI_Hooks):
def __init__(self):
ida_kernwin.UI_Hooks.__init__(self)
def get_lines_rendering_info(self, out, widget, rin):
if HIGHLIGHTED_ITEM and ida_kernwin.get_widget_type(widget) == ida_kernwin.BWN_DISASM:
ea = HIGHLIGHTED_ITEM
for section_lines in rin.sections_lines:
for line in section_lines:
line_ea = line.at.toea()
if ea == line_ea:
e = ida_kernwin.line_rendering_output_entry_t(line)
e.bg_color = HL_COLOR
out.entries.push_back(e)
# -----------------------------------------------------------------------
class ScreenEAHook(ida_kernwin.UI_Hooks):
def __init__(self):
ida_kernwin.UI_Hooks.__init__(self)
self.sh = SignalHandler()
self.new_ea = self.sh.ida_newea
def screen_ea_changed(self, ea, prev_ea):
self.new_ea.emit()
# -----------------------------------------------------------------------
class SignalHandler(QObject):
pw_statechanged = pyqtSignal()
pw_next_filter = pyqtSignal()
pw_prev_filter = pyqtSignal()
ida_newea = pyqtSignal()
# -----------------------------------------------------------------------
class IDBBufHandler():
def __init__(self, loaderSegmentsOnly=False):
pass
def get_buffers(self, ea, count=0):
buffers = []
base = offs = 0
i = 0
result = ida_bytes.get_bytes_and_mask(ea, count)
if result:
buf, mask = result
for m in range(len(mask)):
b = mask[m]
if i == 0:
ismapped = (b&1) != 0
for j in range(8):
bitset = ((b>>j) & 1) != 0
if bitset != ismapped:
offs = i+j
buffers.append((ismapped, buf[base:offs]))
base = i+j
ismapped = not ismapped
if j == 7:
offs = i+j+1
if m == len(mask)-1:
buffers.append((ismapped, buf[base:offs]))
i += 8
return buffers
def get_base(self, ea):
base = ida_idaapi.BADADDR
qty = ida_segment.get_segm_qty()
for i in range(qty):
seg = ida_segment.getnseg(i)
if seg and seg.contains(ea):
base = seg.start_ea
break
return base
# -----------------------------------------------------------------------
class PixelWidget(QWidget):
def __init__(self, form, bufhandler):
super(PixelWidget, self).__init__()
self.form = form
self.set_zoom(10)
self.is_dragging_graph = False
self.is_scrolling = False
self.maxPixelsPerLine = 64
self.maxPixelsTotal = 0
self.prev_mouse_y = 0
self.key = None
self.buffers = None
self.offs = 0
self.base = 0
self.fm = None
self.filter_idx = 0
self.mouseOffs = 0
self.sync = True
self.bh = bufhandler
self.mouse_abs_x = 0
self.mouse_abs_y = 0
self.elemX = 0
self.elemY = 0
self.rect_x = 0
self.rect_x_width = 0
self.lock_width = False
self.lock_sync = False
self.link_pixel = True
self.highlight_cursor = False
self.slider_x = 0
self.slider_y = 0
self.slider_width = 0
self.slider_height = 0
self.babs = 0
self.textbox_content = None
self.textbox_content_type = 0
self.cur_formatter_idx = 2
self.formatters = [(0, "off"), (1, "ascii"), (2, "hex")]
self.max_formatters = len(self.formatters)
# composition modes: https://doc.qt.io/qt-5/qpainter.html#CompositionMode-enum
"""
self.composition_modes = [
(QPainter.CompositionMode_SourceOver, "QPainter.CompositionMode_SourceOver"),
(QPainter.CompositionMode_DestinationOver, "QPainter.CompositionMode_DestinationOver"),
(QPainter.CompositionMode_Clear, "QPainter.CompositionMode_Clear"),
(QPainter.CompositionMode_Source, "QPainter.CompositionMode_Source"),
(QPainter.CompositionMode_Destination, "QPainter.CompositionMode_Destination"),
(QPainter.CompositionMode_SourceIn, "QPainter.CompositionMode_SourceIn"),
(QPainter.CompositionMode_DestinationIn, "QPainter.CompositionMode_DestinationIn"),
(QPainter.CompositionMode_SourceOut, "QPainter.CompositionMode_SourceOut"),
(QPainter.CompositionMode_DestinationOut, "QPainter.CompositionMode_DestinationOut"),
(QPainter.CompositionMode_SourceAtop, "QPainter.CompositionMode_SourceAtop"),
(QPainter.CompositionMode_DestinationAtop, "QPainter.CompositionMode_DestinationAtop"),
(QPainter.CompositionMode_Xor, "QPainter.CompositionMode_Xor"),
(QPainter.CompositionMode_Plus, "QPainter.CompositionMode_Plus"),
(QPainter.CompositionMode_Multiply, "QPainter.CompositionMode_Multiply"),
(QPainter.CompositionMode_Screen, "QPainter.CompositionMode_Screen"),
(QPainter.CompositionMode_Overlay, "QPainter.CompositionMode_Overlay"),
(QPainter.CompositionMode_Darken, "QPainter.CompositionMode_Darken"),
(QPainter.CompositionMode_Lighten, "QPainter.CompositionMode_Lighten"),
(QPainter.CompositionMode_ColorDodge, "QPainter.CompositionMode_ColorDodge"),
(QPainter.CompositionMode_ColorBurn, "QPainter.CompositionMode_ColorBurn"),
(QPainter.CompositionMode_HardLight, "QPainter.CompositionMode_HardLight"),
(QPainter.CompositionMode_SoftLight, "QPainter.CompositionMode_SoftLight"),
(QPainter.CompositionMode_Difference, "QPainter.CompositionMode_Difference"),
(QPainter.CompositionMode_Exclusion, "QPainter.CompositionMode_Exclusion"),
(QPainter.RasterOp_SourceOrDestination, "QPainter.RasterOp_SourceOrDestination"),
(QPainter.RasterOp_SourceAndDestination, "QPainter.RasterOp_SourceAndDestination"),
(QPainter.RasterOp_SourceXorDestination, "QPainter.RasterOp_SourceXorDestination"),
(QPainter.RasterOp_NotSourceAndNotDestination, "QPainter.RasterOp_NotSourceAndNotDestination"),
(QPainter.RasterOp_NotSourceOrNotDestination, "QPainter.RasterOp_NotSourceOrNotDestination"),
(QPainter.RasterOp_NotSourceXorDestination, "QPainter.RasterOp_NotSourceXorDestination"),
(QPainter.RasterOp_NotSource, "QPainter.RasterOp_NotSource"),
(QPainter.RasterOp_NotSourceAndDestination, "QPainter.RasterOp_NotSourceAndDestination"),
(QPainter.RasterOp_SourceAndNotDestination, "QPainter.RasterOp_SourceAndNotDestination"),
(QPainter.RasterOp_NotSourceOrDestination, "QPainter.RasterOp_NotSourceOrDestination"),
(QPainter.RasterOp_ClearDestination, "QPainter.RasterOp_ClearDestination"),
(QPainter.RasterOp_SetDestination, "QPainter.RasterOp_SetDestination"),
(QPainter.RasterOp_NotDestination, "QPainter.RasterOp_NotDestination"),
(QPainter.RasterOp_SourceOrNotDestination, "QPainter.RasterOp_SourceOrNotDestination")]
"""
self.composition_modes = [
(QPainter.CompositionMode_Overlay, "Comp_Overlay"),
(QPainter.CompositionMode_SourceOver, "Comp_SourceOver"),
(QPainter.CompositionMode_Xor, "Comp_Xor"),
(QPainter.CompositionMode_SoftLight, "Comp_SoftLight"),
(QPainter.CompositionMode_Difference, "Comp_Difference"),
(QPainter.CompositionMode_Exclusion, "Comp_Exclusion"),
(QPainter.RasterOp_NotSourceAndNotDestination, "Raster_NotSourceAndNotDestination"),
(QPainter.RasterOp_SourceAndNotDestination, "Raster_SourceAndNotDestination"),
(QPainter.RasterOp_ClearDestination, "Raster_ClearDestination")]
self.cur_compos_mode = 0
self.setMouseTracking(True)
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.sh = SignalHandler()
self.statechanged = self.sh.pw_statechanged
self.next_filter = self.sh.pw_next_filter
self.prev_filter = self.sh.pw_prev_filter
self.qp = QPainter()
self.show()
def paintEvent(self, event):
if not self.fm:
return
# set leftmost x-coordinate of graph
zoom_level = self.get_zoom()
self.rect_x_width = self.get_pixel_qty_per_line() * zoom_level
self.rect_x = floor(self.rect().width() / 2) - floor(self.rect_x_width / 2)
self.qp.begin(self)
# what is a good default font for OSX/Linux?
self.qp.setFont(QFont(FONT_DEFAULT))
# fill background
self.qp.fillRect(self.rect(), Qt.black)
content_addr = content_size = None
if self.fm.support_selection:
selected, start, end = ida_kernwin.read_range_selection(None)
if selected:
content_addr = start#min(start, end)
content_size = end - start#max(start, end) - content_addr
# use colorfilter to render image
img = self.paint_image(addr=content_addr, buf_size=content_size)
if img:
"""
if zoom_level > 6:
opacity = self.qp.opacity()
full_opacity_zoom = 40.0
cur_opacity = (1.0 - (full_opacity_zoom - float(min(zoom_level-1, full_opacity_zoom)))/full_opacity_zoom)
self.qp.setOpacity(1.0-cur_opacity)
"""
# draw image
self.qp.drawImage(
QRect(QPoint(self.rect_x, 0),
QPoint(self.rect_x + self.get_pixel_qty_per_line() * zoom_level, floor((self.get_pixel_qty() / self.get_pixel_qty_per_line()) * zoom_level))),
img)
# TODO: pen color contrast
# TODO: data export: render data
# TODO: default fonts / OS?
# TODO: optimization
# FIXME: there's a bug with gaps/unmapped buffers
if (self.cur_formatter_idx and
not self.fm.disable_data and
zoom_level >= 10 and
self.get_pixel_qty() < 70*70):
self.qp.setPen(QColor(Qt.white))
fontsize = self.qp.font().pointSizeF()
font = self.qp.font()
font.setPointSizeF(zoom_level*0.55)
#font.setPixelSize(zoom_level)
self.qp.setFont(font)
opacity = self.qp.opacity()
full_opacity_zoom = 28
cur_opacity = (1.0 - (full_opacity_zoom - float(min(zoom_level-1, full_opacity_zoom)))/full_opacity_zoom)
self.qp.setOpacity(cur_opacity)
#m = self.qp.fontMetrics()
x = y = 0
num_pixels_per_line = self.get_pixel_qty_per_line()
cm = self.qp.compositionMode()
self.qp.setCompositionMode(self.composition_modes[self.cur_compos_mode][0])
if self.formatters[self.cur_formatter_idx][0] == 1:
fmt = lambda c : "%c" %c if c in range(0x20, 0x7e) else "."
elif self.formatters[self.cur_formatter_idx][0] == 2:
fmt = lambda c : "%02X" % c
for mapped, buf in self.buffers:
for i in range(len(buf)):
if mapped:
b = buf[i]
data = fmt(b)
self.qp.drawText(
self.rect_x + x*zoom_level,
y*zoom_level,
zoom_level,
zoom_level,
Qt.AlignCenter,
data)
x = (i + 1) % num_pixels_per_line
if not x:
y = y + 1
# restore attributes
self.qp.setCompositionMode(cm)
self.qp.setOpacity(opacity)
font.setPointSizeF(fontsize)
self.qp.setFont(font)
if self.show_address_range and self.fm.link_pixel:
self.paint_slider(addr=content_addr, buf_size=content_size)
# get and draw annotations and pointers
annotations = self.fm.on_get_annotations(content_addr if content_addr else self.get_address(),
self.get_pixel_qty(),
self.mouseOffs)
if annotations:
self.paint_annotations(annotations)
self.paint_status()
if self.textbox_content:
self.paint_text_box()
self.qp.end()
return
def paint_image(self, addr=None, buf_size=None, cursor=True):
size = self.size()
self.set_pixel_qty(self.get_pixel_qty_per_line() * floor(size.height() / self.pixelSize))
if addr is None or buf_size is None:
addr = self.base + self.offs
buf_size = self.get_pixel_qty()
self.buffers = self.bh.get_buffers(addr, buf_size)
img = QImage(self.get_pixel_qty_per_line(), floor(size.height() / self.pixelSize), QImage.Format_RGB32)
pixels = self.fm.on_process_buffer(self.buffers, addr, self.get_pixel_qty(), self.mouseOffs)
x = y = 0
# "transparency" effect for unmapped bytes
transparency_dark = [qRgb(0x2F,0x4F,0x4F), qRgb(0x00,0x00,0x00)]
transparency_err = [qRgb(0x7F,0x00,0x00), qRgb(0x33,0x00,0x00)]
for mapped, pix in pixels:
if not mapped:
if pix is None:
pix = transparency_dark[(x&2 != 0) ^ (y&2 != 0)]
img.setPixel(x, y, pix)
x = (x + 1) % self.get_pixel_qty_per_line()
if not x:
y = y + 1
if len(pixels) != self.get_pixel_qty():
for i in range(self.get_pixel_qty() - len(pixels)):
pix = transparency_err[(x&2 != 0) ^ (y&2 != 0)]
img.setPixel(x, y, pix)
x = (x + 1) % self.get_pixel_qty_per_line()
if not x:
y = y + 1
if ((cursor and self.fm.highlight_cursor) and
self.mouse_abs_x >= self.rect_x and
self.mouse_abs_x < self.rect_x + self.rect_x_width):
coords = self.get_coords_by_address(self.get_cursor_address())
if coords:
x,y = coords
else:
x = self.get_elem_x()
y = self.get_elem_y()
p = QPoint(x, y)
img.setPixel(p, (~(img.pixelColor(p)).rgb() & 0xFFFFFFFF))
return img
def paint_annotations(self, annotations=[]):
a_offs = 20
base_x = self.rect_x + self.get_pixel_qty_per_line() * self.pixelSize + a_offs + 10
base_y = self.qp.fontMetrics().height()
offs_x = 5
offs_y = base_y
for coords, arr_color, ann, txt_color in annotations:
# draw arrow (experimental / WIP)
self.qp.setPen(QColor(Qt.white if txt_color is None else txt_color))
self.qp.drawText(base_x+10, floor((base_y+offs_y)/2), ann)
target_x = target_y = None
if coords:
if isinstance(coords, tuple):
target_x, target_y = coords
else:
ptr = self.get_coords_by_address(coords)
if ptr:
target_x, target_y = ptr
if target_x is not None and target_y is not None:
target_x *= self.get_zoom()
target_y *= self.get_zoom()
self.qp.setPen(QColor(Qt.white if arr_color is None else arr_color))
path = QPainterPath()
path.moveTo(base_x+offs_x, (floor(base_y+offs_y)/2-base_y/2))
path.lineTo(base_x+offs_x - 4 - a_offs, floor((base_y+offs_y)/2-base_y/2)) # left
path.lineTo(base_x+offs_x - 4 - a_offs, floor((target_y/10)*9 + self.get_zoom()/2)) # down
path.lineTo(self.rect_x + target_x + floor(self.get_zoom() / 2), floor((target_y/10)*9 + self.get_zoom()/2)) # left
path.lineTo(self.rect_x + target_x + floor(self.get_zoom() / 2), target_y + floor(self.get_zoom()/2)) # down
a_offs = max(a_offs-2, 0)
self.qp.drawPath(path)
else:
if not isinstance(coords, tuple):
direction = self.get_target_direction(coords)
if direction:
self.qp.setPen(QColor(Qt.white if arr_color is None else arr_color))
m = self.qp.fontMetrics()
dirhint = ['', '<<', '>>'][direction]
cwidth = m.width("%s" % (dirhint))
self.qp.drawText(base_x - cwidth, floor((base_y+offs_y)/2), dirhint)
offs_y += 2*base_y + 5
return
def paint_slider(self, addr=None, buf_size=None):
if addr is None or buf_size is None:
addr = self.base + self.offs
buf_size = self.get_pixel_qty()
lowest_ea = ida_ida.inf_get_min_ea()
highest_ea = ida_ida.inf_get_max_ea()
start_offs = addr - lowest_ea
addr_space = highest_ea - lowest_ea
perc_s = float(start_offs) / float(addr_space)
perc_e = float(start_offs+buf_size) / float(addr_space)
bar_width = 20
spaces_bar = 5
bar_x = self.rect_x - spaces_bar - bar_width
bar_y = 5
bar_height = self.rect().height() - 2 * bar_y
self.qp.fillRect(bar_x, bar_y, bar_width, bar_height, QColor(0x191919))
self.babs = self.rect().height() #bar_height - bar_y
slider_offs_s = perc_s * bar_height
slider_offs_e = perc_e * bar_height
spaces_slider = 1
self.slider_x = bar_x + spaces_slider
self.slider_y = bar_y + slider_offs_s
self.slider_width = bar_width - 2 * spaces_slider
# limit slider height to bar_height
self.slider_height = floor(max(min(slider_offs_e - slider_offs_s, bar_height - (self.slider_y - bar_y)), 4))
self.qp.fillRect(floor(self.slider_x), floor(self.slider_y), self.slider_width, self.slider_height, QColor(0x404040))
#self.slider_coords = ((slider_x, slider_y), (slider_x+slider_width, slider_y+slider_height))
self.qp.setPen(QColor(0x808080))
# draw addresses
addr_low = '%X:' % self.get_address()
addr_hi = '%X' % floor(self.get_address() + (floor(self.get_pixel_qty() / self.get_pixel_qty_per_line()) - 1) * self.get_pixel_qty_per_line())
self.qp.drawText(self.rect_x - self.qp.fontMetrics().width(addr_low) - bar_width - 2 * spaces_bar,
self.qp.fontMetrics().height(),
addr_low)
self.qp.drawText(self.rect_x - self.qp.fontMetrics().width(addr_hi) - bar_width - 2 * spaces_bar,
self.rect().height() - floor(self.qp.fontMetrics().height() / 2),
addr_hi)
return
def display_help_box(self, text, isFilter=False):
if text == self.textbox_content or text is None or not(len(text)):
self.textbox_content = None
return
self.textbox_content_type = 0 if isFilter else 1
self.textbox_content = text
return
def paint_text_box(self, borderSize=6):
base_x = floor(self.rect().width()/2)
if self.textbox_content_type == 0:
lines = self.get_filter_helptext().splitlines()
else:
lines = self.textbox_content.splitlines()
line_width = 0
for line in lines:
line_width = max(line_width, self.qp.fontMetrics().width(line))
text_x_pos = floor(base_x - line_width/2)
cm = self.qp.compositionMode()
self.qp.setCompositionMode(QPainter.CompositionMode_HardLight)
total_text_height = len(lines) * self.qp.fontMetrics().height()
self.qp.fillRect(text_x_pos - borderSize,
floor(self.rect().height() / 2) - floor(total_text_height/2) - borderSize,
line_width + borderSize*2,
total_text_height + borderSize,
QColor(0x202020))
self.qp.setPen(QColor(Qt.white))
#self.qp.setPen(QColor(0x000ff41))
cur_line = 0
for line in lines:
text_y_pos = floor(self.rect().height() / 2) - floor(len(lines) / 2) * self.qp.fontMetrics().height() + cur_line * self.qp.fontMetrics().height()
# draw status
self.qp.drawText(text_x_pos,
text_y_pos,
line)
cur_line += 1
self.qp.setCompositionMode(cm)
return
def paint_status(self):
a_offs = 20
base_x = self.rect_x + self.get_pixel_qty_per_line() * self.pixelSize + a_offs + 10
lines = []
lines.append("[Data]")
lines.append(" Type: %s" % self.formatters[self.cur_formatter_idx][1])
lines.append(" Mode: %s (%d/%d)" % (self.composition_modes[self.cur_compos_mode][1], self.cur_compos_mode + 1, len(self.composition_modes)))
cur_line = 1
text_x_pos = base_x + 10
self.qp.setPen(QColor(Qt.white))
for line in lines:
text_y_pos = self.rect().height() - floor(self.qp.fontMetrics().height()/2) - (len(lines) - cur_line) * (self.qp.fontMetrics().height())
# draw status
self.qp.drawText(text_x_pos,
text_y_pos,
line)
cur_line += 1
# functions that can be called by filters
# must not be called from within on_process_buffer()
def on_filter_request_update(self, ea=None, center=True):
if not ea:
self.repaint()
else:
curea = self.get_address()
if ea < curea or ea >= curea + self.get_pixel_qty():
# TODO: verify that ea is valid after following operation
if center:
ea -= floor(self.get_pixel_qty()/2)
self.set_addr(ea)
else:
self.repaint()
def on_filter_update_zoom(self, zoom):
self.set_zoom(zoom)
return
def on_filter_update_zoom_delta(self, delta):
self.set_zoom_delta(delta)
return
# end of functions that can be called by filters
def get_filter_helptext(self):
hlp = self.fm.help
if not hlp:
hlp = "No help available :["
jstfy = "\n"+ 4*" "
hlp_fmt = jstfy + hlp.replace("\n", jstfy)
helptxt = FILTER_HELP % (self.fm.name, hlp_fmt)
return helptxt
def keyPressEvent(self, event):
if self.key is None:
self.key = event.key()
return
def keyReleaseEvent(self, event):
update = False
key = event.key()
modifiers = event.modifiers()
shift_pressed = ((modifiers & Qt.ShiftModifier) == Qt.ShiftModifier)
ctrl_pressed = ((modifiers & Qt.ControlModifier) == Qt.ControlModifier)
if key == Qt.Key_F1 and ctrl_pressed:
self.display_help_box(PLUGIN_HELP)
self.repaint()
elif key == Qt.Key_F2 and ctrl_pressed:
self.display_help_box(self.get_filter_helptext(), isFilter=True)
self.repaint()
elif key == Qt.Key_Escape:
self.display_help_box(None)
self.repaint()
elif key == Qt.Key_G:
addr = ida_kernwin.ask_addr(self.base + self.offs, 'Jump to address')
if addr is not None:
if self.sync:
ida_kernwin.jumpto(addr)
else:
minea = ida_ida.inf_get_min_ea()
maxea = ida_ida.inf_get_max_ea()
dst = min(max(addr, minea), maxea)
self.set_addr(dst)
elif key == Qt.Key_S:
if not self.fm.lock_sync:
self.set_sync_state(not self.get_sync_state())
update = True
elif key == Qt.Key_D:
self.cur_formatter_idx = (self.cur_formatter_idx + 1) % self.max_formatters
self.repaint()
elif key == Qt.Key_T:
self.cur_compos_mode = (self.cur_compos_mode + 1) % len(self.composition_modes)
self.repaint()
elif key == Qt.Key_N:
self.next_filter.emit()
elif key == Qt.Key_B:
self.prev_filter.emit()
elif key == Qt.Key_F12 and shift_pressed and ctrl_pressed:
img = self.paint_image(cursor = False)
img = img.scaled(img.width()*self.pixelSize, img.height()*self.pixelSize, Qt.KeepAspectRatio, Qt.FastTransformation)
done = False
i = 0
while not done:
fname = 'IDACyber_%04d.bmp' % i
if not os.path.isfile(fname):
if img.save(fname):
ida_kernwin.msg('File exported to %s\n' % fname)
else:
ida_kernwin.warning('Error exporting screenshot to %s.' % fname)
done = True
i += 1
if i > 40:
ida_kernwin.warning('Aborted. Error exporting screenshot.')
break
elif key == Qt.Key_PageDown:
self.set_offset_delta(-self.get_pixel_qty())
update = True
elif key == Qt.Key_PageUp:
self.set_offset_delta(self.get_pixel_qty())
update = True
elif key == Qt.Key_Down:
if shift_pressed:
self.set_offset_delta(-1)
else:
self.set_offset_delta(-self.get_pixel_qty_per_line())
update = True
elif key == Qt.Key_Up:
if shift_pressed:
self.set_offset_delta(1)
else:
self.set_offset_delta(self.get_pixel_qty_per_line())
update = True
elif key == Qt.Key_Plus:
if ctrl_pressed:
self.set_zoom_delta(1)
update = True
elif key == Qt.Key_Minus:
if ctrl_pressed:
self.set_zoom_delta(-1)
update = True
self.key = None
if update:
if self.get_sync_state():
ida_kernwin.jumpto(self.base + self.offs, -1, ida_kernwin.UIJMP_ANYVIEW)
self.statechanged.emit()
self.repaint()
return
def wheelEvent(self, event):
delta = floor(event.angleDelta().y()/120)
# zoom
if self.key == Qt.Key_Control:
self.set_zoom_delta(delta)
# width
elif self.key == Qt.Key_X:
if not self.lock_width:
self.set_width_delta(delta)
# offset (fine)
elif self.key == Qt.Key_Shift:
self.set_offset_delta(delta)
if self.get_sync_state():
ida_kernwin.jumpto(self.base + self.offs, -1, ida_kernwin.UIJMP_ANYVIEW)
elif self.key == Qt.Key_H:
if not self.lock_width:
less = delta < 0
w = -8 if less else 8
self.set_pixel_qty_per_line((self.get_pixel_qty_per_line() & 0xFFFFFFF8) + w)
# offset (coarse)
else:
self.set_offset_delta(delta * self.get_pixel_qty_per_line())
if self.get_sync_state():
ida_kernwin.jumpto(self.base + self.offs, -1, ida_kernwin.UIJMP_ANYVIEW)
self.statechanged.emit()
self.repaint()
return
def mousePressEvent(self, event):
x = event.pos().x()
y = event.pos().y()
within_graph = (x >= self.rect_x and x < self.rect_x + self.rect_x_width)
within_slider = (x >= self.slider_x and x < self.slider_x + self.slider_width and
y >= self.slider_y and y < self.slider_y + self.slider_height)
self.is_dragging_graph = (within_graph and event.button() == Qt.LeftButton)
self.is_scrolling = (within_slider and event.button() == Qt.LeftButton)
return
def mouseDoubleClickEvent(self, event):
if self.link_pixel and event.button() == Qt.LeftButton:
addr = self.base + self.offs + self._get_offs_by_pos(event.pos())
ida_kernwin.jumpto(addr)
return
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
if self.is_dragging_graph:
self.is_dragging_graph = False
elif self.is_scrolling:
self.is_scrolling = False
self.prev_mouse_y = event.pos().y()
self.fm.on_mb_click(event, self.get_address(), self.get_pixel_qty(), self.mouseOffs)
if self.get_sync_state():
ida_kernwin.jumpto(self.base + self.offs, -1, ida_kernwin.UIJMP_ANYVIEW)
self.statechanged.emit()
return
def mouseMoveEvent(self, event):
x = event.pos().x()
y = event.pos().y()
within_graph = (x >= self.rect_x and x < self.rect_x + self.rect_x_width)
update_state = self.is_dragging_graph or within_graph or self.is_scrolling
if self.is_scrolling:
if y != self.prev_mouse_y:
lowest_ea = ida_ida.inf_get_min_ea()
highest_ea = ida_ida.inf_get_max_ea()
new_offs = floor((y/self.babs) * (highest_ea-lowest_ea))
#print("%f" % (y/self.babs))
self.set_addr(max(min(lowest_ea+new_offs, highest_ea), lowest_ea))
return
elif self.is_dragging_graph:
# zoom
if self.key == Qt.Key_Control:
self.set_zoom_delta(-1 if y > self.prev_mouse_y else 1)
# width
elif self.key == Qt.Key_X:
if not self.lock_width:
self.set_width_delta(-1 if y > self.prev_mouse_y else 1)
elif self.key == Qt.Key_H:
if not self.lock_width:
less = y > self.prev_mouse_y
delta = -16 if less else 16
self.set_pixel_qty_per_line((self.get_pixel_qty_per_line() & 0xFFFFFFF0) + delta)
# scrolling (offset)
elif y != self.prev_mouse_y:
# offset (fine)
delta = y - self.prev_mouse_y
# offset (coarse)
if self.key != Qt.Key_Shift:
delta *= self.get_pixel_qty_per_line()
self.set_offset_delta(delta)
elif within_graph:
self._update_mouse_coords(event.pos())
self.mouseOffs = self._get_offs_by_pos(event.pos())
if self.link_pixel and self.highlight_cursor:
highlight_item(ida_bytes.get_item_head(self.get_cursor_address()))
#ida_kernwin.request_refresh(True)
ida_kernwin.refresh_idaview_anyway()
elif self.highlight_cursor:
unhighlight_item()
self.setToolTip(self.fm.on_get_tooltip(self.get_address(), self.get_pixel_qty(), self.mouseOffs))
if update_state:
self.prev_mouse_y = y
self.x = x
self.statechanged.emit()
self.repaint()
return
def set_sync_state(self, sync):
self.sync = sync
def get_sync_state(self):
return self.sync
def get_filter_idx(self):
return self.filter_idx
def set_filter(self, fltobj, idx):
if self.fm:
self.fm.on_deactivate()
if fltobj:
self.fm = fltobj
"""load filter config"""
self.set_sync_state(self.fm.sync)
self.lock_width = self.fm.lock_width
self.set_pixel_qty_per_line(self.fm.width)
self.lock_sync = self.fm.lock_sync
self.show_address_range = self.fm.show_address_range
# disabled for now
# self.set_zoom(self.fm.zoom)
self.link_pixel = self.fm.link_pixel
self.highlight_cursor = self.fm.highlight_cursor
self.statechanged.emit()
"""load filter config end"""
self.fm.on_activate(idx)
self.filter_idx = idx
unhighlight_item()
self.repaint()
def set_addr(self, ea, new_cursor=None):
_ea = ea
selection, start, end = ida_kernwin.read_range_selection(None)
if selection:
_ea = start
base = self.bh.get_base(_ea)
self._set_base(base)
self._set_offs(_ea - base)
if new_cursor:
self.set_cursor_offset(new_cursor)
if self.highlight_cursor:
highlight_item(_ea)
self.repaint()
def get_zoom(self):
return self.pixelSize