Beispiel #1
0
 def handleCommand(self, encoded_command):
     """If the bot received a new encoded_command, this method executes the encoded_command"""
     logging.debug("Got (new?) encoded_command: %s"%encoded_command)
     if encoded_command is not None:
         command = json.loads(encoded_command)
         writeLogentry(runnable=type(self).__name__, message="received_command: %s"
                                                             %json.dumps({"bot": self.name, "newcmd": command}))
         executeCurrentCommand(command)
    def _measureCpuLoad(self):
        while True:
            with open("/proc/loadavg", mode="r") as fp:
                line = fp.readline()
                match = re.match("([\.\d]+) ([\.\d]+) ([\.\d]+).*", line)
                assert match, "Unrecognised format: %s"%line
                writeLogentry(runnable=self.__class__.__name__, message="load: %s"%match.group(1))

            time.sleep(1)
Beispiel #3
0
 def _executeCurrentCommand(self, current_command):
     """Executes the last command that has been fetched from the Servent"""
     try:
         writeLogentry(runnable=type(self).__name__, message="received_command: %s"
                                                             %json.dumps({"bot": self.name, "newcmd": current_command}))
         executeCurrentCommand(current_command)
     except TypeError as ex:
         logging.warning("Command %s got invalid parameters %s: %s"
                         %(current_command["command"], current_command["kwargs"], ex.message))
Beispiel #4
0
 def performDuty(self):
     """Implements method from superclass"""
     n = 3
     try:
         starttime = datetime.now()
         for page in self.pagesToWatch:
             loadTime = float(timeit(lambda: measureLoadingTime(page), number=n)/n)
             writeLogentry(runnable=type(self).__name__, message="%s %f"%(page, loadTime), timeissued=starttime)
     except Exception as ex:
         logging.warning("Measurement of the loading times failed with an %s: %s"%(type(ex).__name__, ex.message))
    def _measureRamUsage(self):
        while True:
            proc = Popen(shlex.split("free -m"), shell=True, stdout=PIPE)
            stdout, _ = proc.communicate()
            for line in stdout.splitlines():
                match = re.match("Mem:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+).*", line)
                if match:
                    writeLogentry(runnable=self.__class__.__name__, message="ram: %d"%match.group(2))
                    break

            time.sleep(1)
    def performDuty(self, *args, **kwargs):
        """Sends random traffic to a random host to generate noise in the network.
        ITGSend (belongs to D-ITG) is a traffic generator that sends out random traffic.
        It is able to simulate various application of which one is randomly chosen."""

        if random.uniform(0, 1) < self.probability:
            # We can ignore the log files, because we are just using the traffic as noise
            receiver = random.choice(self.peerlist)
            app = random.choice(self._simulated_apps)
            subprocess.call("ITGSend -a %s -l /dev/null -x /dev/null %s"
                            % (receiver, app), shell=True)
            writeLogentry(type(self).__name__, "Sent %s traffic to %s" % (app, receiver))
    def get(self):
        """Returns the currently set command"""
        writeLogentry(runnable=type(self).__name__, message="received_command_request: %s"
                                                            %json.dumps({"newcmd": self.current_command}))

        if "json" in string.lower(self.request.headers.get("Accept")):
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps(self.current_command))
        else:
            self.set_header("Content-Type", "text/plain")
            if len(self.current_command) > 0:
                self.write(
                    "%s: %s"%(self.current_command["command"], " ".join(self.current_command["kwargs"].values())))
Beispiel #8
0
    def _executeCurrentCommand(self):
        """Executes the last command that has been fetched from the CnC-Server"""

        if isinstance(self.current_command, dict) and self.current_command.has_key("command") \
                and self.current_command["command"] != "":
            try:
                writeLogentry(runnable=type(self).__name__, message="received_command: %s"
                                                                    %json.dumps(
                    {"bot": self.name, "newcmd": self.current_command}))
                BotCommands.executeCurrentCommand(self.current_command)
            except TypeError as ex:
                logging.warning("Command %s got invalid parameters %s: %s"
                                % (self.current_command["command"], self.current_command["kwargs"], ex.message))
Beispiel #9
0
    def executeExperiment(self):
        """This method implements the execution strategy of all botnet experiments. It corresponds to the execute() method
        from the strategy pattern."""
        name = self.__class__.__name__  # Name of the subclass

        writeLogentry(runnable=name, message="Experiment started")

        logging.debug("Initialise %s"%name)
        self._setup()
        self.setNodes("nodes", frozenset(self.mininet.hosts))  # Category that includes all Mininet hosts
        logging.info("Starting %s"%name)
        self._start()
        writeLogentry(runnable=type(self).__name__, message="Experiment fully started")

        doNextStep = True
        currentIteration = 0
        while doNextStep:
            writeLogentry(runnable=type(self).__name__, message="Iteration: %d %d"%(currentIteration, len(self.getNodes("bots"))))
            logging.info("Step %d on %d "%(currentIteration, datetimeToEpoch(datetime.now())))
            doNextStep = self._executeStep(currentIteration)
            currentIteration += 1

        logging.info("Stoping %s after %d iterations"%(name, currentIteration))
        self._stop()
        logging.info("Produce output files")
        self._produceOutputFiles()

        writeLogentry(runnable=name, message="Experiment ended")
Beispiel #10
0
 def _executeCurrentCommand(self, current_command):
     """Executes the last command that has been fetched from the Servent"""
     try:
         writeLogentry(runnable=type(self).__name__,
                       message="received_command: %s" %
                       json.dumps({
                           "bot": self.name,
                           "newcmd": current_command
                       }))
         executeCurrentCommand(current_command)
     except TypeError as ex:
         logging.warning("Command %s got invalid parameters %s: %s" %
                         (current_command["command"],
                          current_command["kwargs"], ex.message))
Beispiel #11
0
    def executeExperiment(self):
        """This method implements the execution strategy of all botnet experiments. It corresponds to the execute() method
        from the strategy pattern."""
        name = self.__class__.__name__  # Name of the subclass

        writeLogentry(runnable=name, message="Experiment started")

        logging.debug("Initialise %s" % name)
        self._setup()
        self.setNodes("nodes", frozenset(
            self.mininet.hosts))  # Category that includes all Mininet hosts
        logging.info("Starting %s" % name)
        self._start()
        writeLogentry(runnable=type(self).__name__,
                      message="Experiment fully started")

        doNextStep = True
        currentIteration = 0
        while doNextStep:
            writeLogentry(runnable=type(self).__name__,
                          message="Iteration: %d %d" %
                          (currentIteration, len(self.getNodes("bots"))))
            logging.info("Step %d on %d " %
                         (currentIteration, datetimeToEpoch(datetime.now())))
            doNextStep = self._executeStep(currentIteration)
            currentIteration += 1

        logging.info("Stoping %s after %d iterations" %
                     (name, currentIteration))
        self._stop()
        logging.info("Produce output files")
        self._produceOutputFiles()

        writeLogentry(runnable=name, message="Experiment ended")
def sendDDoSCommand(hostList, victimip):
    if len(hostList)==0:
        logging.warn("Could not send ddos command to empty host list")
        return

    botToIssueCommandFrom = random.sample(hostList, 1)[0]
    writeLogentry(runnable="KademliaExperiment", message="Send command %s to bot %s"%("ddos_server", botToIssueCommandFrom))

    kwargsStr = json.dumps({"url": "http://%s:%d/ddos_me"%(victimip, PORT)})
    urlToAttack = "http://%s:%d/current_command"%(botToIssueCommandFrom.IP(), PORT)
    result = botToIssueCommandFrom.cmd("timeout 60s wget -q -O - --post-data 'command=ddos_server&kwargs=%s&timestamp=%d' '%s'"
                                       %(kwargsStr, datetimeToEpoch(datetime.now()), urlToAttack), verbose=True)

    assert "OK" in result.strip(), "Could not send the DDoS-command to the bot %s: |%s|"%(botToIssueCommandFrom, result)
Beispiel #13
0
 def performDuty(self):
     """Implements method from superclass"""
     n = 3
     try:
         starttime = datetime.now()
         for page in self.pagesToWatch:
             loadTime = float(
                 timeit(lambda: measureLoadingTime(page), number=n) / n)
             writeLogentry(runnable=type(self).__name__,
                           message="%s %f" % (page, loadTime),
                           timeissued=starttime)
     except Exception as ex:
         logging.warning(
             "Measurement of the loading times failed with an %s: %s" %
             (type(ex).__name__, ex.message))
Beispiel #14
0
    def _executeCurrentCommand(self):
        """Executes the last command that has been fetched from the CnC-Server"""

        if isinstance(self.current_command, dict) and self.current_command.has_key("command") \
                and self.current_command["command"] != "":
            try:
                writeLogentry(runnable=type(self).__name__,
                              message="received_command: %s" %
                              json.dumps({
                                  "bot": self.name,
                                  "newcmd": self.current_command
                              }))
                BotCommands.executeCurrentCommand(self.current_command)
            except TypeError as ex:
                logging.warning("Command %s got invalid parameters %s: %s" %
                                (self.current_command["command"],
                                 self.current_command["kwargs"], ex.message))
def sendDDoSCommand(hostList, victimip):
    if len(hostList) == 0:
        logging.warn("Could not send ddos command to empty host list")
        return

    botToIssueCommandFrom = random.sample(hostList, 1)[0]
    writeLogentry(runnable="KademliaExperiment",
                  message="Send command %s to bot %s" %
                  ("ddos_server", botToIssueCommandFrom))

    kwargsStr = json.dumps({"url": "http://%s:%d/ddos_me" % (victimip, PORT)})
    urlToAttack = "http://%s:%d/current_command" % (botToIssueCommandFrom.IP(),
                                                    PORT)
    result = botToIssueCommandFrom.cmd(
        "timeout 60s wget -q -O - --post-data 'command=ddos_server&kwargs=%s&timestamp=%d' '%s'"
        % (kwargsStr, datetimeToEpoch(datetime.now()), urlToAttack),
        verbose=True)

    assert "OK" in result.strip(
    ), "Could not send the DDoS-command to the bot %s: |%s|" % (
        botToIssueCommandFrom, result)