/usr/lib/python2.7/dist-packages/rekall/plugins/windows/mimikatz.py is in python-rekall-core 1.6.0+dfsg-2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 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 117 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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 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 192 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 235 236 237 238 239 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 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | # Rekall Memory Forensics
# Copyright 2015 Google Inc. All Rights Reserved.
#
# This file is part of Rekall Memory Forensics.
#
# Rekall Memory Forensics is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License Version 2 as
# published by the Free Software Foundation. You may not use, modify or
# distribute this program under any other version of the GNU General Public
# License.
#
# Rekall Memory Forensics is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# Rekall Memory Forensics. If not, see <http://www.gnu.org/licenses/>.
#
"""Emulation of the Mimikatz tool.
This code replicates the algorithm first implemented in the mimikatz tool, which
can be found here:
https://github.com/gentilkiwi/mimikatz
"""
# pylint: disable=protected-access
__author__ = ("Michael Cohen <scudette@google.com> and "
"Francesco Picasso <francesco.picasso@gmail.com>")
import logging
from Crypto.Cipher import AES
from Crypto.Cipher import DES3
from Crypto.Cipher import ARC4
from rekall import addrspace
from rekall import obj
from rekall.plugins.overlays.windows import pe_vtypes
from rekall.plugins.windows import common
from rekall.plugins.windows import lsadecryptxp
mimikatz_common_overlays = {
'_LSA_UNICODE_STRING': [None, {
'Value': lambda x: x.Buffer.dereference_as(
'UnicodeString', target_args=dict(length=x.Length)),
'Raw': lambda x: x.Buffer.dereference_as(
'String', target_args=dict(length=x.Length)).v(),
'RawMax': lambda x: x.Buffer.dereference_as(
'String', target_args=dict(length=x.MaximumLength)).v(),
}],
'_LSA_STRING': [None, {
'Value': lambda x: x.Buffer.dereference_as(
'String', target_args=dict(length=x.Length)),
'Raw': lambda x: x.Buffer.dereference_as(
'String', target_args=dict(length=x.Length)).v(),
'RawMax': lambda x: x.Buffer.dereference_as(
'String', target_args=dict(length=x.MaximumLength)).v(),
}],
'_LUID': [None, {
'Text': lambda x: '{:08x}:{:08x}'.format(x.HighPart, x.LowPart)
}],
'_SID': [None, {
'IdentifierAuthority': [None, ['Enumeration', dict(
choices={
'\x00\x00\x00\x00\x00\x00': 'Null Authority',
'\x00\x00\x00\x00\x00\x01': 'World Authority',
'\x00\x00\x00\x00\x00\x02': 'Local Authority',
'\x00\x00\x00\x00\x00\x03': 'Creator Authority',
'\x00\x00\x00\x00\x00\x04': 'NonUnique Authority',
'\x00\x00\x00\x00\x00\x05': 'NT Authority',
},
target='String',
target_args=dict(length=6, term=None)
)]],
'NumericIdentifier': [0x4, ['unsigned be int']],
'SubAuthority': [None, ['Array', dict(
target='unsigned long',
count=lambda x: x.SubAuthorityCount)]],
}],
}
class _SID(obj.Struct):
"""A Pretty printing implementation of sids.
Reference:
http://www.sekchek.com/downloads/white-papers/windows-about-sids.pdf
"""
def __unicode__(self):
"""Format the Sid using SDDL Notation."""
components = [self.Revision, self.NumericIdentifier]
components.extend(self.SubAuthority)
return u"S-" + u"-".join([str(x) for x in components])
class Lsasrv(pe_vtypes.BasicPEProfile):
"""A profile for lsasrv.dll"""
mimikatz_vtypes = [
'_LIST_ENTRY', '_LSA_UNICODE_STRING', '_LUID',
'_LSA_STRING', '_MSV1_0_PRIMARY_CREDENTIAL',
'_KIWI_BCRYPT_HANDLE_KEY', '_KIWI_BCRYPT_KEY', '_KIWI_HARD_KEY',
'_KIWI_MSV1_0_CREDENTIALS', '_KIWI_MSV1_0_PRIMARY_CREDENTIALS',
'_KIWI_GENERIC_PRIMARY_CREDENTIAL',
'_RPCE_CREDENTIAL_KEYCREDENTIAL', '_RPCE_COMMON_TYPE_HEADER',
'_RPCE_PRIVATE_HEADER', '_MARSHALL_KEY',
'_KIWI_MASTERKEY_CACHE_ENTRY', '_FILETIME']
windows_vtypes = ['_SID', '_SID_IDENTIFIER_AUTHORITY', '_GUID']
# TODO: should be special cases (1or2) addressed?
mimikatz_msv_versioned = {
5.1 : '_KIWI_MSV1_0_LIST_51',
5.2 : '_KIWI_MSV1_0_LIST_52',
6.0 : '_KIWI_MSV1_0_LIST_60',
6.1 : '_KIWI_MSV1_0_LIST_61_ANTI_MIMIKATZ',
6.2 : '_KIWI_MSV1_0_LIST_62',
6.3 : '_KIWI_MSV1_0_LIST_63',
}
@classmethod
def Initialize(cls, profile):
super(cls, Lsasrv).Initialize(profile)
arch = profile.session.profile.metadata('arch')
mimikatz_profile = profile.session.LoadProfile('mimikatz/%s' % arch)
if not mimikatz_profile:
raise IOError('Unable to load mimikatz profile from repository!')
kwargs = {}
for name in cls.mimikatz_vtypes:
kwargs[name] = mimikatz_profile.vtypes[name]
for name in cls.windows_vtypes:
kwargs[name] = profile.session.profile.vtypes[name]
profile.add_types(kwargs)
profile.add_types({
'SIZED_DATA': [lambda x: x.size + 4, {
'size': [0, ['unsigned long', {}]],
'data': [4, ['String', dict(length=lambda x: x.size)]],
}]
})
version = profile.session.profile.metadata('version')
if version not in cls.mimikatz_msv_versioned:
raise IOError('OS version not supported.')
profile.add_types({
'MSV1_0_LIST' : mimikatz_profile.vtypes[
cls.mimikatz_msv_versioned[version]]
})
profile.add_classes(_SID=_SID)
profile.add_overlay(mimikatz_common_overlays)
profile.add_overlay({
'_KIWI_HARD_KEY': [None, {
'data': lambda x: x.m('data').cast(
'String', term=None, length=x.cbSecret)
}],
'MSV1_0_LIST': [None, {
'List': [0, ['_LIST_ENTRY']],
'pSid': [None, ['Pointer', dict(target='_SID')]],
'LogonType': [None, ['Enumeration', dict(
target='unsigned int',
choices={
2: 'Interactive',
3: 'Network',
4: 'Batch',
5: 'Service',
6: 'Proxy',
7: 'Unlock',
8: 'NetworkCleartext',
9: 'NewCredentials',
10: 'RemoteInteractive',
11: 'CachedInteractive',
12: 'CachedRemoteInteractive',
13: 'CachedUnlock',
},
)]],
}],
'_MSV1_0_PRIMARY_CREDENTIAL': [None, {
'NtOwfPassword': [None, ['String', dict(length=16)]],
'LmOwfPassword': [None, ['String', dict(length=16)]],
'ShaOwPassword': [None, ['String', dict(length=20)]],
}],
'_MARSHALL_KEY': [None, {
'unkId': [None, ['Enumeration', dict(
target='unsigned long',
choices={
0x00010002: 'NTLM',
0x00010003: 'NTLM',
0x00020002: 'SHA1',
0x00030002: 'RootKey',
0x00030003: 'RootKey',
0x00040002: 'DPAPI',
0x00040003: 'DPAPI',
},
)]],
}],
'_RPCE_CREDENTIAL_KEYCREDENTIAL': [
# TODO: the object size is wrong, data array takes the first
# instance length, not all (different) lengths.
lambda x: x.key.obj_offset + x.data.obj_size + x.key.obj_size,
{
'key': [None, ['Array', {
'count': lambda x: x.unk0,
'target': '_MARSHALL_KEY'
}]],
'key_data': [lambda x: x.unk1.obj_end + x.key.obj_size, [
'Array', {
'count': lambda x: x.unk0,
'target': 'SIZED_DATA'
}]],
}
],
'_KIWI_MASTERKEY_CACHE_ENTRY': [None, {
'List': [0, ['_LIST_ENTRY']],
'key': [None, ['String', dict(length=lambda x: x.keySize)]],
}],
})
def init_crypto(self):
if self.session.profile.metadata('version') < 6.0:
self.init_crypto_nt5()
else:
self.init_crypto_nt6()
def decrypt(self, encrypted):
if self.session.profile.metadata('version') < 6.0:
return self.decrypt_nt5(encrypted)
else:
return self.decrypt_nt6(encrypted)
def init_crypto_nt6(self):
# TODO: add some checks to alert user if decryption is not possible.
self.iv = self.get_constant_object(
'InitializationVector', 'String', length=16, term=None).v()
aes_handle = self.get_constant_object(
'hAesKey', target='Pointer',
target_args=dict(target='_KIWI_BCRYPT_HANDLE_KEY'))
self.aes_key = aes_handle.key.hardkey.data.v()
des_handle = self.get_constant_object(
'h3DesKey', target='Pointer',
target_args=dict(target='_KIWI_BCRYPT_HANDLE_KEY'))
self.des_key = des_handle.key.hardkey.data.v()
def decrypt_nt6(self, encrypted):
cipher = None
if self.iv:
if len(encrypted) % 8:
if self.aes_key:
cipher = AES.new(self.aes_key, AES.MODE_CFB, self.iv)
else:
if self.des_key:
cipher = DES3.new(self.des_key, DES3.MODE_CBC, self.iv[:8])
if cipher and encrypted:
return cipher.decrypt(encrypted)
return obj.NoneObject()
def init_crypto_nt5(self):
# TODO: add some checks to alert user if decryption is not possible.
rc4_key_len = self.get_constant_object(
'g_cbRandomKey', 'unsigned long').v()
rc4_key_ptr = self.get_constant_object(
'g_pRandomKey', target='Pointer')
self.rc4_key = rc4_key_ptr.dereference_as(
'String', target_args=dict(length=rc4_key_len, term=None)).v()
desx_key_ptr = self.get_constant_object(
'g_pDESXKey', target='Pointer')
self.desx_key = desx_key_ptr.dereference_as(
'String', target_args=dict(length=144, term=None)).v()
self.feedback = self.get_constant_object(
'g_Feedback', target='String',
target_args=dict(length=8)).v()
def decrypt_nt5(self, encrypted):
cipher = None
if len(encrypted) % 8:
if self.rc4_key:
cipher = ARC4.new(self.rc4_key)
else:
if self.desx_key and self.feedback:
cipher = lsadecryptxp.XP_LsaDecryptMemory(
self.desx_key, self.feedback)
if cipher and encrypted:
return cipher.decrypt(encrypted)
return obj.NoneObject()
def get_lsass_logons(self):
logons = {}
lsass_logons = self.get_constant_object(
'LogonSessionList', target='_LIST_ENTRY')
for entry in lsass_logons.list_of_type('MSV1_0_LIST', 'List'):
logons[entry.LocallyUniqueIdentifier.Text] = entry
return logons
def _msv_primary_credentials(self, data):
vm = addrspace.BufferAddressSpace(data=data, session=self.session)
cred_obj = self.Object('_MSV1_0_PRIMARY_CREDENTIAL',
profile=self, vm=vm)
# TODO: check NULL Pointer dereference with this VM.
domain = ''
if cred_obj.LogonDomainName.Buffer.is_valid():
domain = cred_obj.LogonDomainName.Value
user_name = ''
if cred_obj.UserName.Buffer.is_valid():
user_name = cred_obj.UserName.Value
if cred_obj.isLmOwfPassword.v() == 1:
yield (domain, user_name, 'LM',
cred_obj.LmOwfPassword.v().encode('hex'))
if cred_obj.isNtOwfPassword.v() == 1:
yield (domain, user_name, 'NTLM',
cred_obj.NtOwfPassword.v().encode('hex'))
if cred_obj.isShaOwPassword.v() == 1:
yield (domain, user_name, 'SHA1',
cred_obj.ShaOwPassword.v().encode('hex'))
def _msv_rpce_credentials(self, data):
vm = addrspace.BufferAddressSpace(data=data, session=self.session)
cred_obj = self.Object('_RPCE_CREDENTIAL_KEYCREDENTIAL',
profile=self, vm=vm)
# This seems to be corrupt sometimes.
if cred_obj.unk0 > 10:
return
for i in range(0, cred_obj.unk0):
yield (cred_obj.key[i].unkId,
cred_obj.key_data[i].data.v().encode('hex'))
def logons(self, lsass_logons):
for luid, lsass_logon in lsass_logons.iteritems():
for cred in lsass_logon.Credentials.walk_list('next'):
for primary_cred in cred.PrimaryCredentials.walk_list('next'):
dec_cred = self.decrypt(primary_cred.Credentials.Raw)
if not dec_cred:
continue
cur_cred_type = primary_cred.Primary.Value
if cur_cred_type == u'Primary':
for (domain, user_name, secret_type,
secret) in self._msv_primary_credentials(dec_cred):
yield (luid, cur_cred_type, domain, user_name,
secret_type, secret)
elif cur_cred_type == u'CredentialKeys':
for (secret_type,
secret) in self._msv_rpce_credentials(dec_cred):
yield (luid, cur_cred_type, '', '', secret_type,
secret)
else:
pass
def master_keys(self):
keys = self.get_constant_object(
'g_MasterKeyCacheList', target='_LIST_ENTRY')
for entry in keys.list_of_type('_KIWI_MASTERKEY_CACHE_ENTRY', 'List'):
yield (entry.LogonId.Text, '', # TODO: add entry.KeyUid,
'', '', 'masterkey',
self.decrypt(entry.key.v()).encode('hex'))
class Wdigest(pe_vtypes.BasicPEProfile):
"""A profile for wdigest.dll"""
mimikatz_vtypes = [
'_LIST_ENTRY', '_LSA_UNICODE_STRING', '_LUID',
'_KIWI_WDIGEST_LIST_ENTRY', '_KIWI_GENERIC_PRIMARY_CREDENTIAL',
'_KIWI_HARD_KEY']
@classmethod
def Initialize(cls, profile):
super(cls, Wdigest).Initialize(profile)
arch = profile.session.profile.metadata('arch')
mimikatz_profile = profile.session.LoadProfile('mimikatz/%s' % arch)
kwargs = {}
for name in cls.mimikatz_vtypes:
kwargs[name] = mimikatz_profile.vtypes[name]
profile.add_types(kwargs)
profile.add_overlay(mimikatz_common_overlays)
kiwi_cred_offset = 8
if profile.session.profile.metadata('version') < 6.0:
kiwi_cred_offset = 12
profile.add_overlay({
'_KIWI_WDIGEST_LIST_ENTRY': [None, {
'List': [0, ['_LIST_ENTRY']],
'Cred': [lambda x: (x.LocallyUniqueIdentifier.obj_end +
kiwi_cred_offset),
['_KIWI_GENERIC_PRIMARY_CREDENTIAL']]
}],
'_KIWI_HARD_KEY': [None, {
'data': lambda x: x.m('data').cast(
'String', term=None, length=x.cbSecret)
}],
})
def logons(self):
# TODO: if the symbols is wrong? Add a check for the LIST validity.
logons = self.get_constant_object(
'l_LogSessList', target='_LIST_ENTRY')
for entry in logons.list_of_type('_KIWI_WDIGEST_LIST_ENTRY', 'List'):
yield entry
class Livessp(pe_vtypes.BasicPEProfile):
"""A profile for livessp.dll"""
mimikatz_vtypes = [
'_LIST_ENTRY', '_LSA_UNICODE_STRING', '_LUID',
'_KIWI_LIVESSP_LIST_ENTRY', '_KIWI_LIVESSP_PRIMARY_CREDENTIAL',
'_KIWI_GENERIC_PRIMARY_CREDENTIAL']
@classmethod
def Initialize(cls, profile):
super(cls, Livessp).Initialize(profile)
arch = profile.session.profile.metadata('arch')
mimikatz_profile = profile.session.LoadProfile('mimikatz/%s' % arch)
kwargs = {}
for name in cls.mimikatz_vtypes:
kwargs[name] = mimikatz_profile.vtypes[name]
profile.add_types(kwargs)
profile.add_overlay(mimikatz_common_overlays)
profile.add_overlay({
'_KIWI_LIVESSP_LIST_ENTRY': [None, {
'List': [0, ['_LIST_ENTRY']],
}]
})
def logons(self):
logons = self.get_constant_object(
'LiveGlobalLogonSessionList', target='_LIST_ENTRY')
for entry in logons.list_of_type('_KIWI_LIVESSP_LIST_ENTRY', 'List'):
yield (entry.LocallyUniqueIdentifier.Text,
'',
entry.suppCreds.dereference().credentials.Domaine.Value,
entry.suppCreds.dereference().credentials.UserName.Value,
'password',
entry.suppCreds.dereference().credentials.Password)
class Mimikatz(common.WindowsCommandPlugin):
"""Extract and decrypt passwords from the LSA Security Service."""
name = 'mimikatz'
table_header = [
dict(name='LUID', width=20),
dict(name='Type', width=16),
dict(name='Sess', width=2),
dict(name='SID', width=20),
dict(name='Module', width=7),
dict(name='Info', width=7),
dict(name='Domain', width=16),
dict(name='User', width=16),
dict(name='SType', width=9),
dict(name='Secret', width=32)
]
def __init__(self, *args, **kwargs):
super(Mimikatz, self).__init__(*args, **kwargs)
# Track the following modules. If we do not have them in the profile
# repository then try to get them directly from Microsoft.
tracked = self.session.GetParameter(
'autodetect_build_local_tracked') or []
needed = set(['lsasrv', 'wdigest', 'livessp'])
if not needed.issubset(tracked):
needed.update(tracked)
with self.session as session:
session.SetParameter('autodetect_build_local_tracked', needed)
def collect(self):
cc = self.session.plugins.cc()
# Switch to the lsass process.
for task in self.session.plugins.pslist(
proc_regex='lsass.exe').filter_processes():
cc.SwitchProcessContext(task)
lsasrv_module = self.session.address_resolver.GetModuleByName(
'lsasrv')
# lsasrv not mapped in lsass? Weird!
if lsasrv_module:
lsasrv = lsasrv_module.profile
lsasrv.init_crypto()
lsass_logons = lsasrv.get_lsass_logons()
for (luid, info, domain, user_name, secret_type,
secret) in lsasrv.logons(lsass_logons):
lsass_entry = lsass_logons.get(luid, obj.NoneObject())
# TODO: add timestamp field?
yield (luid,
lsass_entry.LogonType,
lsass_entry.Session,
lsass_entry.pSid.deref(),
'msv',
info,
domain,
user_name,
secret_type,
secret)
wdigest_module = self.session.address_resolver.GetModuleByName(
'wdigest')
# Wdigest is mapped
if wdigest_module:
wdigest = wdigest_module.profile
if not wdigest.get_constant('l_LogSessList'):
logging.warning('wdigest not initialized, skipping it.')
else:
for entry in wdigest.logons():
luid = entry.LocallyUniqueIdentifier.Text
lsass_entry = lsass_logons.get(luid, obj.NoneObject())
yield (luid,
lsass_entry.LogonType,
lsass_entry.Session,
lsass_entry.pSid.deref(),
'wdigest',
'',
entry.Cred.Domaine.Value,
entry.Cred.UserName.Value,
'password',
lsasrv.decrypt(entry.Cred.Password.RawMax))
livessp_module = self.session.address_resolver.GetModuleByName(
'livessp')
if livessp_module:
livessp = livessp_module.profile
if not livessp.get_constant('LiveGlobalLogonSessionList'):
logging.warning('livessp not initializated, skipping it.')
else:
for (luid, info, domain, user_name, secret_type,
enc_secret) in livessp.logons():
lsass_entry = lsass_logons.get(luid, obj.NoneObject())
yield (luid,
lsass_entry.LogonType,
lsass_entry.Session,
lsass_entry.pSid.deref(),
'livessp',
info,
domain,
user_name,
secret_type,
lsasrv.decrypt(enc_secret))
if lsasrv_module:
for (luid, info, domain, user_name, secret_type,
secret) in lsasrv.master_keys():
lsass_entry = lsass_logons.get(luid, obj.NoneObject())
yield (luid,
lsass_entry.LogonType,
lsass_entry.Session,
lsass_entry.pSid.deref(),
'lsasrv',
info,
domain,
user_name,
secret_type,
secret)
|