Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rapid7
GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/auxiliary/admin/smb/change_password.rb
19851 views
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
require 'ruby_smb/dcerpc/client'
7
8
class MetasploitModule < Msf::Auxiliary
9
include Msf::Exploit::Remote::SMB::Client
10
include Msf::Exploit::Remote::SMB::Client::Authenticated
11
include Msf::Auxiliary::Report
12
include Msf::OptionalSession::SMB
13
14
def initialize(info = {})
15
super(
16
update_info(
17
info,
18
'Name' => 'SMB Password Change',
19
'Description' => %q{
20
Change the password of an account using SMB. This provides several different
21
APIs, each of which have their respective benefits and drawbacks.
22
},
23
'License' => MSF_LICENSE,
24
'Author' => [
25
'smashery'
26
],
27
'References' => [
28
['URL', 'https://github.com/fortra/impacket/blob/master/examples/changepasswd.py'],
29
],
30
'Notes' => {
31
'Stability' => [CRASH_SAFE],
32
'SideEffects' => [IOC_IN_LOGS, CONFIG_CHANGES],
33
'Reliability' => []
34
},
35
'Actions' => [
36
[ 'RESET', { 'Description' => "Reset the target's password without knowing the existing one (requires appropriate permissions). New AES kerberos keys will be generated." } ],
37
[ 'RESET_NTLM', { 'Description' => "Reset the target's NTLM hash, without knowing the existing password. AES kerberos authentication will not work until a standard password change occurs." } ],
38
[ 'CHANGE', { 'Description' => 'Change the password, knowing the existing one. New AES kerberos keys will be generated.' } ],
39
[ 'CHANGE_NTLM', { 'Description' => 'Change the password to a NTLM hash value, knowing the existing password. AES kerberos authentication will not work until a standard password change occurs.' } ]
40
],
41
'DefaultAction' => 'RESET'
42
)
43
)
44
45
register_options(
46
[
47
OptString.new('NEW_PASSWORD', [false, 'The new password to change to', ''], conditions: ['ACTION', 'in', %w[CHANGE RESET]]),
48
OptString.new('NEW_NTLM', [false, 'The new NTLM hash to change to. Can be either an NT hash or a colon-delimited NTLM hash'], conditions: ['ACTION', 'in', %w[CHANGE_NTLM RESET_NTLM]], regex: /^([0-9a-fA-F]{32}:)?[0-9a-fA-F]{32}$/),
49
OptString.new('TARGET_USER', [false, 'The user to reset the password of.'], conditions: ['ACTION', 'in', %w[RESET RESET_NTLM]])
50
]
51
)
52
end
53
54
def connect_samr
55
vprint_status('Connecting to Security Account Manager (SAM) Remote Protocol')
56
@samr = @tree.open_file(filename: 'samr', write: true, read: true)
57
58
vprint_status('Binding to \\samr...')
59
@samr.bind(endpoint: RubySMB::Dcerpc::Samr)
60
vprint_good('Bound to \\samr')
61
end
62
63
def run
64
case action.name
65
when 'CHANGE'
66
run_change
67
when 'RESET'
68
run_reset
69
when 'RESET_NTLM'
70
run_reset_ntlm
71
when 'CHANGE_NTLM'
72
run_change_ntlm
73
end
74
rescue RubySMB::Error::RubySMBError => e
75
fail_with(Module::Failure::UnexpectedReply, "[#{e.class}] #{e}")
76
rescue Rex::ConnectionError => e
77
fail_with(Module::Failure::Unreachable, "[#{e.class}] #{e}")
78
rescue Msf::Exploit::Remote::MsSamr::MsSamrError => e
79
fail_with(Module::Failure::BadConfig, "[#{e.class}] #{e}")
80
rescue ::StandardError => e
81
raise e
82
ensure
83
@samr.close_handle(@domain_handle) if @domain_handle
84
@samr.close_handle(@server_handle) if @server_handle
85
@samr.close if @samr
86
@tree.disconnect! if @tree
87
88
# Don't disconnect the client if it's coming from the session so it can be reused
89
unless session
90
simple.client.disconnect! if simple&.client.is_a?(RubySMB::Client)
91
disconnect
92
end
93
end
94
95
def authenticate(anonymous_on_expired: false)
96
if session
97
print_status("Using existing session #{session.sid}")
98
self.simple = session.simple_client
99
simple.connect("\\\\#{simple.address}\\IPC$") # smb_login connects to this share for some reason and it doesn't work unless we do too
100
else
101
connect
102
begin
103
begin
104
smb_login
105
rescue Rex::Proto::SMB::Exceptions::LoginError => e
106
if (e.source.is_a?(Rex::Proto::Kerberos::Model::Error::KerberosError) && [Rex::Proto::Kerberos::Model::Error::ErrorCodes::KDC_ERR_KEY_EXPIRED].include?(e.source.error_code) ||
107
e.source.is_a?(::WindowsError::ErrorCode) && [::WindowsError::NTStatus::STATUS_PASSWORD_EXPIRED, ::WindowsError::NTStatus::STATUS_PASSWORD_MUST_CHANGE].include?(e.source))
108
if anonymous_on_expired
109
# Password has expired - we'll need to anonymous connect
110
print_warning('Password expired - binding anonymously')
111
opts = {
112
username: '',
113
password: '',
114
domain: '',
115
auth_protocol: Msf::Exploit::Remote::AuthOption::NTLM
116
}
117
disconnect
118
connect
119
smb_login(opts: opts)
120
elsif action.name == 'CHANGE_NTLM'
121
fail_with(Module::Failure::UnexpectedReply, 'Must change password first. Try using the CHANGE action instead')
122
else
123
raise
124
end
125
else
126
raise
127
end
128
end
129
rescue Rex::Proto::SMB::Exceptions::Error, RubySMB::Error::RubySMBError => e
130
fail_with(Module::Failure::NoAccess, "Unable to authenticate ([#{e.class}] #{e}).")
131
end
132
end
133
134
report_service(
135
host: simple.address,
136
port: simple.port,
137
host_name: simple.client.default_name,
138
proto: 'tcp',
139
name: 'smb',
140
info: "Module: #{fullname}, last negotiated version: SMBv#{simple.client.negotiated_smb_version} (dialect = #{simple.client.dialect})"
141
)
142
143
begin
144
@tree = simple.client.tree_connect("\\\\#{simple.address}\\IPC$")
145
rescue RubySMB::Error::RubySMBError => e
146
fail_with(Module::Failure::Unreachable,
147
"Unable to connect to the remote IPC$ share ([#{e.class}] #{e}).")
148
end
149
150
connect_samr
151
end
152
153
def parse_ntlm_from_config
154
new_ntlm = datastore['NEW_NTLM']
155
fail_with(Msf::Exploit::Failure::BadConfig, 'Must provide NEW_NTLM value') if new_ntlm.blank?
156
case new_ntlm.count(':')
157
when 0
158
new_nt = new_ntlm
159
new_lm = nil
160
when 1
161
new_lm, new_nt = new_ntlm.split(':')
162
else
163
fail_with(Msf::Exploit::Failure::BadConfig, 'Invalid value for NEW_NTLM')
164
end
165
166
new_nt = Rex::Text.hex_to_raw(new_nt)
167
new_lm = Rex::Text.hex_to_raw(new_lm) unless new_lm.nil?
168
fail_with(Msf::Exploit::Failure::BadConfig, 'Invalid NT hash value in NEW_NTLM') unless new_nt.length == 16
169
fail_with(Msf::Exploit::Failure::BadConfig, 'Invalid LM hash value in NEW_NTLM') unless new_lm.nil? || new_nt.length == 16
170
171
[new_nt, new_lm]
172
end
173
174
def get_user_handle(domain, username)
175
vprint_status("Opening handle for #{domain}\\#{username}")
176
@server_handle = @samr.samr_connect
177
domain_sid = @samr.samr_lookup_domain(server_handle: @server_handle, name: domain)
178
@domain_handle = @samr.samr_open_domain(server_handle: @server_handle, domain_id: domain_sid)
179
user_rids = @samr.samr_lookup_names_in_domain(domain_handle: @domain_handle, names: [username])
180
fail_with(Module::Failure::BadConfig, "Could not find #{domain}\\#{username}") if user_rids.nil?
181
rid = user_rids[username][:rid]
182
183
@samr.samr_open_user(domain_handle: @domain_handle, user_id: rid)
184
rescue RubySMB::Dcerpc::Error::SamrError => e
185
fail_with(Msf::Exploit::Failure::BadConfig, e.to_s)
186
end
187
188
def run_change_ntlm
189
fail_with(Module::Failure::BadConfig, 'Must set NEW_NTLM') if datastore['NEW_NTLM'].blank?
190
fail_with(Module::Failure::BadConfig, 'Must set SMBUser to change password') if datastore['SMBUser'].blank?
191
fail_with(Module::Failure::BadConfig, 'Must set SMBPass to change password, or use RESET/RESET_NTLM to force-change a password without knowing the existing password') if datastore['SMBPass'].blank?
192
new_nt, new_lm = parse_ntlm_from_config
193
print_status('Changing NTLM')
194
authenticate(anonymous_on_expired: false)
195
196
user_handle = get_user_handle(datastore['SMBDomain'], datastore['SMBUser'])
197
198
if Net::NTLM.is_ntlm_hash?(Net::NTLM::EncodeUtil.encode_utf16le(datastore['SMBPass']))
199
old_lm, old_nt = datastore['SMBPass'].split(':')
200
old_lm = [old_lm].pack('H*')
201
old_nt = [old_nt].pack('H*')
202
203
@samr.samr_change_password_user(user_handle: user_handle,
204
new_nt_hash: new_nt,
205
new_lm_hash: new_lm,
206
old_nt_hash: old_nt,
207
old_lm_hash: old_lm)
208
else
209
@samr.samr_change_password_user(user_handle: user_handle,
210
old_password: datastore['SMBPass'],
211
new_nt_hash: new_nt,
212
new_lm_hash: new_lm)
213
end
214
215
print_good("Successfully changed password for #{datastore['SMBUser']}")
216
print_warning('AES Kerberos keys will not be available until user changes their password')
217
end
218
219
def run_reset_ntlm
220
fail_with(Module::Failure::BadConfig, "Must set TARGET_USER, or use CHANGE/CHANGE_NTLM to reset this user's own password") if datastore['TARGET_USER'].blank?
221
new_nt, = parse_ntlm_from_config
222
print_status('Resetting NTLM')
223
authenticate(anonymous_on_expired: false)
224
225
user_handle = get_user_handle(datastore['SMBDomain'], datastore['TARGET_USER'])
226
227
user_info = RubySMB::Dcerpc::Samr::SamprUserInfoBuffer.new(
228
tag: RubySMB::Dcerpc::Samr::USER_INTERNAL1_INFORMATION,
229
member: RubySMB::Dcerpc::Samr::SamprUserInternal1Information.new(
230
encrypted_nt_owf_password: RubySMB::Dcerpc::Samr::EncryptedNtOwfPassword.new(buffer: RubySMB::Dcerpc::Samr::EncryptedNtOwfPassword.encrypt_hash(hash: new_nt, key: simple.client.application_key)),
231
encrypted_lm_owf_password: nil,
232
nt_password_present: 1,
233
lm_password_present: 0,
234
password_expired: 0
235
)
236
)
237
@samr.samr_set_information_user2(
238
user_handle: user_handle,
239
user_info: user_info
240
)
241
242
print_good("Successfully reset password for #{datastore['TARGET_USER']}")
243
print_warning('AES Kerberos keys will not be available until user changes their password')
244
end
245
246
def run_reset
247
fail_with(Module::Failure::BadConfig, "Must set TARGET_USER, or use CHANGE/CHANGE_NTLM to reset this user's own password") if datastore['TARGET_USER'].blank?
248
fail_with(Module::Failure::BadConfig, 'Must set NEW_PASSWORD') if datastore['NEW_PASSWORD'].blank?
249
print_status('Resetting password')
250
authenticate(anonymous_on_expired: false)
251
252
user_handle = get_user_handle(datastore['SMBDomain'], datastore['TARGET_USER'])
253
254
user_info = RubySMB::Dcerpc::Samr::SamprUserInfoBuffer.new(
255
tag: RubySMB::Dcerpc::Samr::USER_INTERNAL4_INFORMATION_NEW,
256
member: RubySMB::Dcerpc::Samr::SamprUserInternal4InformationNew.new(
257
i1: {
258
password_expired: 0,
259
which_fields: RubySMB::Dcerpc::Samr::USER_ALL_NTPASSWORDPRESENT | RubySMB::Dcerpc::Samr::USER_ALL_PASSWORDEXPIRED
260
},
261
user_password: {
262
buffer: RubySMB::Dcerpc::Samr::SamprEncryptedUserPasswordNew.encrypt_password(
263
datastore['NEW_PASSWORD'],
264
simple.client.application_key
265
)
266
}
267
)
268
)
269
@samr.samr_set_information_user2(
270
user_handle: user_handle,
271
user_info: user_info
272
)
273
print_good("Successfully reset password for #{datastore['TARGET_USER']}")
274
end
275
276
def run_change
277
fail_with(Module::Failure::BadConfig, 'Must set NEW_PASSWORD') if datastore['NEW_PASSWORD'].blank?
278
fail_with(Module::Failure::BadConfig, 'Must set SMBUser to change password') if datastore['SMBUser'].blank?
279
fail_with(Module::Failure::BadConfig, 'Must set SMBPass to change password, or use RESET/RESET_NTLM to force-change a password without knowing the existing password') if datastore['SMBPass'].blank?
280
print_status('Changing password')
281
authenticate(anonymous_on_expired: true)
282
283
if Net::NTLM.is_ntlm_hash?(Net::NTLM::EncodeUtil.encode_utf16le(datastore['SMBPass']))
284
old_lm, old_nt = datastore['SMBPass'].split(':')
285
old_lm = [old_lm].pack('H*')
286
old_nt = [old_nt].pack('H*')
287
@samr.samr_unicode_change_password_user2(target_username: datastore['SMBUser'], new_password: datastore['NEW_PASSWORD'], old_nt_hash: old_nt, old_lm_hash: old_lm)
288
else
289
@samr.samr_unicode_change_password_user2(target_username: datastore['SMBUser'], old_password: datastore['SMBPass'], new_password: datastore['NEW_PASSWORD'])
290
end
291
292
print_good("Successfully changed password for #{datastore['SMBUser']}")
293
end
294
end
295
296