Ejemplo n.º 1
0
    def rmtsh(self, tmp_sock, slist, server_sock):
        prompt = "rmtsh (EXIT to quit) "
        cwd = ""  # used to keep track of current working dir
        # attempt to get the pwd/cwd so we can use in in our commands
        Comms.sendMsg(tmp_sock, "EXEC pwd")
        Comms.sendMsg(tmp_sock, "GETBUFFER")

        while (1):
            displayPrompt = False
            ready_to_read, ready_to_write, in_error = select.select(
                slist, [], [], 0)

            for sock in ready_to_read:
                displayPrompt = False
                if (sock == sys.stdin):  # server sending message
                    msg = sys.stdin.readline()
                    msg = msg.lstrip(
                        '\r\n '
                    )  # clean up line removing any starting spaces and CRLF
                    if 'EXIT' in msg:  # did we enter EXIT?
                        return
                    else:  #must have entered some other command
                        msg = msg.rstrip('\r\n')
                        if len(msg
                               ) > 0:  # is this a blank line?   just a return?
                            if (cwd):  # do we have a stored cwd?
                                msg = "cd " + cwd + " ; " + msg  # if so, change command to prepend a   "cd <cwd> ; "
                            Comms.sendMsg(
                                tmp_sock, "EXEC " + msg + " ; pwd"
                            )  # append a "; pwd" to the command so we can find out the ending working directory
                            Comms.sendMsg(tmp_sock, "GETBUFFER")
                        else:
                            displayPrompt = True
                elif (sock != server_sock) and (sock != sys.stdin):
                    msg = Comms.readMsg(sock, 4096)
                    msg = msg.rstrip('\r\n')
                    indx = msg.rfind('\n')  # what is the ending line break?
                    if indx == -1:
                        indx = 0
                    cwd = msg[indx:].lstrip('\r\n').rstrip('\r\n')
                    msg = msg[:indx]
                    sys.stdout.write("\r\n")
                    sys.stdout.write(msg)
                    sys.stdout.write("\r\n")
                    displayPrompt = True
                else:
                    displayPrompt = False
            if (displayPrompt):
                sys.stdout.write(prompt + cwd + "> ")
                sys.stdout.flush()
Ejemplo n.º 2
0
    def server(self, host, port):
        slist = []  #array of client sockets
        nid = 0
        prompt = "# (stuck? type HELP)> "

        server_sock = Comms.create_server_socket(host, port)
        slist.append(server_sock)
        slist.append(sys.stdin)

        print("Server started on IPs : " + str(host))
        print("Server started on port: " + str(port))

        # add mesh listener if necessary
        if (self.meshListener):
            slist.append(self.meshListener)
            print("MeshNet Listener started on port: " + str(self.meshPort))

        sys.stdout.write(prompt)
        sys.stdout.flush()

        displayPrompt = False

        while (1):
            self.addNeighbor()
            displayPrompt = False
            # get the list sockets which are ready to be read through select
            # 4th arg, time_out  = 0 : poll and never block
            ready_to_read, ready_to_write, in_error = select.select(
                slist, [], [], 0)

            for sock in ready_to_read:
                displayPrompt = False
                if (self.meshListener) and (sock == self.meshListener):
                    sockfd, addr = sock.accept()
                    msg = Comms.readMsg(sockfd, 4096)

                    # construct msg hash
                    m = hashlib.sha256()
                    m.update(msg.encode('ISO-8859-1'))
                    hash_key = m.hexdigest()
                    timestamp = datetime.datetime.now()

                    good = True
                    if hash_key in self.hashMsgs:
                        stored_timestamp = datetime.datetime.strptime(
                            self.hashMsgs[hash_key], '%Y-%m-%d %H:%M:%S.%f')
                        if (timestamp >= (stored_timestamp +
                                          datetime.timedelta(minutes=10))):
                            good = False

                    # if we have not seen the message before then process it
                    if good:
                        self.hashMsgs[hash_key] = timestamp
                        (srcip, srcport, dstip, dstport,
                         data) = msg.split(':', 4)
                        if (dstip == self.ip) and (int(dstport)
                                                   == self.meshPort):
                            #process msg
                            sys.stdout.write(data)
                            sys.stdout.write("\r\n")
                            displayPrompt = True
                        else:
                            # the server does not forward messages
                            None
                elif (sock == server_sock
                      ):  # a new connection request received
                    nid = nid + 1
                    sockfd, addr = sock.accept()
                    slist.append(sockfd)
                    self.neighbors[self.nodeCount] = Node(
                        addr[0], addr[1], self.genUID(), 1, sockfd, "Direct")
                    self.nodeCount += 1
                    sys.stdout.write("\r" +
                                     "Client %i : (%s, %s) connected\n" %
                                     (nid, addr[0], addr[1]))
                    displayPrompt = True
                elif (sock == sys.stdin):  # server sending message
                    msg = sys.stdin.readline()
                    msg = msg.lstrip('\r\n')
                    msg = msg.rstrip('\r\n')

                    displayPrompt = self.server_process_cmds(
                        slist, [server_sock, self.meshListener], msg,
                        server_sock)

                elif (sock != server_sock) and (sock != sys.stdin):
                    msg = Comms.readMsg(sock, 4096)
                    sys.stdout.write("=====================")
                    sys.stdout.write("\r\n")
                    (ip, port) = sock.getpeername()
                    sys.stdout.write(ip + ":" + str(port))
                    sys.stdout.write("\r\n")
                    sys.stdout.write("---------------------")
                    sys.stdout.write("\r\n")
                    sys.stdout.write(msg)
                    sys.stdout.write("\r\n")
                    displayPrompt = True
                else:
                    sys.stdout.write("[UNKNOWN SOCKET]")
                    sys.stdout.write("\r\n")
                    displayPrompt = True

            if (displayPrompt):
                sys.stdout.write(prompt)
                sys.stdout.flush()
Ejemplo n.º 3
0
    def server_process_cmds(self, slist, ignore_list, msg, server_sock):
        displayPrompt = False

        if (msg.startswith("NODE:")):
            p = re.compile("NODE:(\d+)\s+(.*)")
            m = p.match(msg)
            if (m):
                if (self.neighbors[int(m.group(1))].location == "Direct"):
                    displayPrompt = self.server_process_cmds(
                        [self.neighbors[int(m.group(1))].socket], ignore_list,
                        m.group(2), server_sock)
                else:
                    sys.stdout.write(
                        "Can only use NODE on Direct connections" + '\r\n')
                    displayPrompt = True
            else:
                displayPrompt = True
        elif (msg.startswith("HELP") or msg.startswith("help")
              or msg.startswith("?") or msg.startswith("/?")):
            sys.stdout.write(getHelp())
            displayPrompt = True
        elif (msg.startswith("LIST")):
            sys.stdout.write("List of current client/slave nodes:\r\n")
            sys.stdout.write(
                "------------------------------------------------------\r\n")
            sys.stdout.write('{:5} {:21} {:13}'.format("<#>", "<IP>:<PORT>",
                                                       "<Direct/Mesh>"))
            sys.stdout.write("\r\n")
            for uid in self.neighbors:
                sys.stdout.write('{:5} {:21} {:13}'.format(
                    str(uid), self.neighbors[uid].ip + ":" +
                    str(self.neighbors[uid].port),
                    self.neighbors[uid].location))
                sys.stdout.write("\r\n")
            displayPrompt = True
        elif (msg.startswith("PUSH")):
            (tmp, filename) = msg.split(':', 1)
            for key in self.neighbors:
                if (self.neighbors[key].location == "Direct"):
                    if self.neighbors[key].socket in slist:
                        Comms.sendFile(self.neighbors[key].socket, filename)
            displayPrompt = True
        elif (msg.startswith("PULL")):
            p = re.compile("PULL:(.*)")
            m = p.match(msg)
            if (m):
                Comms.broadcast(slist, ignore_list, msg)
            displayPrompt = True
        elif (msg.startswith("SCAN")):
            Comms.broadcast(slist, ignore_list, msg)
            displayPrompt = True
        elif (msg.startswith("WGET")):
            Comms.broadcast(slist, ignore_list, msg)
            displayPrompt = True
        elif (msg.startswith("EXEC")):
            Comms.broadcast(slist, ignore_list, msg)
            displayPrompt = True
        elif (msg.startswith("SHELL")):
            p = re.compile("SHELL:(\d+)")
            m = p.match(msg)
            if (m):
                if (self.neighbors[int(m.group(1))].location == "Direct"):
                    self.rmtsh(self.neighbors[int(m.group(1))].socket, slist,
                               server_sock)
                else:
                    sys.stdout.write(
                        "Can only use SHELL on Direct connections" + '\r\n')
            displayPrompt = True
        elif (msg.startswith("CLEARBUFFER")):
            Comms.broadcast(slist, ignore_list, msg)
            displayPrompt = True
        elif (msg.startswith("GETBUFFER")):
            Comms.broadcast(slist, ignore_list, msg)
            displayPrompt = False
        elif (msg.startswith("EXIT")):
            Comms.broadcast(slist, ignore_list, msg)
            displayPrompt = True
        elif (msg.startswith("QUIT")):
            self.cleanup()
        elif (msg.startswith("PROCLIST")):
            Comms.broadcast(slist, ignore_list, msg)
            displayPrompt = True
        elif (msg.startswith("NEIGHBORS")):
            Comms.broadcast(slist, ignore_list, msg)
            displayPrompt = True
        elif (msg.startswith("MESH:")):
            p = re.compile("MESH:(\d+)\s+(.*)")
            m = p.match(msg)
            if (m):
                if (self.neighbors[int(m.group(1))].location == "Mesh"):
                    n = self.neighbors[int(m.group(1))]
                    self.forwardTraffic(self.ip, self.meshPort, n.ip, n.port,
                                        m.group(2))
            displayPrompt = True
        elif (msg.startswith("DIST")):
            #match DIST <command> <file>
            #\s+(.+) for command
            #(.*)for filename
            #p compiles the regex
            p = re.compile("DIST:(.*?) (.*)")
            #m matches DIST <something> <something>.
            m = p.match(msg)

            #m.group(1) is the command, m.group(2) is the filename

            #correct command matches? then lets go!
            if (m):
                # make a local list to use
                clist = dict()
                # only copy the Direct neighbors into the new list
                count = 0
                for key in self.neighbors:
                    if self.neighbors[key].location == "Direct":
                        print("testing if command exists : ")
                        Comms.sendMsg(self.neighbors[key].socket,
                                      "EXIST:" + m.group(2))
                        if Comms.readMsg(self.neighbors[key].socket) == "true":
                            clist[count] = self.neighbors[key]
                            print('clist ' + clist[count].ip)
                            count += 1

                #check for clients, sending commands is pointless if no clients
                if len(clist) < 1:
                    #is this the best way? probably not
                    print('no clients!')
                    #give the user back their prompt
                    displayPrompt = True

                #ok, we have clients...now what?
                else:
                    #first, split the input file into n parts, where n is count of nodes
                    #splitjobs.Split takes clist to count nodes, and the filename to split
                    #splitjobs.Split will then write files to ./tmp called 0.splitout 1.splitout ,etc
                    s = Split(clist, m.group(1))
                    files = s.getFiles()

                    print(files)

                    #command logic check--todo
                    #if m.group(2) is nmap, then xx, if its hashcat, then... etc
                    #for now assume any command we want to distribute accepts a text file

                    #for each client in clist
                    for i in range(0, len(clist)):
                        filename = files.pop()
                        for key in self.neighbors:
                            if self.neighbors[key].uid == clist[i].uid:
                                #send this file to a node. file 0.splitout would go to node 0
                                #PUSH code goes here to transfer 0.splitout to node 1 (0th node), etc

                                #issue PUSH as a server command
                                print("running NODE:" + str(key) +
                                      " PUSH:tmp/" + filename)
                                displayPrompt = self.server_process_cmds(
                                    [clist[i].socket], ignore_list,
                                    "NODE:%s PUSH:%s" % (key, filename),
                                    server_sock)

                                time.sleep(2)

                                print("running NODE:%s %s " % (i, m.group(2)) +
                                      filename)
                                displayPrompt = self.server_process_cmds(
                                    [clist[i].socket], ignore_list,
                                    "NODE:%s EXEC %s" % (key, m.group(2)) +
                                    '' + filename, server_sock)

                                time.sleep(2)
                                break
        else:
            # do nothing for now
            displayPrompt = True

        return displayPrompt
Ejemplo n.º 4
0
    def client(self, host, port):
        slist = []  #array of client sockets

        # start the multicast probes
        self.probeNeighbors()

        if (host and port):
            remote_server_sock = Comms.create_direct_socket(host, port)
            slist.append(remote_server_sock)

        # add mesh listener if necessary
        if (self.meshListener):
            slist.append(self.meshListener)
            print("MeshNet Listener started on port: " + str(self.meshPort))

        while (1):
            self.addNeighbor()
            # get the list sockets which are ready to be read through select
            # 4th arg, time_out  = 0 : poll and never block
            ready_to_read, ready_to_write, in_error = select.select(
                slist, [], [], 0)

            for sock in ready_to_read:
                if (self.meshListener) and (sock == self.meshListener):
                    sockfd, addr = sock.accept()
                    msg = Comms.readMsg(sockfd, 4096)

                    # construct msg hash
                    m = hashlib.sha256()
                    m.update(msg.encode('ISO-8859-1'))
                    hash_key = m.hexdigest()
                    timestamp = datetime.datetime.now()

                    good = True
                    if hash_key in self.hashMsgs:
                        stored_timestamp = datetime.datetime.strptime(
                            self.hashMsgs[hash_key], '%Y-%m-%d %H:%M:%S.%f')
                        if (timestamp <= (stored_timestamp +
                                          datetime.timedelta(minutes=10))):
                            good = False

                    # if we have not seen the message before then process it
                    if good:
                        self.hashMsgs[hash_key] = str(timestamp)
                        (srcip, srcport, dstip, dstport,
                         data) = msg.split(':', 4)

                        # set mesh server ip:port
                        self.meshServerIP = srcip
                        self.meshServerPort = int(srcport)

                        if (dstip == self.ip) and (int(dstport)
                                                   == self.meshPort):
                            #process msg
                            self.client_process_cmds(data, None)
                        else:
                            self.forwardTraffic(srcip, srcport, dstip, dstport,
                                                data)
                elif (sock == remote_server_sock
                      ):  # a new connection request received
                    msg = Comms.readMsg(sock, 4096)
                    msg = msg.lstrip('\r\n')
                    self.client_process_cmds(msg, sock)