-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcommunity_base.py
5266 lines (4449 loc) · 293 KB
/
community_base.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 -*-
r''' This text is easier to read when the markdown is parsed: <https://github.com/Harding-Stardust/community_base/blob/main/README.md>
# Summary
This Python script will help you develop scripts for [Hexrays IDA Pro](https://hex-rays.com/ida-pro)
community_base turns IDA Python into a [DWIM (Do What I Mean)](https://en.wikipedia.org/wiki/DWIM) style and I try to follow ["Principle of least astonishment"](https://en.wikipedia.org/wiki/Principle_of_least_astonishment)
You can think of this script as padding between the user created scripts and the IDA Python API.
If you develop scripts with this script as base, then if (when) Hexrays change something in their API, instead of fixing EVERY script out there
the community can fix this script and all the user created scripts (that depends on this script) will work again.
I try to have a low cognitive load. "What matters is the amount of confusion developers feel when going through the code." Quote from <https://minds.md/zakirullin/cognitive>
# Why you should use this script
- Easier to write plugins and scripts for IDA Python
- Type hints on everything!
- Strong typing. I use [Pydantic](https://docs.pydantic.dev/latest/) to force types. This makes the code much easier to read since you get an idea what a function expects and what it returns. I try to follow [PEP 484](https://peps.python.org/pep-0484/) as much as I can.
- Full function/variable names. This makes variables and functions easy to read at a glance.
- Properly documented. I try to document as extensive I can without making redundent comments.
- Easy to debug (hopefully!). All functions that are non-trivial have the last argument named ```arg_debug``` which is a bool that if set, prints out helpful information on what is happening in the code.
- Good default values set. E.g. ```ida_idp.assemble(ea, 0, ea, True, 'mov eax, 1')``` have many arguments you don't know that they should be.
- Understands what the user wants. I have type checks and treat input different depending on what you send in. E.g. addresses vs labels. In my script, everywhere you are expecting an address, you can send in a label (or register) that is then resolved. See ```address()``` and ```eval_expression()``` (same with where tinfo_t (type info) is expected, you can also send in a C-type string)
- I have written the code as easy I can to READ (hopefully), it might not be the most Pythonic way (or the fastest) but I have focused on readability. However, I do understand that this is subjective.
- Do _NOT_ conflict with other plugins. I am very careful to only overwrite things like docstrings, otherwise I add to the classes that are already in the IDA Python
- I have wrappers around some of IDAs Python APIs that actually honors the type hints they have written. You can find them with this simple code:
```python
[wrapper for wrapper in dir(community_base) if wrapper.startswith("_idaapi_")]
```
- Cancel scripts that take too long. You can copy the the string "abort.ida" into the clipboard and within 30 seconds, the script will stop. Check out ```_check_if_long_running_script_should_abort()``` for implementation
- Easy bug reporting. See the function ```bug_report()```
- Get some good links to helpful resources. See the function ```links()```
- when developing, it's nice to have a fast and easy way to reload the script and all it's dependencies, see the function ```reload_module()```
- Load shellcode into the running process. See ```load_file_into_memory()``` using [AppCall](https://www.youtube.com/watch?v=GZUHXkV0vdM)
- Help with [AppCall](https://www.youtube.com/watch?v=GZUHXkV0vdM) to call functions that are inside the executable. (Think of decrypt functions) E.g. ```win_LoadLibraryA()```
- Simple and fast way to get info about APIs, see ```google()```
- 3 new hotkeys:
- - w --> marked bytes will be dumped to disk
- - alt + Ins --> Copy current address into clipboard (same as [x64dbg](https://x64dbg.com/))
- - shift + c --> Copy selected bytes into clipboard as hex text (same as [x64dbg](https://x64dbg.com/))
- Much more that I can't think of right now as I need to publish this script before new years eve!
# Installation
To use this script, put is somewhere that IDA can find it. A good place is this filename:
```python
import idaapi
print(idaapi.__file__.replace("idaapi.py", "community_base.py"))
```
It is strongly advised to edit your idapythonrc.py which can be found by typing the following in IDA:
```python
import idaapi
import os
print(os.path.join(idaapi.get_user_idadir(), "idapythonrc.py"))
```
and to get easy access to this script, add the line:
```python
import community_base as cb
```
Read more: <https://hex-rays.com/blog/igors-tip-of-the-week-33-idas-user-directory-idausr>
# Tested with
```Windows 10 + IDA 9.0 + Python 3.12``` and ```Windows 10 + IDA 8.4 + Python 3.8```
# Future
- I have not had the time to polish everything as much as I would have liked. Keep an eye on this repo and things will get updated!
- I'm planning on doing some short clips on how the script is supposed to be used, this takes time and video editing is not my strong side
- Need help with more testing
- More of everything :-D
'''
__version__ = "2025-02-18 23:02:01"
__author__ = "Harding (https://github.com/Harding-Stardust)"
__description__ = __doc__
__copyright__ = "Copyright 2025"
__credits__ = ["https://www.youtube.com/@allthingsida",
"https://github.com/grayhatacademy/ida/blob/master/plugins/shims/ida_shims.py",
"https://github.com/arizvisa/ida-minsc",
"https://github.com/Shizmob/ida-tools",
"https://github.com/synacktiv/bip/",
"https://github.com/tmr232/Sark"]
__license__ = "GPL 3.0"
__maintainer__ = "Harding (https://github.com/Harding-Stardust)"
__email__ = "[email protected]"
__status__ = "Development"
__url__ = "https://github.com/Harding-Stardust/community_base"
import os # https://peps.python.org/pep-0008/#imports
import sys
import re
import time
import datetime
import ctypes
import json # TODO: Change to json5?
from typing import Union, List, Dict, Tuple, Any, Optional, Callable
from types import ModuleType
import inspect as _inspect
from pydantic import validate_call # pip install pydantic
try:
import chardet
except ImportError:
print(f"{__file__}: Missing import chardet, this module is used to guess string encoding. It's nice to have, not need to have. pip install chardet")
import ida_allins as _ida_allins # type: ignore[import-untyped]
import ida_auto as _ida_auto # type: ignore[import-untyped]
import ida_bytes as _ida_bytes # type: ignore[import-untyped]
import ida_dbg as _ida_dbg # type: ignore[import-untyped]
import ida_funcs as _ida_funcs # type: ignore[import-untyped]
import ida_hexrays as _ida_hexrays # type: ignore[import-untyped]
import ida_idaapi as _ida_idaapi # type: ignore[import-untyped]
import ida_ida as _ida_ida # type: ignore[import-untyped]
import ida_idc as _ida_idc # type: ignore[import-untyped]
import ida_idd as _ida_idd # type: ignore[import-untyped] # The interface consists of structures describing the target debugged processor and a debugging API. https://python.docs.hex-rays.com/namespaceida__idd.html
import ida_idp as _ida_idp # type: ignore[import-untyped] # The interface consists of two structures: definition of target assembler: ::ash and definition of current processor: ::ph. These structures contain information about target processor and assembler features.
import ida_kernwin as _ida_kernwin # type: ignore[import-untyped]
import ida_lines as _ida_lines # type: ignore[import-untyped]
import ida_loader as _ida_loader # type: ignore[import-untyped]
import ida_name as _ida_name # type: ignore[import-untyped]
import ida_nalt as _ida_nalt # type: ignore[import-untyped] # Definitions of various information kept in netnodes. Each address in the program has a corresponding netnode: netnode(ea).
import ida_netnode as _ida_netnode # type: ignore[import-untyped] # Functions that provide the lowest level public interface to the database.
import ida_pro as _ida_pro # type: ignore[import-untyped]
import ida_range as _ida_range # type: ignore[import-untyped]
import ida_search as _ida_search # type: ignore[import-untyped]
import ida_segment as _ida_segment # type: ignore[import-untyped]
import idc as _idc # type: ignore[import-untyped]
import ida_typeinf as _ida_typeinf # type: ignore[import-untyped]
import ida_ua as _ida_ua # type: ignore[import-untyped] # ua stands for UnAssembly (I think...) Functions that deal with the disassembling of program instructions. https://python.docs.hex-rays.com/namespaceida__ua.html
import ida_xref as _ida_xref # type: ignore[import-untyped]
import idautils as _idautils # type: ignore[import-untyped]
import ida_diskio as _ida_diskio # type: ignore[import-untyped]
import PyQt5 # type: ignore[import-untyped]
from PyQt5.Qt import QApplication # type: ignore[import-untyped]
from PyQt5.QtWidgets import QWidget # type: ignore[import-untyped]
HOTKEY_DUMP_TO_DISK = 'w' # Select bytes and press w to dump it to disk in the same directory as the IDB. One can also call dump_to_disk(address, length) to dump from the console
HOTKEY_COPY_SELECTED_BYTES_AS_HEX_TEXT = 'shift-c' # Select bytes and press Shift-C to copy the marked bytes as hex text. Same shortcut as in x64dbg.
HOTKEY_COPY_CURRENT_ADDRESS = 'alt-ins' # Copy the current address as hex text into the clipboard. Same shortcut as x64dbg.
BufferType = Union[str, bytes, bytearray, List[str], List[bytes], List[bytearray]]
# EvaluateType is anything that can be evalutad to an int. E.g. the address() function can take this type and then try to resolve an adress. Give it a str (a label) and it will work, give it a ida_segment.segment_t object and it will give the address to the start of the segment
EvaluateType = Union[str, int, _ida_idp.reg_info_t, _ida_ua.insn_t, _ida_hexrays.cinsn_t, _ida_hexrays.cfuncptr_t, _ida_funcs.func_t, _ida_idaapi.PyIdc_cvt_int64__, _ida_segment.segment_t, _ida_ua.op_t, _ida_typeinf.funcarg_t, _idautils.Strings.StringItem, _ida_dbg.bpt_t, _ida_idd.modinfo_t, _ida_hexrays.carg_t, _ida_hexrays.cexpr_t, _ida_range.range_t]
__GLOBAL_LOG_EVERYTHING = False # If this is set to True, then all calls to log_print() will be printed, this can cause massive logs but good for hard to find bugs
# HELPERS ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _int_to_str_dict_from_module(arg_module: Union[ModuleType, str], arg_regexp: str) -> Dict[int, str]:
''' Internal function. Used to build dict from module enums.
e.g. _int_to_str_dict_from_module(ida_ua, 'o_.*')
'''
l_module: ModuleType = sys.modules[arg_module] if isinstance(arg_module, str) else arg_module
return {getattr(l_module, key): key for key in dir(l_module) if re.fullmatch(arg_regexp, key)}
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def links(arg_open_browser_at_official_python_docs: bool = False) -> Dict[str, Dict[str, str]]:
''' Various information to help you develop your own scripts.
Read more: https://python.docs.hex-rays.com/
'''
l_abbreviations = {
'ASG': "Assign",
'BPU': "Bytes Per Unit",
'CC' : "Calling Convention or Compiler",
'EA' : "Effective Address, just an address in the process",
'MBA': "Microcode",
'PEB': "Process Environment Block",
'TEB': "Thread Environment Block, a.k.a. TIB (Thread Information Block)",
'TIB': "Thread Information Block, a.k.a. TEB (Thread Environment Block)",
'tid': 'Type ID',
'TIF': "type info. E.g. int*, wchar_t* and so on",
'TIL': "Type Information Library, IDAs internal name for it's database with types in it. It's like a huge .h file but in IDAs own format"
}
l_links = {}
l_links["official_python_documentation"] = "https://python.docs.hex-rays.com"
l_links["developer_guide"] = "https://docs.hex-rays.com/developer-guide"
l_links["getting_started_with_idapython"] = "https://docs.hex-rays.com/developer-guide/idapython/idapython-getting-started"
l_links["idapython_examples"] = "https://docs.hex-rays.com/developer-guide/idapython/idapython-examples"
l_links["porting_guide"] = "https://docs.hex-rays.com/developer-guide/idapython/idapython-porting-guide-ida-9"
l_links["HexRays_official_Youtube_channel"] = "https://www.youtube.com/@HexRaysSA"
l_links["AllThingsIDA_Youtube_channel"] = "https://www.youtube.com/@allthingsida"
l_links["AllThingsIDA_github"] = "https://github.com/allthingsida/allthingsida"
l_links["HexRays_official_plugins_repository"] ="https://plugins.hex-rays.com/"
l_links["how_to_create_a_plugin"] = "https://docs.hex-rays.com/developer-guide/idapython/how-to-create-a-plugin"
l_links["appcall_guide"] = "https://docs.hex-rays.com/user-guide/debugger/debugger-tutorials/appcall_primer"
l_links["appcall_practical_examples"] = "https://hex-rays.com/blog/practical-appcall-examples/"
l_links["community_forums"] = "https://community.hex-rays.com/"
# l_links[""] = ""
l_batch_mode = {}
l_batch_mode["command_line"] = "<full_path_to>ida.exe -A -S<script_I_want_to_run.py> -L<full_path_to>ida.log <full_path_to_input_file>"
l_batch_mode["official_link"] = "https://docs.hex-rays.com/user-guide/configuration/command-line-switches"
res = {}
res["links"] = l_links
res["abbreviations"] = l_abbreviations
res["batch_mode"] = l_batch_mode
if arg_open_browser_at_official_python_docs:
_ida_kernwin.open_url(l_links["official_python_documentation"])
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def open_url(arg_text_blob_with_urls_in_it_or_function: Union[str, Callable]) -> None:
''' Opens the default web brower with all URLs in the given text blob.
Works well on the docstrings I have enriched with URLs: open_url(ida_kernwin.process_ui_action)
ida_kernwin.open_url docs: <https://python.docs.hex-rays.com/namespaceida__kernwin.html#aa853ec021675db50a22e8c81eeda1550>
Replacement for ida_kernwin.open_url()
'''
if isinstance(arg_text_blob_with_urls_in_it_or_function, str):
l_url_regex: str = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))" # https://www.geeksforgeeks.org/python-check-url-string/
urls = re.findall(l_url_regex, arg_text_blob_with_urls_in_it_or_function)
if not urls:
log_print(f"No URLs found in '{arg_text_blob_with_urls_in_it_or_function}'", arg_type="ERROR")
for url in urls:
_ida_kernwin.open_url(url[0])
return
# Check the docstring
open_url(getattr(arg_text_blob_with_urls_in_it_or_function, "__doc__", ""))
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def bug_report(arg_bug_description: str, arg_module_to_blame: Union[str, ModuleType, None] = None) -> str:
''' If you find a bug in IDA or community_base (or any other plugin) you can easy save info about the bug by using this function.
It will save what file you have open, the version of IDA pro, version of community_base and the bug description
Will write a JSON file in the same directory as the IDB
@param arg_bug_description A long description of the bug. Preferably on how to reproduce it.
@param arg_module_to_blame The name of the module that is buggy, usually it's the plugin name or "IDA Pro"
@return The full path to the bug report.
'''
l_timestamp: str = time.strftime("%Y_%m_%d_%H_%M_%S", datetime.datetime.timetuple(datetime.datetime.now()))
l_bug_report_file: str = f"{input_file.idb_path}.{l_timestamp}.bug_report.json"
l_bug_report: Dict[str, str] = {}
l_bug_report["bug_in_module"] = _python_module_to_str(arg_module_to_blame)
l_bug_report["IDA_version"] = str(ida_version())
l_bug_report["decompiler_version"] = ida_decompiler_version()
l_bug_report["community_base_version"] = __version__
l_bug_report["python_version"] = str(python_version()[0]) + "." + str(python_version()[1]) # Tuple[major: int, minor: int] --> "3.12"
l_bug_report["datetime"] = _timestamped_line("").strip()
for key, value in input_file._as_dict().items():
l_bug_report["input_file_" + key] = value
l_bug_report["bug_description"] = arg_bug_description
with open(l_bug_report_file, "w", encoding="UTF-8", newline="\n") as f:
f.write(json.dumps(l_bug_report, ensure_ascii=False, indent=4, default=str))
log_print(f"Wrote bug report in {l_bug_report_file}", arg_type="INFO")
log_print("Please post this bug report to the creator of the module so they can fix it. Thank you!", arg_type="INFO")
l_github_issues: str = __url__ + "/issues/new"
# First argument is the default button that will be pressed if the user press ENTER as soon as the box popups
if _ida_kernwin.ask_yn(_ida_kernwin.ASKBTN_YES , f"Open a new issue on Github? ( {l_github_issues} )") == _ida_kernwin.ASKBTN_YES:
_ida_kernwin.open_url(l_github_issues)
return l_bug_report_file
# TODO: This can be used as "poor mans thread" to poll external data
# TODO: This is not working as expected since it runs in it's own thread
class _check_if_long_running_script_should_abort_not_working():
''' Periodically check if any of the strings "abort.ida", "ida.abort", "ida.stop", "stop.ida" are in the clipboard. If anyone is, then throw an exception to abort the long running task.
This is also an example on how to use timers. Read more: <https://github.com/HexRaysSA/IDAPython/blob/9.0sp1/examples/ui/register_timer.py>
'''
def __init__(self):
l_time_between_calls_in_milliseconds = 1000
self.interval = l_time_between_calls_in_milliseconds
self.obj = _ida_kernwin.register_timer(self.interval, self)
if self.obj is None:
raise RuntimeError("Failed to register timer")
self.times = 30
def __call__(self):
''' This is the function that is invoked at each call '''
# print("Timer invoked. %d time(s) left" % self.times)
self.times -= 1
# Unregister the timer when the counter reaches zero
# return -1 --> do not call again, anything else
clipboard = QApplication.clipboard()
res = clipboard.text().strip() in ["abort.ida", "ida.abort", "ida.stop", "stop.ida"]
if res:
log_print(f"String {clipboard.text().strip()} found in clipboard")
log_print("Here should I don something smart to stop the long running script, any ideas?")
return -1 if self.times == 0 else self.interval
def __del__(self):
''' Clean up '''
log_print(f"Timer object disposed {self}")
_g_timestamp_of_last_checked = time.time()
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _check_if_long_running_script_should_abort(arg_debug: bool = False) -> None:
''' Scripts that take long time to run can be aborted by copying any of the following strings into the clipboard: "abort.ida", "ida.abort", "ida.stop", "stop.ida"
This is checked every 30 seconds and raises a TimeoutError() exception
WARNING! If you have multiple instances of IDA running with this script then the string check will be done in all instances and abort all long running scripts!
'''
# TODO: Add the possibility to add a PID in the string to just abort the correct script? Add if ever needed
# TODO: Ask (with a popup) the user if this is the correct IDA to abort?
global _g_timestamp_of_last_checked
l_now = time.time()
if (l_now - _g_timestamp_of_last_checked) > 30:
_g_timestamp_of_last_checked = l_now
if arg_debug:
l_timestamp: str = time.strftime("%Y-%m-%d %H:%M:%S", datetime.datetime.timetuple(datetime.datetime.now()))
print(f"{l_timestamp} _long_running_script_should_abort(): Checking for abort.ida in clipboard...")
clipboard = QApplication.clipboard()
res = clipboard.text().strip() in ["abort.ida", "ida.abort", "ida.stop", "stop.ida"]
if res:
raise TimeoutError(f"String {clipboard.text().strip()} found in clipboard")
return
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _dict_sort(arg_dict: dict, arg_sort_by_value: bool = False, arg_descending: bool = False) -> dict:
''' Internal function. Returns a new sorted dictionary, can sort by value and can sort ascending or descending '''
res = {}
if arg_sort_by_value:
res = dict(sorted(arg_dict.items(), key=lambda item: item[1])) # Sort by value ( lower -> higher )
else:
_list = sorted(arg_dict.items())
for _t in _list:
res[_t[0]] = _t[1]
if arg_descending:
res = {k: res[k] for k in reversed(res)} # Just reverse the dict
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _dict_swap_key_and_value(arg_dict: dict) -> dict:
''' Internal function. Used with _int_to_str_dict_from_module to make dict that behaves as an enum.
e.g.
ofile_type_t = _int_to_str_dict_from_module("ida_loader", "OFILE_.*")
ofile_type_t_enum = _dict_swap_key_and_value(ofile_type_t)
'''
res: dict = {}
for k,v in arg_dict.items():
res[v] = k
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def ida_version() -> int:
''' Returns the version of IDA currently running. 7.7 --> 770, 8.4 --> 840, 9.0 --> 900 '''
return _ida_pro.IDA_SDK_VERSION
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def ida_user_dir() -> str:
''' Returns the path IDA is using as base when it looks for user files
Read more <https://hex-rays.com/blog/igors-tip-of-the-week-33-idas-user-directory-idausr>
'''
return _ida_diskio.get_user_idadir()
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def ida_plugin_dirs() -> List[str]:
''' Returns a list of directories where IDA looks for plugins
For more info, see <https://hex-rays.com/blog/igors-tip-of-the-week-103-sharing-plugins-between-ida-installs>
'''
return _ida_diskio.get_ida_subdirs("plugins")
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def ida_is_running_in_batch_mode() -> bool:
''' Are we running in batch mode? a.k.a. headless
Credits goes to https://github.com/arizvisa: <https://github.com/Harding-Stardust/community_base/issues/1>
'''
return _ida_kernwin.cvar.batch
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def ida_arguments() -> List[str]:
''' The arguments to the IDA Process when it was launched. Can be used to start ida with custom arguments.
E.g. ida.exe c:\\temp\\example.exe --extra_option_that_ida_dont_understand=3
You can then use this function to parse your own arguments. Useful in batch mode
'''
return PyQt5.Qt.qApp.instance().arguments()
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def ida_save_and_exit(arg_exit_code: int = 0) -> None:
''' Save the IDB and clean exit IDA
A good use for this function is as the last call in a script run in batch mode.
See links() for more info about batch mode
To exit without saving the IDB, see: <https://docs.hex-rays.com/developer-guide/idc/idc-api-reference/alphabetical-list-of-idc-functions/197>
and <https://hex-rays.com/blog/igors-tip-of-the-week-116-ida-startup-files>
process_config_directive(): <https://python.docs.hex-rays.com/namespaceida__idp.html#a8f7be5936a3a9e1f1f2bc7e406654f38>
'''
_ida_pro.qexit(arg_exit_code)
return # We will never reach this line
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _idaapi_get_ida_notepad_text() -> str:
''' Wrapper around ida_nalt.get_ida_notepad_text() that actually honors the type hints
Read more: <https://python.docs.hex-rays.com/namespaceida__nalt.html#afbce150733a7444c14e83db7411cf3c9>
Tag: Community fix, IDA Bug
'''
return _ida_nalt.get_ida_notepad_text() or ""
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def notepad_text(arg_text: Optional[str] = None, arg_debug: bool = False) -> str:
''' IDA has a text field that the user can write whatever they want in.
This function can read and write this text field. '''
if arg_text is not None:
_ida_nalt.set_ida_notepad_text(str(arg_text))
res = _idaapi_get_ida_notepad_text()
log_print(f"ida_nalt.get_ida_notepad_text() returned {res}", arg_debug)
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def ida_decompiler_version() -> str:
''' What version of Hexrays decompiler we are running '''
l_arch = f"{input_file.format}, {input_file.bits} bits, {input_file.endian} endian"
l_error_str: str = f"<<< No decompiler for {l_arch} is loaded >>>"
if not _ida_hexrays.init_hexrays_plugin():
log_print(l_error_str, arg_type="ERROR")
return l_error_str
l_temp: Optional[str] = _ida_hexrays.get_hexrays_version()
if l_temp is None:
log_print(l_error_str, arg_type="ERROR")
return l_error_str
return l_temp
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def python_version() -> Tuple[int, int]:
''' Find the Python version we are running.
Returns a tuple with (major_version: int, minor_version: int)
'''
return (sys.version_info.major, sys.version_info.minor)
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _python_module_to_str(arg_module: Union[str, ModuleType, None] = None) -> str:
''' Internal function. Get a Python module name from the argument. If argument is None, then return the module name of ourself '''
return arg_module if isinstance(arg_module, str) else getattr(arg_module, '__name__', __name__)
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def reload_module(arg_module: Union[str, ModuleType, None] = None) -> bool:
''' During development, it's nice to have an easy way to reload the file and update all changes
Read more: <https://hex-rays.com/blog/loading-your-own-modules-from-your-idapython-scripts-with-idaapi-require>
@param arg_module if this is set to None, then reload ourself
@return Returns True if we reloaded successful, False otherwise
Replacement for ida_idaapi.require()
'''
l_module_name: str = _python_module_to_str(arg_module)
log_print(f"Reloading '{l_module_name}' ( {getattr(sys.modules.get(l_module_name, ''), '__file__', '<<< no file found >>>')} ) using ida_idaapi.require('{l_module_name}')", arg_type="INFO")
try:
_ida_idaapi.require(l_module_name)
res = True
except ModuleNotFoundError as exc:
log_print(f"Could NOT reload {l_module_name}, exception: {exc}", arg_type="ERROR")
res = False
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _timestamped_line(arg_str: str) -> str:
''' Add a timestamp at the beginning of the line
e.g. 2024-12-31 13:59:59 This is the string I send in as argument
'''
return time.strftime("%Y-%m-%d %H:%M:%S", datetime.datetime.timetuple(datetime.datetime.now())) + " " + arg_str
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _file_and_line_number(arg_num_function_away: int = 2) -> Optional[_inspect.Traceback]:
''' Internal function. Used in log_print()
Returns the file the script is called from and what line in that script file
! WARNING ! This function is VERY expensive!
'''
try:
callerframerecord = _inspect.stack()[arg_num_function_away] # 0 represents this line
frame = callerframerecord[0] # 1 represents line at caller and so on
return _inspect.getframeinfo(frame) # info.filename, info.function, info.lineno
except Exception as exc:
print(_timestamped_line(f"Caught exception: {exc}"))
return None
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def log_print(arg_string: str, arg_actually_print: bool = True, arg_type: str = "DEBUG", arg_num_function_away: int = 6) -> None:
''' Used for code trace while developing the project '''
_check_if_long_running_script_should_abort(arg_actually_print)
if arg_actually_print or __GLOBAL_LOG_EVERYTHING:
info = _file_and_line_number(arg_num_function_away)
if info is None:
print(_timestamped_line("_file_and_line_number failed"))
return
function_name: str = info.function if info else "<no function name>"
if function_name == "<module>":
function_name = os.path.basename(info.filename)
else:
function_name = f"{os.path.splitext(os.path.basename(info.filename))[0]}.{function_name}"
log_line = _timestamped_line(f"[{arg_type}] {function_name}:{info.lineno} --> {arg_string}")
# Log to disk can be implemented here if needed
print(log_line, flush=True)
return
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def ida_is_64bit() -> bool:
''' Is the IDA process you are running in a 64 bit process? '''
return _ida_idaapi.__EA64__
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _ida_DLL() -> Any: # TODO: This used to be Union[ctypes.CDLL, ctypes.WinDLL] but WinDLL is not supported on Linux
''' Load correct version of ida.dll. Work on IDA 8.4 and 9.0. Example of how to use ctypes. '''
l_bits: str = "64" if ida_is_64bit() else "32"
if ida_version() >= 900:
l_bits = "" # IDA 9.0 removed the ida64.dll and ida32.dll and just calls it ida.dll now
if sys.platform == 'win32':
res = ctypes.windll[f'ida{l_bits}.dll'] # windll is STDCALL
elif 'linux' in sys.platform.lower():
res = ctypes.cdll[f'libida{l_bits}.so'] # cdll is CDECL
elif sys.platform == 'darwin':
res = ctypes.cdll[f'libida{l_bits}.dylib'] # Not tested, cdll is CDECL
else:
log_print(f"You are using an OS I do not know: {sys.platform}", arg_type="ERROR")
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _loader_name() -> str:
''' Internal function. Example of how to use ctypes to call IDA C api.
Read more: <https://hex-rays.com/blog/calling-ida-apis-from-idapython-with-ctypes>
get_loader_name: <https://cpp.docs.hex-rays.com/loader_8hpp.html#a9c79e47be0a36e47363409f3ce9ce6c5>
'''
l_IDA_dll = _ida_DLL()
l_buf_size: int = 0x100
l_buf = ctypes.create_string_buffer(l_buf_size)
l_exported_function_name = 'get_loader_name'
l_IDA_dll[l_exported_function_name].argtypes = ctypes.c_char_p, ctypes.c_size_t # Set the prototype
l_IDA_dll[l_exported_function_name].restype = ctypes.c_size_t # Set the return value
l_IDA_dll[l_exported_function_name](l_buf, l_buf_size) # This is the weird way ctypes calls functions
return l_buf.value.decode('utf-8') # buf.raw gives the whole buffer
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def hex_dump(arg_ea: Union[EvaluateType, bytes, bytearray], arg_len: Optional[EvaluateType] = None, arg_width: int = 0x10, arg_unprintable_char: str = '.', arg_debug: bool = False) -> None:
''' Prints the given data as <address> <byte value> <text> in the same style as IDAs hex view does '''
l_addr: int = 0
if isinstance(arg_ea, (bytes, bytearray)):
l_len: Optional[int] = len(arg_ea) if arg_len is None else eval_expression(arg_len, arg_debug=arg_debug)
if l_len is None:
log_print(f'eval_expression({arg_len}) failed')
return
l_bytes: bytes = bytes(arg_ea[0:l_len])
else:
l_addr = address(arg_ea, arg_debug=arg_debug)
if l_addr == _ida_idaapi.BADADDR:
log_print(f"arg_ea: '{_hex_str_if_int(arg_ea)}' could not be located in the IDB", arg_type="ERROR")
return
l_len = 0x10 if arg_len is None else eval_expression(arg_len, arg_debug=arg_debug)
if l_len is None:
log_print(f'eval_expression({arg_len}) failed', arg_type="ERROR")
return
l_bytes_temp = read_bytes(arg_ea=l_addr, arg_len=l_len, arg_debug=arg_debug)
if l_bytes_temp is None:
log_print(f'read_bytes({_hex_str_if_int(arg_ea)}) failed', arg_type="ERROR")
return
l_bytes = l_bytes_temp
l_temp: List[str] = []
digits: int = 2
l_len = len(l_bytes) if l_bytes is not None else 0x10
for buf_offset in range(0, l_len, arg_width):
s = l_bytes[buf_offset:buf_offset + arg_width]
hexa = ' '.join(["%0*X" % (digits, x) for x in s]) # TODO: Make more readable...
hexa = hexa.ljust(arg_width * (digits + 1), ' ')
text = ''.join([chr(x) if 0x20 <= x < 0x7F else arg_unprintable_char for x in s])
l_temp.append(f"{l_addr+buf_offset:08X} {hexa} {text}")
print('\n'.join(l_temp))
_ida_kernwin.request_refresh(_ida_kernwin.IWID_ALL)
return
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def hex_parse(arg_list_of_strs: BufferType, arg_debug: bool = False) -> List[str]:
''' Parse data that can be very messed up as good as I can
@return List[hex_as_text: str]
e.g.
hex_parse('aa bb cc') --> ['aa', 'bb', 'cc']
'''
if not arg_list_of_strs: # ida_nalt.retrieve_input_file_crc32() for some reason return 0 when no file is loaded, ida_nalt.retrieve_input_file_md5() returns None
return []
l_list_of_inputs = [arg_list_of_strs] if isinstance(arg_list_of_strs, (str, bytes, bytearray)) else arg_list_of_strs
l_list_of_strs: List[str] = []
if isinstance(l_list_of_inputs[0], (bytes, bytearray)):
for line in l_list_of_inputs:
hex_line: str = ""
for b in line:
hex_line += f"{b:02x}"
l_list_of_strs.append(hex_line)
else:
l_list_of_strs = l_list_of_inputs # type: ignore[assignment] # I think this is correct bu mypy does not like it
log_print(f'l_list_of_strs is now: {l_list_of_strs}', arg_debug)
res: List[str] = []
hex_byte: str = "[0-9A-F][0-9A-F]"
beginning_of_line: str = hex_byte + hex_byte + hex_byte + r" \s*?((?:" + hex_byte + "(?:[ -]{1,3}|$))+)"
for line in l_list_of_strs:
line = line.strip()
if not line:
continue
m = re.findall(beginning_of_line, line, re.IGNORECASE)
if len(m) == 0: # There is no "extra output from the host program" so we just parse the hex raw
hex_data = re.findall(hex_byte, line, re.IGNORECASE)
else:
hex_data = re.split(" |-", m[0].strip())
for i in hex_data:
if len(i):
res.append(i)
if not res:
res = []
log_print("Result is empty. Your input might be wrong?", arg_type="ERROR")
log_print(f'res: {res}', arg_debug)
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _signed_hex_text(arg_expression: EvaluateType, arg_nbits: int = 0, arg_debug: bool = False) -> Optional[str]:
''' Easy way to get nice formatting on signed values.
@param arg_nbits: The bit width of the variable. Since Python has no fixed bit width int types, you have to specify this. If you don't specify it, I assume it's the input_file.bits width
'''
l_nbits = arg_nbits if arg_nbits else input_file.bits
l_value: Optional[int] = eval_expression(arg_expression=arg_expression, arg_debug=arg_debug)
if l_value is None:
log_print(f"'{arg_expression}' failed in eval_expression", arg_type="ERROR")
return None
res = hex(_ida_idaapi.as_signed(l_value, nbits=l_nbits))
if not res.startswith('-'):
res = '+' + res
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _operand_parser(arg_operand: _ida_ua.op_t, arg_debug: bool = False) -> Optional[dict]:
''' Internal function. Split the operand into a dict with info about the parts of the operand '''
res = {}
if arg_operand.type == _ida_ua.o_void:
pass # I don't like this code but IDA use invalid operands with the type o_void to say that this is an invalid operand
elif arg_operand.type == _ida_ua.o_reg:
l_reg_name = _ida_idp.get_reg_name(arg_operand.reg, _data_type_sizes[arg_operand.dtype])
l_reg_name = l_reg_name.replace('$','').lower() # MIPS...
l_register = registers._as_dict[l_reg_name.lower()]
res['register'] = l_register
elif arg_operand.type in [_ida_ua.o_mem, _ida_ua.o_far, _ida_ua.o_near]:
res['address'] = arg_operand.addr
elif arg_operand.type in [_ida_ua.o_phrase, _ida_ua.o_displ]:
if input_file.processor != 'metapc':
log_print("This only works for Intel x86 and x64.", arg_type="ERROR")
return None
# specflag1 and specflag2 are not really documented. Use this code at own risk.
if arg_operand.specflag1 == 0:
log_print("specflag1 == 0", arg_debug)
l_base_reg: str = _ida_idp.get_reg_name(arg_operand.reg, input_file.bits // 8)
l_base_reg = l_base_reg.replace('$', '').lower() # MIPS
res['base_register'] = registers._as_dict[l_base_reg]
res['displacement'] = arg_operand.addr
elif arg_operand.specflag1 == 1:
log_print("specflag1 == 1.", arg_debug)
log_print(f"specflag2: {bin(arg_operand.specflag2)}.", arg_debug)
l_scale = (arg_operand.specflag2 >> 6) & 0x03
l_scale = 1 << l_scale if l_scale else 0 # The special case of 0 --> scale 0
l_base_reg = _ida_idp.get_reg_name(arg_operand.specflag2 & 0x07, input_file.bits // 8)
l_base_reg = l_base_reg.replace('$', '').lower() # MIPS
l_index_reg: str = _ida_idp.get_reg_name((arg_operand.specflag2 >> 3) & 0x07, input_file.bits // 8)
l_index_reg = l_index_reg.replace('$', '').lower() # MIPS
res['base_register'] = registers._as_dict[l_base_reg]
res['index_register'] = registers._as_dict[l_index_reg]
res['scale'] = l_scale
res['displacement'] = arg_operand.addr
elif arg_operand.type == _ida_ua.o_imm:
res['value'] = arg_operand.value
elif arg_operand.type == _ida_ua.o_idpspec1:
if input_file.processor == 'metapc':
res['register'] = f"dr{arg_operand.reg}"
return res
elif arg_operand.type == _ida_ua.o_idpspec2:
if input_file.processor == 'metapc':
res['register'] = f"cr{arg_operand.reg}"
return res
else:
l_operand_types = _int_to_str_dict_from_module('_ida_ua', 'o_.*')
log_print(f"Unknown operand type, we got 0x{arg_operand.type:x}: {l_operand_types.get(arg_operand.type, '<unknown operand type>')} which I cannot handle.", arg_type="ERROR")
return None
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _hex_str_if_int(arg_in: Any, arg_debug: bool = False) -> str:
''' If arg_in is an int, then return the string with the hex value, the decimal value and if the int is an valid address: the name of that address
e.g. '0x400000 (4194304) name: main'
If arg_in is NOT an int, then we return str(arg_in)
'''
if not isinstance(arg_in, int):
return str(arg_in)
res: str = f"0x{arg_in:x} ({arg_in})"
if arg_in == _ida_idaapi.BADADDR:
res = f"0x{_ida_idaapi.BADADDR:x} (ida_idaapi.BADADDR)"
elif _ida_bytes.is_mapped(arg_in):
res += f" name: {name(arg_in, arg_debug=arg_debug)}"
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def copy_hex_text_to_clipboard(arg_ea_start: EvaluateType = 0, arg_len: EvaluateType = 0, arg_debug: bool = False) -> None:
''' Selected bytes will be copied as hex text to the clipboard '''
_ = dump_to_disk(arg_ea_start=arg_ea_start, arg_len=arg_len, arg_filename="|clipboard|", arg_debug=arg_debug) # "|clipboard|" --> We don't actually dump to disk
return
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _whitespace_zapper(arg_in_string: str) -> str:
''' Internal function. If there are multiple spaces in a row in the input line, they are replaced by only 1 space. '''
res = arg_in_string
while res != res.replace(' ', ' '):
res = res.replace(' ', ' ')
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _lnot(arg_expression: _ida_hexrays.cexpr_t) -> _ida_hexrays.cexpr_t:
''' Logical NOT of expression. See <https://github.com/tmr232/idapython/blob/0028bac2975e9cfd68ce39e908d1fc923e94000b/examples/vds3.py#L94>
a cexpr_t with "x == y" will return "x != y"
'''
return _ida_hexrays.lnot(_ida_hexrays.cexpr_t(arg_expression))
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _idaapi_retrieve_input_file_md5() -> bytes:
''' Wrapper around ida_nalt.retrieve_input_file_md5() but this we honor the type hints
Tags: Community fix, IDA Bug
'''
return _ida_nalt.retrieve_input_file_md5() or bytes()
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _idaapi_retrieve_input_file_sha256() -> bytes:
''' Wrapper around ida_nalt.retrieve_input_file_sha256() but we honor the type hints
Tags: Community fix, IDA Bug
'''
l_temp: Optional[bytes] = _ida_nalt.retrieve_input_file_sha256()
return l_temp or bytes()
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _pretty_print_size(arg_input_size: int) -> Optional[str]:
''' Convert a large number to the correct postfix (KB, MB, GB, TB)
e.g. _pretty_print_size(1231231332) --> '1.15G'
Read more: <https://cpp.docs.hex-rays.com/group__conv.html#gab6147a3e263d08eb2b9c2439b4653526>
Example on how to use the C api from Python.
'''
l_IDA_dll = _ida_DLL()
l_buf_size = 8 # Enough according to the official docs
l_buf = ctypes.create_string_buffer(l_buf_size)
l_exported_function_name = "pretty_print_size"
l_IDA_dll[l_exported_function_name].argtypes = ctypes.c_char_p, ctypes.c_size_t, ctypes.c_uint64
l_IDA_dll[l_exported_function_name].restype = ctypes.c_size_t
l_IDA_dll[l_exported_function_name](l_buf, l_buf_size, arg_input_size)
return l_buf.value.decode('utf-8') # buf.raw gives the whole buffer
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def google(arg_search: str) -> str:
''' Fast track to search '''
l_search_engine_base: str = "https://www.google.com/search?q="
res = l_search_engine_base + arg_search
_ida_kernwin.open_url(res)
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def ida_licence_info() -> Dict[str, str]:
''' Gets the license info. This function serves as example of 2 things: 1. How to get info that is not easy to get in a real way. 2. That your name is in every IDB, privacy warning!
@return {"serial_number": serial_number: str, "name_info": name_info: str}
'''
res = {"serial_number": "Unknown", "name_info": "Unknown"}
l_lines: List[str] = _ida_lines.generate_disassembly(input_file.min_original_ea, max_lines=100, as_stack=False, notags=True)[1]
l_next_line_is_user_info: bool = False
for l_line in l_lines:
if l_next_line_is_user_info:
l_next_line_is_user_info = False
l_name_or_email_match = re.match(r".*\s\s\s([^\s].*[^\s])\s\s\s", l_line)
if l_name_or_email_match:
res["name_info"] = l_name_or_email_match.group(1)
else:
l_license_info_match = re.match(".*License info: (.*?) ", l_line)
if l_license_info_match:
res["serial_number"] = l_license_info_match.group(1)
l_next_line_is_user_info = True
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _compiler_info() -> _ida_ida.compiler_info_t:
''' Replacement for ida_ida.inf_get_cc()
Official docs: <https://cpp.docs.hex-rays.com/structcompiler__info__t.html>
more info: <https://youtu.be/2w8LdSCPUQc?t=1369>
'''
res = _ida_ida.compiler_info_t() # Create empty objext
_ida_ida.inf_get_cc(res) # Fill the object with info
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _compiler_str() -> str:
''' What compiler was used according to IDA?
Official docs for compiler id: <https://cpp.docs.hex-rays.com/group___c_o_m_p__.html>
more info: <https://youtu.be/2w8LdSCPUQc?t=1369>
'''
l_compiler_info = _compiler_info()
l_compiler_id: int = l_compiler_info.id & _ida_typeinf.COMP_MASK
l_unsure: bool = bool(l_compiler_info.id & _ida_typeinf.COMP_UNSURE)
res = _ida_typeinf.get_compiler_name(l_compiler_id)
res += " (unsure)" if l_unsure else " (sure)"
return res
# API extension ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def pe_header() -> Optional[bytes]:
''' Returns the PE header saved in the IDB.
returns The PE header as bytes if we are in a PE file and None if we don't have any PE header
'''
l_pe_node = _ida_netnode.netnode("$ PE header")
if l_pe_node == _ida_netnode.BADNODE:
return None
return l_pe_node.valobj()
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def pe_header_linker_version() -> Tuple[int, int]:
''' This is a rewrite of Rolf Rolles script to get the linker info from the PE header
returns a tuple that looks like (major_version: int, minor_version: int)
LLVM returns a major_version of 1 or 2, MSVC returns a major_version of 6+
'''
l_pe_header = pe_header()
if l_pe_header is None:
return (0, 0)
l_major_version: int = l_pe_header[0x1A]
l_minor_version: int = l_pe_header[0x1B]
return (l_major_version, l_minor_version)
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def pe_header_os_version() -> Tuple[int, int]:
''' Get the OS version from the PE header '''
l_pe_header = pe_header()
if l_pe_header is None:
return (0, 0)
l_major_version: int = int.from_bytes(l_pe_header[0x40:0x41], byteorder="little")
l_minor_version: int = int.from_bytes(l_pe_header[0x42:0x43], byteorder="little")
return (l_major_version, l_minor_version)
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def pe_header_compiled_time() -> str:
''' Reads the compiled from the PE header. Warning! In win10+ , this is a hash so we can get reproducable builds <https://devblogs.microsoft.com/oldnewthing/20180103-00/?p=97705> '''
l_pe_header = pe_header()
if l_pe_header is None:
return ""
l_timestamp_and_hash: bytes = (l_pe_header[8:12])
l_timestamp = int.from_bytes(l_timestamp_and_hash, byteorder="little")
l_datetime = datetime.datetime.timetuple(datetime.datetime.fromtimestamp(l_timestamp, tz=datetime.UTC))
l_os_version = pe_header_os_version()
if l_os_version >= (10, 0):
log_print(f"This is file from windows {l_os_version[0]}.{l_os_version[1]} which has reproducable builds so the timestamp is not valid", arg_type="ERROR")
return ""
return time.strftime("%Y-%m-%d %H:%M:%S (UTC)", l_datetime)
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def pdb_path() -> str:
''' Return the PDB filename from either 1. the loaded PDB or 2. the PDB path in the PE header
Taken from <https://github.com/gaasedelen/lucid/blob/9f2480dc8e6bbb9421b5711533b0a98d2e9fb5af/plugins/lucid/util/ida.py#L23>
'''
l_pdb_node = _ida_netnode.netnode("$ pdb")
if l_pdb_node != _ida_netnode.BADNODE:
PDB_DLLNAME_NODE_IDX = 0
res = l_pdb_node.supstr(PDB_DLLNAME_NODE_IDX)
if res:
return res
l_pe_netnode = _ida_netnode.netnode('$ PE header')
if l_pe_netnode == _ida_netnode.BADNODE:
return ""
res = l_pe_netnode.supstr(0xFFFFFFFFFFFFFFF7)
if not res:
return ""
return res
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def pdb_load(arg_local_pdb_file: str = "",
arg_image_base: Optional[EvaluateType] = None,
arg_force_reload: bool = False,
arg_local_symbol_cache: str = r"C:\symbols",
arg_debug: bool = False) -> Optional[bool]:
''' Try to load the PDB for this file.
Code taken from <https://gist.github.com/patois/b3f329868934710fbc81218ce1d6d722>
Microsoft symbol server info: <https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/microsoft-public-symbols>
'''
# These come from pdb/common.h
PDB_CC_USER_WITH_DATA = 3
PDB_DLLBASE_NODE_IDX = 0
PDB_DLLNAME_NODE_IDX = 0
l_size: int = 0
l_create_if_not_exists: bool = True
l_pdb_node = _ida_netnode.netnode("$ pdb", l_size, l_create_if_not_exists)
if arg_force_reload:
log_print(f"arg_force_reload set so I will delete the PDB node", arg_debug)
l_pdb_node.altdel(PDB_DLLBASE_NODE_IDX)
l_pdb_node.supdel(PDB_DLLNAME_NODE_IDX)
if l_pdb_node.altval(PDB_DLLBASE_NODE_IDX) == 1:
log_print("PDB info is already loaded", arg_type="ERROR")
return False
l_temp_imagebase = input_file.imagebase if arg_image_base is None else eval_expression(arg_image_base, arg_debug=arg_debug)
if l_temp_imagebase is None:
log_print("arg_image_base resolved to None", arg_type="ERROR")
return False
l_imagebase = l_temp_imagebase
l_default_NT_SYMBOL_PATH = f"srv*{arg_local_symbol_cache}*https://msdl.microsoft.com/download/symbols"
if os.environ.get('_NT_SYMBOL_PATH', None) is None:
log_print(f"Your '_NT_SYMBOL_PATH' is not set at all, setting this to {l_default_NT_SYMBOL_PATH}", arg_type="WARNING")
os.environ['_NT_SYMBOL_PATH'] = l_default_NT_SYMBOL_PATH
l_pdb_file = arg_local_pdb_file or pdb_path()
log_print(f"l_imagebase: 0x{l_imagebase:x}, l_pdb_file: {l_pdb_file}", arg_debug)
l_pdb_node.altset(PDB_DLLBASE_NODE_IDX, l_imagebase) # The alt* part is usually an int
l_pdb_node.supset(PDB_DLLNAME_NODE_IDX, l_pdb_file) # the sup* part is usually a str
plugin_load_and_run("pdb", PDB_CC_USER_WITH_DATA, arg_debug=arg_debug) # See https://reverseengineering.stackexchange.com/questions/8171/
rc = l_pdb_node.altval(PDB_DLLBASE_NODE_IDX)
if not rc:
log_print("Could NOT load PDB", arg_type="ERROR")
return False
return True
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _netnode_list_sups(arg_netnode: Optional[_ida_netnode.netnode] = None) -> None:
''' Internal function to list first 100 items in the netnode. I'm not sure how to work with these at all '''
l_netnode = arg_netnode if arg_netnode else _ida_netnode.netnode('$ PE header')
log_print("vals:", arg_type="INFO")
current_idx = l_netnode.supfirst()
for _ in range(0, 100):
print(f"valobj(0x{current_idx:x}) =")
if l_netnode.valobj() is None:
print("<<< valobj == None >>>")
continue
hex_dump(l_netnode.valobj())
print()
if l_netnode.supval(current_idx) is None:
print("<<< supval == None >>>")
continue
print(f"supval(0x{current_idx:x}) = ")
hex_dump(l_netnode.supval(current_idx))
print()
current_idx = l_netnode.supnext(current_idx)
if current_idx == _ida_idaapi.BADADDR:
break
@validate_call(config={"arbitrary_types_allowed": True, "strict": True, "validate_return": True})
def _netnode_special_netnodes(arg_filter: str = "") -> List[str]:
''' Internal function. <https://python.docs.hex-rays.com/namespaceida__netnode.html> Used to play with the netnodes '''
res = []
nod = _ida_netnode.netnode()
nod.start()
for i in range(0, 10000000):