-
Notifications
You must be signed in to change notification settings - Fork 1
/
sigmaker.py
724 lines (598 loc) · 23.9 KB
/
sigmaker.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
import ctypes
import ctypes.wintypes as w
import enum
import re
import ida_bytes
import ida_ida
import ida_idaapi
import ida_kernwin
import idaapi
import idc
SIGNATURE_REGEX = re.compile(r"\\x[0-9A-F]{2}")
SIGNATURE_REGEX_2 = re.compile(r"((?:0x[0-9A-F]{2})+)")
PLUGIN_NAME = "Signature Maker Python"
PLUGIN_VERSION = "1.0.3"
# Signature types and structures
class SignatureType(enum.Enum):
IDA = 0
x64Dbg = 1
Signature_Mask = 2
SignatureByteArray_Bitmask = 3
class SignatureByte:
def __init__(self, value, isWildcard):
self.value = value
self.isWildcard = isWildcard
Signature = list[SignatureByte]
# Output functions
def BuildIDASignatureString(signature: Signature, doubleQM: bool = False) -> str:
result = []
# Build hex pattern
for byte in signature:
if byte.isWildcard:
result.append("??" if doubleQM else "?")
else:
result.append(f"{byte.value:02X}")
result.append(" ")
str_result = "".join(result).rstrip()
return str_result
def BuildByteArrayWithMaskSignatureString(signature: Signature) -> str:
pattern = []
mask = []
# Build hex pattern
for byte in signature:
pattern.append(f"\\x{byte.value:02X}" if not byte.isWildcard else "\\x00")
mask.append("x" if not byte.isWildcard else "?")
return "".join(pattern) + " " + "".join(mask)
def BuildBytesWithBitmaskSignatureString(signature: Signature) -> str:
pattern = []
mask = []
# Build hex pattern
for byte in signature:
pattern.append(f"0x{byte.value:02X}, " if not byte.isWildcard else "0x00, ")
mask.append("1" if not byte.isWildcard else "0")
pattern_str = "".join(pattern).rstrip(", ")
mask_str = "".join(mask)[::-1] # Reverse bitmask
return pattern_str + " 0b" + mask_str
def FormatSignature(signature: Signature, sig_type: SignatureType) -> str:
if sig_type == SignatureType.IDA:
return BuildIDASignatureString(signature)
elif sig_type == SignatureType.x64Dbg:
return BuildIDASignatureString(signature, True)
elif sig_type == SignatureType.Signature_Mask:
return BuildByteArrayWithMaskSignatureString(signature)
elif sig_type == SignatureType.SignatureByteArray_Bitmask:
return BuildBytesWithBitmaskSignatureString(signature)
return ""
# Utility functions
def AddByteToSignature(signature: Signature, address, wildcard: bool):
byte = SignatureByte(ida_bytes.get_byte(address), wildcard)
signature.append(byte)
def AddBytesToSignature(signature: Signature, address, count: int, wildcard: bool):
for i in range(count):
AddByteToSignature(signature, address + i, wildcard)
def TrimSignature(signature: Signature):
while signature and signature[-1].isWildcard:
signature.pop()
def SetClipboardText(text: str) -> bool:
GMEM_MOVEABLE = 0x0002
GMEM_ZEROINIT = 0x0040
CF_TEXT = 1
u32 = ctypes.WinDLL("user32")
k32 = ctypes.WinDLL("kernel32")
GlobalAlloc = k32.GlobalAlloc
GlobalAlloc.argtypes = w.UINT, w.UINT
GlobalAlloc.restype = w.HGLOBAL
GlobalFree = k32.GlobalFree
GlobalFree.argtypes = (w.HGLOBAL,)
GlobalFree.restype = w.HGLOBAL
SetClipboardData = u32.SetClipboardData
SetClipboardData.argtypes = w.UINT, w.HANDLE
SetClipboardData.restype = w.HANDLE
EmptyClipboard = u32.EmptyClipboard
OpenClipboard = u32.OpenClipboard
OpenClipboard.argtypes = (w.HWND,)
OpenClipboard.restype = w.BOOL
GlobalLock = k32.GlobalLock
GlobalLock.argtypes = (w.HGLOBAL,)
GlobalLock.restype = w.LPVOID
GlobalUnlock = k32.GlobalUnlock
GlobalUnlock.argtypes = (w.HGLOBAL,)
GlobalUnlock.restype = w.BOOL
GetClipboardData = u32.GetClipboardData
GetClipboardData.argtypes = (w.UINT,)
GetClipboardData.restype = w.HANDLE
CloseClipboard = u32.CloseClipboard
CloseClipboard.argtypes = None
CloseClipboard.restype = w.BOOL
if not text:
return False
if not OpenClipboard(None) or not EmptyClipboard():
return False
try:
# Allocate global memory
h_mem = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(text) + 1)
if not h_mem:
return False
# Lock the handle and copy the text
lp_str = GlobalLock(h_mem)
if not lp_str:
GlobalFree(h_mem)
return False
ctypes.memmove(lp_str, text.encode("utf-8"), len(text))
GlobalUnlock(h_mem)
# Set the clipboard data
if not SetClipboardData(CF_TEXT, h_mem):
GlobalFree(h_mem)
return False
except Exception as e:
print(f"Failed to set clipboard text: {e}")
return False
finally:
CloseClipboard()
return True
def GetRegexMatches(string: str, regex: re.Pattern, matches: list[str]) -> bool:
matches.clear()
matches.extend(re.findall(regex, string))
return bool(matches)
class Unexpected(Exception):
pass
class SignatureMakerForm(ida_kernwin.Form):
FormChangeCb: ida_kernwin.Form.FormChangeCb
rAction: ida_kernwin.Form.RadGroupControl
rOutputFormat: ida_kernwin.Form.RadGroupControl
cGroupOptions: ida_kernwin.Form.ChkGroupControl
def __init__(self):
form = f"""\
BUTTON YES* OK
BUTTON CANCEL Cancel
{PLUGIN_NAME} v{PLUGIN_VERSION}
{{FormChangeCb}}
Select action:
<Create unique Signature for current code address:{{rCreateUniqueSig}}>
<Find shortest XREF Signature for current data or code address:{{rFindXRefSig}}>
<Copy selected code:{{rCopyCode}}>
<Search for a signature:{{rSearchSignature}}>{{rAction}}>
Output format:
<IDA Signature:{{rIDASig}}>
<x64Dbg Signature:{{rx64DbgSig}}>
<C Byte Array Signature + String mask:{{rByteArrayMaskSig}}>
<C Raw Bytes Signature + Bitmask:{{rRawBytesBitmaskSig}}>{{rOutputFormat}}>
Options:
<Wildcards for operands:{{cWildcardOperands}}>
<Continue when leaving function scope:{{cContinueOutside}}>{{cGroupOptions}}>
"""
controls = {
"FormChangeCb": ida_kernwin.Form.FormChangeCb(self.OnFormChange),
"rAction": ida_kernwin.Form.RadGroupControl(
(
"rCreateUniqueSig",
"rFindXRefSig",
"rCopyCode",
"rSearchSignature",
)
),
"rOutputFormat": ida_kernwin.Form.RadGroupControl(
(
"rIDASig",
"rx64DbgSig",
"rByteArrayMaskSig",
"rRawBytesBitmaskSig",
)
),
"cGroupOptions": ida_kernwin.Form.ChkGroupControl(
("cWildcardOperands", "cContinueOutside")
),
}
super().__init__(form, controls)
def OnFormChange(self, fid):
# Debug output for when the form changes
# print(f"Form changed, fid: {fid}", self.rAction.id, self.rOutputFormat.id, self.cGroupOptions.id)
if fid == self.rAction.id:
print(
f"Action [{fid}] rAction changed: {self.GetControlValue(self.rAction):06x}"
)
elif fid == self.rOutputFormat.id:
print(
f"Action [{fid}] rOutputFormat changed: {self.GetControlValue(self.rOutputFormat):06x}"
)
elif fid == self.cGroupOptions.id:
print(
f"Action [{fid}] cGroupOptions changed: {self.GetControlValue(self.cGroupOptions):06x}"
)
else:
print(">>fid:%d" % fid)
return 1
# Plugin specific definitions
class PySigMaker(ida_idaapi.plugin_t):
IS_ARM = False
def run(self, arg):
self.run_plugin()
def run_plugin(self):
# Check what processor we have
PySigMaker.IS_ARM = self.IsARM()
form = SignatureMakerForm()
form.Compile()
# Execute the form and get results
ok = form.Execute()
if ok:
action = form.rAction.value
output_format = form.rOutputFormat.value
wildcard_operands = form.cGroupOptions.value & 1
continue_outside_of_function = form.cGroupOptions.value & 2
# Don't forget to free the form after execution
form.Free()
sig_type = SignatureType(output_format)
if action == 0:
# Find unique signature for current address
ea = idc.get_screen_ea()
idaapi.show_wait_box("Generating signature...")
signatures = self.GenerateUniqueSignatureForEA(
ea, wildcard_operands, continue_outside_of_function
)
self.PrintSignatureForEA(signatures, ea, sig_type)
idaapi.hide_wait_box()
elif action == 1:
# Find XREFs for current selection, generate signatures up to 250 bytes length
ea = idc.get_screen_ea()
xref_signatures = []
idaapi.show_wait_box(
"Finding references and generating signatures. This can take a while..."
)
self.FindXRefs(
ea,
wildcard_operands,
continue_outside_of_function,
xref_signatures,
250,
)
# Print top 5 shortest signatures
self.PrintXRefSignaturesForEA(ea, xref_signatures, sig_type, 5)
idaapi.hide_wait_box()
elif action == 2:
# Print selected code as signature
start, end = ida_kernwin.read_range_selection(idaapi.get_current_viewer())
if start and end:
idaapi.show_wait_box("Please stand by...")
self.PrintSelectedCode(start, end, sig_type, wildcard_operands)
idaapi.hide_wait_box()
else:
idc.msg("Select a range to copy the code\n")
elif action == 3:
# Search for a signature
input_signature = idaapi.ask_str("", idaapi.HIST_SRCH, "Enter a signature")
if input_signature:
idaapi.show_wait_box("Searching...")
self.SearchSignatureString(input_signature)
idaapi.hide_wait_box()
def IsARM(self) -> bool:
return "ARM" in ida_idaapi.get_inf_structure().procname
def GetOperandOffsetARM(self, instruction, operand_offset, operand_length):
for op in instruction.ops:
if op.type in {
idaapi.o_mem,
idaapi.o_far,
idaapi.o_near,
idaapi.o_phrase,
idaapi.o_displ,
idaapi.o_imm,
}:
operand_offset[0] = op.offb
operand_length[0] = (
3 if instruction.size == 4 else 7 if instruction.size == 8 else 0
)
return True
return False
def GetOperand(self, instruction, operand_offset, operand_length):
if self.IS_ARM:
return self.GetOperandOffsetARM(instruction, operand_offset, operand_length)
for op in instruction.ops:
if op.type != idaapi.o_void and op.offb != 0:
operand_offset[0] = op.offb
operand_length[0] = instruction.size - op.offb
return True
return False
def FindSignatureOccurences(self, ida_signature: str) -> list:
binary_pattern = idaapi.compiled_binpat_vec_t()
idaapi.parse_binpat_str(
binary_pattern, ida_ida.cvar.inf.min_ea, ida_signature, 16
)
results = []
ea = ida_ida.cvar.inf.min_ea
while True:
occurence = ida_bytes.bin_search(
ea,
ida_ida.cvar.inf.max_ea,
binary_pattern,
ida_bytes.BIN_SEARCH_NOCASE | ida_bytes.BIN_SEARCH_FORWARD,
)
if occurence == idaapi.BADADDR:
return results
results.append(occurence)
ea = occurence + 1
def IsSignatureUnique(self, ida_signature: str) -> bool:
return len(self.FindSignatureOccurences(ida_signature)) == 1
def GenerateUniqueSignatureForEA(
self,
ea,
wildcard_operands,
continue_outside_of_function,
max_signature_length=1000,
ask_longer_signature=True,
):
if ea == idaapi.BADADDR:
raise Unexpected("Invalid address")
if not idaapi.is_code(ida_bytes.get_flags(ea)):
raise Unexpected("Cannot create code signature for data")
signature = []
sig_part_length = 0
current_function = idaapi.get_func(ea)
current_address = ea
while True:
if idaapi.user_cancelled():
raise Unexpected("Aborted")
instruction = idaapi.insn_t()
current_instruction_length = idaapi.decode_insn(
instruction, current_address
)
if current_instruction_length <= 0:
if not signature:
raise Unexpected("Failed to decode first instruction")
idc.msg(
f"Signature reached end of executable code @ {current_address:X}\n"
)
signature_string = BuildIDASignatureString(signature)
idc.msg(f"NOT UNIQUE Signature for {ea:X}: {signature_string}\n")
raise Unexpected("Signature not unique")
if sig_part_length > max_signature_length:
if ask_longer_signature:
result = idaapi.ask_yn(
idaapi.ASKBTN_YES,
f"Signature is already at {len(signature)} bytes. Continue?",
)
if result == 1: # Yes
sig_part_length = 0
elif result == 0: # No
signature_string = BuildIDASignatureString(signature)
idc.msg(
f"NOT UNIQUE Signature for {ea:X}: {signature_string}\n"
)
raise Unexpected("Signature not unique")
else: # Cancel
raise Unexpected("Aborted")
else:
raise Unexpected("Signature exceeded maximum length")
sig_part_length += current_instruction_length
operand_offset = [0]
operand_length = [0]
if (
wildcard_operands
and self.GetOperand(instruction, operand_offset, operand_length)
and operand_length[0] > 0
):
AddBytesToSignature(
signature, current_address, operand_offset[0], False
)
AddBytesToSignature(
signature,
current_address + operand_offset[0],
operand_length[0],
True,
)
if operand_offset[0] == 0:
AddBytesToSignature(
signature,
current_address + operand_length[0],
current_instruction_length - operand_length[0],
False,
)
else:
AddBytesToSignature(
signature, current_address, current_instruction_length, False
)
current_sig = BuildIDASignatureString(signature)
if self.IsSignatureUnique(current_sig):
TrimSignature(signature)
return signature
current_address += current_instruction_length
if (
not continue_outside_of_function
and current_function
and idaapi.get_func(current_address) != current_function
):
raise Unexpected("Signature left function scope")
raise Unexpected("Unknown")
def GenerateSignatureForEARange(self, ea_start, ea_end, wildcard_operands):
if ea_start == idaapi.BADADDR or ea_end == idaapi.BADADDR:
raise Unexpected("Invalid address")
signature = []
sig_part_length = 0
if not idaapi.is_code(ida_bytes.get_flags(ea_start)):
AddBytesToSignature(signature, ea_start, ea_end - ea_start, False)
return signature
current_address = ea_start
while True:
if idaapi.user_cancelled():
raise Unexpected("Aborted")
instruction = idaapi.insn_t()
current_instruction_length = idaapi.decode_insn(
instruction, current_address
)
if current_instruction_length <= 0:
if not signature:
raise Unexpected("Failed to decode first instruction")
idc.msg(
f"Signature reached end of executable code @ {current_address:X}\n"
)
if current_address < ea_end:
AddBytesToSignature(
signature, current_address, ea_end - current_address, False
)
TrimSignature(signature)
return signature
sig_part_length += current_instruction_length
operand_offset = [0]
operand_length = [0]
if (
wildcard_operands
and self.GetOperand(instruction, operand_offset, operand_length)
and operand_length[0] > 0
):
AddBytesToSignature(
signature, current_address, operand_offset[0], False
)
AddBytesToSignature(
signature,
current_address + operand_offset[0],
operand_length[0],
True,
)
if operand_offset[0] == 0:
AddBytesToSignature(
signature,
current_address + operand_length[0],
current_instruction_length - operand_length[0],
False,
)
else:
AddBytesToSignature(
signature, current_address, current_instruction_length, False
)
current_address += current_instruction_length
if current_address >= ea_end:
TrimSignature(signature)
return signature
raise Unexpected("Unknown")
def PrintSignatureForEA(self, signature, ea, sig_type):
if not signature:
idc.msg(f"Error: {signature}\n")
return
signature_str = FormatSignature(signature, sig_type)
idc.msg(f"Signature for {ea:X}: {signature_str}\n")
if not SetClipboardText(signature_str):
idc.msg("Failed to copy to clipboard!")
def FindXRefs(
self,
ea,
wildcard_operands,
continue_outside_of_function,
xref_signatures,
max_signature_length,
):
xref = idaapi.xrefblk_t()
xref_count = 0
for xref_ok in iter(lambda: xref.first_to(ea, idaapi.XREF_FAR), False):
if not idaapi.is_code(ida_bytes.get_flags(xref.frm)):
continue
xref_count += 1
shortest_signature_length = max_signature_length + 1
for i, xref_ok in enumerate(
iter(lambda: xref.first_to(ea, idaapi.XREF_FAR), False)
):
if idaapi.user_cancelled():
break
if not idaapi.is_code(ida_bytes.get_flags(xref.frm)):
continue
idaapi.replace_wait_box(
f"Processing xref {i + 1} of {xref_count} ({(i / xref_count) * 100.0:.1f}%)...\n\nSuitable Signatures: {len(xref_signatures)}\nShortest Signature: {shortest_signature_length if shortest_signature_length <= max_signature_length else 0} Bytes"
)
signature = self.GenerateUniqueSignatureForEA(
xref.frm,
wildcard_operands,
continue_outside_of_function,
max_signature_length,
False,
)
if not signature:
continue
if len(signature) < shortest_signature_length:
shortest_signature_length = len(signature)
xref_signatures.append((xref.frm, signature))
xref_signatures.sort(key=lambda x: len(x[1]))
def PrintXRefSignaturesForEA(self, ea, xref_signatures, sig_type, top_count):
if not xref_signatures:
idc.msg("No XREFs have been found for your address\n")
return
top_length = min(top_count, len(xref_signatures))
idc.msg(
f"Top {top_length} Signatures out of {len(xref_signatures)} xrefs for {ea:X}:\n"
)
for i in range(top_length):
origin_address, signature = xref_signatures[i]
signature_str = FormatSignature(signature, sig_type)
idc.msg(f"XREF Signature #{i + 1} @ {origin_address:X}: {signature_str}\n")
if i == 0:
SetClipboardText(signature_str)
def PrintSelectedCode(self, start, end, sig_type, wildcard_operands):
selection_size = end - start
assert selection_size > 0
signature = self.GenerateSignatureForEARange(start, end, wildcard_operands)
if not signature:
idc.msg(f"Error: {signature}\n")
return
signature_str = FormatSignature(signature, sig_type)
idc.msg(f"Code for {start:X}-{end:X}: {signature_str}\n")
SetClipboardText(signature_str)
def SearchSignatureString(self, input):
converted_signature_string = ""
string_mask = ""
match = re.search(r"x[x?]+", input)
if match:
string_mask = match.group(0)
else:
match = re.search(r"0b[0,1]+", input)
if match:
bits = match.group(0)[2:]
reversed_bits = bits[::-1]
string_mask = "".join("x" if b == "1" else "?" for b in reversed_bits)
if string_mask:
raw_byte_strings = []
if GetRegexMatches(input, SIGNATURE_REGEX, raw_byte_strings) and len(
raw_byte_strings
) == len(string_mask):
converted_signature = []
for i, m in enumerate(raw_byte_strings):
b = SignatureByte(int(m[2:], 16), string_mask[i] == "?")
converted_signature.append(b)
converted_signature_string = BuildIDASignatureString(
converted_signature
)
elif GetRegexMatches(input, SIGNATURE_REGEX_2, raw_byte_strings) and len(
raw_byte_strings
) == len(string_mask):
converted_signature = []
for i, m in enumerate(raw_byte_strings):
b = SignatureByte(int(m[2:], 16), string_mask[i] == "?")
converted_signature.append(b)
converted_signature_string = BuildIDASignatureString(
converted_signature
)
else:
idc.msg(
f'Detected mask "{string_mask}" but failed to match corresponding bytes\n'
)
else:
input = re.sub(r"[)(\[\]]+", "", input)
input = re.sub(r"^\s+", "", input)
input = re.sub(r"[? ]+$", "", input) + " "
input = re.sub(r"\\?\\x", "", input) # Simplify hex pattern matching
input = re.sub(r"\s+", " ", input) # Normalize spaces
converted_signature_string = input
if not converted_signature_string:
idc.msg("Unrecognized signature type\n")
return
idc.msg(f"Signature: {converted_signature_string}\n")
signature_matches = self.FindSignatureOccurences(converted_signature_string)
if not signature_matches:
idc.msg("Signature does not match!\n")
return
for ea in signature_matches:
idc.msg(f"Match @ {ea:X}\n")
# Register the plugin
def PLUGIN_ENTRY():
return PySigMaker()
# PySigMaker().run(None)
# form = SignatureMakerForm()
# form.Compile()
# # Execute the form and get results
# ok = form.Execute()
# form.Free()