-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·2140 lines (1767 loc) · 72.5 KB
/
server.py
File metadata and controls
executable file
·2140 lines (1767 loc) · 72.5 KB
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
"""
MCP server for static analysis and patching of .NET binaries.
Uses dnlib for IL parsing/editing and ILSpy/dnSpy for C# decompilation.
"""
from __future__ import annotations
import logging
import shutil
import sys
import traceback
import urllib.error
import urllib.request
from contextlib import asynccontextmanager
from datetime import datetime
from pathlib import Path
from typing import Any
import click
import uvicorn
from mcp.server.fastmcp import FastMCP
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.routing import Mount, Route
logging.basicConfig(
level=logging.INFO,
stream=sys.stderr,
format='%(asctime)s [%(levelname)s] %(message)s'
)
logger = logging.getLogger(__name__)
# Suppress noisy FastMCP session cleanup errors
logging.getLogger("mcp.server.streamable_http").setLevel(logging.CRITICAL)
import clr
_DNLIB_DIR = Path(__file__).parent / "dll"
clr.AddReference("System")
clr.AddReference(str(_DNLIB_DIR / "dnlib.dll"))
clr.AddReference(str(_DNLIB_DIR / "dnSpy.Contracts.Logic.dll"))
clr.AddReference(str(_DNLIB_DIR / "ICSharpCode.Decompiler.dll"))
ilspy_assembly = clr.AddReference(str(_DNLIB_DIR / "dnSpy.Decompiler.ILSpy.Core.dll"))
import dnlib
import System
from dnSpy.Contracts.Decompiler import StringBuilderDecompilerOutput, DecompilationContext
import ICSharpCode.Decompiler # noqa: F401 – side-effect: loads assembly into CLR
import dnSpy.Decompiler.ILSpy.Core # noqa: F401 – side-effect: loads assembly into CLR
from dnlib.DotNet import *
from dnlib.DotNet.Emit import Instruction, OpCodes
from dnlib.DotNet import UTF8String
import os
SAMPLES_DIR = Path(os.environ.get("SAMPLES_DIR", "/data/samples"))
SAMPLES_DIR.mkdir(parents=True, exist_ok=True)
PYTHONNET_PROJECTS_DIR = Path(os.environ.get("PYTHONNET_PROJECTS_DIR", "/data/pythonnet_projects"))
PYTHONNET_PROJECTS_DIR.mkdir(parents=True, exist_ok=True)
# ---------------------------------------------------------------------------
# Module-level constants
# ---------------------------------------------------------------------------
_CALL_OPCODES: frozenset[str] = frozenset({
str(OpCodes.Call), str(OpCodes.Callvirt),
})
_CALL_OPCODES_EXTENDED: frozenset[str] = frozenset({
str(OpCodes.Call), str(OpCodes.Callvirt),
str(OpCodes.Newobj), str(OpCodes.Ldftn),
})
_RUNTIME_ENTRY_POINTS: frozenset[str] = frozenset({
".ctor", ".cctor", "Main", "Finalize",
"Dispose", "GetHashCode", "Equals", "ToString",
})
_CRYPTO_NAMESPACES: frozenset[str] = frozenset({
"System.Security.Cryptography", "System.Security",
})
_CRYPTO_KEYWORDS: frozenset[str] = frozenset({
"aes", "rsa", "sha", "md5", "des", "rc4", "base64", "cipher",
"encrypt", "decrypt", "rijndael", "hmac", "pbkdf", "salsa", "chacha",
})
_CRYPTO_KEY_SIZES: frozenset[int] = frozenset({16, 24, 32})
_REFLECTION_MARKERS: frozenset[str] = frozenset({
"system.reflection", "assembly.load", "getmethod", "gettype",
"invoke", "activator.createinstance", "emit",
})
_BRANCH_INVERSIONS: dict[str, Any] = {
str(OpCodes.Brtrue): OpCodes.Brfalse,
str(OpCodes.Brtrue_S): OpCodes.Brfalse_S,
str(OpCodes.Brfalse): OpCodes.Brtrue,
str(OpCodes.Brfalse_S): OpCodes.Brtrue_S,
str(OpCodes.Beq): OpCodes.Bne_Un,
str(OpCodes.Beq_S): OpCodes.Bne_Un_S,
str(OpCodes.Bne_Un): OpCodes.Beq,
str(OpCodes.Bne_Un_S): OpCodes.Beq_S,
str(OpCodes.Blt): OpCodes.Bge,
str(OpCodes.Blt_S): OpCodes.Bge_S,
str(OpCodes.Bge): OpCodes.Blt,
str(OpCodes.Bge_S): OpCodes.Blt_S,
str(OpCodes.Bgt): OpCodes.Ble,
str(OpCodes.Bgt_S): OpCodes.Ble_S,
str(OpCodes.Ble): OpCodes.Bgt,
str(OpCodes.Ble_S): OpCodes.Bgt_S,
}
# ---------------------------------------------------------------------------
# Context management
# ---------------------------------------------------------------------------
_pythonnet_contexts: dict[str, dict[str, Any]] = {}
class PythonnetContext:
"""Holds a loaded dnlib module and lazily-initialized decompiler."""
binary_path: Path
module: Any # dnlib.DotNet.ModuleDefMD
_type_index: dict[str, Any]
_decompilation_context: Any | None
_decompiler: Any | None
def __init__(self, binary_path: Path) -> None:
self.binary_path = binary_path
logger.info(f"Loading .NET module: {binary_path}")
self.module = dnlib.DotNet.ModuleDefMD.Load(str(binary_path))
self._type_index = {str(t): t for t in self.module.GetTypes()}
self._decompilation_context = None
self._decompiler = None
logger.info(f"PythonnetContext ready: {self.module} ({len(self._type_index)} types)")
def _ensure_decompiler(self) -> None:
"""Lazily initialise the ILSpy C# decompiler (expensive, done once)."""
if self._decompiler:
return
self._decompilation_context = System.Activator.CreateInstance(DecompilationContext)
csharp_type = ilspy_assembly.GetType(
"dnSpy.Decompiler.ILSpy.Core.CSharp.CSharpDecompiler"
)
settings_type = ilspy_assembly.GetType(
"dnSpy.Decompiler.ILSpy.Core.Settings.CSharpVBDecompilerSettings"
)
settings = System.Activator.CreateInstance(settings_type, None)
self._decompiler = System.Activator.CreateInstance(csharp_type, settings, None)
def get_type(self, class_name: str) -> Any:
"""Return the dnlib TypeDef for *class_name* or raise KeyError."""
t = self._type_index.get(class_name)
if not t:
raise KeyError(f"Class not found: {class_name}")
return t
def close(self) -> None:
if self.module:
self.module.Dispose()
self.module = None
logger.info("PythonnetContext closed")
def _get_context(analysis_id: str = "default") -> PythonnetContext:
"""Return the active context for *analysis_id* and refresh last_accessed."""
if analysis_id not in _pythonnet_contexts:
raise ValueError(
f"No context loaded for analysis '{analysis_id}'. "
"Call pythonnet_load_binary first."
)
entry = _pythonnet_contexts[analysis_id]
entry["last_accessed"] = datetime.now()
return entry["context"]
# ---------------------------------------------------------------------------
# Shared helpers
# ---------------------------------------------------------------------------
def _parse_il_offset(offset: str) -> int:
"""Parse an IL offset string to an integer.
Accepts ``IL_0042``, ``0x42``, and plain decimal/hex strings.
Raises:
ValueError: if the string cannot be parsed.
"""
s = offset.strip().upper().removeprefix("IL_").removeprefix("0X")
try:
return int(s, 16)
except ValueError:
raise ValueError(
f"Invalid offset format: {offset!r} — use IL_XXXX, 0xN, or a decimal integer"
)
def _find_method(t: Any, method_name: str) -> Any | None:
"""Return the first method on *t* whose Name equals *method_name*, or None."""
return next((m for m in t.Methods if m.Name == method_name), None)
def _resolve_method(t: Any, method_name: str, method_index: int = -1) -> Any:
"""Resolve a method by name on *t*, handling overloads and full signatures.
*method_name* may be a bare name (``"Foo"``) or a full signature as
returned by dnlib / ``list_all_methods`` (``"Foo(System.String)"`` or
``"System.Void Ns.Class::Foo(System.String)"``). The signature portion is
stripped before matching so both forms work transparently.
- Exactly one match → returns the method directly.
- Multiple matches and ``method_index == -1`` → returns a dict with key
``"overloads"`` listing all candidates (index + full signature) so the
caller can retry with a specific ``method_index``.
- ``method_index >= 0`` → returns the method at that position.
The return value is either a live method object or a ``dict`` (error or
overload disambiguation). Callers should check ``isinstance(result, dict)``
and return it early on that branch.
"""
# Strip parameter list: "Foo(System.String)" -> "Foo"
bare_name = method_name.split("(")[0].strip()
# Strip return type + class prefix: "System.Void Ns.Class::Foo" -> "Foo"
if "::" in bare_name:
bare_name = bare_name.split("::")[-1].strip()
matches = [m for m in t.Methods if m.Name == bare_name]
if not matches:
return {"error": f"Method not found: {t.Name}.{method_name}"}
if len(matches) == 1:
return matches[0]
if method_index >= 0:
if method_index >= len(matches):
return {"error": f"method_index {method_index} out of range (0–{len(matches) - 1})"}
return matches[method_index]
return {
"overloads": [
{"index": i, "signature": str(m)}
for i, m in enumerate(matches)
],
"hint": (
f"{len(matches)} overloads found for '{method_name}'. "
"Re-call with method_index=N to select one."
),
}
# ---------------------------------------------------------------------------
# MCP tools
# ---------------------------------------------------------------------------
def pythonnet_load_binary(binary_path: str, analysis_id: str = "default") -> str:
"""Load a .NET binary for analysis.
The binary is copied into /data/pythonnet_projects/{analysis_id}/ so that
any subsequent save operations land in a dedicated project directory rather
than overwriting the original sample.
Args:
binary_path: Absolute path to the .NET binary (e.g. /data/samples/malware.exe).
analysis_id: Session identifier — use different IDs to analyse multiple
binaries simultaneously.
Returns:
A human-readable status string with the module name, type count, and
the project directory path.
"""
global _pythonnet_contexts
if analysis_id in _pythonnet_contexts:
logger.info(f"Closing previous context for analysis '{analysis_id}'…")
_pythonnet_contexts[analysis_id]["context"].close()
del _pythonnet_contexts[analysis_id]
src = Path(binary_path)
if not src.is_absolute():
# Bare filename: search /data/samples/ then /data/pythonnet_projects/_uploads/
for search_dir in (SAMPLES_DIR, PYTHONNET_PROJECTS_DIR / "_uploads"):
candidate = search_dir / src.name
if candidate.exists():
src = candidate
break
else:
return f"Error: File not found: {binary_path} (searched {SAMPLES_DIR} and {PYTHONNET_PROJECTS_DIR / '_uploads'})"
elif not src.exists():
return f"Error: File not found: {binary_path}"
try:
# Create a per-analysis project directory and copy the binary there.
project_dir = PYTHONNET_PROJECTS_DIR / analysis_id
project_dir.mkdir(parents=True, exist_ok=True)
working_copy = project_dir / src.name
shutil.copy2(src, working_copy)
logger.info(f"Copied {src} -> {working_copy}")
ctx = PythonnetContext(binary_path=working_copy)
_pythonnet_contexts[analysis_id] = {
"context": ctx,
"project_dir": project_dir,
"original_name": src.name,
"last_accessed": datetime.now(),
"loaded_at": datetime.now(),
}
return (
f"Loaded {binary_path}\n"
f"Working copy : {working_copy}\n"
f"Module : {ctx.module}\n"
f"Types : {len(ctx._type_index)}\n"
f"Project dir : {project_dir}\n"
f"Ready for analysis (use pythonnet_* tools)."
)
except Exception as e:
logger.error(f"Error loading binary: {e}", exc_info=True)
return f"Error loading binary: {e}"
def pythonnet_list_all_methods(
limit: int = 0,
analysis_id: str = "default",
) -> dict:
"""List all methods with a body in the loaded binary.
Args:
limit: Maximum number of methods to return (0 = unlimited).
analysis_id: Analysis session ID.
Returns:
``{"count": int, "methods": [str, …]}``
"""
try:
ctx = _get_context(analysis_id)
except ValueError as e:
return {"error": str(e)}
methods = [
str(m)
for t in ctx._type_index.values()
for m in t.Methods
if m.HasBody
]
if limit:
methods = methods[:limit]
return {"count": len(methods), "methods": methods}
def pythonnet_list_all_methods_inside_class(
class_name: str,
analysis_id: str = "default",
) -> dict:
"""List all methods (with or without body) inside a specific class.
Args:
class_name: Full class path (e.g. ``Namespace.ClassName``).
analysis_id: Analysis session ID.
Returns:
``{"class": str, "count": int, "methods": [str, …]}``
"""
try:
ctx = _get_context(analysis_id)
t = ctx.get_type(class_name)
except (ValueError, KeyError) as e:
return {"error": str(e)}
methods = [str(m) for m in t.Methods]
return {"class": class_name, "count": len(methods), "methods": methods}
def pythonnet_list_all_classes(
limit: int = 0,
analysis_id: str = "default",
) -> dict:
"""List all types defined in the loaded binary.
Args:
limit: Maximum number of classes to return (0 = unlimited).
analysis_id: Analysis session ID.
Returns:
``{"count": int, "classes": [str, …]}``
"""
try:
ctx = _get_context(analysis_id)
except ValueError as e:
return {"error": str(e)}
classes = list(ctx._type_index.keys())
if limit:
classes = classes[:limit]
return {"count": len(classes), "classes": classes}
def pythonnet_decompile_class(class_name: str, analysis_id: str = "default") -> dict:
"""Decompile an entire class to C# source code.
Args:
class_name: Full class path (e.g. ``Namespace.ClassName``).
analysis_id: Analysis session ID.
Returns:
``{"class": str, "decompiled_code": str}``
"""
try:
ctx = _get_context(analysis_id)
t = ctx.get_type(class_name)
except (ValueError, KeyError) as e:
return {"error": str(e)}
ctx._ensure_decompiler()
out = System.Activator.CreateInstance(StringBuilderDecompilerOutput)
ctx._decompiler.Decompile(t, out, ctx._decompilation_context)
return {"class": class_name, "decompiled_code": out.GetText()}
def pythonnet_decompile_method(
class_name: str,
method_name: str,
method_index: int = -1,
analysis_id: str = "default",
) -> dict:
"""Decompile a single method to C# source code.
Args:
class_name: Full class path (e.g. ``Namespace.ClassName``).
method_name: Method name to decompile.
method_index: 0-based index to select among overloads. Omit (or pass
``-1``) for auto-selection; if multiple overloads exist
the response will list them with their indices.
analysis_id: Analysis session ID.
Returns:
``{"class": str, "method": str, "decompiled_code": str}``
"""
try:
ctx = _get_context(analysis_id)
t = ctx.get_type(class_name)
except (ValueError, KeyError) as e:
return {"error": str(e)}
method = _resolve_method(t, method_name, method_index)
if isinstance(method, dict):
return method
ctx._ensure_decompiler()
out = System.Activator.CreateInstance(StringBuilderDecompilerOutput)
ctx._decompiler.Decompile(method, out, ctx._decompilation_context)
logger.info(f"Decompiled {class_name}.{method_name}")
return {"class": class_name, "method": method_name, "decompiled_code": out.GetText()}
def pythonnet_decompile_all_classes(
skip_compiler_generated: bool = True,
analysis_id: str = "default",
) -> dict:
"""Decompile every class in the binary to C# source in one call.
Expensive but useful for handing the full codebase to an LLM for global
analysis. Classes that fail are collected in ``errors`` rather than
aborting the run.
Args:
skip_compiler_generated: Skip types whose name starts with ``<`` or
``$`` (compiler-generated noise). Default ``True``.
analysis_id: Analysis session ID.
Returns:
``{"count": int, "error_count": int, "classes": {name: src}, "errors": {name: msg}}``
"""
try:
ctx = _get_context(analysis_id)
except ValueError as e:
return {"error": str(e)}
ctx._ensure_decompiler()
classes: dict[str, str] = {}
errors: dict[str, str] = {}
for class_name, t in ctx._type_index.items():
if skip_compiler_generated:
name = str(t.Name)
if name.startswith("<") or name.startswith("$"):
continue
try:
out = System.Activator.CreateInstance(StringBuilderDecompilerOutput)
ctx._decompiler.Decompile(t, out, ctx._decompilation_context)
classes[class_name] = out.GetText()
except Exception as e:
errors[class_name] = str(e)
return {
"count": len(classes),
"error_count": len(errors),
"classes": classes,
"errors": errors,
}
def pythonnet_rename_class(
class_name: str,
new_name: str,
new_namespace: str = "",
analysis_id: str = "default",
) -> dict:
"""Rename a class and optionally its namespace (useful for deobfuscation).
Args:
class_name: Full class path to rename (e.g. ``OldNs.OldClass``).
new_name: New class name (without namespace).
new_namespace: If provided, also update the namespace.
analysis_id: Analysis session ID.
Returns:
``{"old_class_name": str, "new_class_name": str}``
"""
try:
ctx = _get_context(analysis_id)
t = ctx.get_type(class_name)
except (ValueError, KeyError) as e:
return {"error": str(e)}
t.Name = UTF8String(new_name)
if new_namespace:
t.Namespace = UTF8String(new_namespace)
# Recompute full name the same way the index was built
new_full_name = str(t)
ctx._type_index[new_full_name] = ctx._type_index.pop(class_name)
logger.info(f"Renamed class {class_name} -> {new_full_name}")
return {"old_class_name": class_name, "new_class_name": new_full_name}
def pythonnet_rename_method(
class_name: str,
method_name: str,
new_method_name: str,
method_index: int = -1,
analysis_id: str = "default",
) -> dict:
"""Rename a method (useful for deobfuscation).
Args:
class_name: Full class path containing the method.
method_name: Current method name.
new_method_name: New method name.
method_index: 0-based index to select among overloads (default ``-1`` = auto).
analysis_id: Analysis session ID.
Returns:
``{"class": str, "old_method_name": str, "new_method_name": str}``
"""
try:
ctx = _get_context(analysis_id)
t = ctx.get_type(class_name)
except (ValueError, KeyError) as e:
return {"error": str(e)}
method = _resolve_method(t, method_name, method_index)
if isinstance(method, dict):
return method
method.Name = UTF8String(new_method_name)
logger.info(f"Renamed method {class_name}.{method_name} -> {new_method_name}")
return {"class": class_name, "old_method_name": method_name, "new_method_name": new_method_name}
def pythonnet_rename_field(
class_name: str,
field_name: str,
new_field_name: str,
analysis_id: str = "default",
) -> dict:
"""Rename a field (useful for deobfuscation).
Args:
class_name: Full class path containing the field.
field_name: Current field name.
new_field_name: New field name.
analysis_id: Analysis session ID.
Returns:
``{"class": str, "old_field_name": str, "new_field_name": str}``
"""
try:
ctx = _get_context(analysis_id)
t = ctx.get_type(class_name)
except (ValueError, KeyError) as e:
return {"error": str(e)}
field = next((f for f in t.Fields if f.Name == field_name), None)
if field is None:
return {"error": f"Field not found: {class_name}.{field_name}"}
field.Name = UTF8String(new_field_name)
logger.info(f"Renamed field {class_name}.{field_name} -> {new_field_name}")
return {"class": class_name, "old_field_name": field_name, "new_field_name": new_field_name}
def pythonnet_save_binary(analysis_id: str = "default") -> dict:
"""Save the (possibly modified) module to disk.
Must be called after any rename/patch operation to persist changes.
Always saves to the project directory as ``{original_stem}_patched{ext}``
(e.g. ``/data/pythonnet_projects/{analysis_id}/malware_patched.dll``).
Args:
analysis_id: Analysis session ID.
Returns:
``{"output_path": str, "project_dir": str, "status": "saved", "download_url": str}``
"""
try:
ctx = _get_context(analysis_id)
except ValueError as e:
return {"error": str(e)}
entry = _pythonnet_contexts[analysis_id]
project_dir: Path = entry.get("project_dir", PYTHONNET_PROJECTS_DIR / analysis_id)
project_dir.mkdir(parents=True, exist_ok=True)
original_name = entry.get("original_name") or Path(str(ctx.binary_path)).name
stem = Path(original_name).stem
suffix = Path(original_name).suffix
output_path = str(project_dir / f"{stem}_patched{suffix}")
try:
ctx.module.Write(output_path)
logger.info(f"Saved binary to {output_path}")
return {
"output_path": output_path,
"project_dir": str(project_dir),
"status": "saved",
"download_url": f"/download?path={output_path}",
}
except Exception as e:
logger.error(f"Error saving binary: {e}", exc_info=True)
return {"error": str(e)}
def pythonnet_get_strings(
limit: int = 0,
analysis_id: str = "default",
) -> dict:
"""List all unique string literals (``ldstr``) across all method bodies.
Args:
limit: Maximum number of strings to return (0 = unlimited).
analysis_id: Analysis session ID.
Returns:
``{"count": int, "strings": [str, …]}``
"""
try:
ctx = _get_context(analysis_id)
except ValueError as e:
return {"error": str(e)}
seen: dict[str, None] = {}
for t in ctx._type_index.values():
for method in t.Methods:
if not method.HasBody:
continue
for instr in method.Body.Instructions:
if instr.OpCode == OpCodes.Ldstr and instr.Operand is not None:
seen[str(instr.Operand)] = None
strings = list(seen)
if limit:
strings = strings[:limit]
return {"count": len(strings), "strings": strings}
def pythonnet_search_string(
query: str,
case_sensitive: bool = False,
analysis_id: str = "default",
) -> dict:
"""Find all methods that reference a given string literal.
Inverse of ``pythonnet_get_strings``: start from a suspicious string and
trace back to the code that uses it.
Args:
query: String (or partial string) to search for.
case_sensitive: Case-sensitive match (default ``False``).
analysis_id: Analysis session ID.
Returns:
``{"query": str, "count": int, "matches": [{"class", "method", "string"}, …]}``
"""
try:
ctx = _get_context(analysis_id)
except ValueError as e:
return {"error": str(e)}
needle = query if case_sensitive else query.lower()
matches = []
for class_name, t in ctx._type_index.items():
for method in t.Methods:
if not method.HasBody:
continue
for instr in method.Body.Instructions:
if instr.OpCode != OpCodes.Ldstr or instr.Operand is None:
continue
value = str(instr.Operand)
haystack = value if case_sensitive else value.lower()
if needle in haystack:
matches.append({
"class": class_name,
"method": str(method.Name),
"string": value,
})
break # one hit per method is enough
return {"query": query, "count": len(matches), "matches": matches}
def pythonnet_search_method_by_name(
query: str,
case_sensitive: bool = False,
analysis_id: str = "default",
) -> dict:
"""Search for methods by partial name across all classes.
Useful when code is obfuscated but partial names remain
(e.g. searching ``"decrypt"`` or ``"http"``).
Args:
query: Partial method name to search for.
case_sensitive: Case-sensitive match (default ``False``).
analysis_id: Analysis session ID.
Returns:
``{"query": str, "count": int, "matches": [{"class", "method", "has_body"}, …]}``
"""
try:
ctx = _get_context(analysis_id)
except ValueError as e:
return {"error": str(e)}
needle = query if case_sensitive else query.lower()
matches = []
for class_name, t in ctx._type_index.items():
for method in t.Methods:
name = str(method.Name)
haystack = name if case_sensitive else name.lower()
if needle in haystack:
matches.append({
"class": class_name,
"method": name,
"has_body": bool(method.HasBody),
})
return {"query": query, "count": len(matches), "matches": matches}
def pythonnet_get_imports(analysis_id: str = "default") -> dict:
"""List all external assemblies and types referenced by the binary.
Useful for quick orientation: ``System.Net.WebClient`` → network activity,
``System.Security.Cryptography`` → crypto, etc.
Args:
analysis_id: Analysis session ID.
Returns:
``{"assembly_refs": [str], "imports_by_assembly": {assembly: [type, …]}}``
"""
try:
ctx = _get_context(analysis_id)
except ValueError as e:
return {"error": str(e)}
assembly_refs = [str(a) for a in ctx.module.GetAssemblyRefs()]
imports_by_assembly: dict[str, list[str]] = {}
for type_ref in ctx.module.GetTypeRefs():
scope = str(type_ref.Scope) if type_ref.Scope is not None else "<unknown>"
full_name = str(type_ref)
bucket = imports_by_assembly.setdefault(scope, [])
if full_name not in bucket:
bucket.append(full_name)
return {"assembly_refs": assembly_refs, "imports_by_assembly": imports_by_assembly}
def pythonnet_get_fields(class_name: str, analysis_id: str = "default") -> dict:
"""List all fields of a class with their types and visibility.
Essential for understanding the layout of obfuscated classes.
Args:
class_name: Full class path (e.g. ``Namespace.ClassName``).
analysis_id: Analysis session ID.
Returns:
``{"class": str, "count": int, "fields": [{"name", "type", "static", "visibility"}, …]}``
"""
try:
ctx = _get_context(analysis_id)
t = ctx.get_type(class_name)
except (ValueError, KeyError) as e:
return {"error": str(e)}
fields = []
for f in t.Fields:
fields.append({
"name": str(f.Name),
"type": str(f.FieldType),
"static": bool(f.IsStatic),
"visibility": (
"public" if f.IsPublic else
"private" if f.IsPrivate else
"protected" if f.IsFamily else
"internal" if f.IsAssembly else
"other"
),
})
return {"class": class_name, "count": len(fields), "fields": fields}
def pythonnet_get_custom_attributes(
class_name: str,
method_name: str = "",
method_index: int = -1,
analysis_id: str = "default",
) -> dict:
"""Read custom attributes on a class or one of its methods.
Revealing in .NET malware: C2 frameworks (Covenant ``[Task]``),
obfuscators, and packers all leave characteristic attributes
(``[Obfuscation]``, ``[UnmanagedFunctionPointer]``, etc.).
Args:
class_name: Full class path (e.g. ``Namespace.ClassName``).
method_name: If provided, read attributes on this method instead of the class.
method_index: 0-based index to select among overloads (default ``-1`` = auto).
analysis_id: Analysis session ID.
Returns:
``{"target": str, "count": int, "attributes": [{"attribute", "constructor_args", "named_args"}, …]}``
"""
try:
ctx = _get_context(analysis_id)
t = ctx.get_type(class_name)
except (ValueError, KeyError) as e:
return {"error": str(e)}
if method_name:
target_obj = _resolve_method(t, method_name, method_index)
if isinstance(target_obj, dict):
return target_obj
target_label = f"{class_name}.{method_name}"
attr_collection = target_obj.CustomAttributes
else:
target_label = class_name
attr_collection = t.CustomAttributes
attributes = []
for attr in attr_collection:
attributes.append({
"attribute": str(attr.AttributeType),
"constructor_args": [
{"type": str(a.Type), "value": str(a.Value)}
for a in attr.ConstructorArguments
],
"named_args": [
{"name": str(a.Name), "type": str(a.Type), "value": str(a.Value)}
for a in attr.NamedArguments
],
})
return {"target": target_label, "count": len(attributes), "attributes": attributes}
def pythonnet_get_opcodes(
class_name: str,
method_name: str,
method_index: int = -1,
analysis_id: str = "default",
) -> dict:
"""Dump the raw IL instructions of a method.
Useful when C# decompilation fails or produces misleading output — IL is
always the ground truth.
Args:
class_name: Full class path (e.g. ``Namespace.ClassName``).
method_name: Method to inspect.
method_index: 0-based index to select among overloads (default ``-1`` = auto).
analysis_id: Analysis session ID.
Returns:
``{"class": str, "method": str, "count": int, "instructions": [{"offset", "opcode", "operand"}, …]}``
"""
try:
ctx = _get_context(analysis_id)
t = ctx.get_type(class_name)
except (ValueError, KeyError) as e:
return {"error": str(e)}
method = _resolve_method(t, method_name, method_index)
if isinstance(method, dict):
return method
if not method.HasBody:
return {"error": f"Method has no body: {class_name}.{method_name}"}
instructions = [
{
"offset": f"IL_{instr.Offset:04X}",
"opcode": str(instr.OpCode.Name),
"operand": str(instr.Operand) if instr.Operand is not None else None,
}
for instr in method.Body.Instructions
]
return {
"class": class_name,
"method": method_name,
"count": len(instructions),
"instructions": instructions,
}
def pythonnet_get_method_calls(
class_name: str,
method_name: str,
method_index: int = -1,
analysis_id: str = "default",
) -> dict:
"""List all outgoing calls from a method (``call``/``callvirt`` instructions).
Allows building a call graph without decompiling. Each entry includes the
target's full dnlib name and whether the dispatch is virtual.
Args:
class_name: Full class path containing the method.
method_name: Method to inspect.
method_index: 0-based index to select among overloads (default ``-1`` = auto).
analysis_id: Analysis session ID.
Returns:
``{"class": str, "method": str, "count": int, "calls": [{"callee", "virtual"}, …]}``
"""
try:
ctx = _get_context(analysis_id)
t = ctx.get_type(class_name)
except (ValueError, KeyError) as e:
return {"error": str(e)}
method = _resolve_method(t, method_name, method_index)
if isinstance(method, dict):
return method
if not method.HasBody:
return {"error": f"Method has no body: {class_name}.{method_name}"}
callvirt = str(OpCodes.Callvirt)
calls = [
{
"callee": str(instr.Operand),
"virtual": str(instr.OpCode) == callvirt,
}
for instr in method.Body.Instructions
if str(instr.OpCode) in _CALL_OPCODES and instr.Operand is not None
]
return {"class": class_name, "method": method_name, "count": len(calls), "calls": calls}
def pythonnet_get_callers(
class_name: str,
method_name: str,
analysis_id: str = "default",
) -> dict:
"""Find all methods that call a given method (reverse call graph).
Scans every method body for ``call``/``callvirt`` instructions targeting
the specified method.
Args:
class_name: Full class path of the target method.
method_name: Target method name.
analysis_id: Analysis session ID.
Returns:
``{"target": str, "count": int, "callers": [{"class", "method"}, …]}``
"""
try:
ctx = _get_context(analysis_id)
t = ctx.get_type(class_name)
except (ValueError, KeyError) as e:
return {"error": str(e)}