Module: Msf::Exploit::Remote::MsSamr

Includes:
Auxiliary::Report, SMB::Client::Authenticated
Defined in:
lib/msf/core/exploit/remote/ms_samr.rb

Defined Under Namespace

Classes: ComputerInfo, MsSamrAuthenticationError, MsSamrBadConfigError, MsSamrConnectionError, MsSamrError, MsSamrNotFoundError, MsSamrUnexpectedReplyError, MsSamrUnknownError, SamrConnection

Constant Summary

Constants included from SMB::Client

SMB::Client::CONST, SMB::Client::DCERPCClient, SMB::Client::DCERPCPacket, SMB::Client::DCERPCResponse, SMB::Client::DCERPCUUID, SMB::Client::NDR, SMB::Client::SIMPLE, SMB::Client::XCEPT

Instance Attribute Summary

Attributes included from SMB::Client

#simple

Attributes included from Tcp

#sock

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Auxiliary::Report

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

Methods included from Metasploit::Framework::Require

optionally, optionally_active_record_railtie, optionally_include_metasploit_credential_creation, #optionally_include_metasploit_credential_creation, optionally_require_metasploit_db_gem_engines

Methods included from Kerberos::ServiceAuthenticator::Options

#kerberos_auth_options

Methods included from Kerberos::Ticket::Storage

#kerberos_storage_options, #kerberos_ticket_storage, store_ccache

Methods included from SMB::Client

#connect, #domain, #domain_username_split, #smb_create, #smb_direct, #smb_enumprinters, #smb_enumprintproviders, #smb_file_exist?, #smb_file_rm, #smb_fingerprint, #smb_fingerprint_windows_lang, #smb_fingerprint_windows_sp, #smb_hostname, #smb_lanman_netshareenumall, #smb_login, #smb_lookup_share_type, #smb_netshareenumall, #smb_netsharegetinfo, #smb_open, #smb_peer_lm, #smb_peer_os, #smb_srvsvc_netshareenumall, #smb_srvsvc_netsharegetinfo, #smbhost, #splitname, #unicode

Methods included from Tcp

#chost, #cleanup, #connect, #connect_timeout, #cport, #disconnect, #handler, #lhost, #lport, #peer, #print_prefix, #proxies, #rhost, #rport, #set_tcp_evasions, #shutdown, #ssl, #ssl_cipher, #ssl_verify_mode, #ssl_version

Class Method Details

.connect_ipcObject



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
# File 'lib/msf/core/exploit/remote/ms_samr.rb', line 165

def connect_ipc
  begin
    connect
  rescue Rex::ConnectionError => e
    raise MsSamrConnectionError, e.message
  end

  begin
    
  rescue Rex::Proto::SMB::Exceptions::Error, RubySMB::Error::RubySMBError => e
    raise MsSamrAuthenticationError, "Unable to authenticate ([#{e.class}] #{e})."
  end
  report_service(
    host: rhost,
    port: rport,
    host_name: simple.client.default_name,
    proto: 'tcp',
    name: 'smb',
    info: "Module: #{fullname}, last negotiated version: SMBv#{simple.client.negotiated_smb_version} (dialect = #{simple.client.dialect})"
  )

  begin
    simple.client.tree_connect("\\\\#{sock.peerhost}\\IPC$")
  rescue RubySMB::Error::RubySMBError => e
    raise MsSamrConnectionError, "Unable to connect to the remote IPC$ share ([#{e.class}] #{e})."
  end
end

.connect_samr(tree) ⇒ Object



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
# File 'lib/msf/core/exploit/remote/ms_samr.rb', line 193

def connect_samr(tree)
  begin
    vprint_status('Connecting to Security Account Manager (SAM) Remote Protocol')
    samr = tree.open_file(filename: 'samr', write: true, read: true)

    vprint_status('Binding to \\samr...')
    samr.bind(endpoint: RubySMB::Dcerpc::Samr)
    vprint_good('Bound to \\samr')
    server_handle = samr.samr_connect
  rescue RubySMB::Dcerpc::Error::FaultError => e
    elog(e.message, error: e)
    raise MsSamrUnexpectedReplyError, "Connection failed (DCERPC fault: #{e.status_name})"
  end

  if datastore['SMBDomain'].blank? || datastore['SMBDomain'] == '.'
    all_domains = samr.samr_enumerate_domains_in_sam_server(server_handle: server_handle).map(&:to_s).map(&:encode)
    all_domains.delete('Builtin')
    if all_domains.empty?
      raise MsSamrNotFoundError, 'No domains were found on the SAM server.'
    elsif all_domains.length > 1
      print_status("Enumerated domains: #{all_domains.join(', ')}")
      raise MsSamrBadConfigError, 'The SAM server has more than one domain, the target must be specified.'
    end

    domain_name = all_domains.first
    print_status("Using automatically identified domain: #{domain_name}")
  else
    domain_name = datastore['SMBDomain']
  end

  domain_sid = samr.samr_lookup_domain(server_handle: server_handle, name: domain_name)
  domain_handle = samr.samr_open_domain(server_handle: server_handle, domain_id: domain_sid)

  SamrConnection.new(samr, server_handle, domain_handle, domain_name)

rescue RubySMB::Dcerpc::Error::DcerpcError => e
  elog(e.message, error: e)
  raise MsSamrUnexpectedReplyError, e.message
rescue RubySMB::Error::RubySMBError
  elog(e.message, error: e)
  raise MsSamrUnknownError, e.message
end

.get_computer_sid(samr_con, computer_name) ⇒ Object



269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/msf/core/exploit/remote/ms_samr.rb', line 269

def get_computer_sid(samr_con, computer_name)
  details = samr_con.samr.samr_lookup_names_in_domain(
    domain_handle: samr_con.domain_handle,
    names: [ computer_name ]
  )
  raise MsSamrNotFoundError, 'The computer was not found.' if details.nil?

  details = details[computer_name]
  samr_con.samr.samr_rid_to_sid(
    object_handle: samr_con.domain_handle,
    rid: details[:rid]
  ).to_s
end

.random_hostname(prefix: 'DESKTOP') ⇒ Object



236
237
238
# File 'lib/msf/core/exploit/remote/ms_samr.rb', line 236

def random_hostname(prefix: 'DESKTOP')
  "#{prefix}-#{Rex::Text.rand_base(8, '', ('A'..'Z').to_a + ('0'..'9').to_a)}$"
end

.report_creds(domain, username, password) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/msf/core/exploit/remote/ms_samr.rb', line 240

def report_creds(domain, username, password)
  service_data = {
    address: datastore['RHOST'],
    port: datastore['RPORT'],
    service_name: 'smb',
    protocol: 'tcp',
    workspace_id: myworkspace_id
  }

  credential_data = {
    module_fullname: fullname,
    origin_type: :service,
    private_data: password,
    private_type: :password,
    username: username,
    realm_key: Metasploit::Model::Realm::Key::ACTIVE_DIRECTORY_DOMAIN,
    realm_value: domain
  }.merge(service_data)

  credential_core = create_credential(credential_data)

   = {
    core: credential_core,
    status: Metasploit::Model::Login::Status::UNTRIED
  }.merge(service_data)

  ()
end

Instance Method Details

#add_computer(opts = {}) ⇒ Object



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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/msf/core/exploit/remote/ms_samr.rb', line 34

def add_computer(opts = {})
  tree = opts[:tree] || connect_ipc

  samr_con = connect_samr(tree)

  computer_name = opts[:computer_name] || datastore['COMPUTER_NAME']
  if computer_name.blank?
    computer_name = random_hostname
    4.downto(0) do |attempt|
      break if samr_con.samr.samr_lookup_names_in_domain(
        domain_handle: samr_con.domain_handle,
        names: [ computer_name ]
      ).nil?

      computer_name = random_hostname
      raise MsSamrBadConfigError, 'Could not find an unused computer name.' if attempt == 0
    end
  else
    if samr_con.samr.samr_lookup_names_in_domain(domain_handle: samr_con.domain_handle, names: [ computer_name ])
      raise MsSamrBadConfigError, 'The specified computer name already exists.'
    end
  end

  result = samr_con.samr.samr_create_user2_in_domain(
    domain_handle: samr_con.domain_handle,
    name: computer_name,
    account_type: RubySMB::Dcerpc::Samr::USER_WORKSTATION_TRUST_ACCOUNT,
    desired_access: RubySMB::Dcerpc::Samr::USER_FORCE_PASSWORD_CHANGE | RubySMB::Dcerpc::Samr::MAXIMUM_ALLOWED
  )

  user_handle = result[:user_handle]
  if datastore['COMPUTER_PASSWORD'].blank?
    computer_password = Rex::Text.rand_text_alphanumeric(32)
  else
    computer_password = datastore['COMPUTER_PASSWORD']
  end

   = RubySMB::Dcerpc::Samr::SamprUserInfoBuffer.new(
    tag: RubySMB::Dcerpc::Samr::USER_INTERNAL4_INFORMATION_NEW,
    member: RubySMB::Dcerpc::Samr::SamprUserInternal4InformationNew.new(
      i1: {
        password_expired: 1,
        which_fields: RubySMB::Dcerpc::Samr::USER_ALL_NTPASSWORDPRESENT | RubySMB::Dcerpc::Samr::USER_ALL_PASSWORDEXPIRED
      },
      user_password: {
        buffer: RubySMB::Dcerpc::Samr::SamprEncryptedUserPasswordNew.encrypt_password(
          computer_password,
          @simple.client.application_key
        )
      }
    )
  )
  samr_con[:samr].samr_set_information_user2(
    user_handle: user_handle,
    user_info: 
  )

   = RubySMB::Dcerpc::Samr::SamprUserInfoBuffer.new(
    tag: RubySMB::Dcerpc::Samr::USER_CONTROL_INFORMATION,
    member: RubySMB::Dcerpc::Samr::UserControlInformation.new(
      user_account_control: RubySMB::Dcerpc::Samr::USER_WORKSTATION_TRUST_ACCOUNT
    )
  )
  samr_con.samr.samr_set_information_user2(
    user_handle: user_handle,
    user_info: 
  )
  print_good("Successfully created #{samr_con.domain_name}\\#{computer_name}")
  print_good("  Password: #{computer_password}")
  print_good("  SID:      #{get_computer_sid(samr_con, computer_name)}")
  report_creds(samr_con.domain_name, computer_name, computer_password)

  ComputerInfo.new(computer_name, computer_password)

rescue RubySMB::Dcerpc::Error::SamrError => e
  raise MsSamrUnknownError, "A DCERPC SAMR error occurred: #{e.message}"
ensure
  if samr_con
    samr_con.samr.close_handle(user_handle) if user_handle
    samr_con.samr.close_handle(samr_con.domain_handle) if samr_con.domain_handle
    samr_con.samr.close_handle(samr_con.server_handle) if samr_con.server_handle
  end
end

#delete_computer(opts = {}) ⇒ Object



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/msf/core/exploit/remote/ms_samr.rb', line 118

def delete_computer(opts = {})
  tree = opts[:tree] || connect_ipc

  samr_con = connect_samr(tree)

  computer_name = opts[:computer_name] || datastore['COMPUTER_NAME']
  if computer_name.blank?
    raise MsSamrBadConfigError, 'Unable to delete the computer account since its name is unknown'
  end

  details = samr_con.samr.samr_lookup_names_in_domain(domain_handle: samr_con.domain_handle, names: [ computer_name ])
  raise MsSamrBadConfigError, 'The specified computer was not found.' if details.nil?
  details = details[computer_name]

  user_handle = samr_con.samr.samr_open_user(domain_handle: samr_con.domain_handle, user_id: details[:rid])
  samr_con.samr.samr_delete_user(user_handle: user_handle)
  print_good('The specified computer has been deleted.')
rescue RubySMB::Dcerpc::Error::SamrError => e
  # `user_handle` only needs to be closed if an error occurs in `samr_delete_user`
  # If this method succeed, the server took care of closing the handle
  samr_con.samr.close_handle(user_handle) if user_handle
  raise MsSamrUnknownError, "Could not delete the computer #{computer_name}: #{e.message}"
ensure
  samr_con.samr.close_handle(samr_con.domain_handle) if samr_con.domain_handle
  samr_con.samr.close_handle(samr_con.server_handle) if samr_con.server_handle
end

#initialize(info = {}) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/msf/core/exploit/remote/ms_samr.rb', line 25

def initialize(info = {})
  super

  register_options([
    OptString.new('COMPUTER_NAME', [ false, 'The computer name' ]),
    OptString.new('COMPUTER_PASSWORD', [ false, 'The password for the new computer' ]),
  ], Msf::Exploit::Remote::MsSamr)
end

#lookup_computer(opts = {}) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/msf/core/exploit/remote/ms_samr.rb', line 145

def lookup_computer(opts = {})
  tree = opts[:tree] || connect_ipc

  samr_con = connect_samr(tree)

  computer_name = opts[:computer_name] || datastore['COMPUTER_NAME']
  if computer_name.blank?
    raise MsSamrBadConfigError, 'Unable to lookup the computer account since its name is unknown'
  end

  sid = get_computer_sid(samr_con, computer_name)
  print_good("Found #{samr_con.domain_name}\\#{computer_name} (SID: #{sid})")
ensure
  samr_con.samr.close_handle(samr_con.domain_handle) if samr_con.domain_handle
  samr_con.samr.close_handle(samr_con.server_handle) if samr_con.server_handle
end