John the ripper zip windows

Содержание

  • Введение
  • Установка John the Ripper
  • Создание парольного ZIP — архива
  • Извлечение хэша ZIP — архива
  • Запуск John the Ripper для взлома пароля
  • Подтверждение пароля
  • Резюме

Введение

В этом лабораторном занятии вы научитесь взламывать пароли защищенных ZIP — архивов с помощью John the Ripper, важного инструмента в области кибербезопасности для пенетрационных тестов. Вы научитесь извлекать хэши из ZIP — архивов и проводить как словарные, так и брутфорс — атаки для восстановления паролей.

В рамках лабораторной работы вы получите практический опыт по установке John the Ripper, созданию тестовых файлов с несложными паролями и проверке взломанных учетных данных. В результате этого упражнения вы поймете уязвимости несложных паролей и важность надежной шифрования в обеспечении безопасности файлов.


Skills Graph

%%%%{init: {‘theme’:’neutral’}}%%%%
flowchart RL
hydra((«Hydra»)) -.-> hydra/HydraGroup([«Hydra»])
nmap((«Nmap»)) -.-> nmap/NmapGroup([«Nmap»])
wireshark((«Wireshark»)) -.-> wireshark/WiresharkGroup([«Wireshark»])
nmap/NmapGroup -.-> nmap/installation(«Installation and Setup»)
wireshark/WiresharkGroup -.-> wireshark/installation(«Installation and Setup»)
hydra/HydraGroup -.-> hydra/installation(«Installation and Setup»)
subgraph Lab Skills
nmap/installation -.-> lab-549930{{«Взломать пароли ZIP в John the Ripper»}}
wireshark/installation -.-> lab-549930{{«Взломать пароли ZIP в John the Ripper»}}
hydra/installation -.-> lab-549930{{«Взломать пароли ZIP в John the Ripper»}}
end

Установка John the Ripper

На этом этапе вы установите John the Ripper, мощный инструмент для взлома паролей, широко используемый в области кибербезопасности. Прежде чем приступить, разберемся, что делает John the Ripper: он помогает профессионалам в области безопасности проверить надежность паролей, пытаясь различными комбинациями (брутфорс — атака) или используя словарные списки (словарные атаки) для угадывания паролей.

Виртуальная среда LabEx уже предустановлена со всеми необходимыми зависимостями, что делает процесс установки простым. Мы будем использовать пакетный менеджер Ubuntu (apt), который управляет установкой и обновлением программного обеспечения.

  1. Сначала нам нужно обновить список пакетов. Это гарантирует, что ваша система знает о последних доступных версиях всего программного обеспечения:

    sudo apt update

    Команда sudo предоставляет вам права администратора, а apt update обновляет список доступных пакетов.

  2. Теперь установите John the Ripper с помощью следующей команды:

    sudo apt install john -y

    Флаг -y автоматически подтверждает установку, не требуя от вас вводить ‘yes’ в процессе.

  3. После завершения установки убедимся, что все работает правильно, проверив установленную версию:

    john --version

    Вы должны увидеть вывод, похожий на следующий:

    John the Ripper 1.9.0-jumbo-1

Эта проверка версии подтверждает, что John the Ripper готов к использованию. В следующих шагах мы используем этот инструмент, чтобы показать, как защищенные паролем ZIP — архивы могут быть уязвимы для попыток взлома. Убедитесь, что вы видите номер версии перед переходом к следующим этапам, так как это свидетельствует о успешной установке.

Создание парольного ZIP — архива

На этом этапе вы создадите парольный ZIP — архив, который мы будем использовать для практики взлома паролей на следующих этапах. ZIP — это распространенный формат архивов, поддерживающий парольную защиту для обеспечения безопасности конфиденциальных файлов. Понимание того, как создавать защищенные ZIP — архивы, является фундаментальным, так как многие реальные системы используют этот метод для защиты файлов.

  1. Сначала создадим пример текстового файла для защиты. Мы будем использовать простой текстовый файл в демонстрационных целях:

    echo "This is a secret file" > secret.txt

    Эта команда создает новый файл с именем secret.txt, содержащий текст «This is a secret file». Символ > перенаправляет вывод команды echo в файл.

  2. Теперь создадим парольный ZIP — архив с помощью утилиты zip. Флаг -e включает шифрование. В учебных целях мы используем «password123» в качестве примера пароля (учтите, что это слабый пароль и его никогда не следует использовать в реальных сценариях):

    zip -e secret.zip secret.txt

    Команда попросит вас дважды ввести и подтвердить пароль. Эта двойная проверка помогает избежать опечаток в пароле:

    Enter password:
    Verify password:
  3. Убедимся, что ZIP — архив был успешно создан. Команда ls -l показывает подробную информацию о файлах в текущем каталоге:

    ls -l secret.zip

    Вы должны увидеть вывод, похожий на следующий, который показывает, что файл существует, а также его размер и временную метку:

    -rw-r--r-- 1 labex labex 210 May 10 10:00 secret.zip
  4. Наконец, проверим парольную защиту, попробовав извлечь файл без предоставления пароля. Это подтверждает, что наш ZIP — архив надежно защищен:

    unzip secret.zip

    Система должна запросить пароль и вывести ошибку, если вы введете неверный пароль или отмените операцию.

Этот защищенный ZIP — архив будет служить нашим тестовым примером на следующих этапах, где мы извлечем его хэш и попытаемся взломать пароль с помощью John the Ripper. Создание этого тестового файла самостоятельно поможет вам понять обе стороны процесса безопасности — как применяется защита и как ее можно проверить.

Извлечение хэша ZIP — архива

На этом этапе вы извлечете криптографический хэш из парольного ZIP — архива, который мы создали ранее. Этот процесс преобразует информацию о безопасности ZIP — архива в формат, который John the Ripper может понять и обработать для взлома пароля.

  1. Сначала перейдем в наш рабочий каталог и убедимся, что ZIP — архив существует. Это гарантирует, что мы работаем с правильным файлом в нужном месте:

    cd ~/project
    ls secret.zip
  2. Теперь мы будем использовать специальный инструмент John the Ripper под названием zip2john. Эта утилита извлекает хэш пароля из ZIP — архивов в формате, который John может взломать. Символ > перенаправляет вывод в новый файл:

    zip2john secret.zip > zip_hash.txt
  3. Посмотрим на извлеченный хэш, чтобы понять, какую информацию он содержит. Команда cat отображает содержимое файла в терминале:

    cat zip_hash.txt

    Вы должны увидеть вывод, похожий на этот пример (ваш фактический хэш будет отличаться):

    secret.zip:$pkzip$1*2*2*0*1c*1a*5e9b8f7d*0*42*0*1c*5e9b*55dc*secret.txt*$/pkzip$
  4. Хэш содержит несколько важных компонентов:

    • secret.zip: Имя исходного ZIP — архива
    • $pkzip$: Указывает, что это хэш в формате PKZIP
    • Длинная строка цифр и букв: Фактические зашифрованные данные пароля
    • secret.txt: Имя файла внутри ZIP — архива

Этот извлеченный файл с хэшем теперь содержит всю необходимую информацию о парольной защите ZIP — архива, отформатированную специально для обработки John the Ripper. На следующем этапе мы используем этот файл с хэшем, чтобы попытаться восстановить пароль различными методами взлома.

Запуск John the Ripper для взлома пароля

На этом этапе вы будете использовать John the Ripper для попытки взлома пароля ZIP — архива, который мы защитили ранее. John — это мощный инструмент для взлома паролей, который работает, пытаясь подобрать различные комбинации паролей для хэша, который мы извлекли. Хэш — это своего рода цифровая подпись вашего пароля, которую John может проанализировать без необходимости наличия исходного ZIP — архива.

  1. Сначала убедитесь, что вы находитесь в правильном каталоге с файлом хэша. Это важно, так как John должен иметь доступ к файлу хэша, который мы создали на предыдущем этапе:

    cd ~/project
    ls zip_hash.txt

    Команда ls просто выводит список файлов, чтобы подтвердить, что zip_hash.txt существует в текущем каталоге.

  2. Теперь запустим John the Ripper с указанным форматом PKZIP, так как мы работаем с ZIP — архивом. Флаг --format=PKZIP сообщает John, какого типа шифрование ожидать:

    john --format=PKZIP zip_hash.txt
  3. John будет отображать информацию о текущем прогрессе, пытаясь подобрать различные комбинации паролей. В нашем случае, так как мы использовали слабый пароль («password123»), взлом должен быть завершен практически мгновенно. Вот как выглядит успешный вывод:

    Loaded 1 password hash (PKZIP [32/64])
    Will run 2 OpenMP threads
    Press 'q' or Ctrl - C to abort, almost any other key for status
    password123      (secret.zip)
    1g 0:00:00:00 DONE (2023 - 05 - 10 10:00) 50.00g/s 50.00p/s 50.00c/s 50.00C/s password123
    Use the "--show" option to display all of the cracked passwords reliably
    Session completed

    «1g» означает, что John проверил 1 вариант, а «password123» — это взломанный пароль.

  4. Чтобы просмотреть взломанный пароль в удобном формате, используем опцию --show. Эта команда отображает все успешно взломанные пароли из файла хэша:

    john --show zip_hash.txt

    Вы увидите вывод, похожий на следующий:

    secret.zip:password123:secret.txt:secret.zip

    Этот вывод содержит четыре части информации, разделенные двоеточиями: имя ZIP — архива, взломанный пароль, файл, содержащийся в архиве, и имя архива снова.

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

Подтверждение пароля

На этом последнем этапе вы убедитесь, что пароль, взломанный с помощью John the Ripper, действительно позволяет извлечь защищенный ZIP — архив. Этот этап подтверждения является важным при проведении реальных оценок безопасности для проверки результатов взлома. Представьте, что вы нашли ключ — вам нужно попробовать открыть замок, чтобы убедиться, что он подходит.

  1. Сначала проверим взломанный пароль из предыдущего этапа. Следующая команда отображает пароли, которые John успешно взломал:

    john --show zip_hash.txt

    Вы должны увидеть вывод, похожий на следующий, показывающий имя файла, взломанный пароль и содержимое:

    secret.zip:password123:secret.txt:secret.zip
  2. Теперь проверим, работает ли этот пароль, пытаясь извлечь ZIP — архив. Команда unzip — это стандартный инструмент для извлечения ZIP — архивов в Linux:

    unzip secret.zip

    Система попросит вас ввести пароль. Введите «password123» (тот, который мы только что взломали):

    Archive:  secret.zip
    [secret.zip] secret.txt password:
  3. После ввода правильного пароля мы должны проверить два момента: что файл был извлечен и что его содержимое соответствует нашим ожиданиям. Эти команды выводят список файлов в каталоге и отображают содержимое секретного файла:

    ls
    cat secret.txt

    Вы должны увидеть следующее, подтверждающее успешное извлечение:

    This is a secret file
  4. Наконец, хорошей практикой является удаление извлеченных файлов после завершения тестирования. Это помогает сохранить чистоту рабочей области и предотвращает случайное использование тестовых файлов в будущих упражнениях:

    rm secret.txt

Успешное извлечение подтверждает, что John the Ripper правильно взломал пароль ZIP — архива. В реальной оценке безопасности этот этап проверки является обязательным перед представлением результатов. Он доказывает, что взломанный пароль не просто теоретически подходит, но и дает доступ к защищенному контенту.

Резюме

В этом практическом занятии вы узнали, как установить John the Ripper с помощью пакетного менеджера apt и проверить, что установка прошла успешно. Вы также попрактиковались в создании ZIP — архива с парольной защитой, содержащего пример текстового документа, чтобы смоделировать реальные сценарии взлома паролей.

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

Perhaps you need a quick overview on how to use the password-cracking tool John the Ripper, or you may be a beginner and wondering why you haven’t been able to get it to work. If that’s you, you’ve come to the right place. We’ve prepared a straightforward tutorial on how to use John the Ripper for you.

A must-have in the pentester’s toolkit, John the Ripper cracks passwords using a rainbow table approach: comparing them with an inbuilt table of hashes. We’ll review John the Ripper’s three major password-cracking modes and several usage examples, with short exercises for those new to this ruthless tool.

But be warned: We don’t condone using John the Ripper for malicious purposes. With great power comes great responsibility.

Without further ado, let’s get cracking.

Table Of Contents

  1. What Is John the Ripper?
  2. John the Ripper Command Generator
  3. Modes for Cracking Passwords
  4. Cracking Passwords With John the Ripper
  5. Other Useful Commands
  6. Conclusion
  7. Frequently Asked Questions

What Is John the Ripper?

Jack the Ripper was a murderer in 1888 in London, England. Just as people exposed to Jack the Ripper died, passwords exposed to John the Ripper are no longer secret.

You can deploy John the Ripper inside Kali Linux with the following terminal command instantly:

john

Hence, for simplicity, we’ll call John the Ripper “John” from this point onward. John’s various options help you customize your experience uncovering passwords:

john -h

John the Ripper Command Generator

Say goodbye to the hassle of trying to remember the exact syntax for your John the Ripper commands! With our John the Ripper Command Generator, you can simply say what you need John the Ripper to do, and we will generate the command for you.

Modes for Cracking Passwords

John the Ripper offers three main password-cracking modes: Single, Wordlist, and Incremental.

Single Crack Mode

Our example here is a username-password pair based on the 1986 Tom Cruise movie, which released its sequel in 2022.

In Single Crack Mode, John takes a string and generates variations of that string to generate a set of passwords. For example, you can use this Mode to generate password variations of the username “topgun” with the corresponding password “Topgun” (or TopGun, ToPgUn, tOpGuN, and so on).

Use the --format flag to specify the hash type and the --single (-si) flag to let John know we want to use the Single Crack Mode.

Afterward, we’ll crack more complex passwords with John’s Wordlist Mode.

Single Crack Mode

Try this exercise

  1. Designate a short string (topgun) as a username and variations on its capitalization as the password (such as Topgun).
  2. Show the output of the SHA-256-hashed password: echo -n 'Topgun' | sha256sum
  3. Create a new text file (simple.txt) to store the username and the password hash value from prior steps: echo -n 'topgun:4558ce5abe3b1e70bbadc3b95f2ff84f54d0a5c30fb524ceebfd401f8233fda7' > simple.txt
  4. Run simple.txt through John the Ripper’s Single Crack Mode (change the --format argument as you see fit): john --single --format=raw-sha256 simple.txt
  5. Get results.
Try this exercise

A self-contained tutorial on generating a password for Single Crack Mode

Oops: If you hash your desired password with the following wrong command instead, you’ll hash an unintended line break at the end:

echo Topgun | sha256sum # wrong command

Wordlist Mode

In Wordlist Mode, we’ll provide John with a list of passwords. John will generate hashes for them in real-time and compare them with our password hash. In this example, we will use the well-known RockYou wordlist, which you can preview at

cat /usr/share/wordlists/rockyou.txt | less

Feel free to copy it to your current working directory to simplify the commands using the --wordlist (-w) flag:

cp /usr/share/wordlists/rockyou.txt rockyou

Now let’s pass text files containing password hashes through John:

john --wordlist=rockyou --format=raw-sha256 crack.txt

john -w=rockyou --format=raw-sha256 crack.txt

Wordlist Mode

Try this exercise

  1. Pipe a hash based on one or more dictionary words (optionally with numbers) to SHA-256: echo -n 'password1234' | sha256sum
  2. Write your username, a colon (:), and the hash as a single long string into a new text file (crack.txt): echo user01:b9c950640e1b3740e98acb93e669c65766f6670dd1609ba91ff41052ba48c6f3>>crack.txt
  3. Repeat Steps 1 and 2 to generate as many username-password pairs as desired and append them to crack.txt.
  4. Run crack.txt through John the Ripper’s Wordlist Mode: john --wordlist=rockyou --format=raw-sha256 crack.txt
  5. Get results.
Try this exercise

Left: John the Ripper Wordlist Mode in action

Right: Generating hashes for three simple passwords

John finds these three passwords rapidly. The weaker the password is, the faster John cracks them.

Let’s move on to John’s final Incremental Mode.

Incremental Mode

In Incremental Mode, John tries all possible character combinations as passwords. This process can be time-consuming if the password is too long or if alphanumeric characters and symbols comprise the password.

You won’t use this Mode unless you don’t have any other options. Typically, a combination of social engineering attacks and Wordlist Mode will help you uncover most passwords.

The syntax for Incremental Mode is:

john --incremental --incremental-charcount=N --format=FORMAT passwords_to_crack.txt

john -inc --incremental-charcount=N --format=FORMAT passwords_to_crack.txt

Let’s break down each flag:

Incremental Mode flags

  • The --incremental (-inc) flag tells John to use the Incremental Mode.
  • The --incremental-charcount=N  flag, where N is a positive integer, is for setting the maximum number of digits in the password.
  • The --format option tells John the hash type of your passwords.
Incremental Mode flags

Try this exercise

  1. Pipe a hash on a simple alphanumeric password to SHA-256: echo -n 'passw0rd' | sha256sum
  2. Write your username, a colon (:), and the hash as a single long string into a new text file (inc.txt): echo user02:8f0e2f76e22b43e2855189877e7dc1e1e7d98c226c95db247cd1d547928334a9>>inc.txt
  3. Run inc.txt through John the Ripper’s Wordlist Mode: john --incremental --format=raw-sha256 inc.txt
  4. Get results.
Generated password hashes

Generated password hashes

Cracking password hashes in Incremental Mode

Cracking password hashes in Incremental Mode

Now that we know how to use John the Ripper, we shall move on to specific use cases.

Cracking Passwords With John the Ripper

Now that we know the different modes, let’s examine some real-world examples of when and how to crack passwords with John.

Choosing a Wordlist

John’s default Wordlist is a file located in /usr/share/john/password.lst in Kali Linux, but its power is finite compared with custom wordlists such as those found by John’s developer OpenWall https://www.openwall.com/wordlists/. 

Apart from RockYou, the Wordlists all.lst (downloadable as all.gz) and huge.lst are good candidates for the --wordlist flag.

Edit the Wordlist by amending the following line in /usr/share/john/john.conf:

Wordlist = $JOHN/password.lst

To make John work more efficiently, remove duplicate entries from and sort the contents of your chosen Wordlist file.

Cracking ZIP files

John has a utility called zip2john. zip2john helps us to get the hash from zip files. Other “2john” utilities exist, such as the rar2john utility for cracking a RAR file.

To crack a password-protected ZIP file, we first get the hash of the ZIP file’s password:

zip2john file.zip > zip.hashes

This command gets the hash from the ZIP file and stores it in the zip.hashes file.

Now you can crack the hash with John:

john zip.hashes # Single Crack Mode

john --wordlist=rockyou zip.hashes # Using the RockYou wordlist

Cracking ZIP files

Try this exercise

  1. Create a password-protected ZIP archive (classified.zip) on Kali Linux: right click on a file/folder, select “Create Archive…”, choose “ZIP” as the compression method, expand “Other options” to give it a weak password, and click “Create.”
  2. Export the ZIP hash to zip.hashes: zip2john classified.zip > zip.hashes
  3. Run zip.hashes through John the Ripper: john zip.hashes
  4. Get results.

Step 1: Create a password-protected ZIP archive on Kali Linux

Create a password-protected ZIP archive on Kali Linux

Steps 2 to 4: zip2john followed by John the Ripper usage

zip2john followed by John the Ripper usage

Cracking SSH Keys

The ssh2john utility creates a hash from your private key file. If your private key file path is /home/kali/.ssh/id_rsa, and you want to store the hash as myHash.txt, the syntax is:

ssh2john /home/kali/.ssh/id_rsa > myHash.txt

Cracking SSH Keys

Cracking SSH Keys

Try this exercise

  1. Use the following command to generate an RSA key pair with a passphrase: ssh-keygen
  2. Export the hashed private key file to a new file (myHash.txt): ssh2john /home/kali/.ssh/id_rsa > myHash.txt
  3. Run myHash.txt through John the Ripper: john --wordlist=rockyou myHash.txt
  4. Get results

Step 1: Demo of ssh-keygen

Demo of ssh-keygen

Cracking Linux Passwords

Linux stores password data in two files:

  • /etc/passwd stores information such as username, user id, and login shell;
  • /etc/shadow is the password file containing data such as hash and expiry date.

A utility bundled with John the Ripper called unshadow can combine both files for cracking. Here, we’ll name the combined file lin.txt:

unshadow /etc/passwd /etc/shadow > lin.txt

Cracking Linux Passwords

Cracking Linux hashes is tricky; Kali Linux’s John the Ripper doesn’t readily detect the hash type of Linux (crypt), where the --wordlist flag is optional. If you omit the --format flag below, John won’t crack anything at all:

Once John has uncovered the passwords, you may view them using the command below:

john --show --format=crypt lin.txt

John has uncovered the passwords

Try this exercise

  1. Create a new user on Kali Linux: sudo useradd user1
  2. Give the new user a weak password: sudo passwd user1
  3. Repeat steps 1 and 2 as desired to create two more new user accounts user2 and user3 with weak passwords.
  4. Unshadow the Linux password hashes for all users: unshadow /etc/passwd /etc/shadow > lin.txt
  5. Export only the usernames and passwords of the three new users to a new file (lin3.txt): tail -n -3 lin.txt > lin3.txt
  6. Run it through John the Ripper: john --format=crypt --wordlist=rockyou lin3.txt
  7. Get results.
Try this exercise

Cracking Windows Passwords

Windows stores hashed passwords in the SAM database. SAM uses the LM/NTLM hash format for passwords. As getting passwords from the SAM database is beyond the scope of this article, we suggest generating your own LM/NTLM hashes to test out this functionality and echo them to a text file, say win.txt, as shown in the demonstration:

The syntax for cracking this file containing the LM/NTLM hashes is the following, where the --wordlist flag is optional:

john --format=LM [--wordlist=rockyou] win.txt

Once John has uncovered the passwords, you may view them using the command below:

john --show --format=LM win.txt

Cracking Windows Passwords

Try this exercise

  1. Designate a short string (topgun) as a username and variations on its capitalization as the password (such as Topgun).
  2. Pass the password from step 1 into an LM/NTLM hash function, such as via a website as shown below.
  3. Create a new text file (ntlm.txt) to store the username and the password hash value from prior steps: echo -n 'topgun::0BA224CF1C751F31AAD3B435B51404EE:D66B0428599B168372A76C8AB73A76A2:::' > ntlm.txt
  4. Run ntlm.txt through John the Ripper’s Single Crack Mode (change the --format argument as you see fit): john --format=LM --single ntlm.txt
  5. Get results. The capitalization of the cracked password may differ from what you’ve intended.

Step 2:

Step 2

Step 3 and 4:

Step 3 and 4

Choosing Specific Hashes to Crack

If you want to override John’s behavior of discovering the hash independently, you may tell John which hash type you’re looking for using the --format=HASH_TYPE flag. Choices for HASH_TYPE include Raw-MD (MD5), Raw-SHA1 (SHA-1), Raw-SHA256 (SHA-256), SSH, RADIUS, TACACS-Plus (TACACS+), ZIP, and RAR.

You can find all hash formats John supports using the following commands:

john --list=formats

john --list=subformats

Other Useful Commands

Here is a brief cheat sheet of John the Ripper commands:

Flag Description
--show FILE Show cracked passwords based on hashes from FILE
--rules, -ru Enable word-mangling rules to teach John the Ripper how to generate passwords
--status Print the status of an interrupted or running session
--session=NAME Give a new John the Ripper session a NAME, to which John will form the session file name NAME.rec; useful for running multiple instances of John in parallel or to be able to recover later a session other than the last one you interrupt
--restore[=NAME] Continue an interrupted cracking session, reading state information from the specified session file or the default session at the file path $JOHN/john.rec
--save-memory=LEVEL Enable memory saving at LEVEL 1, 2, or 3.
Level 1 tells John not to waste memory on login names, and may speed things up.
Levels 2 and 3 reduce John’s use of performance optimizations involving large lookup tables and thus may impact performance negatively.
--test[=TIME] Run tests (and benchmarks, unless TIME is explicitly 0), each spanning TIME seconds
& This symbol only applies to Kali Linux and other Unix-based operating systems.
When you put this symbol at the end of a John the Ripper command, you run it in the background.
--format=NAME Specify the hash type for John the Ripper to detect
--list=formats, --list=subformats Reveal the hash types John the Ripper supports
--single, -si Enable Single Crack Mode
--wordlist=FILE, -w=FILE Enable Wordlist Mode, specifying a Wordlist (dictionary attack)
--incremental, -inc Enable Incremental Mode

Find the complete official documentation for John the Ripper here.

Conclusion

We hope learning how to use John the Ripper helps you, whether you’re exploring cyber security or aiming to become a professional hacker or penetration tester. For more resources, read our blog posts on hacking, join the StationX Master’s Program, and check out our courses below:

Frequently Asked Questions



What can I crack with John the Ripper?

You can crack popular hash formats such as MD5, SHA-1, several DES variants, and Blowfish. Get the full list using the command john --list=formats on the Linux terminal.



How long should John the Ripper take?

Single Crack Mode usually runs for under a second to about a day, depending on the hash type and password length. The more complex your passwords are, the longer it takes; it may take years to crack certain passwords. You may find a detailed answer to this question in the FAQ on John the Ripper’s official documentation.



How does John the Ripper guess passwords?

John the Ripper uses a rainbow table approach: it hashes the guessed password and compares it to the list of password hashes you feed into it. If the hashes match, John remembers the plaintext password associated with it and can return that to the attacker.



Where can I find John cracked passwords?

Use the --show flag and an additional --format flag denoting the hash type if necessary. Example: john --show --format=raw-sha256 crack.txt



Does John the Ripper cost money?

No. It comes free with Kali Linux or as a standalone downloadable utility.



What are the alternatives to John the Ripper?

Another well-known password cracker is Hashcat.



When should I use John the Ripper vs. Hashcat?

Hashcat can do complex cracking using a GPU, but you must adjust its settings to identify the hash yourself. It also requires OpenCL to work. On the other hand, John the Ripper optimizes CPU usage. It seeks quick wins, detects your hash type, and excels in simpler jobs. Experientially it’s also a better choice for cracking SSH keys.


  • Cassandra Lee is a Certified in Cybersecurity (CC) professional, freelance programmer, and former robotics operator. With a background in data science, web development, and journalism, she’s contributed to outlets like HuffPost and Ada Lovelace Day, and advocates passionately for women in STEM through writing, speaking, and mentorship. You can find Cassandra on LinkedIn and Linktree.

Загрузить PDF

Загрузить PDF

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

  1. Step 1 Ознакомьтесь с рисками.

    Необходимо скачать программу, которая подберет пароль к ZIP-файлу. Имейте в виду, что программа может содержать вредоносный код. Поэтому узнайте, как безопасно пользоваться интернетом, и установите антивирус.

    • С помощью большинства бесплатных пробных версий можно подобрать только короткие пароли. Если программа, которая не упоминается в этой статье, предлагает взломать любой пароль, не скачивайте ее, потому что она содержит вредоносный код.
  2. Step 2 Имейте в виду, что описанный здесь процесс займет много времени.

    На подбор простейшего пароля у большинства программ уходит несколько часов; поэтому рассчитывайте, что на взлом пароля уйдет несколько дней.

    • Невозможно подобрать пароль за несколько минут — любая программа, которая утверждает, что способна на это, является вредоносной.[1]
  3. Step 3 Закройте фоновые программы.

    Чтобы взломать пароль, потребуется как можно больше ресурсов компьютера, поэтому закройте мощные программы, такие как Photoshop, видеоигры, аудио- и видеоплееры и так далее.

    • Даже при максимальной производительности компьютера на подбор пароля к ZIP-файлу может уйти несколько дней.
  4. Step 4 Перетащите ZIP-файл на рабочий стол.

    Сделайте это, потому что рабочий стол — это наиболее доступное местоположение на компьютере.

    • Также архив можно скопировать и вставить на рабочий стол: для этого щелкните по ZIP-файлу, нажмите Ctrl+C (Windows) или Command+C (Mac), перейдите на рабочий стол, а затем нажмите Ctrl+V или Command+V.
    • Если ZIP-файл находится на мобильном устройстве (смартфоне или планшете), скопируйте архив на компьютер.

    Реклама

  1. Step 1 Уясните, как работает этот метод.

    John the Ripper — это бесплатная программа с командной строкой, которая используется для взлома паролей. К сожалению, эту программу сложно установить и использовать.

  2. Step 2 Скачайте John the Ripper.

    Перейдите на страницу http://www.openwall.com/john/ в веб-браузере компьютера, а затем нажмите «John the Ripper 1.8.0-jumbo-1 (Windows binaries, ZIP, 34 MB)» в разделе «community enhanced version» (расширенная версия сообщества) в нижней части страницы.

  3. Step 3 Извлеките программу.

    Дважды щелкните по скачанному ZIP-файлу, перейдите на вкладку «Извлечь», нажмите «Извлечь все», а затем щелкните по «Извлечь»; откроется окно.

  4. Step 4 Установите John the Ripper.

    John the Ripper нельзя установить как обычную программу — скопируйте папку с программой на рабочий стол, а затем переименуйте ее в «john»:

    • в открывшемся окне щелкните по папке «john180j1w»;
    • нажмите Ctrl+C;
    • перейдите на рабочий стол и нажмите Ctrl+V;
    • щелкните правой кнопкой мыши по папке и нажмите «Переименовать»;
    • введите john и нажмите Enter.
  5. Step 5 Скопируйте свой ZIP-файл в папку «run», которая находится в папке «john».

    Для этого щелкните по ZIP-файлу, нажмите Ctrl+C, откройте папку «john», откройте папку «run», щелкните по пустому пространству и нажмите Ctrl+V.

  6. Step 6 Откройте командную строку.

  7. Step 7 Измените каталог на папку «run».

    Введите cd desktop/john/run и нажмите Enter.

  8. Step 8 Введите команду «run».

    Введите zip2john.exe имя.zip > имя.hash (вместо «имя» подставьте имя своего ZIP-файла), а затем нажмите Enter.

    • Например, если архив называется «hello.zip», введите zip2john.exe hello.zip > hello.hash.
  9. Step 9 Определите хеш ZIP-файла.

    Введите имя.hash (где «имя» — это имя вашего ZIP-файла) и нажмите Enter. Теперь можно приступить к подбору пароля.

  10. Step 10 Запустите процесс взлома пароля.

    Введите john.exe --pot=имя.pot --wordlist=john/run/password.lst имя.hash и нажмите Enter. John the Ripper начнет подбирать пароль к вашему ZIP-файлу по своей базе данных паролей.[2]

    • Вместо «имя» подставьте имя своего ZIP-файла.
    • Файл «password.lst» содержит список паролей и их вариации.
  11. Step 11 Отобразите найденный пароль.

    Когда пароль будет найден, в нижней части командной строки появится сообщение «Session complete» (Процесс завершен). Введите type имя.pot (вместо «имя» подставьте имя своего архива) и нажмите Enter. Пароль к ZIP-файлу отобразится на экране.

    Реклама

  1. Step 1 Ознакомьтесь с принципом работы этого метода.

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

    • Как правило, платными программами удобно пользоваться.
  2. Step 2 Уясните, какую программу купить.

    У хорошей программы должна быть бесплатная пробная версия и функция полного перебора.

  3. Step 3 Скачайте и установите...

  4. Step 4 Запустите установленную программу.

    Для этого щелкните или дважды щелкните по ее значку.

  5. Step 5 Выберите свой ZIP-файл.

    Для этого в программе нажмите «Browse» (Обзор), «Open» (Открыть), «Add» (Добавить) или аналогичную кнопку, а затем нажмите «Открыть» или «Выбрать».

    • Иногда архив можно просто перетащить в окно программы.
  6. Step 6 Выберите вариант подбора пароля.

    В большинстве случаев можно выбрать опцию «Brute force» (Полный перебор); также можно воспользоваться опцией «Dictionary» (Перебор по словарю), чтобы подобрать пароль по словарю.

    • Метод «Перебор по словарю» используйте тогда, когда вы знаете часть пароля или весь пароль (но не заглавные буквы и символы).
  7. Step 7 Запустите процесс взлома пароля.

    В программе нажмите «Start» (Запустить) или «Run» (Выполнить), а затем подождите, пока процесс завершится (он может занять несколько дней).

  8. Step 8 Просмотрите найденный пароль.

    Он отобразится в окне программы. Теперь с помощью этого пароля можно открыть ZIP-файл.

    Реклама

Советы

  • Существует несколько различных подходов, которые может использовать программа для взлома паролей. Чтобы получить наилучшие результаты, испробуйте каждый из них.
    • Перебор по словарю: пароль подбирается по словарю. Этот метод работает быстро, но не всегда находит пароль, потому что не все пароли являются словами из словаря.
    • Полный перебор: перебираются все возможные комбинации. Этот метод может взломать короткие пароли, а также длинные, если запустить его на очень мощном компьютере.
    • Полный перебор с маской: если вы что-нибудь помните о пароле, можно настроить «маску», прежде чем программа приступит к полному перебору. Например, программа может перебрать возможные комбинации букв без цифр.
  • Возможно, вам придется оставить компьютер включенным на несколько дней, чтобы не прерывать процесс взлома пароля.

Реклама

Предупреждения

  • Копирование или скачивание лицензионного программного обеспечения без его оплаты или без согласия владельца в большинстве стран является незаконным.
  • Программы для взлома паролей можно использовать легально, но только для доступа к своим файлам.
  • Полный перебор может занять много времени, которое зависит от быстродействия компьютера; более того, из-за перегрузки процессора может произойти сбой (если процесс подбора пароля продолжается слишком долго).

Реклама

Об этой статье

Эту страницу просматривали 55 651 раз.

Была ли эта статья полезной?

John the Ripper is free and Open Source software,
distributed primarily in source code form.
If you would rather use a commercial product tailored for your specific
operating system, please consider
John the Ripper Pro,
which is distributed primarily in the form of «native» packages
for the target operating systems and in general is meant to be easier to
install and use while delivering optimal performance.

Proceed to John the Ripper Pro homepage for your OS:

  • John the Ripper Pro for Linux
  • John the Ripper Pro for Mac OS X
  • On Windows, consider Hash Suite

    (developed by a contributor to John the Ripper)

  • On Android, consider Hash Suite Droid

Download one of the latest official free versions
(release notes):

  • John the Ripper 1.8.0 (sources, tar.xz, 4.3 MB) and
    its signature
  • John the Ripper 1.8.x extra charset files archive (tar.xz, 4.5 MB) and
    its signature
  • John the Ripper 1.8.0 (sources, tar.gz, 5.2 MB) and
    its signature
  • John the Ripper 1.7.9 (Windows binaries, ZIP, 2029 KB)

    and its signature

Download the latest community-enhanced version
(release notes,
patch to build 1.8.0-jumbo-1 on non-x86):

  • Latest development source code in GitHub repository
    (tar.gz,
    ZIP)
  • John the Ripper 1.8.0-jumbo-1 (sources, tar.xz, 23 MB) and
    its signature
  • John the Ripper 1.8.0-jumbo-1 (sources, tar.gz, 30 MB) and
    its signature
  • John the Ripper 1.8.0-jumbo-1 (Windows binaries, ZIP, 34 MB)

    and its signature

Get John the Ripper apparel at 0-Day Clothing and support the project


This version integrates lots of contributed patches adding
GPU support (OpenCL and CUDA),
support for a hundred of additional hash and cipher types
(including popular ones such as NTLM, raw MD5, etc., and even things such as
encrypted OpenSSH private keys, ZIP and RAR archives, PDF files, etc.),
as well as some optimizations and features.
Unfortunately, its overall quality is lower than the official version’s.
Requires OpenSSL.
There are
unofficial binary builds
(by John the Ripper user community members) for
Windows,
Linux,
Solaris, and
Mac OS X.

To verify authenticity and integrity of your John the Ripper downloads, please
use our
PGP public key.

You will most likely need to download a «Windows binaries» archive above.
However, if you choose to download the source code instead
(for a specific good reason), then please refer to these pages on
how to extract John the Ripper source code from the tar.gz and tar.xz archives and
how to build (compile) it.

You may also consider the
unofficial builds
on the contributed resources list further down this page.

These and older versions of John the Ripper,
patches, unofficial builds, and many other related files
are also

available from the Openwall file archive.

You may browse the documentation for John the Ripper online,
including a
summary of changes between versions.
Also relevant is our

presentation on the history of password security.

There’s a
wiki section with John the Ripper user community resources.
The more experienced users and software developers may

browse the source code for John the Ripper online,
along with revision history information for each source file.

There’s a
collection of wordlists
for use with John the Ripper.
It includes lists of common passwords,
wordlists for 20+ human languages,
and files with the common passwords and
unique words for all the languages combined,
also with mangling rules applied and any duplicates purged.

Additionally, you may download an ISO image of
Openwall GNU/*/Linux,
which includes a pre-built copy of John the Ripper 1.8.0 ready for use
without requiring another OS and without having to install on a hard disk
(although that is supported).

An implementation of one of the modern password hashes found in
John is also available separately
for use in your software or on your servers.

There’s a
proactive password strength checking module
for PAM-aware password changing programs, which can be used to prevent
your users from choosing passwords that would be easily cracked with
programs like John.

We may help you integrate modern password hashing with
crypt_blowfish
and/or proactive password strength checking with
passwdqc
into your OS installs, please check out our services.

There’s a mailing list where you can share your experience with John the Ripper
and ask questions.

Please be sure to specify an informative message subject whenever
you post to the list
(that is, something better than «question» or «problem»).
To subscribe, enter your e-mail address below or send an empty message to
<john-users-subscribe at lists.openwall.com>.
You will be required to confirm your subscription by «replying»
to the automated confirmation request that will be sent to you.
You will be able to
unsubscribe
at any time and we will not use your e-mail
address for any other purpose or share it with a third party.
However, if you post to the list, other subscribers and those
viewing the archives may see your address(es) as specified on your message.

The list archive is available
locally and via
MARC.
Additionally, there’s a

list of selected most useful and currently relevant postings on the
community wiki.

A separate mailing list exists for John the Ripper development discussions
(that is, if you want to discuss and contribute to the source code).
Its archive is available
locally.

To subscribe, enter your e-mail address below or send an empty message to
<john-dev-subscribe at lists.openwall.com>.

Contributed resources for John the Ripper:

  • There are
    custom builds,
    benchmarks,
    and other information available on the
    community wiki
  • custom builds for Windows (up to 1.8.0.13-jumbo)
  • custom builds for Mac OS X / macOS (up to 1.8.0.9-jumbo)
  • custom builds for Solaris (packages up to 1.7.6, non-packaged up to 1.7.8-jumbo-7)
  • custom builds for Android (up to 1.8.0)
  • Ubuntu snap package
    (documentation,
    announcement)
  • OpenVMS and SYSUAF.DAT support
    (signature)
    by Jean-loup Gailly

    OpenVMS executables for Alpha and VAX
    (signature)

  • Local copies of
    the above files by Jean-loup Gailly and
    a much newer implementation by David Jones

Local copies of these and many other related packages are also

available from the Openwall file archive.

John the Ripper is part of
Owl,
Debian GNU/Linux, Fedora Linux, Gentoo Linux, Mandriva Linux, SUSE Linux,
and a number of other Linux distributions.
It is in the ports/packages collections of FreeBSD, NetBSD, and OpenBSD.

John the Ripper is a registered project with
Open Hub
and it is listed at
SecTools.

https://www.openwall.com/john/

/run/john .\zip.hash 

Incremental Mode

read https://www.openwall.com/john/doc/MODES.shtml

This is the most powerful cracking mode, it can try all possible character combinations as passwords. However, it is assumed that cracking with this mode will never terminate because of the number of combinations being too large (actually, it will terminate if you set a low password length limit or make it use a small charset), and you’ll have to interrupt it earlier.

That’s one reason why this mode deals with trigraph frequencies, separately for each character position and for each password length, to crack as many passwords as possible within a limited time.

To use the mode you need a specific definition for the mode’s parameters, including password length limits and the charset to use. These parameters are defined in the configuration file sections called [Incremental:MODE], where MODE is any name that you assign to the mode (it’s the name that you will need to specify on John’s command line). You can either use a pre-defined incremental mode definition or define a custom one.

As of version 1.8.0, pre-defined incremental modes are «ASCII» (all 95 printable ASCII characters), «LM_ASCII» (for use on LM hashes), «Alnum» (all 62 alphanumeric characters), «Alpha» (all 52 letters), «LowerNum» (lowercase letters plus digits, for 36 total), «UpperNum» (uppercase letters plus digits, for 36 total), «LowerSpace» (lowercase letters plus space, for 27 total), «Lower» (lowercase letters), «Upper» (uppercase letters), and «Digits» (digits only). The supplied .chr files include data for lengths up to 13 for all of these modes except for «LM_ASCII» (where password portions input to the LM hash halves are assumed to be truncated at length 7) and «Digits» (where the supplied .chr file and pre-defined incremental mode work for lengths up to 20). Some of the many .chr files needed by these pre-defined incremental modes might not be bundled with every version of John the Ripper, being available as a separate download.

/run/john --incremental=Alnum .\zip.hash 

Using masks

/run/john --mask=?d?d?d?d?d?d?d?d-?d?d?d?d[a-zA-Z] .\zip.hash 

read https://github.com/magnumripper/JohnTheRipper/blob/bleeding-jumbo/doc/MASK

Checking for GPU support

https://openwall.info/wiki/john/GPU

Cracking ZIP and RAR protected files

read https://dfir.science/2014/07/how-to-cracking-zip-and-rar-protected.html

How-to — Cracking ZIP and RAR protected files with John the Ripper

After seeing how to compile John the Ripper to use all your computer’s processors now we can use it for some tasks that may be useful to digital forensic investigators: getting around passwords. Today we will focus on cracking passwords for ZIP and RAR archive files. Luckily, the JtR community has done most of the hard work for us. For this to work you need to have built the community version of John the Ripper since it has extra utilities for ZIP and RAR files.

For this exercise I have created password protected RAR and ZIP files, that each contain two files.

test.rar: RAR archive data, v1d, os: Unix
test.zip: Zip archive data, at least v1.0 to extract 

The password for the rar file is ‘test1234’ and the password for the zip file is ‘test4321’.

In the ‘run’ folder of John the Ripper community version (I am using John-1.7.9-jumbo-7), there are two programs called ‘zip2john’ and ‘rar2john’. Run them against their respective file types to extract the password hashes:

./zip2john ../test.zip > ../zip.hashes
./rar2john ../test.rar > ../rar.hashes

This will give you files that contain the password hashes to be cracked… something like this:

../test.zip:$pkzip$2*2*1*0*0*1b*a80c*95e4e9547dcfcde4b8b2f05a80aaeb9d15dd76e7526b81803c8bf7*2*0*1b*f*72051312*0*44*0*1b*a808*cbafdd390bf49ea54064ab3ff9f486e6260b9854e37d1ee3a41c54*$/pkzip$

After, that you can run John the Ripper directly on the password hash files:

./john ../zip.hashes

You should get a message like: Loaded 1 password hash (PKZIP [32/64]). By using John with no options it will use its default order of cracking modes. See the examples page for more information on modes.

Notice, in this case we are not using explicit dictionaries. You could potentially speed the cracking process up if you have an idea what the password may be. If you look at your processor usage, if only one is maxed out, then you did not enable OpenMP when building. If you have a multi-processor system, it will greatly speed up the cracking process.

Now sit back and wait for the cracking to finish. On a 64bit quad-core i7 system, without using GPU, and while doing some other CPU-intensive tasks, the password was cracked in 6.5 hours.

Loaded 1 password hash (PKZIP [32/64])
guesses: 0  time: 0:00:40:29 0.00% (3)  c/s: 2278K  trying: eDTvw - ekTsl
guesses: 0  time: 0:01:25:10 0.00% (3)  c/s: 1248K  trying: ctshm#ni - ctshfon9
guesses: 0  time: 0:02:56:40 0.00% (3)  c/s: 1499K  trying: BR489a - BR48jf
guesses: 0  time: 0:03:56:04 0.00% (3)  c/s: 1703K  trying: fjmis5od - fjmidia0
guesses: 0  time: 0:04:46:09 0.00% (3)  c/s: 1748K  trying: Difg1ek - DifgbpS
guesses: 0  time: 0:05:21:22 0.00% (3)  c/s: 1855K  trying: btkululp - btkulene
guesses: 0  time: 0:06:02:43 0.00% (3)  c/s: 1857K  trying: ghmnymik - ghmnyasd
test4321         (../test.zip)
guesses: 1  time: 0:06:32:34 DONE (Mon Jul 28 17:50:22 2014)  c/s: 1895K  trying: telkuwhy – test43ac

Now if you want to see the cracked passwords give john the following arguments:

./john ../zip.hashes --show

It should output something like:

../test.zip:test4321 
1 password hash cracked, 0 left 

Note: the hash file should have the same type of hashes. For example, we cannot put the rar AND zip hashes in the same file. But this means you could try to crack more than one zip/rar file at a time.

For the rar file it did not take nearly as long since the password was relatively common. If you take a look at john.conf in the run directory, it has a list of the patterns it checks (in order). The pattern 12345 is much more likely than 54321, so it is checked first resulting in a quick crack.

Loaded 1 password hash (RAR3 SHA-1 AES [32/64]) 
guesses: 0  time: 0:00:00:10 1.38% (1) (ETA: Mon Jul 28 18:23:58 2014)  c/s: 24.86  trying: rar.tsett - ttests 
guesses: 0  time: 0:00:02:12 13.40% (1) (ETA: Mon Jul 28 18:28:19 2014)  c/s: 25.98  trying: Test29 - Test2rar9 
test1234         (test.rar) 
guesses: 1  time: 0:00:17:03 DONE (Mon Jul 28 18:28:56 2014)  c/s: 24.01  trying: test1234 - testrar1234 
Use the "--show" option to display all of the cracked passwords reliably 

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Где находятся файлы карантина защитника windows 10
  • Windows sxs что это
  • Ftp сервер для windows 2016
  • Как запускать приложения windows на mac os
  • Windows features как открыть windows 10 cmd