/
bot.py
269 lines (245 loc) · 10.4 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import InlineKeyboardButton, InlineKeyboardMarkup
import time
import subprocess
from pprint import pprint
import pathlib
from hashcat import Hashcat
import os
TYPE_DICTIONARY = 0
TYPE_HASHFILES = 1
TYPE_OPTIONS = 2
class Chat:
def __init__(self, chat_id, bot, hashcat):
self.bot = bot
self.chat_id = chat_id
self.exec_command = ''
self.hashcat = hashcat
self.directory = ['wordlists/', 'documents/' + str(chat_id) + '/']
self.potfile = 'potfile.pot'
self.chooser = Chooser(chat_id, bot, self, self.potfile)
for path in self.directory:
os.makedirs(path, exist_ok=True)
self.options = ['', '', '']
def on_message_received(self, msg):
content_type, chat_type, chat_id = telepot.glance(msg)
if content_type == 'text':
print('on_message_received: ', msg['text'])
if 'entities' in msg:
for entity in msg['entities']:
if entity['type'] == 'bot_command':
self.on_command_received(msg['text'][entity['offset']:])
elif self.chooser.is_choosing():
self.chooser.update_chooser(msg, is_callback=False)
elif content_type == 'document':
file_id = msg['document']['file_id']
file_name = msg['document']['file_name']
print('file_id =', file_id, 'fil_name =', file_name)
if file_name.split('.')[-1] == 'txt':
self.bot.download_file(file_id, self.directory[TYPE_DICTIONARY] + file_name)
self.chooser.choose(file_name, TYPE_DICTIONARY, append_directory=True)
else:
self.bot.download_file(file_id, self.directory[TYPE_HASHFILES] + file_name)
self.chooser.choose(file_name, TYPE_HASHFILES, append_directory=True)
def on_callback_received(self, msg):
command = msg['data'].split()[0]
if self.chooser.is_choosing():
self.chooser.update_chooser(msg)
elif command == 'exec':
self.on_command_received('/cmd ' + self.exec_command)
elif command == '/status':
self.on_command_received(msg['data'])
elif command == 'cleanpotfile':
#os.system('rm ' + self.directory[TYPE_HASHFILES] + self.potfile)
open(self.directory[TYPE_HASHFILES] + self.potfile, 'w').close()
self.bot.sendMessage(self.chat_id, 'Potfile has been deleted')
def on_command_received(self, command):
command = command.split(' ', 1)
comm = command[0]
if command[0] == '/start':
self.bot.sendMessage(self.chat_id, 'Hello there, I\'m hashcat bot v0.2. Send /begin command or "/cmd hashcat [options]".' + \
'All uploaded .txt files are in ' + self.directory[TYPE_DICTIONARY] + ' and other files are in ' + \
self.directory[TYPE_HASHFILES])
elif command[0] == '/begin':
self.options = ['', '', '']
self.chooser.send_chooser(TYPE_HASHFILES, self.directory[TYPE_HASHFILES])
elif command[0] == '/status':
if len(command) > 1:
self.hashcat.send_keystroke(command[1])
time.sleep(0.1)
hashcat_status = self.hashcat.get_status(self.chat_id)
if hashcat_status == Hashcat.STATUS_RUNNING:
screnshot = 'terminal.png'
if self.hashcat.save_screenshot(screnshot):
buttons = ['s', 'p', 'r', 'b', 'c', 'q']
keyboard = [[InlineKeyboardButton(text=button, callback_data='/status ' + button) for button in buttons]]
self.bot.sendPhoto(self.chat_id, photo=open(screnshot, 'rb'),
reply_markup=InlineKeyboardMarkup(inline_keyboard=keyboard))
else:
self.bot.sendMessage(self.chat_id, 'No terminal output yet')
elif hashcat_status == Hashcat.STATUS_STOPPED:
self.bot.sendMessage(self.chat_id, 'Hashcat is not running. Send /status or /potfile comands')
elif hashcat_status == Hashcat.STATUS_DIFFERENT_USER:
(first, count) = self.hashcat.get_queue_position(self.chat_id)
if count != 0:
self.bot.sendMessage(self.chat_id, 'There are ' + str(count) + ' queries before you')
else:
self.bot.sendMessage(self.chat_id, 'You dont have any queries')
elif command[0] == '/potfile':
text = ''
try:
file = open(self.directory[TYPE_HASHFILES] + self.potfile, 'r')
text = file.read()
except:
open(self.directory[TYPE_HASHFILES] + self.potfile, 'w')
text = subprocess.check_output('cat ' + self.directory[TYPE_HASHFILES] + self.potfile, shell=True).decode('utf-8')
#lines = text.splitlines()
#passwords = [' '.join(x.split(':')[3:5]) for x in lines]
#text = '\n'.join(passwords)
if len(text) < 3:
self.bot.sendMessage(self.chat_id, 'Potfile is empty')
else:
self.bot.sendMessage(self.chat_id, text, reply_markup=InlineKeyboardMarkup(inline_keyboard=
[[InlineKeyboardButton(text='clean', callback_data='cleanpotfile')]]
))
elif command[0] == '/cmd' and len(command) > 1:
print('executing: ' + command[1])
self.hashcat.add_to_queue(command[1], self.chat_id)
self.bot.sendMessage(self.chat_id, 'Wait a couple of seconds and then send /status or /potfile commands')
else:
self.bot.sendMessage(self.chat_id, 'unrecognized command')
def on_choosen(self, data, type):
print('on_choosen:', data, 'type:', type)
self.options[type] = data
for mType in range(3):
if self.options[mType] == '':
if mType == TYPE_OPTIONS:
self.chooser.send_chooser(mType, None)
else:
self.chooser.send_chooser(mType, self.directory[mType])
return
self.exec_command = 'hashcat ' + self.options[TYPE_OPTIONS] + ' --potfile-path="'
self.exec_command += self.directory[TYPE_HASHFILES] + self.potfile + '" "'
self.exec_command += self.options[TYPE_HASHFILES] + '" "' + self.options[TYPE_DICTIONARY] + '"'
self.bot.sendMessage(self.chat_id, '<code>' + self.exec_command + '</code>', parse_mode='HTML',
reply_markup=InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text='Execute', callback_data='exec')]]))
class Chooser:
def __init__(self, chat_id, bot, chat, potfile):
self.chat_id = chat_id
self.bot = bot
self.chat = chat
self.set(TYPE_HASHFILES, None)
self.choosing = False
self.directory = None
self.potfile = potfile
def set(self, type, directory):
print('set chooser type as:', type)
self.directory = directory
self.type = type
self.choosing = True
if type == TYPE_HASHFILES:
self.text_primary = 'Choose available hashfiles or upload your own (up to 20MB)'
self.text_secondary = 'Upload hashfile (up to 20MB)'
self.text_choosen = 'Choosen hashfile: '
elif type == TYPE_DICTIONARY:
self.text_primary = 'Write password mask, choose dictionary or upload dictionary (up to 20MB)'
self.text_secondary = 'Write password mask or upload dictionary (up to 20MB)'
self.text_choosen = 'Choosen dictionary/mask: '
def send_chooser(self, type, directory):
print('send_chooser type: ' + str(type))
self.set(type, directory)
if type == TYPE_OPTIONS:
self.bot.sendMessage(self.chat_id, 'Set options (ex: <code>--force -m 2500</code>)', parse_mode='HTML')
elif not self.isEmpty(self.directory):
file_list = self.show_files(self.directory)
self.bot.sendMessage(self.chat_id, self.text_primary + file_list, parse_mode='HTML',
reply_markup=InlineKeyboardMarkup(inline_keyboard=[[
InlineKeyboardButton(text='Choose', callback_data='Chooser')
]]))
else:
self.bot.sendMessage(self.chat_id, self.text_secondary)
def update_chooser(self, msg, is_callback=True):
if is_callback:
if msg['data'] == 'Chooser':
file_list = subprocess.check_output('ls ' + self.directory + ' -I ' + self.potfile, shell=True).decode('utf-8').splitlines()
print('file_list:', file_list)
keyboard = [[InlineKeyboardButton(text=file, callback_data=file)] for file in file_list]
self.bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']),
text=self.text_primary, reply_markup=InlineKeyboardMarkup(inline_keyboard=keyboard))
else:
self.choose(msg['data'], self.type, append_directory=True)
else:
self.choose(msg['text'], self.type, quiet=True)
def choose(self, data, type, quiet=False, append_directory=False):
self.set(type, self.directory)
self.choosing = False
if append_directory:
data = self.directory + data
if not quiet:
self.bot.sendMessage(self.chat_id, self.text_choosen + '<code>' + data + '</code>', parse_mode='HTML')
self.chat.on_choosen(data, self.type)
def is_choosing(self):
return self.choosing
def isEmpty(self, directory):
txt = subprocess.check_output('ls ' + directory + ' -I ' + self.potfile, shell=True)
print('Chooser.isEmpty: ', txt)
if len(txt) < 3:
return True
return False
def show_files(self, directory):
file_names = subprocess.check_output('ls ' + directory + ' -I ' + self.potfile, shell=True).decode('utf-8').splitlines()
file_sizes = subprocess.check_output('ls -lah ' + directory + ' -I ' + self.potfile +
' | grep ^- | awk \'{print $5}\'\n', shell=True).decode('utf-8').splitlines()
print('file_names:', file_names)
print('file_sizes:', file_sizes)
file_list = ''
for i in range(len(file_names)):
file_list += '{:5s} {}\n'.format(file_sizes[i], file_names[i])
print('dir =',directory,'len(file_list):', len(file_list))
if len(file_list) < 3:
return None
return '\n<pre>' + file_list + '</pre>'
class HashBot:
def __init__(self, token):
self.chats = {}
self.bot = telepot.Bot(token)
self.hashcat = Hashcat()
print('Hashbot.__init__(): hashcat.update()')
self.admins_file = 'admins.txt'
self.admins = []
try:
file = open(self.admins_file, 'r')
print('opened admins_file')
lines = file.readlines()
self.admins = [int(line.strip()) for line in lines]
file.close()
except:
open(self.admins_file, 'w')
def handle_message(self, msg):
content_type, chat_type, chat_id = telepot.glance(msg)
if chat_id not in self.chats:
self.chats[chat_id] = Chat(chat_id, self.bot, self.hashcat)
if chat_id in self.admins:
self.chats[chat_id].on_message_received(msg)
else:
self.deny_permission(chat_id)
def handle_callback(self, msg):
content_type, chat_type, chat_id = telepot.glance(msg['message'])
if chat_id not in self.chats:
self.chats[chat_id] = Chat(chat_id, self.bot, self.hashcat)
if chat_id in self.admins:
self.chats[chat_id].on_callback_received(msg)
else:
self.deny_permission(chat_id)
def deny_permission(self, chat_id):
print('admins:', self.admins)
self.bot.sendMessage(chat_id, "You are not authorized to use this bot. Your chat id is: <code>" + \
str(chat_id) + "</code> add it to <code>$bot$/admins.txt</code>", parse_mode='HTML')
def start(self):
MessageLoop(self.bot, {'chat': self.handle_message, 'callback_query': self.handle_callback}).run_as_thread()
while 1:
self.hashcat.update()
time.sleep(0.1)
mybot = HashBot('615164406:AAFFc86M5WE6NJvlMA6oC-99GpORq5Q08C4')
mybot.start()