-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathMetasploitMCP.py
More file actions
1773 lines (1551 loc) · 86.1 KB
/
MetasploitMCP.py
File metadata and controls
1773 lines (1551 loc) · 86.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
# -*- coding: utf-8 -*-
import asyncio
import base64
import contextlib
import logging
import os
import pathlib
import re
import shlex
import socket
import subprocess
import sys
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple, Union
# --- Third-party Libraries ---
import uvicorn
from fastapi import FastAPI, HTTPException, Request, Response
from mcp.server.fastmcp import FastMCP
from mcp.server.sse import SseServerTransport
from pymetasploit3.msfrpc import MsfConsole, MsfRpcClient, MsfRpcError
from starlette.applications import Starlette
from starlette.routing import Mount, Route, Router
# --- Configuration & Constants ---
# Metasploit Connection Config (from environment variables)
MSF_PASSWORD = os.getenv('MSF_PASSWORD', 'yourpassword')
MSF_SERVER = os.getenv('MSF_SERVER', '127.0.0.1')
MSF_PORT_STR = os.getenv('MSF_PORT', '55553')
MSF_SSL_STR = os.getenv('MSF_SSL', 'false')
PAYLOAD_SAVE_DIR = os.getenv('PAYLOAD_SAVE_DIR', str(pathlib.Path.home() / "payloads"))
LOG_LEVEL = os.getenv('LOG_LEVEL', 'info')
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
)
logger = logging.getLogger("metasploit_mcp_server")
logger.setLevel(LOG_LEVEL.upper())
logger.debug(f"MSF_PASSWORD : {MSF_PASSWORD}")
logger.debug(f"MSF_SERVER : {MSF_SERVER}")
logger.debug(f"MSF_PORT_STR : {MSF_PORT_STR}")
logger.debug(f"MSF_SSL_STR : {MSF_SSL_STR}")
logger.debug(f"PAYLOAD_SAVE_DIR: {PAYLOAD_SAVE_DIR}")
logger.debug(f"LOG_LEVEL : {LOG_LEVEL}")
session_shell_type: Dict[str, str] = {}
# Timeouts and Polling Intervals (in seconds)
DEFAULT_CONSOLE_READ_TIMEOUT = 15 # Default for quick console commands
LONG_CONSOLE_READ_TIMEOUT = 60 # For commands like run/exploit/check
SESSION_COMMAND_TIMEOUT = 60 # Default for commands within sessions
SESSION_READ_INACTIVITY_TIMEOUT = 10 # Timeout if no data from session
EXPLOIT_SESSION_POLL_TIMEOUT = 60 # Max time to wait for session after exploit job
EXPLOIT_SESSION_POLL_INTERVAL = 2 # How often to check for session
RPC_CALL_TIMEOUT = 30 # Default timeout for RPC calls like listing modules
# Regular Expressions for Prompt Detection
MSF_PROMPT_RE = re.compile(rb'\x01\x02msf\d+\x01\x02 \x01\x02> \x01\x02') # Matches the msf6 > prompt with control chars
SHELL_PROMPT_RE = re.compile(r'([#$>]|%)\s*$') # Matches common shell prompts (#, $, >, %) at end of line
# --- Metasploit Client Setup ---
_msf_client_instance: Optional[MsfRpcClient] = None
def initialize_msf_client() -> MsfRpcClient:
"""
Initializes the global Metasploit RPC client instance.
Raises exceptions on failure.
"""
global _msf_client_instance
if _msf_client_instance is not None:
return _msf_client_instance
logger.info("Attempting to initialize Metasploit RPC client...")
try:
msf_port = int(MSF_PORT_STR)
msf_ssl = MSF_SSL_STR.lower() == 'true'
except ValueError as e:
logger.error(f"Invalid MSF connection parameters (PORT: {MSF_PORT_STR}, SSL: {MSF_SSL_STR}). Error: {e}")
raise ValueError("Invalid MSF connection parameters") from e
try:
logger.debug(f"Attempting to create MsfRpcClient connection to {MSF_SERVER}:{msf_port} (SSL: {msf_ssl})...")
client = MsfRpcClient(
password=MSF_PASSWORD,
server=MSF_SERVER,
port=msf_port,
ssl=msf_ssl
)
# Test connection during initialization
logger.debug("Testing connection with core.version call...")
version_info = client.core.version
msf_version = version_info.get('version', 'unknown') if isinstance(version_info, dict) else 'unknown'
logger.info(f"Successfully connected to Metasploit RPC at {MSF_SERVER}:{msf_port} (SSL: {msf_ssl}), version: {msf_version}")
_msf_client_instance = client
return _msf_client_instance
except MsfRpcError as e:
logger.error(f"Failed to connect or authenticate to Metasploit RPC ({MSF_SERVER}:{msf_port}, SSL: {msf_ssl}): {e}")
raise ConnectionError(f"Failed to connect/authenticate to Metasploit RPC: {e}") from e
except Exception as e:
logger.error(f"An unexpected error occurred during MSF client initialization: {e}", exc_info=True)
raise RuntimeError(f"Unexpected error initializing MSF client: {e}") from e
def get_msf_client() -> MsfRpcClient:
"""Gets the initialized MSF client instance, raising an error if not ready."""
if _msf_client_instance is None:
logger.error("Metasploit client has not been initialized. Check MSF server connection.")
raise ConnectionError("Metasploit client has not been initialized.") # Strict check preferred
logger.debug("Retrieved MSF client instance successfully.")
return _msf_client_instance
async def check_msf_connection() -> Dict[str, Any]:
"""
Check the current status of the Metasploit RPC connection.
Returns connection status information for debugging.
"""
try:
client = get_msf_client()
logger.debug(f"Testing MSF connection with {RPC_CALL_TIMEOUT}s timeout...")
version_info = await asyncio.wait_for(
asyncio.to_thread(lambda: client.core.version),
timeout=RPC_CALL_TIMEOUT
)
msf_version = version_info.get('version', 'N/A') if isinstance(version_info, dict) else 'N/A'
return {
"status": "connected",
"server": f"{MSF_SERVER}:{MSF_PORT_STR}",
"ssl": MSF_SSL_STR,
"version": msf_version,
"message": "Connection to Metasploit RPC is healthy"
}
except asyncio.TimeoutError:
return {
"status": "timeout",
"server": f"{MSF_SERVER}:{MSF_PORT_STR}",
"ssl": MSF_SSL_STR,
"timeout_seconds": RPC_CALL_TIMEOUT,
"message": f"Metasploit server not responding within {RPC_CALL_TIMEOUT}s timeout"
}
except ConnectionError as e:
return {
"status": "not_initialized",
"server": f"{MSF_SERVER}:{MSF_PORT_STR}",
"ssl": MSF_SSL_STR,
"message": f"Metasploit client not initialized: {e}"
}
except MsfRpcError as e:
return {
"status": "rpc_error",
"server": f"{MSF_SERVER}:{MSF_PORT_STR}",
"ssl": MSF_SSL_STR,
"message": f"Metasploit RPC error: {e}"
}
except Exception as e:
return {
"status": "error",
"server": f"{MSF_SERVER}:{MSF_PORT_STR}",
"ssl": MSF_SSL_STR,
"message": f"Unexpected error: {e}"
}
@contextlib.asynccontextmanager
async def get_msf_console() -> MsfConsole:
"""
Async context manager for creating and reliably destroying an MSF console.
"""
client = get_msf_client() # Raises ConnectionError if not initialized
console_object: Optional[MsfConsole] = None
console_id_str: Optional[str] = None
try:
logger.debug("Creating temporary MSF console...")
# Create console object directly
console_object = await asyncio.to_thread(lambda: client.consoles.console())
# Get ID using .cid attribute
if isinstance(console_object, MsfConsole) and hasattr(console_object, 'cid'):
console_id_val = getattr(console_object, 'cid')
console_id_str = str(console_id_val) if console_id_val is not None else None
if not console_id_str:
raise ValueError("Console object created, but .cid attribute is empty or None.")
logger.info(f"MSF console created (ID: {console_id_str})")
# Read initial prompt/banner to clear buffer and ensure readiness
await asyncio.sleep(0.2) # Short delay for prompt to appear
initial_read = await asyncio.to_thread(lambda: console_object.read())
logger.debug(f"Initial console read (clearing buffer): {initial_read}")
yield console_object # Yield the ready console object
else:
# This case should ideally not happen if .console() works as expected
logger.error(f"client.consoles.console() did not return expected MsfConsole object with .cid. Got type: {type(console_object)}")
raise MsfRpcError(f"Unexpected result from console creation: {console_object}")
except MsfRpcError as e:
logger.error(f"MsfRpcError during console operation: {e}")
raise MsfRpcError(f"Error creating/accessing MSF console: {e}") from e
except Exception as e:
logger.exception("Unexpected error during console creation/setup")
raise RuntimeError(f"Unexpected error during console operation: {e}") from e
finally:
# Destruction Logic
if console_id_str and _msf_client_instance: # Check client still exists
try:
logger.info(f"Attempting to destroy Metasploit console (ID: {console_id_str})...")
# Use lambda to avoid potential issues with capture
destroy_result = await asyncio.to_thread(
lambda cid=console_id_str: _msf_client_instance.consoles.destroy(cid)
)
logger.debug(f"Console destroy result: {destroy_result}")
except Exception as e:
# Log error but don't raise exception during cleanup
logger.error(f"Error destroying MSF console {console_id_str}: {e}")
elif console_object and not console_id_str:
logger.warning("Console object created but no valid ID obtained, cannot explicitly destroy.")
# else: logger.debug("No console ID obtained, skipping destruction.")
async def run_command_safely(console: MsfConsole, cmd: str, execution_timeout: Optional[int] = None) -> str:
"""
Safely run a command on a Metasploit console and return the output.
Relies primarily on detecting the MSF prompt for command completion.
Args:
console: The Metasploit console object (MsfConsole).
cmd: The command to run.
execution_timeout: Optional specific timeout for this command's execution phase.
Returns:
The command output as a string.
"""
if not (hasattr(console, 'write') and hasattr(console, 'read')):
logger.error(f"Console object {type(console)} lacks required methods (write, read).")
raise TypeError("Unsupported console object type for command execution.")
try:
logger.debug(f"Running console command: {cmd}")
await asyncio.to_thread(lambda: console.write(cmd + '\n'))
output_buffer = b"" # Read as bytes to handle potential encoding issues and prompt matching
start_time = asyncio.get_event_loop().time()
# Determine read timeout - use inactivity timeout as fallback
read_timeout = execution_timeout or (LONG_CONSOLE_READ_TIMEOUT if cmd.strip().startswith(("run", "exploit", "check")) else DEFAULT_CONSOLE_READ_TIMEOUT)
check_interval = 0.1 # Seconds between reads
last_data_time = start_time
while True:
await asyncio.sleep(check_interval)
current_time = asyncio.get_event_loop().time()
# Check overall timeout first
if (current_time - start_time) > read_timeout:
logger.warning(f"Overall timeout ({read_timeout}s) reached for console command '{cmd}'.")
break
# Read available data
try:
chunk_result = await asyncio.to_thread(lambda: console.read())
# console.read() returns {'data': '...', 'prompt': '...', 'busy': bool}
chunk_data = chunk_result.get('data', '').encode('utf-8', errors='replace') # Ensure bytes
# Handle the prompt - ensure it's bytes for pattern matching
prompt_str = chunk_result.get('prompt', '')
prompt_bytes = prompt_str.encode('utf-8', errors='replace') if isinstance(prompt_str, str) else prompt_str
except Exception as read_err:
logger.warning(f"Error reading from console during command '{cmd}': {read_err}")
await asyncio.sleep(0.5) # Wait a bit before retrying or timing out
continue
if chunk_data:
# logger.debug(f"Read chunk (bytes): {chunk_data[:100]}...") # Log sparingly
output_buffer += chunk_data
last_data_time = current_time # Reset inactivity timer
# Primary Completion Check: Did we receive the prompt?
if prompt_bytes and MSF_PROMPT_RE.search(prompt_bytes):
logger.debug(f"Detected MSF prompt in console.read() result for '{cmd}'. Command likely complete.")
break
# Secondary Check: Does the buffered output end with the prompt?
# Needed if prompt wasn't in the last read chunk but arrived earlier.
if MSF_PROMPT_RE.search(output_buffer):
logger.debug(f"Detected MSF prompt at end of buffer for '{cmd}'. Command likely complete.")
break
# Fallback Completion Check: Inactivity timeout
elif (current_time - last_data_time) > SESSION_READ_INACTIVITY_TIMEOUT: # Use a shorter inactivity timeout here
logger.debug(f"Console inactivity timeout ({SESSION_READ_INACTIVITY_TIMEOUT}s) reached for command '{cmd}'. Assuming complete.")
break
# Decode the final buffer
final_output = output_buffer.decode('utf-8', errors='replace').strip()
logger.debug(f"Final output for '{cmd}' (length {len(final_output)}):\n{final_output[:500]}{'...' if len(final_output) > 500 else ''}")
return final_output
except Exception as e:
logger.exception(f"Error executing console command '{cmd}'")
raise RuntimeError(f"Failed executing console command '{cmd}': {e}") from e
from mcp.server.session import ServerSession
####################################################################################
# Temporary monkeypatch which avoids crashing when a POST message is received
# before a connection has been initialized, e.g: after a deployment.
# pylint: disable-next=protected-access
old__received_request = ServerSession._received_request
async def _received_request(self, *args, **kwargs):
try:
return await old__received_request(self, *args, **kwargs)
except RuntimeError:
pass
# pylint: disable-next=protected-access
ServerSession._received_request = _received_request
####################################################################################
# --- MCP Server Initialization ---
mcp = FastMCP("Metasploit Tools Enhanced (Streamlined)")
# --- Internal Helper Functions ---
def _parse_options_gracefully(options: Union[Dict[str, Any], str, None]) -> Dict[str, Any]:
"""
Gracefully parse options from different formats.
Handles:
- Dict format (correct): {"key": "value", "key2": "value2"}
- String format (common mistake): "key=value,key=value"
- None: returns empty dict
Args:
options: Options in dict format, string format, or None
Returns:
Dictionary of parsed options
Raises:
ValueError: If string format is malformed
"""
if options is None:
return {}
if isinstance(options, dict):
# Already correct format
return options
if isinstance(options, str):
# Handle the common mistake format: "key=value,key=value"
if not options.strip():
return {}
logger.info(f"Converting string format options to dict: {options}")
parsed_options = {}
try:
# Split by comma and then by equals
pairs = [pair.strip() for pair in options.split(',') if pair.strip()]
for pair in pairs:
if '=' not in pair:
raise ValueError(f"Invalid option format: '{pair}' (missing '=')")
key, value = pair.split('=', 1) # Split only on first '='
key = key.strip()
value = value.strip()
# Validate key is not empty
if not key:
raise ValueError(f"Invalid option format: '{pair}' (empty key)")
# Remove quotes if they wrap the entire value
if (value.startswith('"') and value.endswith('"')) or \
(value.startswith("'") and value.endswith("'")):
value = value[1:-1]
# Basic type conversion
if value.lower() in ('true', 'false'):
value = value.lower() == 'true'
elif value.isdigit():
try:
value = int(value)
except ValueError:
pass # Keep as string if conversion fails
parsed_options[key] = value
logger.info(f"Successfully converted string options to dict: {parsed_options}")
return parsed_options
except Exception as e:
raise ValueError(f"Failed to parse options string '{options}': {e}. Expected format: 'key=value,key2=value2' or dict {{'key': 'value'}}")
# For any other type, try to convert to dict
try:
return dict(options)
except (TypeError, ValueError) as e:
raise ValueError(f"Options must be a dictionary or comma-separated string format 'key=value,key2=value2'. Got {type(options)}: {options}")
async def _get_module_object(module_type: str, module_name: str) -> Any:
"""Gets the MSF module object, handling potential path variations."""
client = get_msf_client()
base_module_name = module_name # Start assuming it's the base name
if '/' in module_name:
parts = module_name.split('/')
if parts[0] in ('exploit', 'payload', 'post', 'auxiliary', 'encoder', 'nop'):
# Looks like full path, extract base name
base_module_name = '/'.join(parts[1:])
if module_type != parts[0]:
logger.warning(f"Module type mismatch: expected '{module_type}', got path starting with '{parts[0]}'. Using provided type.")
# Else: Assume it's like 'windows/smb/ms17_010_eternalblue' - already the base name
logger.debug(f"Attempting to retrieve module: client.modules.use('{module_type}', '{base_module_name}')")
try:
module_obj = await asyncio.to_thread(lambda: client.modules.use(module_type, base_module_name))
logger.debug(f"Successfully retrieved module object for {module_type}/{base_module_name}")
return module_obj
except (MsfRpcError, KeyError) as e:
# KeyError can be raised by pymetasploit3 if module not found
error_str = str(e).lower()
if "unknown module" in error_str or "invalid module" in error_str or isinstance(e, KeyError):
logger.error(f"Module {module_type}/{base_module_name} (from input {module_name}) not found.")
raise ValueError(f"Module '{module_name}' of type '{module_type}' not found.") from e
else:
logger.error(f"MsfRpcError getting module {module_type}/{base_module_name}: {e}")
raise MsfRpcError(f"Error retrieving module '{module_name}': {e}") from e
async def _set_module_options(module_obj: Any, options: Dict[str, Any]):
"""Sets options on a module object, performing basic type guessing."""
logger.debug(f"Setting options for module {getattr(module_obj, 'fullname', '')}: {options}")
for k, v in options.items():
# Basic type guessing
original_value = v
if isinstance(v, str):
if v.isdigit():
try: v = int(v)
except ValueError: pass # Keep as string if large number or non-integer
elif v.lower() in ('true', 'false'):
v = v.lower() == 'true'
# Add more specific checks if needed (e.g., for file paths)
elif isinstance(v, (int, bool)):
pass # Already correct type
# Add handling for other types like lists if necessary
try:
# Use lambda to capture current k, v for the thread
await asyncio.to_thread(lambda key=k, value=v: module_obj.__setitem__(key, value))
# logger.debug(f"Set option {k}={v} (original: {original_value})")
except (MsfRpcError, KeyError, TypeError) as e:
# Catch potential errors if option doesn't exist or type is wrong
logger.error(f"Failed to set option {k}={v} on module: {e}")
raise ValueError(f"Failed to set option '{k}' to '{original_value}': {e}") from e
async def _execute_module_rpc(
module_type: str,
module_name: str, # Can be full path or base name
module_options: Dict[str, Any],
payload_spec: Optional[Union[str, Dict[str, Any]]] = None # Payload name or {name: ..., options: ...}
) -> Dict[str, Any]:
"""
Helper to execute an exploit, auxiliary, or post module as a background job via RPC.
Includes polling logic for exploit sessions.
"""
client = get_msf_client()
module_obj = await _get_module_object(module_type, module_name) # Handles path variants
full_module_path = getattr(module_obj, 'fullname', f"{module_type}/{module_name}") # Get canonical name
await _set_module_options(module_obj, module_options)
payload_obj_to_pass = None
payload_name_for_log = None
payload_options_for_log = None
# Prepare payload if needed (primarily for exploits, also used by start_listener)
if module_type == 'exploit' and payload_spec:
if isinstance(payload_spec, str):
payload_name_for_log = payload_spec
# Passing name string directly is supported by exploit.execute
payload_obj_to_pass = payload_name_for_log
logger.info(f"Executing {full_module_path} with payload '{payload_name_for_log}' (passed as string).")
elif isinstance(payload_spec, dict) and 'name' in payload_spec:
payload_name = payload_spec['name']
payload_options = payload_spec.get('options', {})
payload_name_for_log = payload_name
payload_options_for_log = payload_options
try:
payload_obj = await _get_module_object('payload', payload_name)
await _set_module_options(payload_obj, payload_options)
payload_obj_to_pass = payload_obj # Pass the configured payload object
logger.info(f"Executing {full_module_path} with configured payload object for '{payload_name}'.")
except (ValueError, MsfRpcError) as e:
logger.error(f"Failed to prepare payload object for '{payload_name}': {e}")
return {"status": "error", "message": f"Failed to prepare payload '{payload_name}': {e}"}
else:
logger.warning(f"Invalid payload_spec format: {payload_spec}. Expected string or dict with 'name'.")
return {"status": "error", "message": "Invalid payload specification format."}
logger.info(f"Executing module {full_module_path} as background job via RPC...")
try:
if module_type == 'exploit':
exec_result = await asyncio.to_thread(lambda: module_obj.execute(payload=payload_obj_to_pass))
else: # auxiliary, post
exec_result = await asyncio.to_thread(lambda: module_obj.execute())
logger.info(f"RPC execute() result for {full_module_path}: {exec_result}")
# --- Process Execution Result ---
if not isinstance(exec_result, dict):
logger.error(f"Unexpected result type from {module_type} execution: {type(exec_result)} - {exec_result}")
return {"status": "error", "message": f"Unexpected result from module execution: {exec_result}", "module": full_module_path}
if exec_result.get('error', False):
error_msg = exec_result.get('error_message', exec_result.get('error_string', 'Unknown RPC error during execution'))
logger.error(f"Failed to start job for {full_module_path}: {error_msg}")
# Check for common errors
if "could not bind" in error_msg.lower():
return {"status": "error", "message": f"Job start failed: Address/Port likely already in use. {error_msg}", "module": full_module_path}
return {"status": "error", "message": f"Failed to start job: {error_msg}", "module": full_module_path}
job_id = exec_result.get('job_id')
uuid = exec_result.get('uuid')
if job_id is None:
logger.warning(f"{module_type.capitalize()} job executed but no job_id returned: {exec_result}")
# Sometimes handlers don't return job_id but are running, check by UUID/name later maybe
if module_type == 'exploit' and 'handler' in full_module_path:
# Check jobs list for a match based on payload/lhost/lport
await asyncio.sleep(1.0)
jobs_list = await asyncio.to_thread(lambda: client.jobs.list)
for jid, jinfo in jobs_list.items():
if isinstance(jinfo, dict) and jinfo.get('name','').endswith('Handler') and \
jinfo.get('datastore',{}).get('LHOST') == module_options.get('LHOST') and \
jinfo.get('datastore',{}).get('LPORT') == module_options.get('LPORT') and \
jinfo.get('datastore',{}).get('PAYLOAD') == payload_name_for_log:
logger.info(f"Found probable handler job {jid} matching parameters.")
return {"status": "success", "message": f"Listener likely started as job {jid}", "job_id": jid, "uuid": uuid, "module": full_module_path}
return {"status": "unknown", "message": f"{module_type.capitalize()} executed, but no job ID returned.", "result": exec_result, "module": full_module_path}
# --- Exploit Specific: Poll for Session ---
found_session_id = None
if module_type == 'exploit' and uuid:
start_time = asyncio.get_event_loop().time()
logger.info(f"Exploit job {job_id} (UUID: {uuid}) started. Polling for session (timeout: {EXPLOIT_SESSION_POLL_TIMEOUT}s)...")
while (asyncio.get_event_loop().time() - start_time) < EXPLOIT_SESSION_POLL_TIMEOUT:
try:
sessions_list = await asyncio.to_thread(lambda: client.sessions.list)
for s_id, s_info in sessions_list.items():
# Ensure comparison is robust (uuid might be str or bytes, info dict keys too)
s_id_str = str(s_id)
if isinstance(s_info, dict) and str(s_info.get('exploit_uuid')) == str(uuid):
found_session_id = s_id # Keep original type from list keys
logger.info(f"Found matching session {found_session_id} for job {job_id} (UUID: {uuid})")
break # Exit inner loop
if found_session_id is not None: break # Exit outer loop
# Optional: Check if job died prematurely
# job_info = await asyncio.to_thread(lambda: client.jobs.info(str(job_id)))
# if not job_info or job_info.get('status') != 'running':
# logger.warning(f"Job {job_id} stopped or disappeared during session polling.")
# break
except MsfRpcError as poll_e: logger.warning(f"Error during session polling: {poll_e}")
except Exception as poll_e: logger.error(f"Unexpected error during polling: {poll_e}", exc_info=True); break
await asyncio.sleep(EXPLOIT_SESSION_POLL_INTERVAL)
if found_session_id is None:
logger.warning(f"Polling timeout ({EXPLOIT_SESSION_POLL_TIMEOUT}s) reached for job {job_id}, no matching session found.")
# --- Construct Final Success/Warning Message ---
message = f"{module_type.capitalize()} module {full_module_path} started as job {job_id}."
status = "success"
if module_type == 'exploit':
if found_session_id is not None:
message += f" Session {found_session_id} created."
else:
message += " No session detected within timeout."
status = "warning" # Indicate job started but session didn't appear
return {
"status": status, "message": message, "job_id": job_id, "uuid": uuid,
"session_id": found_session_id, # None if not found/not applicable
"module": full_module_path, "options": module_options,
"payload_name": payload_name_for_log, # Include payload info if exploit
"payload_options": payload_options_for_log
}
except (MsfRpcError, ValueError) as e: # Catch module prep errors too
error_str = str(e).lower()
logger.error(f"Error executing module {full_module_path} via RPC: {e}")
if "missing required option" in error_str or "invalid option" in error_str:
missing = getattr(module_obj, 'missing_required', [])
return {"status": "error", "message": f"Missing/invalid options for {full_module_path}: {e}", "missing_required": missing}
elif "invalid payload" in error_str:
return {"status": "error", "message": f"Invalid payload specified: {payload_name_for_log or 'None'}. {e}"}
return {"status": "error", "message": f"Error running {full_module_path}: {e}"}
except Exception as e:
logger.exception(f"Unexpected error executing module {full_module_path} via RPC")
return {"status": "error", "message": f"Unexpected server error running {full_module_path}: {e}"}
async def _execute_module_console(
module_type: str,
module_name: str, # Can be full path or base name
module_options: Dict[str, Any],
command: str, # Typically 'exploit', 'run', or 'check'
payload_spec: Optional[Union[str, Dict[str, Any]]] = None,
timeout: int = LONG_CONSOLE_READ_TIMEOUT
) -> Dict[str, Any]:
"""Helper to execute a module synchronously via console."""
# Determine full path needed for 'use' command
if '/' not in module_name:
full_module_path = f"{module_type}/{module_name}"
else:
# Assume full path or relative path was given; ensure type prefix
if not module_name.startswith(module_type + '/'):
# e.g., got 'windows/x', type 'exploit' -> 'exploit/windows/x'
# e.g., got 'exploit/windows/x', type 'exploit' -> 'exploit/windows/x' (no change)
if not any(module_name.startswith(pfx + '/') for pfx in ['exploit', 'payload', 'post', 'auxiliary', 'encoder', 'nop']):
full_module_path = f"{module_type}/{module_name}"
else: # Already has a type prefix, use it as is
full_module_path = module_name
else: # Starts with correct type prefix
full_module_path = module_name
logger.info(f"Executing {full_module_path} synchronously via console (command: {command})...")
payload_name_for_log = None
payload_options_for_log = None
async with get_msf_console() as console:
try:
setup_commands = [f"use {full_module_path}"]
# Add module options
for key, value in module_options.items():
val_str = str(value)
if isinstance(value, str) and any(c in val_str for c in [' ', '"', "'", '\\']):
val_str = shlex.quote(val_str)
elif isinstance(value, bool):
val_str = str(value).lower() # MSF console expects lowercase bools
setup_commands.append(f"set {key} {val_str}")
# Add payload and payload options (if applicable)
if payload_spec:
payload_name = None
payload_options = {}
if isinstance(payload_spec, str):
payload_name = payload_spec
elif isinstance(payload_spec, dict) and 'name' in payload_spec:
payload_name = payload_spec['name']
payload_options = payload_spec.get('options', {})
if payload_name:
payload_name_for_log = payload_name
payload_options_for_log = payload_options
# Need base name for 'set PAYLOAD'
if '/' in payload_name:
parts = payload_name.split('/')
if parts[0] == 'payload': payload_base_name = '/'.join(parts[1:])
else: payload_base_name = payload_name # Assume relative
else: payload_base_name = payload_name # Assume just name
setup_commands.append(f"set PAYLOAD {payload_base_name}")
for key, value in payload_options.items():
val_str = str(value)
if isinstance(value, str) and any(c in val_str for c in [' ', '"', "'", '\\']):
val_str = shlex.quote(val_str)
elif isinstance(value, bool):
val_str = str(value).lower()
setup_commands.append(f"set {key} {val_str}")
# Execute setup commands
for cmd in setup_commands:
setup_output = await run_command_safely(console, cmd, execution_timeout=DEFAULT_CONSOLE_READ_TIMEOUT)
# Basic error check in setup output
if any(err in setup_output for err in ["[-] Error setting", "Invalid option", "Unknown module", "Failed to load"]):
error_msg = f"Error during setup command '{cmd}': {setup_output}"
logger.error(error_msg)
return {"status": "error", "message": error_msg, "module": full_module_path}
await asyncio.sleep(0.1) # Small delay between setup commands
# Execute the final command (exploit, run, check)
logger.info(f"Running final console command: {command}")
module_output = await run_command_safely(console, command, execution_timeout=timeout)
logger.debug(f"Synchronous execution output length: {len(module_output)}")
# --- Parse Console Output ---
session_id = None
session_opened_line = ""
# More robust session detection pattern
session_match = re.search(r"(?:meterpreter|command shell)\s+session\s+(\d+)\s+opened", module_output, re.IGNORECASE)
if session_match:
try:
session_id = int(session_match.group(1))
session_opened_line = session_match.group(0) # The matched line segment
logger.info(f"Detected session {session_id} opened in console output.")
except (ValueError, IndexError):
logger.warning("Found session opened pattern, but failed to parse ID.")
status = "success"
message = f"{module_type.capitalize()} module {full_module_path} completed via console ({command})."
if command in ['exploit', 'run'] and session_id is None and \
any(term in module_output.lower() for term in ['session opened', 'sending stage']):
message += " Session may have opened but ID detection failed or session closed quickly."
status = "warning"
elif command in ['exploit', 'run'] and session_id is not None:
message += f" Session {session_id} detected."
# Check for common failure indicators
if any(fail in module_output.lower() for fail in ['exploit completed, but no session was created', 'exploit failed', 'run failed', 'check failed', 'module check failed']):
status = "error" if status != "warning" else status # Don't override warning if session might have opened
message = f"{module_type.capitalize()} module {full_module_path} execution via console appears to have failed. Check output."
logger.error(f"Failure detected in console output for {full_module_path}.")
return {
"status": status,
"message": message,
"module_output": module_output,
"session_id_detected": session_id,
"session_opened_line": session_opened_line,
"module": full_module_path,
"options": module_options,
"payload_name": payload_name_for_log,
"payload_options": payload_options_for_log
}
except (RuntimeError, MsfRpcError, ValueError) as e: # Catch errors from run_command_safely or setup
logger.error(f"Error during console execution of {full_module_path}: {e}")
return {"status": "error", "message": f"Error executing {full_module_path} via console: {e}"}
except Exception as e:
logger.exception(f"Unexpected error during console execution of {full_module_path}")
return {"status": "error", "message": f"Unexpected server error running {full_module_path} via console: {e}"}
# --- MCP Tool Definitions ---
@mcp.tool()
async def list_exploits(search_term: str = "") -> List[str]:
"""
List available Metasploit exploits, optionally filtered by search term.
Args:
search_term: Optional term to filter exploits (case-insensitive).
Returns:
List of exploit names matching the term (max 200), or top 100 if no term.
"""
client = get_msf_client()
logger.info(f"Listing exploits (search term: '{search_term or 'None'}')")
try:
# Add timeout to prevent hanging on slow/unresponsive MSF server
logger.debug(f"Calling client.modules.exploits with {RPC_CALL_TIMEOUT}s timeout...")
exploits = await asyncio.wait_for(
asyncio.to_thread(lambda: client.modules.exploits),
timeout=RPC_CALL_TIMEOUT
)
logger.debug(f"Retrieved {len(exploits)} total exploits from MSF.")
if search_term:
term_lower = search_term.lower()
filtered_exploits = [e for e in exploits if term_lower in e.lower()]
count = len(filtered_exploits)
limit = 200
logger.info(f"Found {count} exploits matching '{search_term}'. Returning max {limit}.")
return filtered_exploits[:limit]
else:
limit = 100
logger.info(f"No search term provided, returning first {limit} exploits.")
return exploits[:limit]
except asyncio.TimeoutError:
error_msg = f"Timeout ({RPC_CALL_TIMEOUT}s) while listing exploits from Metasploit server. Server may be slow or unresponsive."
logger.error(error_msg)
return [f"Error: {error_msg}"]
except MsfRpcError as e:
logger.error(f"Metasploit RPC error while listing exploits: {e}")
return [f"Error: Metasploit RPC error: {e}"]
except Exception as e:
logger.exception("Unexpected error listing exploits.")
return [f"Error: Unexpected error listing exploits: {e}"]
@mcp.tool()
async def list_payloads(platform: str = "", arch: str = "") -> List[str]:
"""
List available Metasploit payloads, optionally filtered by platform and/or architecture.
Args:
platform: Optional platform filter (e.g., 'windows', 'linux', 'python', 'php').
arch: Optional architecture filter (e.g., 'x86', 'x64', 'cmd', 'meterpreter').
Returns:
List of payload names matching filters (max 100).
"""
client = get_msf_client()
logger.info(f"Listing payloads (platform: '{platform or 'Any'}', arch: '{arch or 'Any'}')")
try:
# Add timeout to prevent hanging on slow/unresponsive MSF server
logger.debug(f"Calling client.modules.payloads with {RPC_CALL_TIMEOUT}s timeout...")
payloads = await asyncio.wait_for(
asyncio.to_thread(lambda: client.modules.payloads),
timeout=RPC_CALL_TIMEOUT
)
logger.debug(f"Retrieved {len(payloads)} total payloads from MSF.")
filtered = payloads
if platform:
plat_lower = platform.lower()
# Match platform at the start of the payload path segment or within common paths
filtered = [p for p in filtered if p.lower().startswith(plat_lower + '/') or f"/{plat_lower}/" in p.lower()]
if arch:
arch_lower = arch.lower()
# Match architecture more flexibly (e.g., '/x64/', 'meterpreter')
filtered = [p for p in filtered if f"/{arch_lower}/" in p.lower() or arch_lower in p.lower().split('/')]
count = len(filtered)
limit = 100
logger.info(f"Found {count} payloads matching filters. Returning max {limit}.")
return filtered[:limit]
except asyncio.TimeoutError:
error_msg = f"Timeout ({RPC_CALL_TIMEOUT}s) while listing payloads from Metasploit server. Server may be slow or unresponsive."
logger.error(error_msg)
return [f"Error: {error_msg}"]
except MsfRpcError as e:
logger.error(f"Metasploit RPC error while listing payloads: {e}")
return [f"Error: Metasploit RPC error: {e}"]
except Exception as e:
logger.exception("Unexpected error listing payloads.")
return [f"Error: Unexpected error listing payloads: {e}"]
@mcp.tool()
async def generate_payload(
payload_type: str,
format_type: str,
options: Union[Dict[str, Any], str], # Required: e.g., {"LHOST": "1.2.3.4", "LPORT": 4444} or "LHOST=1.2.3.4,LPORT=4444"
encoder: Optional[str] = None,
iterations: int = 0,
bad_chars: str = "",
nop_sled_size: int = 0,
template_path: Optional[str] = None,
keep_template: bool = False,
force_encode: bool = False,
output_filename: Optional[str] = None,
) -> Dict[str, Any]:
"""
Generate a Metasploit payload using the RPC API (payload.generate).
Saves the generated payload to a file on the server if successful.
Args:
payload_type: Type of payload (e.g., windows/meterpreter/reverse_tcp).
format_type: Output format (raw, exe, python, etc.).
options: Dictionary of required payload options (e.g., {"LHOST": "1.2.3.4", "LPORT": 4444})
or string format "LHOST=1.2.3.4,LPORT=4444". Prefer dict format.
encoder: Optional encoder to use.
iterations: Optional number of encoding iterations.
bad_chars: Optional string of bad characters to avoid (e.g., '\\x00\\x0a\\x0d').
nop_sled_size: Optional size of NOP sled.
template_path: Optional path to an executable template.
keep_template: Keep the template working (requires template_path).
force_encode: Force encoding even if not needed by bad chars.
output_filename: Optional desired filename (without path). If None, a default name is generated.
Returns:
Dictionary containing status, message, payload size/info, and server-side save path.
"""
client = get_msf_client()
logger.info(f"Generating payload '{payload_type}' (Format: {format_type}) via RPC. Options: {options}")
# Parse options gracefully
try:
parsed_options = _parse_options_gracefully(options)
except ValueError as e:
return {"status": "error", "message": f"Invalid options format: {e}"}
if not parsed_options:
return {"status": "error", "message": "Payload 'options' dictionary (e.g., LHOST, LPORT) is required."}
try:
# Get the payload module object
payload = await _get_module_object('payload', payload_type)
# Set payload-specific required options (like LHOST/LPORT)
await _set_module_options(payload, parsed_options)
# Set payload generation options in payload.runoptions
# as per the pymetasploit3 documentation
logger.info("Setting payload generation options in payload.runoptions...")
# Define a function to update an individual runoption
async def update_runoption(key, value):
if value is None:
return
await asyncio.to_thread(lambda k=key, v=value: payload.runoptions.__setitem__(k, v))
logger.debug(f"Set runoption {key}={value}")
# Set generation options individually
await update_runoption('Format', format_type)
if encoder:
await update_runoption('Encoder', encoder)
if iterations:
await update_runoption('Iterations', iterations)
if bad_chars is not None:
await update_runoption('BadChars', bad_chars)
if nop_sled_size:
await update_runoption('NopSledSize', nop_sled_size)
if template_path:
await update_runoption('Template', template_path)
if keep_template:
await update_runoption('KeepTemplateWorking', keep_template)
if force_encode:
await update_runoption('ForceEncode', force_encode)
# Generate the payload bytes using payload.payload_generate()
logger.info("Calling payload.payload_generate()...")
raw_payload_bytes = await asyncio.to_thread(lambda: payload.payload_generate())
if not isinstance(raw_payload_bytes, bytes):
error_msg = f"Payload generation failed. Expected bytes, got {type(raw_payload_bytes)}: {str(raw_payload_bytes)[:200]}"
logger.error(error_msg)
# Try to extract specific error from potential dictionary response
if isinstance(raw_payload_bytes, dict) and raw_payload_bytes.get('error'):
error_msg = raw_payload_bytes.get('error_message', str(raw_payload_bytes))
return {"status": "error", "message": f"Payload generation failed: {error_msg}"}
payload_size = len(raw_payload_bytes)
logger.info(f"Payload generation successful. Size: {payload_size} bytes.")
# --- Save Payload ---
# Ensure directory exists
try:
os.makedirs(PAYLOAD_SAVE_DIR, exist_ok=True)
logger.debug(f"Ensured payload directory exists: {PAYLOAD_SAVE_DIR}")
except OSError as e:
logger.error(f"Failed to create payload save directory {PAYLOAD_SAVE_DIR}: {e}")
return {
"status": "error",
"message": f"Payload generated ({payload_size} bytes) but could not create save directory: {e}",
"payload_size": payload_size, "format": format_type
}
# Determine filename (with basic sanitization)
final_filename = None
if output_filename:
sanitized = re.sub(r'[^a-zA-Z0-9_.\-]', '_', os.path.basename(output_filename)) # Basic sanitize + basename
if sanitized: final_filename = sanitized
if not final_filename:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_payload_type = re.sub(r'[^a-zA-Z0-9_]', '_', payload_type)
safe_format = re.sub(r'[^a-zA-Z0-9_]', '_', format_type)
final_filename = f"payload_{safe_payload_type}_{timestamp}.{safe_format}"
save_path = os.path.join(PAYLOAD_SAVE_DIR, final_filename)
# Write payload to file
try:
with open(save_path, "wb") as f:
f.write(raw_payload_bytes)
logger.info(f"Payload saved to {save_path}")
return {
"status": "success",
"message": f"Payload '{payload_type}' generated successfully and saved.",
"payload_size": payload_size,
"format": format_type,
"server_save_path": save_path
}
except IOError as e:
logger.error(f"Failed to write payload to {save_path}: {e}")
return {
"status": "error",
"message": f"Payload generated but failed to save to file: {e}",
"payload_size": payload_size, "format": format_type
}
except (ValueError, MsfRpcError) as e: # Catches errors from _get_module_object, _set_module_options
error_str = str(e).lower()
logger.error(f"Error generating payload {payload_type}: {e}")
if "invalid payload type" in error_str or "unknown module" in error_str:
return {"status": "error", "message": f"Invalid payload type: {payload_type}"}
elif "missing required option" in error_str or "invalid option" in error_str:
missing = getattr(payload, 'missing_required', []) if 'payload' in locals() else []
return {"status": "error", "message": f"Missing/invalid options for payload {payload_type}: {e}", "missing_required": missing}
return {"status": "error", "message": f"Error generating payload: {e}"}
except AttributeError as e: # Specifically catch if payload_generate is missing
logger.exception(f"AttributeError during payload generation for '{payload_type}': {e}")
if "object has no attribute 'payload_generate'" in str(e):
return {"status": "error", "message": f"The pymetasploit3 payload module doesn't have the payload_generate method. Please check library version/compatibility."}
return {"status": "error", "message": f"An attribute error occurred: {e}"}
except Exception as e:
logger.exception(f"Unexpected error during payload generation for '{payload_type}'.")
return {"status": "error", "message": f"An unexpected server error occurred during payload generation: {e}"}
@mcp.tool()
async def run_exploit(
module_name: str,
options: Dict[str, Any],
payload_name: Optional[str] = None,
payload_options: Optional[Union[Dict[str, Any], str]] = None,
run_as_job: bool = False,
check_vulnerability: bool = False, # New option
timeout_seconds: int = LONG_CONSOLE_READ_TIMEOUT # Used only if run_as_job=False
) -> Dict[str, Any]: