-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathfindrpc.py
2262 lines (1693 loc) · 77.4 KB
/
findrpc.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 ctypes
import binascii
import struct
import logging
import json
import inspect
from collections import namedtuple
from ctypes import Array, Structure, Union, _Pointer, _SimpleCData
from json import JSONEncoder
# IDA libraries
import idaapi
import idc
from PyQt5 import QtCore, QtWidgets, QtGui
# IDA API retrocompatibility
if idaapi.IDA_SDK_VERSION <= 695:
from idaapi import get_segm_qty, getnseg
if idaapi.IDA_SDK_VERSION >= 700:
from ida_segment import get_segm_qty, getnseg
import ida_typeinf
else:
pass
# we can't use ctypes.c_voidp since it rely on Python engine's arch, not the curent PE arch.
POINTER = ( ctypes.c_uint32, ctypes.c_uint64 )[idaapi.get_inf_structure().is_64bit()]
POINTER_SIZE = ctypes.sizeof(POINTER)
READ_PTR_VALUE = (ida_bytes.get_32bit, ida_bytes.get_64bit) [idaapi.get_inf_structure().is_64bit()]
#################################
## ctypes to JSON encoder, copied from https://github.com/rinatz/ctypes_json
class CDataJSONEncoder(JSONEncoder):
def default(self, obj):
if hasattr(obj, "_json_serialize"):
return obj._json_serialize()
if isinstance(obj, (Array, list)):
return [self.default(e) for e in obj]
if isinstance(obj, _Pointer):
return self.default(obj.contents) if obj else None
if isinstance(obj, _SimpleCData):
return self.default(obj.value)
if isinstance(obj, (bool, int, float, str, long)):
return obj
if obj is None:
return obj
if isinstance(obj, (Structure, Union)):
result = {}
anonymous = getattr(obj, '_anonymous_', [])
for key, value in getattr(obj, '_fields_', []):
value = getattr(obj, key)
# private fields don't encode
if key.startswith('_'):
continue
if key in anonymous:
result.update(self.default(value))
else:
result[key] = self.default(value)
return result
return JSONEncoder.default(self, obj)
#################################
## ctypes rpc structures
class RpcStructure(ctypes.Structure):
@classmethod
def get_c_instance_name(cls, name):
""" return a standard name for the extracted C struct instance """
instance_name = getattr(cls, "__instance_name__")
return "{name:s}_{instance:s}".format(
name = name,
instance = instance_name
)
@classmethod
def get_c_instance_pointer(cls, name, address):
""" return a standard name for the extracted C struct instance pointer """
if not address:
return "NULL"
return "&%s" % cls.get_c_instance_name(name)
@classmethod
def generate_format_string_offsets_table(cls, name, fso_ea, handlers_count = 0):
result = ""
# Format string offsets
format_string_offset_pointer = "NULL"
if not fso_ea or not handlers_count:
return format_string_offset_pointer, result
format_string_offset_name = "%s_format_string_offset" % cls.get_c_instance_name(name)
format_string_offset_pointer = "&%s" % format_string_offset_name
offsets = [ ida_bytes.get_word(fso_ea + 2*i) for i in range(handlers_count)]
fso_instance = "static const unsigned short {name:s}[] = {{{values:s}}};".format(
name = format_string_offset_name,
values = ",".join(["0x%04x" % x for x in offsets])
)
result += fso_instance
result += "\n\n"
return format_string_offset_pointer, result
@classmethod
def generate_transfer_syntax_instance(cls, name, transfer_syntax):
result = ""
transfer_syntax_pointer = "NULL"
if not transfer_syntax:
return transfer_syntax_pointer, result
transfer_syntax_struct_name = "%s_transfer_syntax" % cls.get_c_instance_name(name);
transfer_syntax_pointer = "&%s" % transfer_syntax_struct_name
transfer_syntax_struct = "\n".join([
"static const RPC_SYNTAX_IDENTIFIER %s = %s;" % (
transfer_syntax_struct_name,
transfer_syntax.gen_c_struct()
),
"",
""
])
result += transfer_syntax_struct
return transfer_syntax_pointer, result
@classmethod
def generate_proc_string_instance(cls, name, proc_string_ea, bytes_read):
result = ""
proc_string_pointer = "NULL"
if not proc_string_ea:
return proc_string_pointer, result
proc_string_name = "%s_proc_string" % cls.get_c_instance_name(name)
proc_string_pointer = "&%s" % proc_string_name
raw_buffer = [ord(x) for x in ida_bytes.get_bytes(proc_string_ea, bytes_read)]
ps_instance = "static const unsigned char {name:s}[] = {{{values:s}}};".format(
name = proc_string_name,
values = ",".join(["0x%02x" % x for x in raw_buffer])
)
result += ps_instance
result += "\n\n"
return proc_string_pointer, result
class GUID(RpcStructure):
_fields_ = [
('Data1', ctypes.c_uint),
('Data2', ctypes.c_ushort),
('Data3', ctypes.c_ushort),
('Data4', ctypes.c_ubyte * 8),
]
def __eq__(self, other):
return self.Data1 == other.Data1 and \
self.Data2 == other.Data2 and \
self.Data3 == other.Data3 and \
all( x == y for x, y in zip(self.Data4, other.Data4))
def __str__(self):
return "%04x-%02x-%02x-%s" % (
self.Data1,
self.Data2,
self.Data3,
"".join("%02x" % x for x in self.Data4)
)
def gen_c_struct(self):
return "{0x%08x, 0x%04x, 0x%04x, %s}" % (
self.Data1,
self.Data2,
self.Data3,
"{ %s }" % b", ".join("0x%02x" % x for x in self.Data4)
)
def _json_serialize(self):
"""
Return the GUID in a way Microsoft likes.
"""
return "%08x-%04x-%04x-%04x-%s" % (
self.Data1,
self.Data2,
self.Data3,
self.Data4[0]*256 + self.Data4[1],
b"".join("%02x" % x for x in self.Data4[2:])
)
@classmethod
def from_guid_string(cls, guid_string):
if guid_string.count('-') == 3:
# "%04x-%02x-%02x-%s" GUID style
hexData1, hexData2, hexData3, hexData4 = guid_string.split('-')
Data1 = int(hexData1, 16)
Data2 = int(hexData2, 16)
Data3 = int(hexData3, 16)
Data4 = [int(hexData4[i:i+2], 16) for i in range(0, len(hexData4), 2)]
return cls(Data1, Data2, Data3, (ctypes.c_ubyte*8)(*Data4))
elif guid_string.count('-') == 4:
# "%04x-%02x-%02x-%02x-%s" GUID style
hexData1, hexData2, hexData3, hexData4Hi, hexData4 = guid_string.split('-')
Data4Hi = int(hexData4Hi, 16)
Data1 = int(hexData1, 16)
Data2 = int(hexData2, 16)
Data3 = int(hexData3, 16)
Data4 = [Data4Hi >> 8, Data4Hi & 0xff] + [int(hexData4[i:i+2], 16) for i in range(0, len(hexData4), 2)]
return cls(Data1, Data2, Data3, (ctypes.c_ubyte*8)(*Data4))
else:
raise ValueError("Unrecognized GUID format string : %s" % guid_string)
class RPC_VERSION(RpcStructure):
_fields_ = [
('MajorVersion', ctypes.c_ushort),
('MinorVersion', ctypes.c_ushort),
]
def __str__(self):
return "%d.%d" % (self.MajorVersion, self.MinorVersion)
def gen_c_struct(self):
return "{%d, %d}" % (self.MajorVersion, self.MinorVersion)
def __eq__ (self, other):
return self.MajorVersion == other.MajorVersion and \
self.MinorVersion == other.MinorVersion
class RPC_SYNTAX_IDENTIFIER(RpcStructure):
_fields_ = [
('SyntaxGUID', GUID),
('SyntaxVersion', RPC_VERSION),
]
def __eq__ (self, other):
return self.SyntaxGUID == other.SyntaxGUID and \
self.SyntaxVersion == other.SyntaxVersion
def gen_c_struct(self):
return "{%s, %s}" % (self.SyntaxGUID.gen_c_struct(), self.SyntaxVersion.gen_c_struct())
def __str__(self):
if self == DCE_TransferSyntax:
return "DCE syntax (%s)" % (self.SyntaxVersion)
elif self == NDR64_TransferSyntax:
return "NDR64 syntax (%s)" % (self.SyntaxVersion)
else:
return "%s (%s)" % (self.SyntaxGUID, self.SyntaxVersion)
# Well-known UUID constants
DCE_TransferSyntax = RPC_SYNTAX_IDENTIFIER(GUID.from_guid_string("8A885D04-1CEB-11C9-9FE8-08002B104860"), (2, 0))
NDR64_TransferSyntax = RPC_SYNTAX_IDENTIFIER(GUID.from_guid_string("71710533-BEBA-4937-8319-B5DBEF9CCC36"), (1, 0))
class RPC_SERVER_INTERFACE(RpcStructure):
_pack_ = POINTER_SIZE
_fields_ = [
('Length', ctypes.c_uint),
('InterfaceId', RPC_SYNTAX_IDENTIFIER),
('TransferSyntax', RPC_SYNTAX_IDENTIFIER),
('DispatchTable', POINTER),
('RpcProtseqEndpointCount', ctypes.c_uint),
('RpcProtseqEndpoint', POINTER),
('DefaultManagerEpv', POINTER),
('InterpreterInfo', POINTER),
('Flags', ctypes.c_uint),
]
__instance_name__ = "interface"
def gen_c_struct(self, name, fa, is_client = False):
result = ""
struct_name = ("RPC_SERVER_INTERFACE", "RPC_CLIENT_INTERFACE")[is_client]
dispatch_table_pointer = "NULL"
if self.DispatchTable:
dispatch_table_pointer = "&%s_dispatch_table" % name
interpreter_info_pointer = "NULL"
if self.InterpreterInfo:
interpreter_info_pointer = "&%s_interpreter_info" % name
interface_struct = "\n".join([
"static const %s %s = {" % (struct_name, RPC_SERVER_INTERFACE.get_c_instance_name(name)),
" .Length = sizeof(%s)," % struct_name,
" .InterfaceId = %s," % self.InterfaceId.gen_c_struct(),
" .TransferSyntax = %s," % self.TransferSyntax.gen_c_struct(),
" .DispatchTable = %s," % dispatch_table_pointer,
" .RpcProtseqEndpointCount : %d," % self.RpcProtseqEndpointCount,
" .RpcProtseqEndpoint : NULL, // FIXME", # % self.RpcProtseqEndpoint,
" .DefaultManagerEpv : NULL, // FIXME", # % self.DefaultManagerEpv,
" .InterpreterInfo : %s," % interpreter_info_pointer,
" .Flags : 0x%x" % self.Flags,
"};",
"",
""
])
result += interface_struct
return result
def has_proxy_info(self):
# TODO : 0x6000000 is an undocumented flag indicating that InterpreterInfo
# is a stubless proxy structure, not a fully defined MIDL_SERVER_INFO instance.
# TODO : self.Flags == 0 can also means "inlined" server with no interpretor info
return (self.Flags & 0x2000000) == 0x2000000
def has_interpreter_info(self):
return (self.Flags & 0x4000000) == 0x4000000
def __str__(self):
return "\n".join([
" -Length : %d" % self.Length,
" -InterfaceId : %s" % self.InterfaceId,
" -TransferSyntax : %s" % self.TransferSyntax,
" -DispatchTable : 0x%x" % self.DispatchTable,
" -RpcProtseqEndpointCount : %d" % self.RpcProtseqEndpointCount,
" -RpcProtseqEndpoint : 0x%x" % self.RpcProtseqEndpoint,
" -DefaultManagerEpv : 0x%x" % self.DefaultManagerEpv,
" -InterpreterInfo : 0x%x" % self.InterpreterInfo,
" -Flags : 0x%x" % self.Flags
])
class MIDL_SERVER_INFO(RpcStructure):
_fields_ = [
('pStubDesc', POINTER), # MIDL_STUB_DESC
('DispatchTable', POINTER),
('ProcString', POINTER),
('FmtStringOffset', POINTER),
('ThunkTable', POINTER),
('pTransferSyntax', POINTER),
('nCount', POINTER),
('pSyntaxInfo', POINTER), # MIDL_SYNTAX_INFO
]
__instance_name__ = "interpreter_info"
def __str__(self):
return "\n".join([
" -pStubDesc : 0x%x" % self.pStubDesc,
" -DispatchTable : 0x%x" % self.DispatchTable,
" -ProcString : 0x%x" % self.ProcString,
" -FmtStringOffset : 0x%x" % self.FmtStringOffset,
" -ThunkTable : 0x%x" % self.ThunkTable,
" -pTransferSyntax : 0x%x" % self.pTransferSyntax,
" -nCount : %d" % self.nCount,
" -pSyntaxInfo : 0x%x" % self.pSyntaxInfo,
])
def gen_c_struct(self, name, fa, bytes_read = 0x100):
result = ""
dispatch_table_functions_pointer = "NULL"
query_fa_result = list(filter(lambda r: r.stub_desc.address == self.pStubDesc, fa.results))[0]
proc_handlers_ea = list(query_fa_result.get_proc_handlers())
# Dispatch table
if len(proc_handlers_ea):
# Read dispatch table functions names, or generate fun_xxx if not
rpc_dispatch_functions = [idaapi.get_name(ea) for ea in proc_handlers_ea]
rpc_dispatch_functions = "\n ".join(["%s," % fun for fun in rpc_dispatch_functions])
# generate a function pointer table for it
dispatch_table_functions_instance = "\n".join([
"static const SERVER_ROUTINE %s_routine_table[] = {" % MIDL_SERVER_INFO.get_c_instance_name(name),
" %s" % rpc_dispatch_functions,
" NULL",
"};",
"",
""
])
dispatch_table_functions_pointer = "&%s_routine_table" % MIDL_SERVER_INFO.get_c_instance_name(name)
result += dispatch_table_functions_instance
# Format string offsets
format_string_offset_pointer, fso_instance = MIDL_SERVER_INFO.generate_format_string_offsets_table(name, self.FmtStringOffset, len(proc_handlers_ea))
result += fso_instance
# Proc string
proc_string_pointer, ps_instance = MIDL_SERVER_INFO.generate_proc_string_instance(name, self.ProcString, bytes_read)
result += ps_instance
# transfer syntax
transfer_syntax_object = fa.query_rpc_struct(self.pTransferSyntax)
transfer_syntax_pointer, ts_instance = MIDL_SERVER_INFO.generate_transfer_syntax_instance(name, transfer_syntax_object)
result += ts_instance
midl_server_instance = "\n".join([
"static const MIDL_SERVER_INFO %s = {" % MIDL_SERVER_INFO.get_c_instance_name(name),
" .pStubDesc = {stub_desc:s},".format(stub_desc=MIDL_STUB_DESC.get_c_instance_pointer(name, self.pStubDesc)),
" .DispatchTable = {dp:s},".format(dp = dispatch_table_functions_pointer),
" .FmtStringOffset = %s," % format_string_offset_pointer,
" .ProcString = %s," % proc_string_pointer,
" .ThunkTable = NULL, // FIXME",
" .pTransferSyntax = %s," % transfer_syntax_pointer,
" .nCount={c:d},".format(c = self.nCount),
" .pSyntaxInfo = NULL //FIXME",
"};",
"",
""
])
result += midl_server_instance
return result;
class MIDL_STUBLESS_PROXY_INFO(RpcStructure):
_fields_ = [
('pStubDesc', POINTER), # MIDL_STUB_DESC
('ProcString', POINTER),
('FmtStringOffset', POINTER),
('pTransferSyntax', POINTER),
('nCount', POINTER),
('pSyntaxInfo', POINTER), # MIDL_SYNTAX_INFO
]
__instance_name__ = "interpreter_info"
def __str__(self):
return "\n".join([
" -pStubDesc : 0x%x" % self.pStubDesc,
" -ProcString : 0x%x" % self.ProcString,
" -FmtStringOffset : 0x%x" % self.FmtStringOffset,
" -pTransferSyntax : 0x%x" % self.pTransferSyntax,
" -nCount : %d" % self.nCount,
" -pSyntaxInfo : 0x%x" % self.pSyntaxInfo
])
def gen_c_struct(self, name, fa, bytes_read = None):
result = ""
stub_desc_pointer = MIDL_STUB_DESC.get_c_instance_pointer(name, self.pStubDesc)
# Proc string
proc_string_pointer, ps_instance = MIDL_SERVER_INFO.generate_proc_string_instance(name, self.ProcString, bytes_read)
result += ps_instance
# transfer syntax
transfer_syntax_object = fa.query_rpc_struct(self.pTransferSyntax)
transfer_syntax_pointer, ts_instance = MIDL_SERVER_INFO.generate_transfer_syntax_instance(name, transfer_syntax_object)
result += ts_instance
# we have no way to know how many proc handlers are defined from the client side,
# so we go overboard
format_string_offset_pointer, fso_instance = MIDL_SERVER_INFO.generate_format_string_offsets_table(name, self.FmtStringOffset, bytes_read/2)
result += fso_instance
interpreter_struct = "\n".join([
"static const MIDL_STUBLESS_PROXY_INFO %s_interpreter_info = {" % (name),
" .pStubDesc = %s," % stub_desc_pointer,
" .FmtStringOffset = %s," % format_string_offset_pointer,
" .ProcString = %s," % proc_string_pointer,
" .pTransferSyntax = %s," % transfer_syntax_pointer,
" .nCount = %d," % self.nCount,
" .pSyntaxInfo = NULL, // FIXME", # %
"};",
"",
""
])
result += interpreter_struct
return result
class RPC_DISPATCH_TABLE(RpcStructure):
_pack_ = POINTER_SIZE
_fields_ = [
('DispatchTableCount', ctypes.c_uint),
('DispatchTable', POINTER),
('Reserved', POINTER),
]
__instance_name__ = "dispatch_table"
def __str__(self):
return "\n".join([
" -DispatchTableCount : %d" % self.DispatchTableCount,
" -DispatchTable : 0x%x" % self.DispatchTable
])
def gen_c_struct(self, name, fa):
result = ""
dispatch_table_functions_pointer = "NULL"
if self.DispatchTableCount:
# Read dispatch table functions names (usually NdrServerCall/NdrClientCall or NdrAsyncServerCall/NdrAsyncClientCall)
rpc_dispatch_functions_ea = [ self.DispatchTable + ph_ea*POINTER_SIZE for ph_ea in range(0, self.DispatchTableCount)]
rpc_dispatch_functions = [idaapi.get_name(READ_PTR_VALUE(ea)) for ea in rpc_dispatch_functions_ea]
rpc_dispatch_functions = "\n ".join(["%s," % fun for fun in rpc_dispatch_functions])
# generate a function pointer table for it
dispatch_table_functions_instance = "\n".join([
"static const RPC_DISPATCH_FUNCTION %s_table[] = {" % RPC_DISPATCH_TABLE.get_c_instance_name(name),
" %s" % rpc_dispatch_functions,
" NULL",
"};",
"",
""
])
dispatch_table_functions_pointer = "&%s_table" % RPC_DISPATCH_TABLE.get_c_instance_name(name)
result += dispatch_table_functions_instance
dispatch_table_instance = "\n".join([
"static const RPC_DISPATCH_TABLE {instance:s} = {{".format(instance = RPC_DISPATCH_TABLE.get_c_instance_name(name)),
" .DispatchTableCount = {count:d},".format(count = self.DispatchTableCount),
" .DispatchTable = (RPC_DISPATCH_FUNCTION*) {dispatch_table_ptr:s}".format(dispatch_table_ptr = dispatch_table_functions_pointer),
"};",
"",
""
])
result += dispatch_table_instance
return result
class MIDL_STUB_DESC(RpcStructure):
_pack_ = POINTER_SIZE
_fields_ = [
('RpcInterfaceInformation', POINTER),
('pfnAllocate', POINTER),
('pfnFree', POINTER),
('pAutoHandle', POINTER), # TODO : correctly implement the union
('apfnNdrRundownRoutines', POINTER), # const NDR_RUNDOWN
('aGenericBindingRoutinePairs', POINTER), # const GENERIC_BINDING_ROUTINE_PAIR
('apfnExprEval', POINTER), # const EXPR_EVAL
('aXmitQuintuple', POINTER), # const XMIT_ROUTINE_QUINTUPLE
('pFormatTypes', POINTER), # unsigned char *
('fCheckBounds', ctypes.c_int),
('Version', ctypes.c_ulong),
('pMallocFreeStruct', POINTER), # MALLOC_FREE_STRUCT
('MIDLVersion', ctypes.c_long),
('CommFaultOffsets', POINTER), # const COMM_FAULT_OFFSETS
('aUserMarshalQuadruple', POINTER), # const USER_MARSHAL_ROUTINE_QUADRUPLE
('NotifyRoutineTable', POINTER), # const NDR_NOTIFY_ROUTINE
('mFlags', POINTER),
('CsRoutineTables', POINTER), # const NDR_CS_ROUTINES
('ProxyServerInfo', POINTER),
('pExprInfo', POINTER), # const NDR_EXPR_DESC
]
__instance_name__ = "stub_desc"
def __str__(self):
return "\n".join([
" -RpcInterfaceInformation : 0x%x" % self.RpcInterfaceInformation,
" -pfnAllocate : 0x%x" % self.pfnAllocate,
" -pfnFree : 0x%x" % self.pfnFree,
" -pFormatTypes : 0x%x" % self.pFormatTypes,
" -Version : 0x%x" % self.Version,
" -MIDLVersion : 0x%x" % self.MIDLVersion,
" -mFlags : 0x%x" % self.mFlags,
" -ProxyServerInfo : 0x%x" % self.ProxyServerInfo,
" -pExprInfo : 0x%x" % self.pExprInfo
])
def gen_c_struct(self, name, fa):
return "\n".join([
"static const MIDL_STUB_DESC %s = {" % MIDL_STUB_DESC.get_c_instance_name(name),
" .RpcInterfaceInformation = {interface:s},".format(interface = RPC_SERVER_INTERFACE.get_c_instance_pointer(name, self.RpcInterfaceInformation)),
" .pfnAllocate = MIDL_user_allocate,",
" .pfnFree = MIDL_user_free,",
" // FIXME",
" .fCheckBounds : %d," % self.fCheckBounds,
" .Version : 0x%x," % self.Version,
" // FIXME",
" .MIDLVersion : 0x%x," % self.MIDLVersion,
" // FIXME",
" .mFlags : 0x%x," % self.mFlags,
" // FIXME",
"};",
"",
""
])
class MIDL_SYNTAX_INFO(RpcStructure):
_pack_ = POINTER_SIZE
_fields_ = [
('TransferSyntax', RPC_SYNTAX_IDENTIFIER),
('DispatchTable', POINTER), # RPC_DISPATCH_TABLE
('ProcString', POINTER),
('FmtStringOffset', POINTER),
('TypeString', POINTER),
('aUserMarshalQuadruple', POINTER),
('pMethodProperties', POINTER), # MIDL_INTERFACE_METHOD_PROPERTIES
('pReserved2', POINTER),
]
__instance_name__ = "syntax_info"
def __str__(self):
return "\n".join([
" -TransferSyntax : %s" % self.TransferSyntax,
" -DispatchTable : 0x%x" % self.DispatchTable,
" -ProcString : 0x%x" % self.ProcString,
" -FmtStringOffset : 0x%x" % self.FmtStringOffset
])
def gen_c_struct(self, name, fa):
result += ""
return "\n".join([
"static const MIDL_SYNTAX_INFO %s = {" % MIDL_SYNTAX_INFO.get_c_instance_name(name),
" .TransferSyntax={syntax:s},".format(syntax = self.TransferSyntax.gen_c_struct()),
"};",
"",
""
])
#################################
## results view
# translation between rpc struct type and it's IDA name
TYPE_RPC_SERVER_INTERFACE = "_RPC_SERVER_INTERFACE"
TYPE_MIDL_STUB_DESC = "_MIDL_STUB_DESC"
TYPE_MIDL_SYNTAX_INFO = "_MIDL_SYNTAX_INFO"
TYPE_MIDL_SERVER_INFO = "_MIDL_SERVER_INFO_"
TYPE_MIDL_STUBLESS_PROXY_INFO = "MIDL_STUBLESS_PROXY_INFO"
TYPE_RPC_SYNTAX_IDENTIFIER = "RPC_SYNTAX_IDENTIFIER"
TYPE_RPC_DISPATCH_TABLE = "RPC_DISPATCH_TABLE"
class CancelTypingForm(Form):
s = """ LOL
Hey, this guy wants to cancel its changes.
'Might as well ask for an "undo" button in IDA !
(This joke got stale with IDA 7.3 -_-)
"""
def __init__(self):
Form.__init__(self, CancelTypingForm.s ,{})
class RpcResultsModel(QtCore.QAbstractTableModel):
COL_SYNTAX_GUID = 0x00
COL_RPC_TYPE = 0x01
COL_ADDRESS = 0x02
COL_DESCRIPTION = 0x03
COL_EMPTY = 0x04
SAMPLE_CONTENTS = [
'XXXXXXXX-YYYY-ZZZZ-TTTTTTTTTT',
'MIDL_STUBLESS_PROXY_INFO',
'0xcafebabe',
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
]
def __init__(self, rpc_endpoints, parent=None):
super(RpcResultsModel, self).__init__(parent)
#----------------------------------------------------------------------
# Headers
#----------------------------------------------------------------------
self._column_headers = {
RpcResultsModel.COL_SYNTAX_GUID : 'GUID',
RpcResultsModel.COL_RPC_TYPE : 'Object type',
RpcResultsModel.COL_ADDRESS : 'Address',
RpcResultsModel.COL_DESCRIPTION : 'Description'
}
#----------------------------------------------------------------------
# UI
#----------------------------------------------------------------------
self._font = QtGui.QFont("Monospace")
self._font.setStyleHint(QtGui.QFont.TypeWriter)
#----------------------------------------------------------------------
# Data store
#----------------------------------------------------------------------
self._results = list(rpc_endpoints)
self._row_count = len(self._results)
def flags(self, index):
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def rowCount(self, index=QtCore.QModelIndex()):
"""
The number of table rows.
"""
return self._row_count
def columnCount(self, index=QtCore.QModelIndex()):
"""
The number of table columns.
"""
return len(self._column_headers)
def headerData(self, column, orientation, role=QtCore.Qt.DisplayRole):
"""
Define the properties of the the table rows & columns.
"""
if orientation == QtCore.Qt.Horizontal:
# the title of the header columns has been requested
if role == QtCore.Qt.DisplayRole:
try:
return self._column_headers[column]
except KeyError as e:
pass
# the text alignment of the header has beeen requested
elif role == QtCore.Qt.TextAlignmentRole:
# center align all columns
return QtCore.Qt.AlignHCenter
# unhandled header request
return None
def data(self, index, role=QtCore.Qt.DisplayRole):
"""
Define how Qt should access the underlying model data.
"""
# data display request
if role == QtCore.Qt.DisplayRole:
# grab for speed
row = index.row()
column = index.column()
if column == RpcResultsModel.COL_SYNTAX_GUID:
return str(self._results[row].IID.get_syntax_guid())
elif column == RpcResultsModel.COL_RPC_TYPE:
return self._results[row].type
elif column == RpcResultsModel.COL_ADDRESS:
return "0x%x" % self._results[row].address
elif column == RpcResultsModel.COL_DESCRIPTION:
return str(self._results[row])
# font color request
elif role == QtCore.Qt.ForegroundRole:
return QtGui.QColor(QtCore.Qt.black)
# font format request
elif role == QtCore.Qt.FontRole:
return self._font
# text alignment request
elif role == QtCore.Qt.TextAlignmentRole:
column = index.column()
return (
QtCore.Qt.AlignLeft,
QtCore.Qt.AlignLeft,
QtCore.Qt.AlignHCenter,
QtCore.Qt.AlignLeft
)[column]
# unhandeled request, nothing to do
return None
class RpcResultsForm( idaapi.PluginForm ):
def __init__(self, _rpc_endpoints):
super(RpcResultsForm, self).__init__()
self._rpc_endpoints = _rpc_endpoints
def OnCreate(self, form):
"""
Initialize the custom PyQt5 content on form creation.
"""
# Get parent widget
self._widget = self.FormToPyQtWidget(form)
self._init_ui()
def show(self):
"""
Make the created form visible as a tabbed view.
"""
flags = idaapi.PluginForm.WOPN_TAB | idaapi.PluginForm.WOPN_PERSIST
return idaapi.PluginForm.Show(self, "detected rpc strcutures", flags)
def _init_ui(self):
self._font = QtGui.QFont("Monospace")
self._font.setStyleHint(QtGui.QFont.TypeWriter)
self._font_metrics = QtGui.QFontMetricsF(self._font)
self._model = RpcResultsModel(self._rpc_endpoints, self._widget)
self._table = QtWidgets.QTableView()
self._table.setStyleSheet(
"QTableView { gridline-color: white; background-color: white } " +
"QTableView::item:selected { color: grey; background-color: lightblue; } "
)
# set these properties so the user can arbitrarily shrink the table
self._table.setMinimumHeight(0)
self._table.setSizePolicy(
QtWidgets.QSizePolicy.Ignored,
QtWidgets.QSizePolicy.Ignored
)
self._table.setModel(self._model)
# jump to disassembly on table row double click
self._table.doubleClicked.connect(self._ui_entry_double_click)
# right click popup menu
self._table.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self._table.customContextMenuRequested.connect(self._ui_ctx_menu_handler)
self._action_apply_type = QtWidgets.QAction("Apply type", None)
self._action_clear_type = QtWidgets.QAction("Clear applied type", None)
self._action_rename_struct = QtWidgets.QAction("Renamed applied type", None)
self._action_rename_proc_handlers = QtWidgets.QAction("Renamed proc handlers", None)
# set the initial column widths for the table
self._guess_column_width()
# table selection should be by row, not by cell
self._table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
# more code-friendly, readable aliases
vh = self._table.verticalHeader()
hh = self._table.horizontalHeader()
vh.setSectionResizeMode(QtWidgets.QHeaderView.Fixed)
# hide the vertical header themselves as we don't need them
vh.hide()
# stretch the last column (which is blank)
hh.setStretchLastSection(True)
# Allow multiline cells
self._table.setWordWrap(True)
self._table.setTextElideMode(QtCore.Qt.ElideMiddle);
self._table.resizeColumnsToContents()
self._table.resizeRowsToContents()
layout = QtWidgets.QGridLayout()
layout.addWidget(self._table)
self._widget.setLayout(layout)
def _guess_column_width(self):
"""
Initial column redimensionning based on "hints" (sample values)
"""
for i in range(len(self._model.__class__.SAMPLE_CONTENTS)):
sample_width = self._font_metrics.boundingRect(self._model.__class__.SAMPLE_CONTENTS[i]).width()
header_width = self._font_metrics.boundingRect(self._model._column_headers[i]).width()
self._table.setColumnWidth(i, max(header_width, sample_width))
def _ui_entry_double_click(self, index):
"""
Handle double click event on the coverage table.
A double click on the coverage table view will jump the user to
the corresponding function in the IDA disassembly view.
"""
idaapi.jumpto(self._model._results[index.row()].address)
def _ui_ctx_menu_handler(self, position):
"""
Handle right click context menu event on the coverage table.
"""
# create a right click menu based on the state and context
ctx_menu = self._populate_ctx_menu()
if not ctx_menu:
return
# show the popup menu to the user, and wait for their selection
action = ctx_menu.exec_(self._table.viewport().mapToGlobal(position))
# process the user action
self._process_ctx_menu_action(action)
def _populate_ctx_menu(self):
"""
Populate a context menu for the table view based on selection.
Returns a populated QMenu, or None.
"""
# get the list rows currently selected in the coverage table
selected_rows = self._table.selectionModel().selectedRows()
if len(selected_rows) == 0:
return None
# the context menu we will dynamically populate
ctx_menu = QtWidgets.QMenu()
ctx_menu.addAction(self._action_apply_type)
ctx_menu.addAction(self._action_clear_type)
ctx_menu.addSeparator()
ctx_menu.addAction(self._action_rename_struct)
if (len(selected_rows) == 1):
item = self._model._results[selected_rows[0].row()]
if item.IID.get_proc_handlers():
ctx_menu.addSeparator()
ctx_menu.addAction(self._action_rename_proc_handlers)
# return the completed context menu
return ctx_menu
def _process_ctx_menu_action(self, action):
"""
Process the given (user selected) context menu action.
"""
# a right click menu action was not clicked. nothing else to do
if not action:
return
# get the list rows currently selected in the coverage table
selected_rows = self._table.selectionModel().selectedRows()
if len(selected_rows) == 0:
return
for row in selected_rows:
row_n = row.row()
result = self._model._results[row_n]
if action == self._action_apply_type:
success = idc.create_struct(result.address, -1, result.type)
print("[findrpc] Applying type %s at address 0x%x : %s" % (result.type, result.address, ("KO", "OK")[success]))
if not success:
warning("Could not apply type via idapython. Do it by hand instead (Alt+Q > %s)" % result.type)
# handle the 'Copy name' action
elif action == self._action_clear_type:
#logging.debug("Clearing applied types to selected lines to item %d" % row_n)
f = CancelTypingForm()
f, args = f.Compile()
ok = f.Execute()
elif action == self._action_rename_struct:
chosen_name = "_findrpc_{iid:s}_{type:s}".format(
iid = str(result.IID.interface.object.InterfaceId.SyntaxGUID).replace('-', '_'),
type = str(result.type).lower()
)
print("[findrpc] renaming address 0x%x to %s" % (result.address, chosen_name))
idc.MakeName(result.address, chosen_name)