-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
executable file
·1245 lines (1041 loc) · 49.1 KB
/
server.py
File metadata and controls
executable file
·1245 lines (1041 loc) · 49.1 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
#!/usr/bin/env python3
"""
Memory Forensics MCP Server
Provides memory analysis capabilities via Volatility 3 through the MCP protocol.
Works with any MCP client (Claude Code, Claude Desktop, custom clients, etc.)
"""
import asyncio
import logging
from pathlib import Path
from typing import Any, Optional
import zipfile
import tempfile
import shutil
from datetime import datetime
from mcp.server.models import InitializationOptions
from mcp.server import NotificationOptions, Server
from mcp.server.stdio import stdio_server
from mcp.types import (
Resource,
Tool,
TextContent,
ImageContent,
EmbeddedResource,
LoggingLevel
)
from database import ForensicsDatabase
from volatility_handler import VolatilityHandler
from provenance import ProvenanceTracker
from hashing import get_or_calculate_hashes, format_hashes
from exporters import DataExporter
from timeline import TimelineGenerator
from anomaly_detector import AnomalyDetector
from extractors import create_extractor
from validation import DataValidator
from cleanup import (
ManagedExtraction, cleanup_old_extractions, cleanup_all_extractions,
get_disk_usage, list_extractions
)
from config import (
DB_PATH, DUMPS_DIR, EXPORT_DIR, EXTRACTED_FILES_DIR, EXTRACTION_DIR,
LLM_PROFILE, CURRENT_PROFILE_SETTINGS,
EXTRACTION_RETENTION_HOURS, AUTO_CLEANUP_ON_STARTUP, DATA_DIR
)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("memory-forensics-mcp")
logger.info(f"LLM Profile: {LLM_PROFILE}")
logger.info(f"Output format: {CURRENT_PROFILE_SETTINGS.get('format')}")
# Global database instance
db = ForensicsDatabase(DB_PATH)
# Global provenance tracker
provenance_tracker = ProvenanceTracker(db)
# Cache for VolatilityHandler instances
vol_handlers = {}
def get_dump_id(file_path: str) -> str:
"""Generate dump ID from filename"""
return Path(file_path).stem
def extract_dump_if_needed(dump_path: Path) -> Path:
"""Extract memory dump from zip if necessary"""
if dump_path.suffix.lower() == '.zip':
logger.info(f"Extracting {dump_path.name}...")
# Use persistent extraction directory instead of tmpfs
import time
dump_id = get_dump_id(str(dump_path))
timestamp = int(time.time())
temp_dir = EXTRACTION_DIR / f"memdump_{dump_id}_{timestamp}"
temp_dir.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(dump_path, 'r') as zip_ref:
# Extract all files
zip_ref.extractall(temp_dir)
# Find the actual memory dump file (usually .raw, .mem, .dmp, .vmem)
for ext in ['.raw', '.mem', '.dmp', '.vmem', '.bin']:
extracted_files = list(temp_dir.rglob(f'*{ext}'))
if extracted_files:
logger.info(f"Extracted to: {extracted_files[0]}")
return extracted_files[0]
# If no specific extension, return first file
files = list(temp_dir.iterdir())
if files:
logger.info(f"Extracted to: {files[0]}")
return files[0]
raise ValueError(f"No memory dump found in {dump_path}")
return dump_path
def get_volatility_handler(dump_id: str) -> Optional[VolatilityHandler]:
"""Get or create VolatilityHandler for a dump"""
if dump_id in vol_handlers:
return vol_handlers[dump_id]
# Find the dump file
for dump_file in DUMPS_DIR.iterdir():
if get_dump_id(str(dump_file)) == dump_id:
# Extract if needed
actual_dump = extract_dump_if_needed(dump_file)
# Create handler with dump_id and provenance tracking
handler = VolatilityHandler(
dump_path=actual_dump,
dump_id=dump_id,
provenance_tracker=provenance_tracker
)
vol_handlers[dump_id] = handler
return handler
return None
def adapt_description(description: str) -> str:
"""Adapt tool description based on LLM profile"""
max_length = CURRENT_PROFILE_SETTINGS.get('max_description_length', 500)
if len(description) <= max_length:
return description
# Truncate and add ellipsis
return description[:max_length-3] + "..."
# Create the MCP server
server = Server("memory-forensics")
@server.list_resources()
async def handle_list_resources() -> list[Resource]:
"""List available memory dumps as resources"""
dumps = await db.list_dumps()
resources = []
for dump in dumps:
resources.append(Resource(
uri=f"memdump://{dump['dump_id']}",
name=f"Memory Dump: {dump['dump_id']}",
description=f"Memory dump from {dump['file_path']} ({dump.get('os_type', 'Unknown OS')})",
mimeType="application/x-memory-dump"
))
return resources
@server.list_tools()
async def handle_list_tools() -> list[Tool]:
"""List available memory forensics tools"""
return [
Tool(
name="list_dumps",
description=adapt_description("List all available memory dumps for analysis"),
inputSchema={
"type": "object",
"properties": {},
"required": []
}
),
Tool(
name="process_dump",
description=adapt_description("Process a memory dump with Volatility 3 and extract artifacts (processes, network, etc.)"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump to process (from list_dumps)"
}
},
"required": ["dump_id"]
}
),
Tool(
name="list_processes",
description=adapt_description("List all processes from a memory dump"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
},
"suspicious_only": {
"type": "boolean",
"description": "Only show suspicious processes",
"default": False
}
},
"required": ["dump_id"]
}
),
Tool(
name="analyze_process",
description=adapt_description("Get detailed information about a specific process (command line, DLLs, network connections)"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
},
"pid": {
"type": "integer",
"description": "Process ID to analyze"
}
},
"required": ["dump_id", "pid"]
}
),
Tool(
name="detect_code_injection",
description=adapt_description("Detect potential code injection using malfind (unbacked executable memory regions)"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
},
"pid": {
"type": "integer",
"description": "Optional: only check specific process",
"default": None
}
},
"required": ["dump_id"]
}
),
Tool(
name="network_analysis",
description=adapt_description("Analyze network connections and correlate with processes"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
},
"remote_ip": {
"type": "string",
"description": "Optional: filter by remote IP address"
}
},
"required": ["dump_id"]
}
),
Tool(
name="detect_hidden_processes",
description=adapt_description("Find hidden processes by comparing psscan and pslist"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
}
},
"required": ["dump_id"]
}
),
Tool(
name="get_process_tree",
description=adapt_description("Get hierarchical process tree showing parent-child relationships"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
}
},
"required": ["dump_id"]
}
),
Tool(
name="get_dump_metadata",
description=adapt_description("Get detailed metadata about a memory dump including hashes, OS info, and processing statistics"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
}
},
"required": ["dump_id"]
}
),
Tool(
name="export_data",
description=adapt_description("Export forensic data in JSON, CSV, or HTML format"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
},
"format": {
"type": "string",
"description": "Export format: 'json', 'csv', or 'html'",
"enum": ["json", "csv", "html"]
},
"data_type": {
"type": "string",
"description": "Type of data to export (for csv): 'processes', 'network', 'memory_regions', or 'all' (for json/html)",
"default": "all"
},
"output_filename": {
"type": "string",
"description": "Optional output filename (will be placed in exports directory)",
"default": None
}
},
"required": ["dump_id", "format"]
}
),
Tool(
name="get_command_history",
description=adapt_description("View all Volatility commands executed for a dump (provenance/audit trail)"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
},
"limit": {
"type": "integer",
"description": "Maximum number of commands to return",
"default": 50
}
},
"required": ["dump_id"]
}
),
Tool(
name="generate_timeline",
description=adapt_description("Generate chronological timeline of events from memory dump"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
},
"format": {
"type": "string",
"description": "Output format: 'summary' (display), 'json', 'csv', or 'text'",
"enum": ["summary", "json", "csv", "text"],
"default": "summary"
},
"suspicious_only": {
"type": "boolean",
"description": "Only include suspicious events",
"default": False
},
"output_filename": {
"type": "string",
"description": "Optional output filename for file exports",
"default": None
}
},
"required": ["dump_id"]
}
),
Tool(
name="detect_anomalies",
description=adapt_description("Detect suspicious process behavior (wrong parents, typosquatting, unusual paths)"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
}
},
"required": ["dump_id"]
}
),
Tool(
name="health_check",
description=adapt_description("Check data integrity and consistency for a processed memory dump"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump to validate"
}
},
"required": ["dump_id"]
}
),
Tool(
name="extract_process",
description=adapt_description("Extract detailed process information to JSON file"),
inputSchema={
"type": "object",
"properties": {
"dump_id": {
"type": "string",
"description": "ID of the memory dump"
},
"pid": {
"type": "integer",
"description": "Process ID to extract"
}
},
"required": ["dump_id", "pid"]
}
),
Tool(
name="cleanup_extractions",
description=adapt_description("Clean up old memory dump extractions to free disk space"),
inputSchema={
"type": "object",
"properties": {
"mode": {
"type": "string",
"description": "Cleanup mode: 'old' (remove extractions older than retention period), 'all' (remove all), 'list' (show extractions)",
"enum": ["old", "all", "list"],
"default": "old"
},
"dry_run": {
"type": "boolean",
"description": "If true, show what would be removed without actually deleting",
"default": False
}
},
"required": []
}
),
Tool(
name="get_disk_usage",
description=adapt_description("Get disk space usage statistics for the MCP server (database, exports, extractions)"),
inputSchema={
"type": "object",
"properties": {},
"required": []
}
)
]
@server.call_tool()
async def handle_call_tool(name: str, arguments: dict) -> list[TextContent]:
"""Handle tool execution"""
try:
if name == "list_dumps":
# Check for available dumps in the dumps directory
available_dumps = []
for dump_file in DUMPS_DIR.iterdir():
if dump_file.is_file() and dump_file.suffix in ['.zip', '.raw', '.mem', '.dmp', '.vmem']:
dump_id = get_dump_id(str(dump_file))
file_size = dump_file.stat().st_size
# Check if already in database
existing = await db.get_dump(dump_id)
if not existing:
# Register new dump
await db.add_dump(dump_id, str(dump_file), file_size)
available_dumps.append({
'dump_id': dump_id,
'file_name': dump_file.name,
'file_size_mb': round(file_size / (1024*1024), 2),
'status': existing.get('status', 'new') if existing else 'new'
})
result = f"Found {len(available_dumps)} memory dumps:\n\n"
for dump in available_dumps:
result += f"- **{dump['dump_id']}**\n"
result += f" File: {dump['file_name']}\n"
result += f" Size: {dump['file_size_mb']} MB\n"
result += f" Status: {dump['status']}\n\n"
return [TextContent(type="text", text=result)]
elif name == "process_dump":
dump_id = arguments["dump_id"]
logger.info(f"Processing dump: {dump_id}")
# Get Volatility handler
vol = get_volatility_handler(dump_id)
if not vol:
return [TextContent(type="text", text=f"Error: Dump '{dump_id}' not found")]
result = f"Processing memory dump: {dump_id}\n\n"
# Extract processes
result += "Extracting processes...\n"
processes = await vol.list_processes()
await db.add_processes(dump_id, processes)
result += f"[OK] Found {len(processes)} processes\n\n"
# Extract network connections
result += "Extracting network connections...\n"
connections = await vol.get_network_connections()
# Clear old network data before inserting to prevent duplicates on reprocessing
await db.clear_network_connections(dump_id)
await db.add_network_connections(dump_id, connections)
result += f"[OK] Found {len(connections)} network connections\n\n"
# Detect code injection
result += "Scanning for code injection...\n"
suspicious_regions = await vol.detect_malfind()
# Clear old memory region data before inserting to prevent duplicates on reprocessing
await db.clear_memory_regions(dump_id)
await db.add_memory_regions(dump_id, suspicious_regions)
result += f"[OK] Found {len(suspicious_regions)} suspicious memory regions\n\n"
# Detect hidden processes
result += "Detecting hidden processes...\n"
hidden_pids = await vol.detect_hidden_processes()
# Mark hidden processes in database
if hidden_pids:
for pid in hidden_pids:
proc = await db.get_process_by_pid(dump_id, pid)
if proc:
proc['is_hidden'] = True
proc['is_suspicious'] = True
await db.add_processes(dump_id, [proc])
result += f"[OK] Found {len(hidden_pids)} hidden processes: {hidden_pids}\n\n"
else:
result += "[OK] No hidden processes detected\n\n"
# Update dump status
dump = await db.get_dump(dump_id)
if dump:
await db.add_dump(dump_id, dump['file_path'], dump['file_size'], dump.get('os_type'))
# Validate data integrity
result += "Validating data integrity...\n"
validator = DataValidator(db)
# Compare Volatility results with database
db_processes = await db.get_processes(dump_id)
db_connections = await db.get_network_connections(dump_id)
validation_warnings = await validator.compare_volatility_to_database(
dump_id,
{
'processes': len(processes),
'network_connections': len(connections),
'suspicious_memory_regions': len(suspicious_regions)
},
{
'processes': len(db_processes),
'network_connections': len(db_connections),
'suspicious_memory_regions': len(suspicious_regions)
}
)
if validation_warnings:
result += "\n**Data Integrity Warnings:**\n"
for warning in validation_warnings:
result += f"- WARNING: {warning}\n"
logger.warning(f"[{dump_id}] {warning}")
else:
result += "[OK] All data validated successfully\n"
result += "\n**Processing complete!** You can now use other tools to analyze the extracted data."
return [TextContent(type="text", text=result)]
elif name == "list_processes":
dump_id = arguments["dump_id"]
suspicious_only = arguments.get("suspicious_only", False)
processes = await db.get_processes(dump_id, suspicious_only)
if not processes:
return [TextContent(type="text", text=f"No processes found. Run 'process_dump' first for dump: {dump_id}")]
result = f"**Processes in {dump_id}**"
if suspicious_only:
result += " (suspicious only)"
result += f"\n\nTotal: {len(processes)} processes\n\n"
# Format as table
result += "| PID | PPID | Name | Created | Flags |\n"
result += "|-----|------|------|---------|-------|\n"
for proc in processes:
flags = []
if proc.get('is_hidden'):
flags.append('HIDDEN')
if proc.get('is_suspicious'):
flags.append('SUSPICIOUS')
flag_str = ', '.join(flags) if flags else '-'
result += f"| {proc['pid']} | {proc.get('ppid', '-')} | {proc.get('name', 'N/A')} | {proc.get('create_time', 'N/A')[:19]} | {flag_str} |\n"
return [TextContent(type="text", text=result)]
elif name == "analyze_process":
dump_id = arguments["dump_id"]
pid = arguments["pid"]
# Get process info
process = await db.get_process_by_pid(dump_id, pid)
if not process:
return [TextContent(type="text", text=f"Process {pid} not found in dump {dump_id}")]
result = f"**Process Analysis: PID {pid}**\n\n"
result += f"**Basic Information:**\n"
result += f"- Name: {process.get('name', 'N/A')}\n"
result += f"- Path: {process.get('path', 'N/A')}\n"
result += f"- Parent PID: {process.get('ppid', 'N/A')}\n"
result += f"- Created: {process.get('create_time', 'N/A')}\n"
if process.get('is_hidden'):
result += f"- [WARNING] **HIDDEN PROCESS** (not in standard process list)\n"
if process.get('is_suspicious'):
result += f"- [WARNING] **MARKED AS SUSPICIOUS**\n"
result += "\n"
# Get command line
vol = get_volatility_handler(dump_id)
if vol:
cmdlines = await vol.get_cmdline(pid)
if cmdlines:
result += f"**Command Line:**\n```\n{cmdlines[0].get('cmdline', 'N/A')}\n```\n\n"
# Get DLLs
result += "**Loaded DLLs:**\n"
dlls = await vol.get_dlls(pid)
if dlls:
for dll in dlls[:10]: # Show first 10
result += f"- {dll.get('name', 'N/A')} @ {dll.get('base_address', 'N/A')}\n"
if len(dlls) > 10:
result += f"- ... and {len(dlls) - 10} more\n"
else:
result += "- No DLLs found\n"
result += "\n"
# Get network connections
connections = await db.get_network_connections(dump_id, pid)
if connections:
result += f"**Network Connections ({len(connections)}):**\n"
for conn in connections:
result += f"- {conn.get('protocol', 'TCP')} {conn.get('local_addr')}:{conn.get('local_port')} → "
result += f"{conn.get('remote_addr')}:{conn.get('remote_port')} [{conn.get('state', 'N/A')}]\n"
result += "\n"
# Get suspicious memory regions
regions = await db.get_suspicious_memory_regions(dump_id, pid)
if regions:
result += f"**[WARNING] Suspicious Memory Regions ({len(regions)}):**\n"
for region in regions:
result += f"- Base: {region.get('base_address')} | Protection: {region.get('protection')} | "
result += f"Unbacked: {not region.get('is_file_backed')}\n"
result += "\n**This may indicate code injection!**\n"
return [TextContent(type="text", text=result)]
elif name == "detect_code_injection":
dump_id = arguments["dump_id"]
target_pid = arguments.get("pid")
# Get suspicious memory regions
regions = await db.get_suspicious_memory_regions(dump_id, target_pid)
if not regions:
return [TextContent(type="text", text="No code injection detected. All processes appear clean.")]
# Group by PID
by_pid = {}
for region in regions:
pid = region['pid']
if pid not in by_pid:
by_pid[pid] = []
by_pid[pid].append(region)
result = f"**Code Injection Detection Results**\n\n"
result += f"Found suspicious memory regions in {len(by_pid)} process(es):\n\n"
for pid, pid_regions in by_pid.items():
# Get process name
proc = await db.get_process_by_pid(dump_id, pid)
proc_name = proc.get('name', 'Unknown') if proc else 'Unknown'
result += f"**PID {pid} ({proc_name})** - {len(pid_regions)} suspicious region(s)\n"
for region in pid_regions:
result += f" - Base: {region.get('base_address')} | Protection: {region.get('protection')}\n"
result += "\n"
result += "**Recommendation:** Investigate these processes further. Unbacked executable memory often indicates:\n"
result += "- Process hollowing\n"
result += "- Reflective DLL injection\n"
result += "- Shellcode injection\n"
return [TextContent(type="text", text=result)]
elif name == "network_analysis":
dump_id = arguments["dump_id"]
remote_ip = arguments.get("remote_ip")
connections = await db.get_network_connections(dump_id)
if not connections:
return [TextContent(type="text", text="No network connections found.")]
# Filter by IP if specified
if remote_ip:
connections = [c for c in connections if c.get('remote_addr') == remote_ip]
if not connections:
return [TextContent(type="text", text=f"No connections found to {remote_ip}")]
result = f"**Network Analysis**\n\n"
result += f"Total connections: {len(connections)}\n\n"
# Group by process
by_pid = {}
for conn in connections:
pid = conn.get('pid')
if pid not in by_pid:
by_pid[pid] = []
by_pid[pid].append(conn)
for pid, pid_conns in sorted(by_pid.items(), key=lambda x: (x[0] is None, x[0] or 0)):
if pid:
proc = await db.get_process_by_pid(dump_id, pid)
proc_name = proc.get('name', 'Unknown') if proc else 'Unknown'
result += f"**PID {pid} ({proc_name})** - {len(pid_conns)} connection(s)\n"
else:
result += f"**Unknown PID** - {len(pid_conns)} connection(s)\n"
for conn in pid_conns:
result += f" - {conn.get('protocol', 'TCP')} {conn.get('local_addr')}:{conn.get('local_port')} → "
result += f"{conn.get('remote_addr')}:{conn.get('remote_port')} [{conn.get('state', 'N/A')}]\n"
result += "\n"
return [TextContent(type="text", text=result)]
elif name == "detect_hidden_processes":
dump_id = arguments["dump_id"]
vol = get_volatility_handler(dump_id)
if not vol:
return [TextContent(type="text", text=f"Error: Dump '{dump_id}' not found")]
hidden_pids = await vol.detect_hidden_processes()
if not hidden_pids:
return [TextContent(type="text", text="No hidden processes detected. All processes appear in the standard process list.")]
result = f"**[WARNING] Hidden Process Detection**\n\n"
result += f"Found {len(hidden_pids)} hidden process(es):\n\n"
for pid in hidden_pids:
proc = await db.get_process_by_pid(dump_id, pid)
if proc:
result += f"- PID {pid}: {proc.get('name', 'Unknown')}\n"
else:
result += f"- PID {pid}: (process details not available)\n"
result += "\n**Explanation:** These processes appear in memory scans but not in the standard process list, "
result += "which may indicate rootkit activity or process hiding techniques.\n"
return [TextContent(type="text", text=result)]
elif name == "get_process_tree":
dump_id = arguments["dump_id"]
processes = await db.get_processes(dump_id)
if not processes:
return [TextContent(type="text", text=f"No processes found. Run 'process_dump' first.")]
# Build process tree
proc_map = {p['pid']: p for p in processes}
children_map = {}
roots = []
for proc in processes:
ppid = proc.get('ppid')
if ppid and ppid in proc_map:
if ppid not in children_map:
children_map[ppid] = []
children_map[ppid].append(proc['pid'])
else:
roots.append(proc['pid'])
def format_tree(pid, indent=0):
proc = proc_map.get(pid)
if not proc:
return ""
prefix = " " * indent
flags = []
if proc.get('is_hidden'):
flags.append('HIDDEN')
if proc.get('is_suspicious'):
flags.append('SUSP')
flag_str = f" [{', '.join(flags)}]" if flags else ""
line = f"{prefix}├─ {pid}: {proc.get('name', 'N/A')}{flag_str}\n"
# Add children
if pid in children_map:
for child_pid in children_map[pid]:
line += format_tree(child_pid, indent + 1)
return line
result = f"**Process Tree for {dump_id}**\n\n```\n"
for root_pid in sorted(roots):
result += format_tree(root_pid)
result += "```\n"
return [TextContent(type="text", text=result)]
elif name == "get_dump_metadata":
dump_id = arguments["dump_id"]
# Get dump info
dump = await db.get_dump(dump_id)
if not dump:
return [TextContent(type="text", text=f"Dump '{dump_id}' not found")]
result = f"**Memory Dump Metadata**\n\n"
# File information
result += "**File Information:**\n"
result += f"- Dump ID: {dump_id}\n"
result += f"- File Path: {dump.get('file_path', 'N/A')}\n"
result += f"- File Size: {dump.get('file_size', 0) / (1024*1024):.2f} MB\n"
# Get or calculate hashes
dump_path = Path(dump['file_path'])
if dump_path.suffix == '.zip':
# For zip files, find the actual dump
dump_path = extract_dump_if_needed(dump_path)
hashes = await get_or_calculate_hashes(db, dump_id, dump_path)
result += "\n" + format_hashes(hashes)
# OS information
if dump.get('os_type'):
result += f"\n**Operating System:**\n"
result += f"- OS Type: {dump.get('os_type', 'Unknown')}\n"
# Processing status
result += f"\n**Processing Status:**\n"
result += f"- Status: {dump.get('status', 'new')}\n"
result += f"- Last Processed: {dump.get('last_processed', 'Never')}\n"
# Get command statistics
stats = await db.get_command_stats(dump_id)
if stats and stats.get('total_commands', 0) > 0:
result += f"- Commands Executed: {stats.get('total_commands', 0)}\n"
result += f"- Average Execution Time: {int(stats.get('avg_execution_time', 0))} ms\n"
# Count suspicious findings
processes = await db.get_processes(dump_id)
suspicious_procs = sum(1 for p in processes if p.get('is_suspicious'))
regions = await db.get_suspicious_memory_regions(dump_id)
if suspicious_procs > 0 or len(regions) > 0:
result += f"- Suspicious Findings: {suspicious_procs} processes, {len(regions)} memory regions\n"
return [TextContent(type="text", text=result)]
elif name == "export_data":
dump_id = arguments["dump_id"]
export_format = arguments["format"]
data_type = arguments.get("data_type", "all")
output_filename = arguments.get("output_filename")
# Generate filename if not provided
if not output_filename:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
if export_format == "csv":
output_filename = f"{dump_id}_{data_type}_{timestamp}.csv"
elif export_format == "json":
output_filename = f"{dump_id}_{timestamp}.json"
else: # html
output_filename = f"{dump_id}_report_{timestamp}.html"
output_path = EXPORT_DIR / output_filename
# Create exporter
exporter = DataExporter(db)
# Export data
try:
if export_format == "json":
data_types = [data_type] if data_type != "all" else ["processes", "network", "memory_regions"]
stats = await exporter.export_json(dump_id, output_path, data_types=data_types)
elif export_format == "csv":
if data_type == "all":
return [TextContent(type="text", text="Error: CSV format requires a specific data_type (processes, network, or memory_regions)")]
stats = await exporter.export_csv(dump_id, data_type, output_path)
elif export_format == "html":
stats = await exporter.export_html(dump_id, output_path)
else:
return [TextContent(type="text", text=f"Unknown format: {export_format}")]
result = f"**Data Export Complete**\n\n"
result += f"Format: {stats['format']}\n"
result += f"Output: {stats['output_path']}\n"
result += f"Size: {stats.get('file_size', 0) / 1024:.2f} KB\n"
if 'total_records' in stats:
result += f"Records: {stats['total_records']}\n"
return [TextContent(type="text", text=result)]
except Exception as e:
logger.error(f"Export failed: {e}", exc_info=True)
return [TextContent(type="text", text=f"Export failed: {str(e)}")]
elif name == "get_command_history":
dump_id = arguments["dump_id"]
limit = arguments.get("limit", 50)
# Get provenance summary
summary = await provenance_tracker.get_provenance_summary(dump_id)
return [TextContent(type="text", text=summary)]
elif name == "generate_timeline":
dump_id = arguments["dump_id"]
format_type = arguments.get("format", "summary")
suspicious_only = arguments.get("suspicious_only", False)
output_filename = arguments.get("output_filename")
# Create timeline generator
timeline_gen = TimelineGenerator(db)
if format_type == "summary":
# Display summary
summary = await timeline_gen.get_timeline_summary(dump_id)
return [TextContent(type="text", text=summary)]
else:
# Export to file
if not output_filename:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_filename = f"{dump_id}_timeline_{timestamp}.{format_type}"
output_path = EXPORT_DIR / output_filename
try:
if format_type == "json":
stats = await timeline_gen.export_timeline_json(
dump_id, output_path, suspicious_only=suspicious_only
)
elif format_type == "csv":
stats = await timeline_gen.export_timeline_csv(
dump_id, output_path, suspicious_only=suspicious_only
)
elif format_type == "text":
stats = await timeline_gen.export_timeline_text(
dump_id, output_path, suspicious_only=suspicious_only
)
else:
return [TextContent(type="text", text=f"Unknown format: {format_type}")]
result = f"**Timeline Export Complete**\n\n"
result += f"Format: {stats['format']}\n"
result += f"Output: {stats['output_path']}\n"
result += f"Events: {stats['event_count']}\n"
result += f"Size: {stats.get('file_size', 0) / 1024:.2f} KB\n"
return [TextContent(type="text", text=result)]
except Exception as e:
logger.error(f"Timeline export failed: {e}", exc_info=True)
return [TextContent(type="text", text=f"Timeline export failed: {str(e)}")]
elif name == "detect_anomalies":
dump_id = arguments["dump_id"]
# Create anomaly detector
detector = AnomalyDetector(db)
# Detect anomalies (returns list of anomaly dicts)
anomalies = await detector.detect_anomalies(dump_id)
# Extract PIDs of suspicious processes and persist to database
suspicious_pids = set()