Hackware.ru

Features

General

Platform idependent — all commands have a «live» and a normal version where applicable. The «live» version will use the current system and only works on Windows. The normal commands are platform independent.
Can be used as a library for your projects.

LSASS processing

Can parse the secrets hidden in the LSASS process. This is just like mimikatz’s but with different commands.
The main difference here is that all the parsing logic is separated from the data source, so if you define a new reader object you can basically perform the parsing of LSASS from anywhere.

Currently supported data sources:

  1. live — reads the LSASS porcess’ memory directly
  2. minidump — processes a minidump file created by dumping the LSASS process
  3. rekall (volatility fork) — processes basically ANY windows memory dumps that rekall can parse
  4. pcileech — can dump secrets DIRECTLY via DMA of a live computer
  5. remote — this is another project. TBD 🙂
  6. seriously, it’s super-simple to integrate.

Registry processing

Parses the registry hives to obtain stroed credentials, like NT and LM hashes, domain cached credentials (DCC/DCC2) and LSA secrets.

Currently supported data sources:

  1. live — has two techniques to parse live registry. First it’s in-memory doesn’t touch disk, the second is dumping the hives and parsing them with the offline parser
  2. offline (hive files)
  3. seriously, it’s super-simple to integrate.

DPAPI functions — MASTERKEY/BLOB/VAULT/CREDENTIAL

DPAPI is the protector of local secrets of many kinds. Currently the project supports decrypting masterkeys, dpapi blobs, credential files, vault files.
The results are not 100% correct, as there is not much documentation on most of these things. PR is always welcomed!

Currently supported data sources:

  1. live — obtains masterkeys directly from LSASS -OR- the user/machine keys from live registry and decrypts the masterkeyfile.
  2. hive files (offline)- the user/machine keys from live registry and decrypts the masterkeyfile
  3. valid credentials (offline) — can decrypt masterkey files by letting you type in the correct SID and password.

Impersonating users

Can spawn a new process as any user who has a process running on the machine.
Can assign any available token of choise to your thread
This is just a basic stuff really. Reson is there that I hate to constanly use psexec to get a system shell from admin…

Timestamp override

Reason for this parameter to exist: In order to choose the correct structure for parsing we need the timestamp info of the msv dll file. Rekall sadly doesnt always have this info for some reason, therefore the parsing may be failing.
If the parsing is failing this could solve the issue.

Parameter:
Values: or
Example:

What is Mimikatz?

Many people refer to it as a post-exploitation tool, something you would use to take a stronger hold of a network already compromised.

It carries out techniques such as Pass the Hash, Pass the Ticket, Over-Pass The Hash (AKA Pass the Key), Kerberos Golden Ticket, Kerberos Silver Ticket, Pass the Cache & Attacking the Kerberos Session Ticket (TGS).

Mimikatz Features

  • Dump credentials from LSASS (Windows Local Security Account database)
    • MSV1.0: hashes & keys (dpapi)
    • Kerberos password, ekeys, tickets, & PIN
    • TsPkg (password)
    • WDigest (clear-text password)
    • LiveSSP (clear-text password)
    • SSP (clear-text password)
  • Generate Kerberos Golden Tickets (Kerberos TGT logon token ticket attack)
  • Generate Kerberos Silver Tickets (Kerberos TGS service ticket attack)
  • Export certificates and keys (even those not normally exportable).
  • Dump cached credentials
  • Stop event monitoring.
  • Bypass Microsoft AppLocker / Software Restriction Polcies
  • Patch Terminal Server
  • Basic GPO bypass

Commands

The primary command components are sekurlsa, kerberos, crypto, vault, and lsadump.

Sekurlsa interacts with the LSASS process in memory to gather credential data and provides enhanced capability over kerberos.

The Mimikatz kerberos command set enables modification of Kerberos tickets and interacts with the official Microsoft Kerberos API. This is the command that creates Golden Tickets. Pass the ticket is also possible with this command since it can inject Kerberos ticket(s) (TGT or TGS) into the current session. External Kerberos tools may be used for session injection, but they must follow the Kerberos credential format (KRB_CRED). Mimikatz kerberos also enables the creation of Silver Tickets which are Kerberos tickets (TGT or TGS) with arbitrary data enabling AD user/ group

Crypto enables export of certificates on the system that are not marked exportable since it bypasses the standard export process.

Vault enables dumping data from the Windows vault.

Lsadump enables dumping credential data from the Security Account Manager (SAM) database which contains the NTLM (sometimes LM hash) and supports online and offline mode as well as dumping credential data from the LSASS process in memory. Lsadump can also be used to dump cached credentials. In a Windows domain, credentials are cached (up to 10) in case a Domain Controller is unavailable for authentication. However, these credentials are stored on the computer.

Mimikatz Windows OS Support

Mimikatz works on:

  • Windows XP
  • Windows Vista
  • Windows 7
  • Windows 8
  • Windows Server 2003
  • Windows Server 2008 / 2008 R2
  • Windows Server 2012 / 2012 R2
  • Windows 10 (beta support)

You can download mimikatz most recent release here:

Or read more here.

Reading Hashes and Passwords from Memory

We can use both the built-in Metasploit commands as well as the native Mimikatz commands to extract hashes and clear-text credentials from the compromised machine.

Built-In Metasploit:

meterpreter > msv
 Running as SYSTEM
 Retrieving msv credentials
msv credentials
===============

AuthID   Package    Domain           User              Password
------   -------    ------           ----              --------
0;78980  NTLM       WINXP-E95CE571A1  Administrator     lm{ 00000000000000000000000000000000 }, ntlm{ d6eec67681a3be111b5605849505628f }
0;996    Negotiate  NT AUTHORITY     NETWORK SERVICE   lm{ aad3b435b51404eeaad3b435b51404ee }, ntlm{ 31d6cfe0d16ae931b73c59d7e0c089c0 }
0;997    Negotiate  NT AUTHORITY     LOCAL SERVICE     n.s. (Credentials KO)
0;56683  NTLM                                          n.s. (Credentials KO)
0;999    NTLM       WORKGROUP        WINXP-E95CE571A1$  n.s. (Credentials KO)

meterpreter > kerberos
 Running as SYSTEM
 Retrieving kerberos credentials
kerberos credentials
====================

AuthID   Package    Domain           User              Password
------   -------    ------           ----              --------
0;999    NTLM       WORKGROUP        WINXP-E95CE571A1$  
0;997    Negotiate  NT AUTHORITY     LOCAL SERVICE     
0;56683  NTLM                                          
0;996    Negotiate  NT AUTHORITY     NETWORK SERVICE   
0;78980  NTLM       WINXP-E95CE571A1  Administrator     SuperSecretPassword

Native Mimikatz:

meterpreter > mimikatz_command -f samdump::hashes
Ordinateur : winxp-e95ce571a1
BootKey    : 553d8c1349162121e2a5d3d0f571db7f

Rid  : 500
User : Administrator
LM   : 
NTLM : d6eec67681a3be111b5605849505628f

Rid  : 501
User : Guest
LM   : 
NTLM : 

Rid  : 1000
User : HelpAssistant
LM   : 6165cd1a0ebc61e470475c82cd451e14
NTLM : 

Rid  : 1002
User : SUPPORT_388945a0
LM   : 
NTLM : 771ee1fce7225b28f8aec4a88aea9b6a

meterpreter > mimikatz_command -f sekurlsa::searchPasswords
 { Administrator ; WINXP-E95CE571A1 ; SuperSecretPassword }

How Do You Use Mimikatz

When you run Mimikatz with the executable, you get a Mimikatz console in interactive mode where you can run commands in real time.

Run Mimikatz as Administrator: Mimikatz needs to be “Run as Admin” to function completely, even if you are using an Administrator account.

Checking Version of Mimikatz

There are 2 versions of Mimikatz: 32bit and 64bit. Make sure you are running the correct version for your installation of Windows. Run the command ‘version’ from the Mimikatz prompt to get information about the Mimikatz executable, the Windows version, and if there are any Windows settings that will prevent Mimikatz from running correctly.

Extracting clear text passwords from memory

The  module sekurlsa in Mimikatz lets you dump passwords from memory. To use the commands in the sekurlsa module, you must have Admin or SYSTEM permissions.

First, run the command:

The output will show if you have appropriate permissions to continue.

Next, start the logging functions so you can refer back to your work.

And finally, output all of the clear text passwords stored on this computer.

Using Other Mimikatz modules

The crypto module allows you to access the CryptoAPI in Windows which lets you list and export certificates and their private keys, even if they’re marked as non-exportable.

The kerberos module accesses the Kerberos API so you can play with that functionality by extracting and manipulating Kerberos tickets.

The service module allows you to start, stop, disable, etc. Windows services.

And lastly, the coffee command returns ascii art of coffee. Cause everyone needs coffee.

There is so much more to Mimikatz. If you are looking at penetration testing or you just want to dig into the Windows authentication internals, check out some of these other references and links:

  • Guide to Pen Testing Active Directory Environments
  • Unofficial Guide to Mimikatz & Command Reference
  • Koadic: LoL Malware Meets Python-Based Command and Control (C2) Server
  • Official Mimikatz Wiki

Want to Mimikatz in action and learn how Varonis protects you from infiltration?  Join our free Live Cyber Attack Workshop and see our engineers execute a live cyberattack in our security lab.

Mimikatz with Meterpreter

As stated earlier, Offensive Security has added v1 of Mimikatz as a meterpreter script with easy access to all its features. Let us see how it works. We start by loading Mimikatz in meterpreter by running the following command: “load mimikatz.”

It is imperative to know here that we should run this command only when we have the Administrator privileges. Once loaded, we can start by checking the version and to confirm that mimikatz has been loaded successfully. We can do that with the following command: “mimikatz_command –f version”:

Next, we can try running the “msv” command to see if we get anything:

Ethical Hacking Boot Camp — Exam Pass Guarantee

We can see that we are provided with the LM and NTLM hashes but not with a clear text password. We can now run “mimikatz_command –f samdump::hashes” to see what it returns:

Followed by running “mimikatz_command –f sekurlsa::searchPasswords”:

which returns the password in clear text.

Another module of Mimikatz is called the Service module. This module helps us to list, start, stop, or remove services running on the machine:

“mimikatz_command –f service::”

As we can see that this command lists all the services that are currently running.

Another module of Mimikatz is called the Crypto module. This module helps us tolist and export any certificates and their corresponding private keys that may be stored on the compromised machine. This is possible even if they are marked as non-exportable.

Как защитить Windows от извлечения паролей из памяти через mimikatz?

В Windows 8.1 и Server 2012 R2 (и выше) возможности по извлечению паролей через LSASS несколько ограничены. Так, по-умолчанию в этих системах в памяти не хранятся LM хэш и пароли в открытом виде. Этот же функционал бэкпортирован и на более ранние версии Windows (7/8/2008R2/2012), в которых нужно установить специальное обновление KB2871997 (обновление дает и другие возможности усилить безопасность системы) и в ветке HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest установить параметр DWORD реестра UseLogonCredential равным (WDigest отключен).

Если после установки обновления и ключа UseLogonCredential попробовать извлечь пароли из памяти, вы увидите, что mimikats с помощью команды creds_wdigest не сможет извлечь пароли и хэши.

Однако при наличии прав администратора вы сможете легко изменить этот ключ:

После этого вы опять сможете получить доступ к паролям в памяти LSA.

В инструментарии mimikatz есть и другие инструменты получения паролей и их хэшей из памяти (WDigest, LM-hash, NTLM-hash, модуль для захвата билетов Kerberos), поэтому в качестве рекомендаций рекомендуется реализовать следующие меры:

  • Запретить хранить пароли с использование обратимого шифрования (Reversible Encryption)
  • Отключить NTLM
  • Запретить использование сохранённых паролей в Credential Manager
  • Запретить кэшировать учетные данные доменных пользователей (ключ CachedLogonsCount и политика Interactive logon: Number of previous logons to cache)
  • Если функциональный уровень домена не ниже Windows Server 2012 R2, можно добавить учетные записи администартороав в специальную группу Protected Users

Совет. Подробная статья о способах защите памяти Windows систем от извлечения паролей и хэшей —  Методы защиты от mimikatz в домене Windows

При тестировании mimkatz в Windows 10 Pro x64 с настройками утилита mimkatz 2.0 смогла получить хэши пароля активного пользователя (но не пароль в открытом виде).

На более старых системах нужно в качестве временного решения нужно ограничить получение привилегии debug и отключить поставщика безопасности wdigest через реестр. Для этого в ветке HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa найдите ключ Security Packages и удалить из списка пакетов строку wdigest. Однако нужно понимать, что атакующему, при наличии соответствующих прав на реестр, не составит труда вернуть настройки обратно.

Выводы. Еще раз напоминаем прописные истины:

  • Не стоит использовать одинаковые пароли для разных сервисов (особенно терминальных, находящихся во владении третьих лиц).
  • Задумайтесь о безопасности ваших паролей и данных, находящихся на виртуальных машинах в облаках, ведь вы не можете быть уверенными в том, у кого еще имеется доступ к гипервизорам и хранилищу, на котором расположены файлы виртуальных машины.
  • Минимизируйте в своих системах количество учетных записей, обладающих правами локального администратора (см. гайд об организации защиты учетных записей администраторов в среде Windows)
  • Никогда не заходите с учетной записью администратора домена на сервера и компьютеры, доступные другим пользователям

Отключение LM и NTLM

Устаревший протокол LM аутентификации и, соответственно, хранение LM хэшей  нужно обязательно отключить с помощью групповой политики Network Security: Do Not Store LAN Manager Hash Value On Next Password Change (на уровне Default Domain Policy).

Далее нужно отказаться от использования как минимум протокола NTLMv1 (политика в разделе Computer Configuration -> Policies -> Windows Settings -> Security Settings -> Local Policies -> Security Options  —  Network Security: Restrict NTLM: NTLM authentication in this domain), а как максимум и NTLMv2

И если отказ от NTLMv1 как правило проходит безболезненно, то при отказе от NTLMv2 придется потрудиться. В больших инфраструктурах, как правило, приходят к сценарию максимального ограничения использования NTLMv2. Т.е. везде, где возможно должна использоваться Kerberos аутентификация (как правило придется уделить дополнительное время настройке Kerberos аутентификации на IIS и SQL), а на оставшихся системах —  NTLMv2.

Запрет кэширования учетных данных

Одной из возможностей mimikats – получения хэша паролей пользователей из ветки реестра HKEY_LOCAL_MACHINE\SECURITY\Cache, в которую сохраняются хэши паролей последних 10 (по-умолчанию) доменных пользователей, врошедших в систему. Эти хэши в обычном случае могут использоваться для авторизации пользователей в системе при недоступности контроллера домена.

Желательно запретить использование сохранения кэшированных данных с помощью включения политики Interactive Logon: Number of previous logons to cache (in case domain controller is not available) в разделе Computer Configuration -> Windows Settings -> Local Policy -> Security Options, изменив значение ее параметра на 0.

Кроме того, чтобы ускорить очистку памяти процесса lsass от учётных записей пользователей, завершивших сеанс, нужно в в ветке HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa нужно создать ключ типа DWORD с именем TokenLeakDetectDelaySecs и значением 30. Т.е. память будет очищаться через 30 секунд после логофа пользователя. В Windows 7, 8/ Server 2008R2, 2012 чтобы этот ключ заработал, нужно установить уже упоминавшееся ранее обновление KB2871997.

What Can Mimikatz Do?

Mimikatz originally demonstrated how to exploit a single vulnerability in the Windows authentication system. Now the tool demonstrates several different kinds of vulnerabilities. Mimikatz can perform credential-gathering techniques such as:

  • Pass-the-Hash: Windows used to store password data in an NTLM hash. Attackers use Mimikatz to pass that exact hash string to the target computer to login. Attackers don’t even need to crack the password, they just need to use the hash string as is. It’s the equivalent of finding the master key to a building on the floor. You need that one key to get into all the doors.
  • Pass-the-Ticket: Newer versions of windows store password data in a construct called a ticket.  Mimikatz provides functionality for a user to pass a kerberos ticket to another computer and login with that user’s ticket. It’s basically the same as pass-the-hash otherwise.
  • Over-Pass the Hash (Pass the Key): Yet another flavor of the pass-the-hash, but this technique passes a unique key to impersonate a user you can obtain from a domain controller.
  • Kerberos Golden Ticket: This is a pass-the-ticket attack, but it’s a specific ticket for a hidden account called KRBTGT, which is the account that encrypts all of the other tickets. A golden ticket gives you domain admin credentials to any computer on the network that doesn’t expire.
  • Kerberos Silver Ticket: Another pass-the-ticket, but a silver ticket takes advantage of a feature in Windows that makes it easy for you to use services on the network. Kerberos grants a user a TGS ticket, and a user can use that ticket to log into any services on the network. Microsoft doesn’t always check a TGS after it’s issued, so it’s easy to slip it past any safeguards.
  • Pass-the-Cache: Finally an attack that doesn’t take advantage of Windows! A pass-the-cache attack is generally the same as a pass-the-ticket, but this one uses the saved and encrypted login data on a Mac/UNIX/Linux system.

Rekall usage

There are two ways to use rekall-based memory parsing.

Via the command

Via rekall command line

IMPORTANT NOTICES:

  1. If you are just now deciding to install please note: it MUST be run in a virtualenv, and you will need to install pypykatz in the same virtualenv!
  2. rekall command line is not suitable to show all information acquired from the memory, you should use the and command switches!

You can find a rekall plugin file named in the folder of pypykatz.
You will need to copy it in rekall’s folder, and rename it to .
After this modify the file located the same folder and add the following line at the end:
If everything is okay you can use the command from the command line directly.

HELP WANTED

Why do I need these dumps files?

In order to create mimikatz in Python one would have to create structure definitions of a gazillion different structures (check the original code) without the help of the build-in parser that you’d naturally get from using a native compiler. Now, the problem is that even a single byte misalignemt will render the parsing of these structures run to an error. Problem is mostly revolving around 32 — 64 aligments, so 32 bit Windows version lsass dumps are apprechiated as well!

Summary

I need data I can verify the code on and administer necessary changes on the parsers until everything works fine.
Submitting issues on this github page wouldn’t help at all without the actual file and github wouldn’t like 40-300Mb file attachments.

Mimikatz Walkthrough Intro

Security researchers have been obsessed with Windows security since the beginning of time. Various tools have been released over the years which try to weaken the security/bypass it in some way or the other. Mimikatz is a tool written in `C` as an attempt to play with Windows security. Its primary function is to gather credentials of a Windows machine. Mimikatz is available for both 32-bit as well as for 64-bit Windows machines.

During a pentest, it is considered to be a post-exploitation tool. It can perform various credential gathering techniques such as:

  • Pass the Hash
  • Pass the Ticket
  • Over-Pass the Hash (Pass the Key)
  • Kerberos Golden Ticket
  • Kerberos Silver Ticket
  • Pass the Cache
  • Attacking the Kerberos Session Ticket

Developed by Benjamin Delpy, the official GitHub repository can be found at https://github.com/gentilkiwi/mimikatz. Delpy gives us the option to directly download the binaries at https://github.com/gentilkiwi/mimikatz/releases or build our own using Microsoft Visual Studio 2010, 2012, or 2013.

To synchronize with the latest updates, the following links are helpful:

  • GIT URL: https://github.com/gentilkiwi/mimikatz.git
  • ZIP file URL: https://github.com/gentilkiwi/mimikatz/archive/master.zip

Offensive Security has already integrated the version 1 of Mimikatz as a meterpreter script which allows easy access to its complete feature set without the hassle of the attacker uploading scripts to the target machine. However, the latest version of Mimikatz (v2) can be found at the links mentioned above.

Хранение паролей и хэшей в памяти Windows

Большинство системных администраторов пребывают в уверенности, что Windows не хранит пароли пользователей в открытом виде, а только в виде его хэша. И хотя на сегодня существует большое количество утилит, способных извлечь хэши пользовательских паролей из системы, можно с определенной уверенностью сказать, что при использовании достаточно сложного пароля не «из словаря», у злоумышленника практически нет шансов подобрать его прямым брутфорсом или по базе уже рассчитанных хэшей.

В принципе, это так, но есть различные нюансы, касающиеся пользователей, залогиненых в конкретной системе Windows.  Дело в том, что некоторые системные процессы в своих служебных целях все-таки используют пароли пользователей в открытом (или зашифрованном) виде, а не их хэши.

Так, например, механизм дайджест-аутентификации (HTTP Digest Authentication), используемый для поддержки SSO (Single Sign On), для своей работы требует знания вводимого пароля пользователя, а не только его хеша (о том, почему разработчиками это было реализовано именно так, можно только догадываться).  Пароли (именно пароли, а не их хэши) пользователей в зашифрованном виде хранятся в памяти ОС, а если быть более точным в памяти процесса LSASS.EXE. Проблема в том, что шифрование паролей реализовано с помощью стандартных Win32 функций LsaProtectMemory и LsaUnprotectMemory, которые предназначены для шифрования/расшифровки некоторого участка памяти. Утилита французских разработчиков mimikatz позволяет получать зашифрованные данные из памяти и расшифровывать их с помощью функции LsaUnprotectMemory, позволяя вывести на консоль все учетные записи пользователей, авторизованных в системе, и их пароли (в открытом, уже расшифрованном виде!). Для эксплуатации уязвимости атакующий должен иметь возможность присоединить специальную библиотеку к процессу lsass.exe.

Скачать утилиту mimikatz можно тут: http://blog.gentilkiwi.com/mimikatz

Инфо. Утилита mimikatz детектируется большинством антивирусов и браузерами, как потенциально опасное ПО (хакерская утилита).

Утилита mimikatz позволяет извлечь пароли пользователей непосредственно из памяти (путем инъекции в lsass.exe библиотеки sekurlsa.dll), из сохраненного дампа памяти компьютера или даже из файла гибернации.

Dumping Clear Text Credentials

Once downloaded/built, run Mimikatz as an administrator. Depending on the Windows machine you are using (32-bit or 64-bit), run Mimikatz accordingly. This is what it will look like when it starts:

Before we start dumping passwords, we need to start the logging process and debug privilege. To start the logging process, we simply write ‘log.’

The file Mimikatz.log will be created, when running the first time, and all Input/output communication would be stored in it for future reference. Next, we debug privilege. To do that, simply write ‘privilege::debug‘. The debug privilege allows debugging a process that they normally wouldn’t have access to.

Note: ERROR kuhl_m_privilege_simple; RtlAdjustPrivilege (20) c0000061 means that you do not have the require privilege to run the command. Try running Mimikatz as an administrator.

The ‘version‘ command will tell us the details of the windows machine being used:

Typically, instructions are in the following format:

Modulename::commandName arguments

To check the clear text passwords ‘sekurlsa::logonpasswords‘ command is used:

And there you have it, password in NTLM and clear text.

Выводы

Рассмотренные выше меры позволят существенно снизить возможности mimikatz и ей подобных утилит для получения паролей и хэшей администраторов из процесса LSASS и системного реестра. В любом случае, при принятии решения о внедрения этих политик и методик, их нужно вводить поэтапно с обязательным тестированием.

В следующей статье мы разберем лучшие практики по повышению безопасности Windows сети за счет ограничения использования учетных записей администраторов, которые на техническом и организационном уровнях дожны улучшить защиту домена Windows от подобных атак. Следите за обновлениями!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *