Class: Rex::Proto::SMB::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/rex/proto/smb/client.rb

Constant Summary collapse

CONST =

Some short-hand class aliases

Rex::Proto::SMB::Constants
CRYPT =
Rex::Proto::SMB::Crypt
UTILS =
Rex::Proto::SMB::Utils
XCEPT =
Rex::Proto::SMB::Exceptions
EVADE =
Rex::Proto::SMB::Evasions
NTLM_CRYPT =
Rex::Proto::NTLM::Crypt
NTLM_CONST =
Rex::Proto::NTLM::Constants
NTLM_UTILS =
Rex::Proto::NTLM::Utils

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(socket) ⇒ Client

Returns a new instance of Client


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/rex/proto/smb/client.rb', line 29

def initialize(socket)
  self.socket = socket
  self.native_os = 'Windows 2000 2195'
  self.native_lm = 'Windows 2000 5.0'
  self.encrypt_passwords = true
  self.extended_security = false
  self.multiplex_id = rand(0xffff)
  self.process_id = rand(0xffff)
  self.read_timeout = 10
  self.evasion_opts = {

    # Padding is performed between packet headers and data
    'pad_data' => EVADE::EVASION_NONE,

    # File path padding is performed on all open/create calls
    'pad_file' => EVADE::EVASION_NONE,

    # Modify the \PIPE\ string in trans_named_pipe calls
    'obscure_trans_pipe' => EVADE::EVASION_NONE,
  }

  self.verify_signature = false
  self.use_ntlmv2 = false
  self.usentlm2_session = true
  self.send_lm = true
  self.use_lanman_key = false
  self.send_ntlm  = true

  # Signing
  self.sequence_counter = 0
  self.signing_key      = ''
  self.require_signing  = false

  #Misc
  self.spnopt = {}

end

Instance Attribute Details

#auth_userObject

Returns the value of attribute auth_user


1940
1941
1942
# File 'lib/rex/proto/smb/client.rb', line 1940

def auth_user
  @auth_user
end

#auth_user_idObject

Returns the value of attribute auth_user_id


1940
1941
1942
# File 'lib/rex/proto/smb/client.rb', line 1940

def auth_user_id
  @auth_user_id
end

#challenge_keyObject

public read methods


1939
1940
1941
# File 'lib/rex/proto/smb/client.rb', line 1939

def challenge_key
  @challenge_key
end

#default_domainObject

Returns the value of attribute default_domain


1940
1941
1942
# File 'lib/rex/proto/smb/client.rb', line 1940

def default_domain
  @default_domain
end

#default_nameObject

Returns the value of attribute default_name


1940
1941
1942
# File 'lib/rex/proto/smb/client.rb', line 1940

def default_name
  @default_name
end

#dialectObject

public read methods


1939
1940
1941
# File 'lib/rex/proto/smb/client.rb', line 1939

def dialect
  @dialect
end

#dns_domain_nameObject

Returns the value of attribute dns_domain_name


1942
1943
1944
# File 'lib/rex/proto/smb/client.rb', line 1942

def dns_domain_name
  @dns_domain_name
end

#dns_host_nameObject

Returns the value of attribute dns_host_name


1942
1943
1944
# File 'lib/rex/proto/smb/client.rb', line 1942

def dns_host_name
  @dns_host_name
end

#encrypt_passwordsObject

public read/write methods


1932
1933
1934
# File 'lib/rex/proto/smb/client.rb', line 1932

def encrypt_passwords
  @encrypt_passwords
end

#evasion_optsObject

public read/write methods


1932
1933
1934
# File 'lib/rex/proto/smb/client.rb', line 1932

def evasion_opts
  @evasion_opts
end

#extended_securityObject

public read/write methods


1932
1933
1934
# File 'lib/rex/proto/smb/client.rb', line 1932

def extended_security
  @extended_security
end

#last_file_idObject

Returns the value of attribute last_file_id


1941
1942
1943
# File 'lib/rex/proto/smb/client.rb', line 1941

def last_file_id
  @last_file_id
end

#last_search_idObject

Returns the value of attribute last_search_id


1941
1942
1943
# File 'lib/rex/proto/smb/client.rb', line 1941

def last_search_id
  @last_search_id
end

#last_tree_idObject

Returns the value of attribute last_tree_id


1941
1942
1943
# File 'lib/rex/proto/smb/client.rb', line 1941

def last_tree_id
  @last_tree_id
end

#multiplex_idObject

Returns the value of attribute multiplex_id


1941
1942
1943
# File 'lib/rex/proto/smb/client.rb', line 1941

def multiplex_id
  @multiplex_id
end

#native_lmObject

public read/write methods


1932
1933
1934
# File 'lib/rex/proto/smb/client.rb', line 1932

def native_lm
  @native_lm
end

#native_osObject

public read/write methods


1932
1933
1934
# File 'lib/rex/proto/smb/client.rb', line 1932

def native_os
  @native_os
end

#peer_native_lmObject

public read methods


1939
1940
1941
# File 'lib/rex/proto/smb/client.rb', line 1939

def peer_native_lm
  @peer_native_lm
end

#peer_native_osObject

public read methods


1939
1940
1941
# File 'lib/rex/proto/smb/client.rb', line 1939

def peer_native_os
  @peer_native_os
end

#process_idObject

Returns the value of attribute process_id


1941
1942
1943
# File 'lib/rex/proto/smb/client.rb', line 1941

def process_id
  @process_id
end

#read_timeoutObject

public read/write methods


1932
1933
1934
# File 'lib/rex/proto/smb/client.rb', line 1932

def read_timeout
  @read_timeout
end

#require_signingObject

signing related


1945
1946
1947
# File 'lib/rex/proto/smb/client.rb', line 1945

def require_signing
  @require_signing
end

#security_modeObject

Returns the value of attribute security_mode


1943
1944
1945
# File 'lib/rex/proto/smb/client.rb', line 1943

def security_mode
  @security_mode
end

#send_lmObject

Returns the value of attribute send_lm


1933
1934
1935
# File 'lib/rex/proto/smb/client.rb', line 1933

def send_lm
  @send_lm
end

#send_ntlmObject

Returns the value of attribute send_ntlm


1933
1934
1935
# File 'lib/rex/proto/smb/client.rb', line 1933

def send_ntlm
  @send_ntlm
end

#sequence_counterObject

signing related


1945
1946
1947
# File 'lib/rex/proto/smb/client.rb', line 1945

def sequence_counter
  @sequence_counter
end

#server_guidObject

Returns the value of attribute server_guid


1943
1944
1945
# File 'lib/rex/proto/smb/client.rb', line 1943

def server_guid
  @server_guid
end

#session_idObject

public read methods


1939
1940
1941
# File 'lib/rex/proto/smb/client.rb', line 1939

def session_id
  @session_id
end

#signing_keyObject

signing related


1945
1946
1947
# File 'lib/rex/proto/smb/client.rb', line 1945

def signing_key
  @signing_key
end

#socketObject

Returns the value of attribute socket


1956
1957
1958
# File 'lib/rex/proto/smb/client.rb', line 1956

def socket
  @socket
end

#spnoptObject

misc


1936
1937
1938
# File 'lib/rex/proto/smb/client.rb', line 1936

def spnopt
  @spnopt
end

#system_timeObject

Returns the value of attribute system_time


1934
1935
1936
# File 'lib/rex/proto/smb/client.rb', line 1934

def system_time
  @system_time
end

#system_zoneObject

Returns the value of attribute system_zone


1934
1935
1936
# File 'lib/rex/proto/smb/client.rb', line 1934

def system_zone
  @system_zone
end

#use_lanman_keyObject

Returns the value of attribute use_lanman_key


1933
1934
1935
# File 'lib/rex/proto/smb/client.rb', line 1933

def use_lanman_key
  @use_lanman_key
end

#use_ntlmv2Object

Returns the value of attribute use_ntlmv2


1933
1934
1935
# File 'lib/rex/proto/smb/client.rb', line 1933

def use_ntlmv2
  @use_ntlmv2
end

#usentlm2_sessionObject

Returns the value of attribute usentlm2_session


1933
1934
1935
# File 'lib/rex/proto/smb/client.rb', line 1933

def usentlm2_session
  @usentlm2_session
end

#verify_signatureObject

Returns the value of attribute verify_signature


1933
1934
1935
# File 'lib/rex/proto/smb/client.rb', line 1933

def verify_signature
  @verify_signature
end

Instance Method Details

#close(file_id = self.last_file_id, tree_id = self.last_tree_id, do_recv = true) ⇒ Object

Closes an open file handle


1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
# File 'lib/rex/proto/smb/client.rb', line 1225

def close(file_id = self.last_file_id, tree_id = self.last_tree_id, do_recv = true)

  pkt = CONST::SMB_CLOSE_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_CLOSE
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['TreeID'] = tree_id
  pkt['Payload']['SMB'].v['WordCount'] = 3

  pkt['Payload'].v['FileID'] = file_id
  pkt['Payload'].v['LastWrite'] = -1

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_CLOSE)

  return ack
end

#create(filename, disposition = 1, impersonation = 2, do_recv = true) ⇒ Object

Creates a file or opens an existing pipe


1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
# File 'lib/rex/proto/smb/client.rb', line 1116

def create(filename, disposition = 1, impersonation = 2, do_recv = true)

  pkt = CONST::SMB_CREATE_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_NT_CREATE_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 24

  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['FileNameLen'] = filename.length
  pkt['Payload'].v['CreateFlags'] = 0x16
  pkt['Payload'].v['AccessMask'] = 0x02000000 # Maximum Allowed
  pkt['Payload'].v['ShareAccess'] = 7
  pkt['Payload'].v['CreateOptions'] = 0
  pkt['Payload'].v['Impersonation'] = impersonation
  pkt['Payload'].v['Disposition'] = disposition
  pkt['Payload'].v['Payload'] = filename + "\x00"

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_NT_CREATE_ANDX)

  # Save off the FileID
  if (ack['Payload'].v['FileID'] > 0)
    self.last_file_id = ack['Payload'].v['FileID']
  end

  return ack
end

#create_directory(name) ⇒ Object

Creates a new directory on the mounted tree


1925
1926
1927
1928
1929
# File 'lib/rex/proto/smb/client.rb', line 1925

def create_directory(name)
  files = { }
  parm = [0].pack('V') + name + "\x00"
  resp = trans2(CONST::TRANS2_CREATE_DIRECTORY, parm, '')
end

#create_pipe(filename, disposition = 1, impersonation = 2) ⇒ Object

Returns a SMB_CREATE_RES response for a given named pipe


1111
1112
1113
# File 'lib/rex/proto/smb/client.rb', line 1111

def create_pipe(filename, disposition = 1, impersonation = 2)
  self.create(filename)
end

#delete(filename, tree_id = self.last_tree_id, do_recv = true) ⇒ Object

Deletes a file from a share


1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
# File 'lib/rex/proto/smb/client.rb', line 1157

def delete(filename, tree_id = self.last_tree_id, do_recv = true)

  pkt = CONST::SMB_DELETE_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_DELETE
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['TreeID'] = tree_id
  pkt['Payload']['SMB'].v['WordCount'] = 1

  pkt['Payload'].v['SearchAttributes'] = 0x06
  pkt['Payload'].v['BufferFormat'] = 4
  pkt['Payload'].v['Payload'] = filename + "\x00"

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_DELETE)

  return ack
end

#find_first(path) ⇒ Object

Enumerates a specific path on the mounted tree


1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
# File 'lib/rex/proto/smb/client.rb', line 1830

def find_first(path)
  files = { }
  parm = [
    26,  # Search for ALL files
    20,  # Maximum search count
    6,   # Resume and Close on End of Search
    260, # Level of interest
    0,   # Storage type is zero
  ].pack('vvvvV') + path + "\x00"

  begin
    resp = trans2(CONST::TRANS2_FIND_FIRST2, parm, '')
    search_next = 0
    begin
      pcnt = resp['Payload'].v['ParamCount']
      dcnt = resp['Payload'].v['DataCount']
      poff = resp['Payload'].v['ParamOffset']
      doff = resp['Payload'].v['DataOffset']

      # Get the raw packet bytes
      resp_rpkt = resp.to_s

      # Remove the NetBIOS header
      resp_rpkt.slice!(0, 4)

      resp_parm = resp_rpkt[poff, pcnt]
      resp_data = resp_rpkt[doff, dcnt]

      if search_next == 0
        # search id, search count, end of search, error offset, last name offset
        sid, scnt, eos, eoff, loff = resp_parm.unpack('v5')
      else
        # FINX_NEXT doesn't return a SID
        scnt, eos, eoff, loff = resp_parm.unpack('v4')
      end
      didx = 0
      while (didx < resp_data.length)
        info_buff = resp_data[didx, 70]
        break if info_buff.length != 70
        info = info_buff.unpack(
          'V'+	# Next Entry Offset
          'V'+	# File Index
          'VV'+	# Time Create
          'VV'+	# Time Last Access
          'VV'+	# Time Last Write
          'VV'+	# Time Change
          'VV'+	# End of File
          'VV'+	# Allocation Size
          'V'+	# File Attributes
          'V'+	# File Name Length
          'V'+	# Extended Attr List Length
          'C'+	# Short File Name Length
          'C' 	# Reserved
        )
        name = resp_data[didx + 70 + 24, info[15]].sub(/\x00+$/n, '')
        files[name] =
        {
          'type' => ((info[14] & 0x10)==0x10) ? 'D' : 'F',
          'attr' => info[14],
          'info' => info
        }

        break if info[0] == 0
        didx += info[0]
      end
      last_search_id = sid
      last_offset = loff
      last_filename = name
      if eos == 0 and last_offset != 0 #If we aren't at the end of the search, run find_next
        resp = find_next(last_search_id, last_offset, last_filename)
        search_next = 1 # Flip bit so response params will parse correctly
      end
    end until eos != 0 or last_offset == 0
  rescue ::Exception
    raise $!
  end

  return files
end

#find_next(sid, resume_key, last_filename) ⇒ Object

Supplements find_first if file/dir count exceeds max search count


1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
# File 'lib/rex/proto/smb/client.rb', line 1911

def find_next(sid, resume_key, last_filename)

  parm = [
    sid, # Search ID
    20, # Maximum search count (Size of 20 keeps response to 1 packet)
    260, # Level of interest
    resume_key,   # Resume key from previous (Last name offset)
    6,   # Close search if end of search
  ].pack('vvvVv') + last_filename.to_s + "\x00" # Last filename returned from find_first or find_next
  resp = trans2(CONST::TRANS2_FIND_NEXT2, parm, '')
  return resp # Returns the FIND_NEXT2 response packet for parsing by the find_first function
end

#negotiate(smb_extended_security = true, do_recv = true) ⇒ Object

Negotiate a SMB dialect


478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
# File 'lib/rex/proto/smb/client.rb', line 478

def negotiate(smb_extended_security=true, do_recv = true)

  dialects = ['LANMAN1.0', 'LM1.2X002' ]

  if (self.encrypt_passwords)
    dialects.push('NT LANMAN 1.0', 'NT LM 0.12')
  end

  data = dialects.collect { |dialect| "\x02" + dialect + "\x00" }.join('')

  pkt = CONST::SMB_NEG_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_NEGOTIATE
  pkt['Payload']['SMB'].v['Flags1'] = 0x18

  if(smb_extended_security)
    pkt['Payload']['SMB'].v['Flags2'] = 0x2801
  else
    pkt['Payload']['SMB'].v['Flags2'] = 0xc001
  end

  pkt['Payload'].v['Payload'] = data

  ret = self.smb_send(pkt.to_s, EVADE::EVASION_NONE)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_NEGOTIATE)

  idx = ack['Payload'].v['Dialect']

  # Check for failed dialect selection
  if (idx < 0 or idx >= dialects.length)
    return nil
  end

  # Set the selected dialect
  self.dialect = dialects[idx]

  # Does the server support extended security negotiation?
  if (ack['Payload'].v['Capabilities'] & 0x80000000 != 0)
    self.extended_security = true
  end

  # Set the security mode
  self.security_mode = ack['Payload'].v['SecurityMode']

  #set require_signing
  if (ack['Payload'].v['SecurityMode'] & 0x08 != 0)
    self.require_signing	= true
  end

  # Set the challenge key
  if (ack['Payload'].v['EncryptionKey'] != nil)
    self.challenge_key = ack['Payload'].v['EncryptionKey']
  else
    # Handle Windows NT 4.0 responses
    if (ack['Payload'].v['KeyLength'] > 0)
      self.challenge_key = ack['Payload'].v['Payload'][0, ack['Payload'].v['KeyLength']]
    end
  end

  # Set the session identifier
  if (ack['Payload'].v['SessionKey'] != nil)
    self.session_id = ack['Payload'].v['SessionKey']
  end

  # Extract the payload (GUID/SecurityBlob)
  buf = ack['Payload'].v['Payload'] || ''

  # Set the server GUID
  if (self.extended_security and buf.length >= 16)
    self.server_guid = buf[0,16]
  end

  # Set the server SecurityBlob
  if (self.extended_security and buf.length > 16)
    # buf[16, buf.length - 16]
  end

  # The number of 100-nanosecond intervals that have elapsed since January 1, 1601, in
  # Coordinated Universal Time (UTC) format.
  # We convert it to a friendly Time object here
  self.system_time = UTILS.time_smb_to_unix(ack['Payload'].v['SystemTimeHigh'],ack['Payload'].v['SystemTimeLow'])
  self.system_time = ::Time.at( self.system_time )

  # A signed 16-bit signed integer that represents the server's time zone, in minutes,
  # from UTC. The time zone of the server MUST be expressed in minutes, plus or minus,
  # from UTC.
  # NOTE: althought the spec says +/- it doesn't say that it should be inverted :-/
  system_zone = ack['Payload'].v['ServerTimeZone']
  # Convert the ServerTimeZone to _seconds_ and back into a signed integer :-/
  if (system_zone & 0x8000) == 0x8000
    system_zone = (( (~system_zone)  & 0x0FFF ) + 1 )
  else
    system_zone *= -1
  end
  self.system_zone = system_zone * 60

  return ack
end

#nttrans(subcommand, param = '', body = '', setup_count = 0, setup_data = '', do_recv = true) ⇒ Object

Perform a nttransaction request using the specified subcommand, parameters, and data


1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
# File 'lib/rex/proto/smb/client.rb', line 1629

def nttrans(subcommand, param = '', body = '', setup_count = 0, setup_data = '', do_recv = true)

  data = param + body

  pkt = CONST::SMB_NTTRANS_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  base_offset = pkt.to_s.length + (setup_count * 2) - 4
  param_offset = base_offset
  data_offset = param_offset + param.length

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_NT_TRANSACT
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 19 + setup_count

  pkt['Payload'].v['ParamCountTotal'] = param.length
  pkt['Payload'].v['DataCountTotal'] = body.length
  pkt['Payload'].v['ParamCountMax'] = 1024
  pkt['Payload'].v['DataCountMax'] = 65000
  pkt['Payload'].v['ParamCount'] = param.length
  pkt['Payload'].v['ParamOffset'] = param_offset
  pkt['Payload'].v['DataCount'] = body.length
  pkt['Payload'].v['DataOffset'] = data_offset
  pkt['Payload'].v['SetupCount'] = setup_count
  pkt['Payload'].v['SetupData'] = setup_data
  pkt['Payload'].v['Subcommand'] = subcommand

  pkt['Payload'].v['Payload'] = data

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_NT_TRANSACT)
  return ack
end

#nttrans_secondary(param = '', body = '', do_recv = true) ⇒ Object

Perform a nttransaction request using the specified subcommand, parameters, and data


1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
# File 'lib/rex/proto/smb/client.rb', line 1674

def nttrans_secondary(param = '', body = '', do_recv = true)

  data = param + body

  pkt = CONST::SMB_NTTRANS_SECONDARY_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  base_offset = pkt.to_s.length - 4
  param_offset = base_offset
  data_offset = param_offset + param.length

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_NT_TRANSACT_SECONDARY
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 18

  pkt['Payload'].v['ParamCountTotal'] = param.length
  pkt['Payload'].v['DataCountTotal'] = body.length
  pkt['Payload'].v['ParamCount'] = param.length
  pkt['Payload'].v['ParamOffset'] = param_offset
  pkt['Payload'].v['DataCount'] = body.length
  pkt['Payload'].v['DataOffset'] = data_offset

  pkt['Payload'].v['Payload'] = data

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_NT_TRANSACT_SECONDARY)
  return ack
end

#open(filename, mode = 0x12, access = 0x42, do_recv = true) ⇒ Object

Opens an existing file or creates a new one


1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
# File 'lib/rex/proto/smb/client.rb', line 1188

def open(filename, mode = 0x12, access = 0x42, do_recv = true)

  pkt = CONST::SMB_OPEN_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_OPEN_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 15

  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['Access'] = access
  pkt['Payload'].v['SearchAttributes'] = 0x06
  pkt['Payload'].v['OpenFunction'] = mode
  pkt['Payload'].v['Payload'] = filename + "\x00"

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_OPEN_ANDX)

  # Save off the FileID
  if (ack['Payload'].v['FileID'] > 0)
    self.last_file_id = ack['Payload'].v['FileID']
  end

  return ack
end

#queryfs(level) ⇒ Object


1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
# File 'lib/rex/proto/smb/client.rb', line 1713

def queryfs(level)
  parm = [level].pack('v')

  begin
    resp = trans2(CONST::TRANS2_QUERY_FS_INFO, parm, '')

    pcnt = resp['Payload'].v['ParamCount']
    dcnt = resp['Payload'].v['DataCount']
    poff = resp['Payload'].v['ParamOffset']
    doff = resp['Payload'].v['DataOffset']

    # Get the raw packet bytes
    resp_rpkt = resp.to_s

    # Remove the NetBIOS header
    resp_rpkt.slice!(0, 4)

    resp_parm = resp_rpkt[poff, pcnt]
    resp_data = resp_rpkt[doff, dcnt]
    return resp_data

  rescue ::Exception
    raise $!
  end
end

#queryfs_fs_attributeObject

Obtains file system attribute information on the mounted tree


1819
1820
1821
1822
1823
1824
1825
1826
1827
# File 'lib/rex/proto/smb/client.rb', line 1819

def queryfs_fs_attribute
  data = queryfs(CONST::SMB_QUERY_FS_ATTRIBUTE_INFO)
  vals = data.unpack('VVVA*')
  return {
    'fs_attributes' => vals[0],
    'max_file_name' => vals[1],
    'fs_name'       => vals[3][0, vals[2]].gsub("\x00", '')
  }
end

#queryfs_fs_deviceObject

Obtains file system device information on the mounted tree


1809
1810
1811
1812
1813
1814
1815
1816
# File 'lib/rex/proto/smb/client.rb', line 1809

def queryfs_fs_device
  data = queryfs(CONST::SMB_QUERY_FS_DEVICE_INFO)
  vals = data.unpack('VV')
  return {
    'device_type'   => vals[0],
    'device_chars'  => vals[1],
  }
end

#queryfs_fs_sizeObject

Obtains file system size information on the mounted tree


1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
# File 'lib/rex/proto/smb/client.rb', line 1797

def queryfs_fs_size
  data = queryfs(CONST::SMB_QUERY_FS_SIZE_INFO)
  vals = data.unpack('VVVVVV')
  return {
    'total_alloc_units' => (vals[1] << 32) + vals[0],
    'total_free_units'  => (vals[3] << 32) + vals[2],
    'sectors_per_unit'  => vals[4],
    'bytes_per_sector'  => vals[5]
  }
end

#queryfs_fs_volumeObject

Obtains file system volume information on the mounted tree


1786
1787
1788
1789
1790
1791
1792
1793
1794
# File 'lib/rex/proto/smb/client.rb', line 1786

def queryfs_fs_volume
  data = queryfs(CONST::SMB_QUERY_FS_VOLUME_INFO)
  vals = data.unpack('VVVVCCA*')
  return {
    'create_time' => (vals[1] << 32) + vals[0],
    'serial'      => vals[2],
    'label'       => vals[6][0,vals[3]].gsub("\x00", '')
  }
end

#queryfs_info_allocationObject

Obtains allocation information on the mounted tree


1766
1767
1768
1769
1770
1771
1772
1773
# File 'lib/rex/proto/smb/client.rb', line 1766

def queryfs_info_allocation
  data = queryfs(CONST::SMB_INFO_ALLOCATION)
  head = %w{fs_id sectors_per_unit unit_total units_available bytes_per_sector}
  vals = data.unpack('VVVVv')
  info = { }
  head.each_index {|i| info[head[i]]=vals[i]}
  return info
end

#queryfs_info_volumeObject

Obtains volume information on the mounted tree


1776
1777
1778
1779
1780
1781
1782
1783
# File 'lib/rex/proto/smb/client.rb', line 1776

def queryfs_info_volume
  data = queryfs(CONST::SMB_INFO_VOLUME)
  vals = data.unpack('VCA*')
  return {
    'serial' => vals[0],
    'label'  => vals[2][0,vals[1]].gsub("\x00", '')
  }
end

#read(file_id = self.last_file_id, offset = 0, data_length = 64000, do_recv = true) ⇒ Object

Reads data from an open file handle


1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
# File 'lib/rex/proto/smb/client.rb', line 1296

def read(file_id = self.last_file_id, offset = 0, data_length = 64000, do_recv = true)

  pkt = CONST::SMB_READ_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_READ_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 10

  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['FileID'] = file_id
  pkt['Payload'].v['Offset'] = offset
  # pkt['Payload'].v['MaxCountHigh'] = (data_length / 65536).to_i
  pkt['Payload'].v['MaxCountLow'] = (data_length % 65536).to_i
  pkt['Payload'].v['MinCount'] = data_length
  pkt['Payload'].v['Reserved2'] = -1

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_READ_ANDX, true)

  err = ack['Payload']['SMB'].v['ErrorClass']

  # Catch some non-fatal error codes
  if (err != 0 && err != CONST::SMB_ERROR_BUFFER_OVERFLOW)
    failure = XCEPT::ErrorCode.new
    failure.word_count = ack['Payload']['SMB'].v['WordCount']
    failure.command = ack['Payload']['SMB'].v['Command']
    failure.error_code = ack['Payload']['SMB'].v['ErrorClass']
    raise failure
  end

  return ack
end

#session_request(name = '*SMBSERVER', do_recv = true) ⇒ Object

Request a SMB session over NetBIOS


449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'lib/rex/proto/smb/client.rb', line 449

def session_request(name = '*SMBSERVER', do_recv = true)

  name ||= '*SMBSERVER'

  data = ''
  data << "\x20" + UTILS.nbname_encode(name) + "\x00"
  data << "\x20" + CONST::NETBIOS_REDIR      + "\x00"

  pkt = CONST::NBRAW_PKT.make_struct
  pkt.v['Type'] = 0x81
  pkt['Payload'].v['Payload'] = data

  # Most SMB implementations can't handle this being fragmented
  ret = self.smb_send(pkt.to_s, EVADE::EVASION_NONE)
  return ret if not do_recv

  res = self.smb_recv

  ack = CONST::NBRAW_PKT.make_struct
  ack.from_s(res)

  if (ack.v['Type'] != 130)
    raise XCEPT::NetbiosSessionFailed
  end

  return ack
end

#session_setup(*args) ⇒ Object

Authenticate and establish a session


582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# File 'lib/rex/proto/smb/client.rb', line 582

def session_setup(*args)

  if (self.dialect =~ /^(NT LANMAN 1.0|NT LM 0.12)$/)

    if (self.challenge_key)
      return self.session_setup_no_ntlmssp(*args)
    end

    if ( self.extended_security )
      return self.session_setup_with_ntlmssp(*args)
    end

  end

  return self.session_setup_clear(*args)
end

#session_setup_clear(user = '', pass = '', domain = '', do_recv = true) ⇒ Object

Authenticate using clear-text passwords


600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
# File 'lib/rex/proto/smb/client.rb', line 600

def session_setup_clear(user = '', pass = '', domain = '', do_recv = true)

  data = [ pass, user, domain, self.native_os, self.native_lm ].collect{ |a| a + "\x00" }.join('');

  pkt = CONST::SMB_SETUP_LANMAN_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_SESSION_SETUP_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 10
  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['MaxBuff'] = 0xffdf
  pkt['Payload'].v['MaxMPX'] = 2
  pkt['Payload'].v['VCNum'] = 1
  pkt['Payload'].v['PasswordLen'] = pass.length + 1
  pkt['Payload'].v['Capabilities'] = 64
  pkt['Payload'].v['SessionKey'] = self.session_id
  pkt['Payload'].v['Payload'] = data

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_SESSION_SETUP_ANDX)

  if (ack['Payload'].v['Action'] != 1 and user.length > 0)
    self.auth_user = user
  end

  self.auth_user_id = ack['Payload']['SMB'].v['UserID']

  info = ack['Payload'].v['Payload'].split(/\x00/n)
  self.peer_native_os = info[0]
  self.peer_native_lm = info[1]
  self.default_domain = info[2]

  return ack
end

#session_setup_no_ntlmssp(user = '', pass = '', domain = '', do_recv = true) ⇒ Object

Authenticate without NTLMSSP


647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/rex/proto/smb/client.rb', line 647

def session_setup_no_ntlmssp(user = '', pass = '', domain = '', do_recv = true)

  # Requires a challenge key to have been seen during negotiation
  raise XCEPT::NTLM1MissingChallenge if not self.challenge_key

  #
  # We can not yet handle signing in this situation
  # But instead of throwing an exception,we will disable signing, continue and hope for the best.
  #

  #raise XCEPT::SigningError if self.require_signing
  self.require_signing = false if self.require_signing


  if NTLM_UTILS.is_pass_ntlm_hash?(pass)
    arglm = {
      :lm_hash => [ pass.upcase()[0,32] ].pack('H32'),
      :challenge =>  self.challenge_key
    }
    hash_lm = NTLM_CRYPT::lm_response(arglm)

    argntlm = {
      :ntlm_hash =>  [ pass.upcase()[33,65] ].pack('H32'),
      :challenge =>  self.challenge_key
    }
    hash_nt = NTLM_CRYPT::ntlm_response(argntlm)
  else
    hash_lm = pass.length > 0 ? NTLM_CRYPT.lanman_des(pass, self.challenge_key) : ''
    hash_nt = pass.length > 0 ? NTLM_CRYPT.ntlm_md4(pass, self.challenge_key)   : ''
  end

  data = ''
  data << hash_lm
  data << hash_nt
  data << user + "\x00"
  data << domain + "\x00"
  data << self.native_os + "\x00"
  data << self.native_lm + "\x00"

  pkt = CONST::SMB_SETUP_NTLMV1_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_SESSION_SETUP_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  pkt['Payload']['SMB'].v['Flags2'] = 0x2001
  pkt['Payload']['SMB'].v['WordCount'] = 13
  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['MaxBuff'] = 0xffdf
  pkt['Payload'].v['MaxMPX'] = 2
  pkt['Payload'].v['VCNum'] = 1
  pkt['Payload'].v['PasswordLenLM'] = hash_lm.length
  pkt['Payload'].v['PasswordLenNT'] = hash_nt.length
  pkt['Payload'].v['Capabilities'] = 64
  pkt['Payload'].v['SessionKey'] = self.session_id
  pkt['Payload'].v['Payload'] = data

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_SESSION_SETUP_ANDX)

  if (ack['Payload'].v['Action'] != 1 and user.length > 0)
    self.auth_user = user
  end

  self.auth_user_id = ack['Payload']['SMB'].v['UserID']

  info = ack['Payload'].v['Payload'].split(/\x00/n)

  self.peer_native_os = info[0]
  self.peer_native_lm = info[1]
  self.default_domain = info[2]

  return ack
end

#session_setup_no_ntlmssp_prehash(user, domain, hash_lm, hash_nt, do_recv = true) ⇒ Object

Authenticate without ntlmssp with a precomputed hash pair


725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
# File 'lib/rex/proto/smb/client.rb', line 725

def session_setup_no_ntlmssp_prehash(user, domain, hash_lm, hash_nt, do_recv = true)

  data = ''
  data << hash_lm
  data << hash_nt
  data << user + "\x00"
  data << domain + "\x00"
  data << self.native_os + "\x00"
  data << self.native_lm + "\x00"

  pkt = CONST::SMB_SETUP_NTLMV1_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_SESSION_SETUP_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  pkt['Payload']['SMB'].v['Flags2'] = 0x2001
  pkt['Payload']['SMB'].v['WordCount'] = 13
  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['MaxBuff'] = 0xffdf
  pkt['Payload'].v['MaxMPX'] = 2
  pkt['Payload'].v['VCNum'] = 1
  pkt['Payload'].v['PasswordLenLM'] = hash_lm.length
  pkt['Payload'].v['PasswordLenNT'] = hash_nt.length
  pkt['Payload'].v['Capabilities'] = 64
  pkt['Payload'].v['SessionKey'] = self.session_id
  pkt['Payload'].v['Payload'] = data

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_SESSION_SETUP_ANDX)

  if (ack['Payload'].v['Action'] != 1 and user.length > 0)
    self.auth_user = user
  end

  self.auth_user_id = ack['Payload']['SMB'].v['UserID']

  info = ack['Payload'].v['Payload'].split(/\x00/n)

  self.peer_native_os = info[0]
  self.peer_native_lm = info[1]
  self.default_domain = info[2]

  return ack
end

#session_setup_with_ntlmssp(user = '', pass = '', domain = '', name = nil, do_recv = true) ⇒ Object

Authenticate using extended security negotiation


773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
# File 'lib/rex/proto/smb/client.rb', line 773

def session_setup_with_ntlmssp(user = '', pass = '', domain = '', name = nil, do_recv = true)

  ntlm_options = {
      :signing 		=> self.require_signing,
      :usentlm2_session 	=> self.usentlm2_session,
      :use_ntlmv2 		=> self.use_ntlmv2,
      :send_lm 		=> self.send_lm,
      :send_ntlm		=> self.send_ntlm,
      :use_lanman_key		=> self.use_lanman_key
      }

  ntlmssp_flags = NTLM_UTILS.make_ntlm_flags(ntlm_options)

  if (name == nil)
    name = Rex::Text.rand_text_alphanumeric(16)
  end

  blob = NTLM_UTILS.make_ntlmssp_secblob_init(domain, name, ntlmssp_flags)

  native_data = ''
  native_data << self.native_os + "\x00"
  native_data << self.native_lm + "\x00"

  pkt = CONST::SMB_SETUP_NTLMV2_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_SESSION_SETUP_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end
  pkt['Payload']['SMB'].v['WordCount'] = 12
  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['MaxBuff'] = 0xffdf
  pkt['Payload'].v['MaxMPX'] = 2
  pkt['Payload'].v['VCNum'] = 1
  pkt['Payload'].v['SecurityBlobLen'] = blob.length
  pkt['Payload'].v['Capabilities'] = 0x800000d4
  pkt['Payload'].v['SessionKey'] = self.session_id
  pkt['Payload'].v['Payload'] = blob + native_data

  ret = self.smb_send(pkt.to_s)

  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_SESSION_SETUP_ANDX, true)


  # The server doesn't know about NTLM_NEGOTIATE
  if (ack['Payload']['SMB'].v['ErrorClass'] == 0x00020002)
    return session_setup_no_ntlmssp(user, pass, domain)
  end

  # Make sure the error code tells us to continue processing
  if (ack['Payload']['SMB'].v['ErrorClass'] != 0xc0000016)
    failure = XCEPT::ErrorCode.new
    failure.word_count = ack['Payload']['SMB'].v['WordCount']
    failure.command = ack['Payload']['SMB'].v['Command']
    failure.error_code = ack['Payload']['SMB'].v['ErrorClass']
    raise failure
  end

  # Extract the SecurityBlob from the response
  data = ack['Payload'].v['Payload']
  blob = data.slice!(0, ack['Payload'].v['SecurityBlobLen'])

  # Extract the native lanman and os strings
  info = data.split(/\x00/n)
  self.peer_native_os = info[0]
  self.peer_native_lm = info[1]

  # Save the temporary UserID for use in the next request
  temp_user_id = ack['Payload']['SMB'].v['UserID']

  # Get default data
  blob_data = NTLM_UTILS.parse_ntlm_type_2_blob(blob)
  self.challenge_key = blob_data[:challenge_key]
  server_ntlmssp_flags = blob_data[:server_ntlmssp_flags] #else should raise an error
  #netbios name
  self.default_name =  blob_data[:default_name] || ''
  #netbios domain
  self.default_domain = blob_data[:default_domain] || ''
  #dns name
  self.dns_host_name =  blob_data[:dns_host_name] || ''
  #dns domain
  self.dns_domain_name =  blob_data[:dns_domain_name] || ''
  #Client time
  chall_MsvAvTimestamp = blob_data[:chall_MsvAvTimestamp] || ''


  resp_lm, resp_ntlm, client_challenge, ntlm_cli_challenge = NTLM_UTILS.create_lm_ntlm_responses(user, pass, self.challenge_key, domain,
                      default_name, default_domain, dns_host_name,
                      dns_domain_name, chall_MsvAvTimestamp ,
                      self.spnopt, ntlm_options)
  enc_session_key = ''
  self.sequence_counter = 0

  if self.require_signing
    self.signing_key, enc_session_key, ntlmssp_flags = NTLM_UTILS.create_session_key(ntlmssp_flags, server_ntlmssp_flags, user, pass, domain,
                    self.challenge_key, client_challenge, ntlm_cli_challenge,
                    ntlm_options)
  end

  # Create the security blob data
  blob = NTLM_UTILS.make_ntlmssp_secblob_auth(domain, name, user, resp_lm, resp_ntlm, enc_session_key, ntlmssp_flags)

  pkt = CONST::SMB_SETUP_NTLMV2_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_SESSION_SETUP_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end
  pkt['Payload']['SMB'].v['WordCount'] = 12
  pkt['Payload']['SMB'].v['UserID'] = temp_user_id
  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['MaxBuff'] = 0xffdf
  pkt['Payload'].v['MaxMPX'] = 2
  pkt['Payload'].v['VCNum'] = 1
  pkt['Payload'].v['Capabilities'] = 0x8000d05c
  pkt['Payload'].v['SessionKey'] = self.session_id
  pkt['Payload'].v['SecurityBlobLen'] = blob.length
  pkt['Payload'].v['Payload'] = blob + native_data

  # NOTE: if do_recv is set to false, we cant reach here...
  self.smb_send(pkt.to_s)

  ack = self.smb_recv_parse(CONST::SMB_COM_SESSION_SETUP_ANDX, true)

  # Make sure that authentication succeeded
  if (ack['Payload']['SMB'].v['ErrorClass'] != 0)

    if (user.length == 0)
      # Ensure that signing is disabled when we hit this corner case
      self.require_signing = false

      # Fall back to the non-ntlmssp authentication method
      return self.session_setup_no_ntlmssp(user, pass, domain)
    end

    failure = XCEPT::ErrorCode.new
    failure.word_count = ack['Payload']['SMB'].v['WordCount']
    failure.command = ack['Payload']['SMB'].v['Command']
    failure.error_code = ack['Payload']['SMB'].v['ErrorClass']
    raise failure
  end

  self.auth_user_id = ack['Payload']['SMB'].v['UserID']

  if (ack['Payload'].v['Action'] != 1 and user.length > 0)
    self.auth_user = user
  end

  return ack
end

#session_setup_with_ntlmssp_blob(blob = '', do_recv = true, userid = 0) ⇒ Object

An exploit helper function for sending arbitrary SPNEGO blobs


940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
# File 'lib/rex/proto/smb/client.rb', line 940

def session_setup_with_ntlmssp_blob(blob = '', do_recv = true, userid = 0)
  native_data = ''
  native_data << self.native_os + "\x00"
  native_data << self.native_lm + "\x00"

  pkt = CONST::SMB_SETUP_NTLMV2_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_SESSION_SETUP_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  pkt['Payload']['SMB'].v['Flags2'] = 0x2801
  pkt['Payload']['SMB'].v['WordCount'] = 12
  pkt['Payload']['SMB'].v['UserID'] = userid
  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['MaxBuff'] = 0xffdf
  pkt['Payload'].v['MaxMPX'] = 2
  pkt['Payload'].v['VCNum'] = 1
  pkt['Payload'].v['SecurityBlobLen'] = blob.length
  pkt['Payload'].v['Capabilities'] = 0x8000d05c
  pkt['Payload'].v['SessionKey'] = self.session_id
  pkt['Payload'].v['Payload'] = blob + native_data

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  self.smb_recv_parse(CONST::SMB_COM_SESSION_SETUP_ANDX, false)
end

#session_setup_with_ntlmssp_temp(domain = '', name = nil, do_recv = true) ⇒ Object

Authenticate using extended security negotiation (NTLMSSP), but stop half-way, using the temporary ID


970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
# File 'lib/rex/proto/smb/client.rb', line 970

def session_setup_with_ntlmssp_temp(domain = '', name = nil, do_recv = true)

  if (name == nil)
    name = Rex::Text.rand_text_alphanumeric(16)
  end

  blob = NTLM_UTILS.make_ntlmssp_secblob_init(domain, name)

  native_data = ''
  native_data << self.native_os + "\x00"
  native_data << self.native_lm + "\x00"

  pkt = CONST::SMB_SETUP_NTLMV2_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_SESSION_SETUP_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  pkt['Payload']['SMB'].v['Flags2'] = 0x2801
  pkt['Payload']['SMB'].v['WordCount'] = 12
  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['MaxBuff'] = 0xffdf
  pkt['Payload'].v['MaxMPX'] = 2
  pkt['Payload'].v['VCNum'] = 1
  pkt['Payload'].v['SecurityBlobLen'] = blob.length
  pkt['Payload'].v['Capabilities'] = 0x8000d05c
  pkt['Payload'].v['SessionKey'] = self.session_id
  pkt['Payload'].v['Payload'] = blob + native_data

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_SESSION_SETUP_ANDX, true)

  # The server doesn't know about NTLM_NEGOTIATE, try ntlmv1
  if (ack['Payload']['SMB'].v['ErrorClass'] == 0x00020002)
    return session_setup_no_ntlmssp(user, pass, domain)
  end

  # Make sure the error code tells us to continue processing
  if (ack['Payload']['SMB'].v['ErrorClass'] != 0xc0000016)
    failure = XCEPT::ErrorCode.new
    failure.word_count = ack['Payload']['SMB'].v['WordCount']
    failure.command = ack['Payload']['SMB'].v['Command']
    failure.error_code = ack['Payload']['SMB'].v['ErrorClass']
    raise failure
  end

  # Extract the SecurityBlob from the response
  data = ack['Payload'].v['Payload']
  blob = data.slice!(0, ack['Payload'].v['SecurityBlobLen'])

  # Extract the native lanman and os strings
  info = data.split(/\x00/n)
  self.peer_native_os = info[0]
  self.peer_native_lm = info[1]

  # Save the temporary UserID for use in the next request
  self.auth_user_id = ack['Payload']['SMB'].v['UserID']

  # Extract the NTLM challenge key the lazy way
  cidx = blob.index("NTLMSSP\x00\x02\x00\x00\x00")

  if (cidx == -1)
    raise XCEPT::NTLM2MissingChallenge
  end

  # Store the challenge key
  self.challenge_key = blob[cidx + 24, 8]

  return ack
end

#smb_defaults(packet) ⇒ Object

Set the SMB parameters to some reasonable defaults


146
147
148
149
150
151
# File 'lib/rex/proto/smb/client.rb', line 146

def smb_defaults(packet)
  packet.v['MultiplexID'] = self.multiplex_id.to_i
  packet.v['TreeID'] = self.last_tree_id.to_i
  packet.v['UserID'] = self.auth_user_id.to_i
  packet.v['ProcessID'] = self.process_id.to_i
end

#smb_parse_close(pkt, data) ⇒ Object

Process incoming SMB_COM_CLOSE packets


425
426
427
428
429
430
431
432
433
# File 'lib/rex/proto/smb/client.rb', line 425

def smb_parse_close(pkt, data)

  # Process SMB error responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    return pkt
  end

  raise XCEPT::InvalidWordCount
end

#smb_parse_create(pkt, data) ⇒ Object

Process incoming SMB_COM_NT_CREATE_ANDX packets


314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/rex/proto/smb/client.rb', line 314

def smb_parse_create(pkt, data)

  # Windows says 42, but Samba says 34, same structure :-/
  if (pkt['Payload']['SMB'].v['WordCount'] == 42)
    res = CONST::SMB_CREATE_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  if (pkt['Payload']['SMB'].v['WordCount'] == 34)
    res = CONST::SMB_CREATE_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  # Process SMB error responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    return pkt
  end

  raise XCEPT::InvalidWordCount
end

#smb_parse_delete(pkt, data) ⇒ Object

Process incoming SMB_COM_DELETE packets


436
437
438
439
440
441
442
443
444
445
446
# File 'lib/rex/proto/smb/client.rb', line 436

def smb_parse_delete(pkt, data)

  # Process SMB error responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    res = CONST::SMB_DELETE_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  raise XCEPT::InvalidWordCount
end

#smb_parse_negotiate(pkt, data) ⇒ Object

Process incoming SMB_COM_NEGOTIATE packets


229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/rex/proto/smb/client.rb', line 229

def smb_parse_negotiate(pkt, data)
  #Process NTLM negotiate responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 17)
    res = CONST::SMB_NEG_RES_NT_PKT.make_struct
    res.from_s(data)
    return res
  end

  # Process LANMAN negotiate responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 13)
    res = CONST::SMB_NEG_RES_LM_PKT.make_struct
    res.from_s(data)
    return res
  end

  # Process ERROR negotiate responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 1)
    res = CONST::SMB_NEG_RES_ERR_PKT.make_struct
    res.from_s(data)
    return res
  end

  # Process SMB error responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    return pkt
  end

  raise XCEPT::InvalidWordCount
end

#smb_parse_nttrans(pkt, data) ⇒ Object

Process incoming SMB_COM_NT_TRANSACT packets


355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/rex/proto/smb/client.rb', line 355

def smb_parse_nttrans(pkt, data)

  # Process SMB error responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    return pkt
  end

  if (pkt['Payload']['SMB'].v['WordCount'] >= 18)
    res = CONST::SMB_NTTRANS_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  raise XCEPT::InvalidWordCount
end

#smb_parse_open(pkt, data) ⇒ Object

Process incoming SMB_COM_OPEN_ANDX packets


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# File 'lib/rex/proto/smb/client.rb', line 372

def smb_parse_open(pkt, data)
  # Process open responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 15)
    res = CONST::SMB_OPEN_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  # Process SMB error responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    return pkt
  end

  raise XCEPT::InvalidWordCount
end

#smb_parse_read(pkt, data) ⇒ Object

Process incoming SMB_COM_READ_ANDX packets


407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/rex/proto/smb/client.rb', line 407

def smb_parse_read(pkt, data)

  # Process read responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 12)
    res = CONST::SMB_READ_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  # Process SMB error responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    return pkt
  end

  raise XCEPT::InvalidWordCount
end

#smb_parse_session_setup(pkt, data) ⇒ Object

Process incoming SMB_COM_SESSION_SETUP_ANDX packets


260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/rex/proto/smb/client.rb', line 260

def smb_parse_session_setup(pkt, data)
  # Process NTLMSSP negotiate responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 4)
    res = CONST::SMB_SETUP_NTLMV2_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  # Process LANMAN responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 3)
    res = CONST::SMB_SETUP_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  # Process SMB error responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    return pkt
  end

  raise XCEPT::InvalidWordCount
end

#smb_parse_trans(pkt, data) ⇒ Object

Process incoming SMB_COM_TRANSACTION packets


338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/rex/proto/smb/client.rb', line 338

def smb_parse_trans(pkt, data)

  if (pkt['Payload']['SMB'].v['WordCount'] == 10)
    res = CONST::SMB_TRANS_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  # Process SMB error responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    return pkt
  end

  raise XCEPT::InvalidWordCount
end

#smb_parse_tree_connect(pkt, data) ⇒ Object

Process incoming SMB_COM_TREE_CONNECT_ANDX packets


284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/rex/proto/smb/client.rb', line 284

def smb_parse_tree_connect(pkt, data)

  if (pkt['Payload']['SMB'].v['WordCount'] == 3)
    res = CONST::SMB_TREE_CONN_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  # Process SMB error responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    return pkt
  end

  raise XCEPT::InvalidWordCount
end

#smb_parse_tree_disconnect(pkt, data) ⇒ Object

Process incoming SMB_COM_TREE_DISCONNECT packets


301
302
303
304
305
306
307
308
309
310
311
# File 'lib/rex/proto/smb/client.rb', line 301

def smb_parse_tree_disconnect(pkt, data)

  # Process SMB responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    res = CONST::SMB_TREE_DISCONN_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  raise XCEPT::InvalidWordCount
end

#smb_parse_write(pkt, data) ⇒ Object

Process incoming SMB_COM_WRITE_ANDX packets


389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/rex/proto/smb/client.rb', line 389

def smb_parse_write(pkt, data)

  # Process write responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 6)
    res = CONST::SMB_WRITE_RES_PKT.make_struct
    res.from_s(data)
    return res
  end

  # Process SMB error responses
  if (pkt['Payload']['SMB'].v['WordCount'] == 0)
    return pkt
  end

  raise XCEPT::InvalidWordCount
end

#smb_recvObject

Read a SMB packet from the socket


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
101
102
103
104
105
106
107
108
109
110
# File 'lib/rex/proto/smb/client.rb', line 68

def smb_recv

  data = socket.timed_read(4, self.read_timeout)
  if (data.nil? or data.length < 4)
    raise XCEPT::NoReply
  end

  recv_len = data[2,2].unpack('n')[0]
  if (recv_len == 0)
    return data
  end

  recv_len += 4

  while (data.length != recv_len)
    buff = ''

    begin
      buff << self.socket.timed_read(recv_len - data.length, self.read_timeout)
    rescue Timeout::Error
    rescue
      raise XCEPT::ReadPacket
    end

    if (buff.nil? or buff.length == 0)
      raise XCEPT::ReadPacket
    end

    data << buff
  end

  #signing
  if self.require_signing && self.signing_key != ''
    if self.verify_signature
      raise XCEPT::IncorrectSigningError if not CRYPT::is_signature_correct?(self.signing_key,self.sequence_counter,data)
    end
    self.sequence_counter += 1
  end

  return data


end

#smb_recv_parse(expected_type, ignore_errors = false) ⇒ Object

The main dispatcher for all incoming SMB packets


155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
# File 'lib/rex/proto/smb/client.rb', line 155

def smb_recv_parse(expected_type, ignore_errors = false)

  # This will throw an exception if it fails to read the whole packet
  data = self.smb_recv

  pkt = CONST::SMB_BASE_PKT.make_struct
  pkt.from_s(data)
  res  = pkt

  begin
    case pkt['Payload']['SMB'].v['Command']

      when CONST::SMB_COM_NEGOTIATE
        res =  smb_parse_negotiate(pkt, data)

      when CONST::SMB_COM_SESSION_SETUP_ANDX
        res =  smb_parse_session_setup(pkt, data)

      when CONST::SMB_COM_TREE_CONNECT_ANDX
        res =  smb_parse_tree_connect(pkt, data)

      when CONST::SMB_COM_TREE_DISCONNECT
        res =  smb_parse_tree_disconnect(pkt, data)

      when CONST::SMB_COM_NT_CREATE_ANDX
        res =  smb_parse_create(pkt, data)

      when CONST::SMB_COM_TRANSACTION, CONST::SMB_COM_TRANSACTION2
        res =  smb_parse_trans(pkt, data)

      when CONST::SMB_COM_NT_TRANSACT
        res =  smb_parse_nttrans(pkt, data)

      when CONST::SMB_COM_NT_TRANSACT_SECONDARY
        res =  smb_parse_nttrans(pkt, data)

      when CONST::SMB_COM_OPEN_ANDX
        res =  smb_parse_open(pkt, data)

      when CONST::SMB_COM_WRITE_ANDX
        res =  smb_parse_write(pkt, data)

      when CONST::SMB_COM_READ_ANDX
        res =  smb_parse_read(pkt, data)

      when CONST::SMB_COM_CLOSE
        res =  smb_parse_close(pkt, data)

      when CONST::SMB_COM_DELETE
        res =  smb_parse_delete(pkt, data)

      else
        raise XCEPT::InvalidCommand
    end

    if (pkt['Payload']['SMB'].v['Command'] != expected_type)
      raise XCEPT::InvalidType
    end

    if (ignore_errors == false and pkt['Payload']['SMB'].v['ErrorClass'] != 0)
      raise XCEPT::ErrorCode
    end

  rescue XCEPT::InvalidWordCount, XCEPT::InvalidCommand, XCEPT::InvalidType, XCEPT::ErrorCode
      $!.word_count = pkt['Payload']['SMB'].v['WordCount']
      $!.command = pkt['Payload']['SMB'].v['Command']
      $!.error_code = pkt['Payload']['SMB'].v['ErrorClass']
      raise $!
  end

  return res
end

#smb_send(data, evasion_level = 0) ⇒ Object

Send a SMB packet down the socket


113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/rex/proto/smb/client.rb', line 113

def smb_send(data, evasion_level=0)

  # evasion_level is ignored, since real evasion happens
  # in the actual socket layer

  size = 0
  wait = 0

  #signing
  if self.require_signing && self.signing_key != ''
    data = CRYPT::sign_smb_packet(self.signing_key, self.sequence_counter, data)
    self.sequence_counter += 1
  end

  begin
    # Just send the packet and return
    if (size == 0 or size >= data.length)
      return self.socket.put(data)
    end

    # Break the packet up into chunks and wait between them
    ret = 0
    while ( (chunk = data.slice!(0, size)).length > 0 )
      ret = self.socket.put(chunk)
      if (wait > 0)
        ::IO.select(nil, nil, nil, wait)
      end
    end
    return ret
  end
end

1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
# File 'lib/rex/proto/smb/client.rb', line 1739

def symlink(src,dst)
  parm = [513, 0x00000000].pack('vV') + src + "\x00"

  begin
    resp = trans2(CONST::TRANS2_SET_PATH_INFO, parm, dst + "\x00")

    pcnt = resp['Payload'].v['ParamCount']
    dcnt = resp['Payload'].v['DataCount']
    poff = resp['Payload'].v['ParamOffset']
    doff = resp['Payload'].v['DataOffset']

    # Get the raw packet bytes
    resp_rpkt = resp.to_s

    # Remove the NetBIOS header
    resp_rpkt.slice!(0, 4)

    resp_parm = resp_rpkt[poff, pcnt]
    resp_data = resp_rpkt[doff, dcnt]
    return resp_data

  rescue ::Exception
    raise $!
  end
end

#trans(pipe, param = '', body = '', setup_count = 0, setup_data = '', no_response = false, do_recv = true) ⇒ Object

Perform a transaction against a given pipe name


1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
# File 'lib/rex/proto/smb/client.rb', line 1358

def trans(pipe, param = '', body = '', setup_count = 0, setup_data = '', no_response = false, do_recv = true)

  # Null-terminate the pipe parameter if needed
  if (pipe[-1,1] != "\x00")
    pipe << "\x00"
  end

  pkt = CONST::SMB_TRANS_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  # Packets larger than mlen will cause XP SP2 to disconnect us ;-(
  mlen = 4200

  # Figure out how much space is taken up by our current arguments
  xlen =  pipe.length + param.length + body.length

  filler1 = ''
  filler2 = ''

  # Fill any available space depending on the evasion settings
  if (xlen < mlen)
    filler1 = EVADE.make_offset_filler(evasion_opts['pad_data'], (mlen-xlen)/2)
    filler2 = EVADE.make_offset_filler(evasion_opts['pad_data'], (mlen-xlen)/2)
  end

  # Squish the whole thing together
  data = pipe + filler1 + param + filler2 + body

  # Throw some form of a warning out?
  if (data.length > mlen)
    # XXX This call will more than likely fail :-(
  end

  # Calculate all of the offsets
  base_offset = pkt.to_s.length + (setup_count * 2) - 4
  param_offset = base_offset + pipe.length + filler1.length
  data_offset = param_offset + filler2.length + param.length

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_TRANSACTION
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 14 + setup_count

  pkt['Payload'].v['ParamCountTotal'] = param.length
  pkt['Payload'].v['DataCountTotal'] = body.length
  pkt['Payload'].v['ParamCountMax'] = 1024
  pkt['Payload'].v['DataCountMax'] = 65000
  pkt['Payload'].v['ParamCount'] = param.length
  pkt['Payload'].v['ParamOffset'] = param_offset
  pkt['Payload'].v['DataCount'] = body.length
  pkt['Payload'].v['DataOffset'] = data_offset
  pkt['Payload'].v['SetupCount'] = setup_count
  pkt['Payload'].v['SetupData'] = setup_data

  pkt['Payload'].v['Payload'] = data

  if no_response
    pkt['Payload'].v['Flags'] = 2
  end

  ret = self.smb_send(pkt.to_s)
  return ret if no_response or not do_recv

  self.smb_recv_parse(CONST::SMB_COM_TRANSACTION)
end

#trans2(subcommand, param = '', body = '', do_recv = true) ⇒ Object

Perform a transaction2 request using the specified subcommand, parameters, and data


1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
# File 'lib/rex/proto/smb/client.rb', line 1580

def trans2(subcommand, param = '', body = '', do_recv = true)

  setup_count = 1
  setup_data = [subcommand].pack('v')

  data = param + body

  pkt = CONST::SMB_TRANS2_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  base_offset = pkt.to_s.length + (setup_count * 2) - 4
  param_offset = base_offset
  data_offset = param_offset + param.length

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_TRANSACTION2
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 14 + setup_count

  pkt['Payload'].v['ParamCountTotal'] = param.length
  pkt['Payload'].v['DataCountTotal'] = body.length
  pkt['Payload'].v['ParamCountMax'] = 1024
  pkt['Payload'].v['DataCountMax'] = 65000
  pkt['Payload'].v['ParamCount'] = param.length
  pkt['Payload'].v['ParamOffset'] = param_offset
  pkt['Payload'].v['DataCount'] = body.length
  pkt['Payload'].v['DataOffset'] = data_offset
  pkt['Payload'].v['SetupCount'] = setup_count
  pkt['Payload'].v['SetupData'] = setup_data

  pkt['Payload'].v['Payload'] = data

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_TRANSACTION2)

  return ack
end

#trans_mailslot(name, data = '') ⇒ Object

Perform a mailslot write over SMB Warning: This can kill srv.sys unless MS06-035 is applied


1349
1350
1351
1352
1353
1354
1355
# File 'lib/rex/proto/smb/client.rb', line 1349

def trans_mailslot (name, data = '')
  # Setup data must be:
  #  Operation: 1 (write)
  #   Priority: 0
  #      Class: Reliable
  self.trans_maxzero(name, '', data, 3, [1, 0, 1].pack('vvv'), true )
end

#trans_maxzero(pipe, param = '', body = '', setup_count = 0, setup_data = '', no_response = false, do_recv = true) ⇒ Object

Perform a transaction against a given pipe name Difference from trans: sets MaxParam/MaxData to zero This is required to trigger mailslot bug :-(


1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
# File 'lib/rex/proto/smb/client.rb', line 1436

def trans_maxzero(pipe, param = '', body = '', setup_count = 0, setup_data = '', no_response = false, do_recv = true)

  # Null-terminate the pipe parameter if needed
  if (pipe[-1] != 0)
    pipe << "\x00"
  end

  pkt = CONST::SMB_TRANS_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  # Packets larger than mlen will cause XP SP2 to disconnect us ;-(
  mlen = 4200

  # Figure out how much space is taken up by our current arguments
  xlen =  pipe.length + param.length + body.length

  filler1 = ''
  filler2 = ''

  # Fill any available space depending on the evasion settings
  if (xlen < mlen)
    filler1 = EVADE.make_offset_filler(evasion_opts['pad_data'], (mlen-xlen)/2)
    filler2 = EVADE.make_offset_filler(evasion_opts['pad_data'], (mlen-xlen)/2)
  end

  # Squish the whole thing together
  data = pipe + filler1 + param + filler2 + body

  # Throw some form of a warning out?
  if (data.length > mlen)
    # XXX This call will more than likely fail :-(
  end

  # Calculate all of the offsets
  base_offset = pkt.to_s.length + (setup_count * 2) - 4
  param_offset = base_offset + pipe.length + filler1.length
  data_offset = param_offset + filler2.length + param.length

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_TRANSACTION
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 14 + setup_count

  pkt['Payload'].v['ParamCountTotal'] = param.length
  pkt['Payload'].v['DataCountTotal'] = body.length
  pkt['Payload'].v['ParamCountMax'] = 0
  pkt['Payload'].v['DataCountMax'] = 0
  pkt['Payload'].v['ParamCount'] = param.length
  pkt['Payload'].v['ParamOffset'] = param_offset
  pkt['Payload'].v['DataCount'] = body.length
  pkt['Payload'].v['DataOffset'] = data_offset
  pkt['Payload'].v['SetupCount'] = setup_count
  pkt['Payload'].v['SetupData'] = setup_data

  pkt['Payload'].v['Payload'] = data

  if no_response
    pkt['Payload'].v['Flags'] = 2
  end

  ret = self.smb_send(pkt.to_s)
  return ret if no_response or not do_recv

  self.smb_recv_parse(CONST::SMB_COM_TRANSACTION)
end

#trans_named_pipe(file_id, data = '', no_response = nil) ⇒ Object

Perform a transaction against a named pipe


1342
1343
1344
1345
# File 'lib/rex/proto/smb/client.rb', line 1342

def trans_named_pipe(file_id, data = '', no_response = nil)
  pipe = EVADE.make_trans_named_pipe_name(evasion_opts['pad_file'])
  self.trans(pipe, '', data, 2, [0x26, file_id].pack('vv'), no_response)
end

#trans_nonull(pipe, param = '', body = '', setup_count = 0, setup_data = '', no_response = false, do_recv = true) ⇒ Object

Perform a transaction against a given pipe name (no null terminator)


1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
# File 'lib/rex/proto/smb/client.rb', line 1511

def trans_nonull(pipe, param = '', body = '', setup_count = 0, setup_data = '', no_response = false, do_recv = true)

  pkt = CONST::SMB_TRANS_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  # Packets larger than mlen will cause XP SP2 to disconnect us ;-(
  mlen = 4200

  # Figure out how much space is taken up by our current arguments
  xlen =  pipe.length + param.length + body.length

  filler1 = ''
  filler2 = ''

  # Fill any available space depending on the evasion settings
  if (xlen < mlen)
    filler1 = EVADE.make_offset_filler(evasion_opts['pad_data'], (mlen-xlen)/2)
    filler2 = EVADE.make_offset_filler(evasion_opts['pad_data'], (mlen-xlen)/2)
  end

  # Squish the whole thing together
  data = pipe + filler1 + param + filler2 + body

  # Throw some form of a warning out?
  if (data.length > mlen)
    # XXX This call will more than likely fail :-(
  end

  # Calculate all of the offsets
  base_offset = pkt.to_s.length + (setup_count * 2) - 4
  param_offset = base_offset + pipe.length + filler1.length
  data_offset = param_offset + filler2.length + param.length

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_TRANSACTION
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 14 + setup_count

  pkt['Payload'].v['ParamCountTotal'] = param.length
  pkt['Payload'].v['DataCountTotal'] = body.length
  pkt['Payload'].v['ParamCountMax'] = 0
  pkt['Payload'].v['DataCountMax'] = 0
  pkt['Payload'].v['ParamCount'] = param.length
  pkt['Payload'].v['ParamOffset'] = param_offset
  pkt['Payload'].v['DataCount'] = body.length
  pkt['Payload'].v['DataOffset'] = data_offset
  pkt['Payload'].v['SetupCount'] = setup_count
  pkt['Payload'].v['SetupData'] = setup_data

  pkt['Payload'].v['Payload'] = data

  if no_response
    pkt['Payload'].v['Flags'] = 2
  end

  ret = self.smb_send(pkt.to_s)
  return ret if no_response or not do_recv

  self.smb_recv_parse(CONST::SMB_COM_TRANSACTION)
end

#tree_connect(share = 'IPC$', pass = '', do_recv = true) ⇒ Object

Connect to a specified share with an optional password


1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
# File 'lib/rex/proto/smb/client.rb', line 1043

def tree_connect(share = 'IPC$', pass = '', do_recv = true)

  data = [ pass, share, '?????' ].collect{ |a| a + "\x00" }.join('');

  pkt = CONST::SMB_TREE_CONN_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])
  pkt['Payload']['SMB'].v['TreeID'] = 0

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_TREE_CONNECT_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 4
  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['PasswordLen'] = pass.length + 1
  pkt['Payload'].v['Capabilities'] = 64
  pkt['Payload'].v['Payload'] = data

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_TREE_CONNECT_ANDX)

  self.last_tree_id = ack['Payload']['SMB'].v['TreeID']
  # why bother?
  # info = ack['Payload'].v['Payload'].split(/\x00/)

  return ack
end

#tree_disconnect(tree_id = self.last_tree_id, do_recv = true) ⇒ Object

Disconnect from the current tree


1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
# File 'lib/rex/proto/smb/client.rb', line 1080

def tree_disconnect(tree_id = self.last_tree_id, do_recv = true)

  pkt = CONST::SMB_TREE_DISCONN_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_TREE_DISCONNECT
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2807
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 0
  pkt['Payload']['SMB'].v['TreeID'] = tree_id

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_TREE_DISCONNECT)

  if (tree_id == self.last_tree_id)
    self.last_tree_id = 0
  end

  return ack
end

#write(file_id = self.last_file_id, offset = 0, data = '', do_recv = true) ⇒ Object

Writes data to an open file handle


1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
# File 'lib/rex/proto/smb/client.rb', line 1255

def write(file_id = self.last_file_id, offset = 0, data = '', do_recv = true)
  pkt = CONST::SMB_WRITE_PKT.make_struct
  self.smb_defaults(pkt['Payload']['SMB'])

  data_offset = pkt.to_s.length - 4

  filler = EVADE.make_offset_filler(evasion_opts['pad_data'], 4096 - data.length - data_offset)

  pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_WRITE_ANDX
  pkt['Payload']['SMB'].v['Flags1'] = 0x18
  if self.require_signing
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] = 0x2805
  else
    #ascii
    pkt['Payload']['SMB'].v['Flags2'] =  0x2801
  end

  pkt['Payload']['SMB'].v['WordCount'] = 14

  pkt['Payload'].v['AndX'] = 255
  pkt['Payload'].v['FileID'] = file_id
  pkt['Payload'].v['Offset'] = offset
  pkt['Payload'].v['Reserved2'] = -1
  pkt['Payload'].v['WriteMode'] = 8
  pkt['Payload'].v['Remaining'] = data.length
  # pkt['Payload'].v['DataLenHigh'] = (data.length / 65536).to_i
  pkt['Payload'].v['DataLenLow'] = (data.length % 65536).to_i
  pkt['Payload'].v['DataOffset'] = data_offset + filler.length
  pkt['Payload'].v['Payload'] = filler + data

  ret = self.smb_send(pkt.to_s)
  return ret if not do_recv

  ack = self.smb_recv_parse(CONST::SMB_COM_WRITE_ANDX)

  return ack
end