Hashcat (hashcat & oclhashcat)
Содержание:
Dictionary loading
The reason behind the special loading of the dictionary is that some kernels require all plaintexts to be of the same length to process them efficiently.
Brute-force crackers usually do not have this problem because the length of the generated plaintext is always the same. But it’s not so in wordlists. Usually the words in wordlists are not sorted by their length. So the idea was oclHashcat-plus would cache each of the loaded words once, and store them into specific buffers. Each word-length has one unique buffer. If a word has the length 8; it sorts it into buffer number 8. Then, if buffer 8’s threshold is reached, it processes them and clears it afterwards. This is why it is so hard for oclHashcat-plus to have a restore / resume position.
Hint: You can optimize your wordlists for oclhashcat-plus usage. You just need to sort them by their length. It is recommended that you generate seperate wordlists sorted by their length. The hashcat-utils ship with a tool called: “splitlen”, which was written for this task. (Note: sorting wordlists by length order is no longer necessary in modern versions of hashcat.)
Resume support
The following Informations are outdated. With version 0.12 oclHashcat-plus got real resume support added.
While it is not officially supported, one of our users, undeath , had a neat idea:
To gain the possibility of resuming wordlists with oclHashcat-plus, you can pipe the words into stdin using hashcat. It is then recommended that you sort your wordlists by length as described above prior to this.
hashcat --stdout wordlists/list.dict | oclhashcat-plus ...
On aborting using CTRL+C, you will see the well known message: “To restore Session use Parameter -s xxx” so you can restore the cracking process later as with the cpu version. Also, you are able to use all word altering functions provided by hashcat (like Table Lookup attack or Permutation attack).
Drivers for hashcat
The following drivers are required for video cards:
- AMD GPUs on Windows require «AMD Radeon Adrenalin 2020 Edition» (20.2.2 or later)
- Intel CPUs require «OpenCL Runtime for Intel Core and Intel Xeon Processors» (16.1.1 or later)
- NVIDIA GPUs require «NVIDIA Driver» (440.64 or later) and «CUDA Toolkit» (9.0 or later)
Most likely, drivers for AMD and NVIDIA graphics cards in Windows are already installed, or you know how to do it.
Therefore, I will only talk about OpenCL Runtime and the OpenCL driver installation.
Previously, Intel CPU Runtime for OpenCLApplications for Windows OS was available in a single file along with the graphics driver of the central processor. Now the situation has changed: the graphics processor driver and CPU Runtime for OpenCLApplications are divided into two files. Moreover, the driver can simply be downloaded from the site, and to download the runtime, you need to register on the Intel site.
Parsing the restore-file
If you want to automatically check the status of the progress it is a good idea to parse the restore-file rather than to parse STDOUT.
The format used by oclHashcat previous to version 1.20 was different and is incompatible with the new format.
There is just one entry in the restore-file of the following datatype.
typedef struct
{
uint32_t version_bin;
char cwd;
uint32_t pid;
uint32_t dictpos;
uint32_t maskpos;
uint64_t pw_cur;
uint32_t argc;
char **argv;
} restore_data_t;
- “version_bin” is the version of oclHashcat that was used to create the file.
- “cwd” is the current working directory. oclHashcat will cd to that directory on startup if it is in —restore mode.
- “argc” and “argv” is the argument line itself, 1:1 copied.
- “pid” is the current pid oclHashcat is running with. This is used for to avoid multiple instances of the same session name.
- “dictpos” indicates the number of dictionary that is beeing parsed last for instance if you specified a folder instead of a single file.
- “maskpos” indicates the number in the maskfile (if not used it will always be 0).
- “pw_cur” is used to indicate the last position in dict/mask, comparable to the –skip value
The restore file is written asychonously as soon as there is an update ready.
When I click on hashcat64.exe a black window flashes, and then disappears
Hashcat is a command-line utility. So it does not have a graphical interface in the form of a familiar window. Therefore, Windows users may think that the program is launched in an unusual way.
To start the program, open the command window (or PowerShell). To do this, press Win+x, and select Windows PowerShell:
Then you can act in two ways.
The first option: you can just drag-n-drop the executable file into the command window. The executable file is hashcat64.exe or hashcat32.exe depending on your system.
The second option: on the command line, you can change the current working directory to the one where executable hashcat files are located. For example, my program is located in the folder C:\Users\Alex\Downloads\hashcat-4.1.0\, to change the current working folder, use the cd command, after which the folder to which you specify the desired folder, in my case the command looks like this:
cd C:\Users\Alex\Downloads\hashcat-4.1.0\

As you can see from the screenshot, the folder C:\WINDOWS\system32 is changed to C:\Users\Alex\Downloads\hashcat-4.1.0.
Now to start the program it is enough to type the name of the executable file indicating the current folder. The current folder is indicated by a period (.), Then you need to put a backslash, it looks like this:
.\hashcat64.exe

Since we did not enter any options, nothing happens, only a brief hint is displayed.
Throughout the instruction, we will run the executable hashcat file with options. The simplest option is -h, if you write it, you will get a reference for using the program:
.\hashcat64.exe -h

Hashcat suite
- hashcat — World’s fastest and most advanced password recovery utility
- hashcat-utils — Small utilities that are useful in advanced password cracking
- maskprocessor — High-performance word generator with a per-position configureable charset
- statsprocessor — Word generator based on per-position markov-chains
- princeprocessor — Standalone password candidate generator using the PRINCE algorithm
- kwprocessor — Advanced keyboard-walk generator with configureable basechars, keymap and routes
Documentation for older hashcat versions like hashcat-legacy, oclHashcat, … can be found by using the Sitemap button.
Specifying the hash type
Different hashes are computed using different algorithms. Similarly, their cracking is performed using different algorithms. In order to correctly launch an attack in Hashcat, you must specify the type of attacked hash. To do this, use the -m option, after which you must specify a number corresponding to the selected hash type.
In the baseline, we are given that the provided hash is MD5. So on the page https://en.kali.tools/?p=155 we are looking for ‘MD5’:

Opposite the found hash, look at the column ‘#’, i.e. number. In this case, this number is ‘’.
So, to the Hashcat launch command, you need to add -m 0, it is the option and its value.
If we were given a SHA1 hash, then its number would be 100 and to the Hashcat launch command we would add -m 100 and similarly for any other algorithm.
Typically, a hash type is known from the source where this hash was obtained. In case the type of attacked hash is not known reliably, you can try to guess it with the help of specialized tools.
Mask for unknown password length
The password length is not always known exactly. Even by the condition of our task, the password has a length of six to ten characters.
In order to generate passwords of different lengths, the following options are available:
Options Short / Long | Type | Description | Example
-i, --increment | | Enable mask increment mode |
--increment-min | Num | Start mask incrementing at X | --increment-min=4
--increment-max | Num | Stop mask incrementing at X | --increment-max=8
The -i option is optional. If it is used, it means that the length of candidates for passwords should not be fixed, it should increase by the number of characters.
The —increment-min option is also optional. It determines the minimum length of candidates for passwords. If the -i option is used, the —increment-min value is 1 by default.
And the —increment-max option is optional. It determines the maximum length of candidates for passwords. If the -i option is specified, but the —increment-max option is omitted, then its default value is the mask length.
Rules for using mask increment options:
- Before using —increment-min and —increment-max, you must specify the -i option
- the value of the —increment-min option can be less than or equal to the value of the —increment-max option, but can not exceed it
- the length of the mask can be larger in the number of characters or equal to the number of characters specified by the —increment-max option, but the mask length can not be less than the character length set by —increment-max.
So, we will correct the launch command for our task (the password has a length of six to ten characters):
.\hashcat64.exe -m 0 -a 3 -i --increment-min=6 --increment-max=10 53ab0dff8ecc7d5a18b4416d00568f02 ?l?l?l?l?l?l?l?l?l?l
This command is similar to the previous one, but three new options have been added (explained just above):
- -i
- —increment-min=6
- —increment-max=10
And also the mask length is increased to 10 characters: ?l?l?l?l?l?l?l?l?l?l (as required by the rules for using increment options).
It took a bit more time to complete the search, as candidates in passwords of 6 (+1 seconds on my gland) and 7 symbols (+22 seconds) were tested in addition:

Note the new value of the Status line:
Status...........: Exhausted
It means that all the password candidates was tested, but none proved true.
Writing rules
The most important thing in writing rules is knowing what you want to write. That typically means you have to analyze dozens of plaintext passwords, maybe from a customer, to see a pattern. For example, a common pattern is that people append a digit to their passwords to improve its strength. So we have two “parameters”:
- We want to append something.
- The value we want to append is a digit.
If we take a look at the function overview we see that we can append something using the ‘$’ function. So, for example, if we want to add a “1” to our password, we write a rule that looks like this.
$1
Simple enough. But what if we want to do all numbers 1 — 9? Well thats what we call a Hybrid attack, just take a look at this page.
Also note:
- White spaces are ignored as long as they are not used as a parameter. That enables formating of our “source code” a bit.
- To comment out some text, it has to start with a “#” char.
Dictionary loading
The reason behind the special loading of the dictionary is that some kernels require all plaintexts to be of the same length to process them efficiently.
Brute-force crackers usually do not have this problem because the length of the generated plaintext is always the same. But it’s not so in wordlists. Usually the words in wordlists are not sorted by their length. So the idea was oclHashcat would cache each of the loaded words once, and store them into specific buffers. Each word-length has one unique buffer. If a word has the length 8; it sorts it into buffer number 8. Then, if buffer 8’s threshold is reached, it processes them and clears it afterwards. This is why it is so hard for oclHashcat to have a restore / resume position.
Hint: You can optimize your wordlists for oclhashcat usage. You just need to sort them by their length. It is recommended that you generate seperate wordlists sorted by their length. The hashcat-utils ship with a tool called: “splitlen”, which was written for this task.
Example
Let’s do some easy example. We want to create the square password «rtyhnbvf» as straight as possible, as we have seen in one of the image above.
Note that we can not force the KWP to generate a square, with the reasons stated in the background section in the beginning of this document, but we can configure it as close as possible so that you can see what’s going on here. That means, we can use a very specific route that is able to generate squares, but in general this route we define will not be limited to only generate squares but it will generate all patterns that follow that specific sequence of geographic direction changes of the defined lengths.
The first configuration item the KWP wants from you is a list of base characters. This is usually a list of characters, but we can also use a single character if we want to.
So we create a file «basechar.txt» with the content «r», that’s it.
The second configuration item the generator wants from you is the keymap. We could take the preconfigured english keymap, it’s simple enough, but I want to show you that it’s pretty easy to generate your own keymap. So lets leave everything of no importance and create a file «keymap.txt» with the following content:
The only important part here is that you make this file to have exactly 12 lines. For the purpose of this example I’ve truncated it.
The third and last configuration item the generator wants from you is the route. Let’s think for a second how such a route needs to look like. Even if you believe such a thing is not required for regular use because KWP comes with a set of predefined routes, it may help you if you want to pick a special one yourself.
- We’ll start with the «r» because it’s the only existing base-character.
- We want to have «ty» next. That make two steps, so all we need to configure is «2».
- We want to have «hn» next. That make two steps, so all we need to configure is «2».
- We want to have «bv» next. That make two steps, so all we need to configure is «2».
- We want to have «f» next. That makes one step, so all we need to configure is «1».
- The final content in our «route.txt» is: 2221
Now all the configuration is taken care of. Here’s what this will generate:
As you can see I’ve filtered this to print out only the pattern we were looking for. That’s just a proof that it actually generated it. Here’s the full output:
You may notice there’s no use of the «g» character, even if it’s an adjacent tile character and it’s part of the keymap. The reason for that is that diagonal tiles are disabled by default. Of course you can enable them, see —help for details.
But more important here is how the pattern looks like. I made pictures for some of them to get a better feeling for it. The following keyboard walks show some nice patterns:
Rectangle east : rfvbnhyt
Rectangle south : rtyhnbvf
Rectangle south and north : rfvbnbvf
Rectangle east and west : rtyhnhyt
But there are even those pattern who aren’t perfectly aligned like this one:
Rectangle east and west : rfvbnbvb
However, they are still good candidates and they match up what we were initially looking for. We have the perfect ones and those that are not perfect, which makes them human.
Как пользоваться Hashcat?
Как я уже сказал, утилита позволяет расшифровывать хэши, созданные с помощью различных алгоритмов с помощью перебора. Мы будем перебирать хэш md5 и рассмотрим два типа атаки — на основе словаря и полным перебором.
1. Перебор по словарю в Hashcat
Расшифровка md5 проще всего выполняется по словарю. Поскольку полный перебор занимает очень много времени, то перебрать наиболее часто употребляемые варианты может быть намного быстрее. Для перебора нам понадобится словарь, обычно используется rockyou. Словарь можно скачать командой:

Теперь нам еще осталось подготовить хэши, которые будем перебирать. Проще всего это сделать с помощью команды Linux md5sum:
echo -n «password» | md5sum

Например, создадим три хэша. Затем сложим их в файл
2ac9cb7dc02b3c0083eb70898e549b63 5f4dcc3b5aa765d61d8327deb882cf99 b59c67bf196a4758191e42f76670ceba
Теперь, когда все собрано, мы готовы к перебору. Команда перебора по словарю будет выглядеть вот так:
hashcat -m 0 -D 1 -a 0 -t 20
/rockyou.txt -o data.txt

Здесь -m 0 указывает на то, что нужно перебирать хэш md5, а -a 0 указывает на использование обычной атаки по словарю. С помощью опции -n мы задаем количество потоков. Опция -D 1 говорит программе, что нужно использовать процессор. Если вам нужна видеокарта hashcat, используйте -D 0.
Затем, мы указываем файл с хэшами, которые будем перебирать — hashes и словарь. Перебор может занять долгое время, но когда комбинация будет найдена, программа запишет ее в файл data.txt.
Что касается других алгоритмов, то для них нужно будет указать только другой номер типа хєша. Например, для SHA это будет 100. Чтобы узнать нужный номер вы можете использовать такую команду:
hashcat —help | grep SHA1

https://youtube.com/watch?v=KnkjBW3fMVo
2. Расшифровка md5 полным перебором
Анализ по словарю выполняется достаточно быстро. На моем железе, такой небольшой словарь анализировался меньше минуты. Программа выдала скорость около 1300 kHash в секунду, а это очень много. Но в словаре есть далеко не все комбинации. Поэтому вы можете попытаться выполнить полный перебор нужной последовательности символов. Например:
hashcat -m 300 -a 3 -n 32 —custom-charset=?l?d

Здесь мы просто указали набор символов, буквы в нижнем регистре и цифры, а затем запустили перебор. Также можно указать ограничения на минимальное и максимальное количество символов:
hashcat -m 0 -a 3 —force -D 1 —potfile-disable —increment-min 5 —increment —increment-max 6 —custom-charset1=?l?d

Здесь мы говорим программе, что нужно начинать с размера слова 5 символов и завершить размером 6. Также можно использовать маски. Маска позволяет точно указать какой набор символов использовать, в какой последовательности и сколько. Указывать маску нужно на месте словаря. Например, маска слова из четырех цифр будет ?d?d?d?d, а маска из четырех любых цифр, букв разного регистра и специальных символов будет выглядеть ?a?a?a?a. Также можно комбинировать маску с известной частью: abc?a?a. Рассмотрим пример команды:
hashcat -m 0 -a 3 —force -D 1 —potfile-disable

Маска уменьшает в разы количество вариантов, тем самым увеличивая скорость. Таким образом, расшифровка хеша md5 длиной 4 символа была выполнена меньше чем за секунду. С помощью следующей команды вы можете проверить не перебирали ли вы раньше эти хэши:
hashcat -m 0 —show

Какие хэши можно перебрать?
Как я уже говорил, существует несколько алгоритмов хэширования, но сложность перебора каждого из них отличается. Каждый из алгоритмов может иметь коллизии. Это когда для одного хэша можно подобрать несколько различных исходных наборов данных. Самым небезопасным из популярных алгоритмов на данный момент считается md5. Было доказано, что в этом алгоритме можно найти множество коллизий, а это значит, что перебрать значение такого хэша будет намного проще. Алгоритм sha1 тоже имеет коллизии, но их намного сложнее найти, а значит перебор будет ненамного проще. Существования коллизий для Sha2 пока не доказано, но не исключено.
Программа hashcat поддерживает работу с такими алгоритмами хэширования: md5, md5crypt, sha1, sha2, sha256, md4, mysql, sha512, wpa, wpa2, grub2, android, sha256crypt, drupal7, scrypt, django и другими.
Hashcat options
Working with programs in the command-line interface is very different from working in the graphical user interface. In the GUI, we press different buttons, move switches, etc. This is not the case with programs with a command-line interface. But at the same time the command line utility can have even greater capabilities than a similar program with a window interface. In order to control the functionality of console utilities, options are used.
In the output of the help you probably noticed a lot of information. This information is mostly devoted to the options.
Options are specified after the file name separated by a space. Some options require specifying a certain value. Some are used without values (such options are also called ‘flags’).
Options can be used one at a time or several at a time. With the help of options you can very accurately configure the program, use it at maximum capacity.
With one option we have already met, it is the -h option, which displays program help, then we’ll get acquainted with even more options and their possible values.
The next one is the -b option.
Dictionary Attack in Hashcat
The attack starts with the dictionary as follows:
hashcat hash|hashfile|hccapxfile path_to_dictionary
To crack our hash, create a small dictionary: an ordinary text file named dictionary.txt and copy into it:
Note: By the way, with Hashcat comes with an example of a dictionary, it’s called example.dict.
So, at this stage we have everything you need to launch an dictionary attack. We collect everything together:
.\hashcat64.exe -m 0 -a 0 53ab0dff8ecc7d5a18b4416d00568f02 dictionary.txt
Here:
- .\hashcat64.exe is a executable file
- -m 0 is an option that sets the MD5 hash type
- -a 0 is an option, which value triggers a dictionary attack
- 53ab0dff8ecc7d5a18b4416d00568f02 is a hash to be cracked
- dictionary.txt is a path to the dictionary file.
Since the dictionary is very small, the program will finish its work very quickly:

The result of the program:
53ab0dff8ecc7d5a18b4416d00568f02:hackware Session..........: hashcat Status...........: Cracked Hash.Type........: MD5 Hash.Target......: 53ab0dff8ecc7d5a18b4416d00568f02 Time.Started.....: Mon Mar 05 07:23:25 2018 (0 secs) Time.Estimated...: Mon Mar 05 07:23:25 2018 (0 secs) Guess.Base.......: File (dictionary.txt) Guess.Queue......: 1/1 (100.00%) Speed.Dev.#1.....: 17783 H/s (0.04ms) @ Accel:1024 Loops:1 Thr:1 Vec:4 Speed.Dev.#2.....: 0 H/s (0.00ms) @ Accel:256 Loops:1 Thr:256 Vec:1 Speed.Dev.#3.....: 12530 H/s (0.03ms) @ Accel:1024 Loops:1 Thr:1 Vec:4 Speed.Dev.#*.....: 30313 H/s Recovered........: 1/1 (100.00%) Digests, 1/1 (100.00%) Salts Progress.........: 24/48 (50.00%) Rejected.........: 0/24 (0.00%) Restore.Point....: 0/48 (0.00%) Candidates.#1....: aaaaaaaaaa -> dancing2009 Candidates.#2....: Candidates.#3....: danciotu -> hackware HWMon.Dev.#1.....: N/A HWMon.Dev.#2.....: Util: 37% Core: 800MHz Mem:1000MHz Bus:16 HWMon.Dev.#3.....: N/A
The first line is 53ab0dff8ecc7d5a18b4416d00568f02: hackware contains the attacked hash and after the colon the hacked password, in this case it is hackware.
On the successful hacking says the Status ………..: Cracked line
Hash does not need to be specified in the command line, it can be written to a file, then when the attack is launched, the path to the file containing the hash is specified. For example, create a hashmd5.txt file and copy into it 53ab0dff8ecc7d5a18b4416d00568f02.
Then the command to run will be:
.\hashcat64.exe -m 0 -a 0 hashmd5.txt dictionary.txt
The command contains the same options as the previous one, but instead of directly hash, we specified the path to the file containing the hash to crack.
Note: since for educational purposes we crack the same hash in different ways, in case you repeat the examples, you will see the message:
INFO: All hashes found in potfile! Use --show to display them.
It means that the hash that you are trying to crack has already been cracked before. All compromised hashes are stored in the hashcat.potfile file in the same directory as Hashcat. This is a plain text file, you can open it and see the contents, in my case it’s:
53ab0dff8ecc7d5a18b4416d00568f02:hackware
This file can be deleted to start attack anew on the same hash in different ways.
There is also the option —show, after which you need to specify the hash of interest:
.\hashcat64.exe --show 53ab0dff8ecc7d5a18b4416d00568f02
and if it is found in the hashcat.potfile file, then information about the cracked password will be displayed.
Multi-rules
With release of old oclHashcat-plus v0.07 a complete new feature in the rule-based cracking world was added.
Instead of just giving one -r parameter and a file, you can now add as many -r’s as you want.
They are not executed in a sequence!
Each rule of each rule-file is combined with each rule of each rule-file. This way you can easily cook your own attack mode.
$ cat 123.rule $1 $2 $3 $ cat abc.rule $a $b $c $ hashcat --stdout -r 123.rule -r abc.rule wordlist hashcat1a hashcat2a hashcat3a hashcat1b hashcat2b hashcat3b hashcat1c hashcat2c hashcat3c
Because the total number of generated rules is the product of all lists, stacking multiple large lists can quickly exceed available memory. But a few well-chosen rules can be stacked to great effect.
Утилита hashcat
Сначала давайте рассмотрим синтаксис и возможные опции утилиты, а потом уже перейдем к ее использованию. Это консольная утилита, поэтому придется использовать ее через терминал. Давайте сначала рассмотрим синтаксис:
$ hashcat опции файл_хэшей словари_и_настройки
Как видите, все довольно просто. Начнем с основных опций, которые настраивают как будет вести себя утилита:
- -h — вывести доступные команды и опции;
- -V — версия программы;
- -m — тип хэша, который нужно перебрать, например, md5 или sha;
- -a — вид атаки;
- -b — запустить тестирование производительности;
- —hex-salt — указать соль, которая использовалась при хэшировании;
- —hex-charset — набор символов, для исходных данных;
- —status — автоматически обновлять состояние подбора;
- -o — файл для записи результата;
- -p — символ, которым разделены хэши для перебора;
- -c — размер кэша для словаря;
- -n — количество потоков;
- -l — ограничить количество слов для перебора;
- -r — файл с правилами генерации вариантов;
- -D — устройство для перебора, CPU или GPU;
- —pw-min — минимальная длина варианта, символов;
- —pw-max — максимальная длина варианта, символов;
- —table-min — длина пароля для табличной атаки;
- —table-max — максимальная длина пароля для табличной атаки;
- —table-file — файл таблицы, для атаки по таблице.
Мы рассмотрели все основные опции, которые сегодня будем использовать. Многие из параметров, например, тип хэша и атаки, задаются в виде цифр. Я не буду рассматривать цифровые коды для типа хэша подробно. Вы можете найти эту информацию, выполнив man hashcat. Рассмотрим типы атак:
- Straight — обычная атака, берет слова из словаря и проверяет их;
- Combination — комбинирует слова из словаря в разные комбинации;
- Toggle-Case — по очереди пробует разный регистр букв для каждого символа слова;
- Brute-force — атака простым перебором на основе маски или символов;
- Permutation — при этом типе атаки программа берет слова из словаря и меняет в них буквы местами для получения разных комбинаций;
- Table-Lookup — Табличная атака, берется одно слово и словаря, а затем на его основе создаются варианты из таблицы. Каждый символ из таблицы будет заменен на набор прописанных вариантов;
- Prince — новый вид атаки перебора, которая работает быстрее, обычной.
Кроме того, при переборе на основе брутфорса нам понадобится выбрать набор символов, которые будет использовать программа для генерации возможных вариантов. Вот возможные значения:
- ?l = abcdefghijklmnopqrstuvwxyz;
- ?u = ABCDEFGHIJKLMNOPQRSTUVWXYZ;
- ?d = 0123456789;
- ?s = !»#$%&'()*+,-./:;<=>?@[]^_`{|}~;
- ?a = ?l?u?d?s — любой символ;
- ?b = 0x00 — 0xff.
Теперь мы разобрали все необходимое и можно переходить к практике.