def detect(self, pkt):
        """
        Detect ping of death attack
        by calculating load threshold.

        Args:
            pkt (scapy_object): Packet to dissect and observe

        Raises:
            None

        Returns:
            None
        """
        if (pkt.haslayer(scapy.IP) and pkt.haslayer(scapy.ICMP)):
            # If packet has load
            if pkt.haslayer(scapy.Raw):

                load_len = len(pkt[scapy.Raw].load)

                if (load_len >= self._THRESHOLD):
                    source_ip = pkt[scapy.IP].src
                    msg = "Possible ping of death attack detected " \
                          "from: {}".format(source_ip)
                    self.logger.log(msg, logtype="warning")
                    # Generate CSV report using OSINT tools
                    self.osint_obj.perform_osint_scan(source_ip.strip(" "))
                    # Write malicious IP to file
                    write_mal_ip(str(source_ip).strip(" "))
Exemplo n.º 2
0
    def detect_port_scan(self, data):
        """
        Detect possible Port Scan recon attacks.
        Look for a possible port scan user agent payload
        in the user agent field.

        Args:
            data (dict): Parsed log file data

        Raises:
            None

        Returns:
            None
        """
        for ip in data.keys():
            user_agent = data[ip]["ua"]
            if (self.payload_match(user_agent)):
                if ip not in self.logged_IP:
                    self.logged_IP.append(ip)
                    last_time = data[ip]["ep_time"][0]
                    msg = "Possible port scan detected from: " + str(ip) + \
                          " on: " + utils.epoch_to_date(last_time)
                    self.logger.log(msg, logtype="warning")
                    utils.write_ip(str(ip))
                    # Generate CSV report using OSINT tools
                    self.osint_obj.perform_osint_scan(ip.strip(" "))
                    # Write malicious IP to file, to teach Firewall about the IP
                    write_mal_ip(ip.strip(" "))
Exemplo n.º 3
0
    def detect_web_shell(self, data):
        """
        Detect possible Web Shell attacks.
        Use string comparison to scan GET request with the
        list of possible web shell payloads.

        Args:
            data (dict): Parsed log file data

        Raises:
            None

        Returns:
            None
        """
        for ip in data.keys():
            get_req = data[ip]["get"]
            if (self.payload_match(get_req)):
                if ip not in self.logged_IP:  # if not logged earlier
                    self.logged_IP.append(ip)
                    last_time = data[ip]["ep_time"][0]
                    msg = "Possible web shell detected from: " + str(ip) + \
                          " on: " + str(utils.epoch_to_date(last_time))
                    self.logger.log(msg, logtype="warning")
                    utils.write_ip(str(ip))
                    # Generate CSV report using OSINT tools
                    self.osint_obj.perform_osint_scan(ip.strip(" "))
                    # Write malicious IP to file, to teach Firewall about the IP
                    write_mal_ip(ip.strip(" "))
Exemplo n.º 4
0
    def detect_port_scan(self):
        """
        Detect port scan by comparing the
        calculated ratio with the set threshold.

        Args:
            None

        Raises:
            None

        Returns:
            None
        """
        for ip in self.ip_dict.keys():
            count = self.ip_dict[ip]["count"]
            last_time = self.ip_dict[ip]["last_time"]
            current_time = time.time()

            try:
                delta_time = int(current_time - last_time)
                calc_threshold = count / delta_time
            except ZeroDivisionError:
                calc_threshold = int(count)

            if calc_threshold > self.THRESHOLD:
                msg = "Possible port scan detected from: " \
                      + ip.split(self.SALT)[0] + " on " \
                      + ip.split(self.SALT)[1]
                self.logger.log(msg, logtype="warning")
                # Generate CSV report using OSINT tools
                self.osint_obj.perform_osint_scan(
                    ip.split(self.SALT)[0].strip(" "))
                # Write malicious IP to file, to teach Firewall about the IP
                write_mal_ip(ip.split(self.SALT)[0].strip(" "))
Exemplo n.º 5
0
    def calc_intrusion(self, scan_dict, msg):
        """
        Detect intrusion by comparing observed and expected
        threshold ratio.

        Args:
            scan_dict (dict): IP dictionary
            msg (str): Message to display when intrusion is detected

        Raises:
            None

        Returns:
            None
        """
        for key in scan_dict.keys():
            current_time = time.time()
            start_time = scan_dict[key]["start_time"]
            port_len = len(scan_dict[key]["ports"])
            count = scan_dict[key]["count"]
            delta_time = int(current_time - start_time)

            try:
                calc_threshold = int(port_len / delta_time)
            except ZeroDivisionError:
                calc_threshold = int(port_len)

            if (calc_threshold >= self._THRESHOLD or count >= self._COUNT):
                # Intrusion detected
                new_msg = msg + " from IP: " + str(key)
                self.logger.log(new_msg, logtype="warning")
                # Generate CSV report using OSINT tools
                self.osint_obj.perform_osint_scan(str(key).strip(" "))
                # Write malicious IP to file
                write_mal_ip(str(key).strip(" "))
Exemplo n.º 6
0
    def detect_sqli(self, data):
        """
        Detect possible SQL Injection (sqli) attacks.
        Use regex rules and string matching to detect
        SQLi attacks.
        4 Level rules:
            - Simple regex
            - Hex regex
            - Payload string matching
            - URI encoded string matching

        Args:
            data (dict): Parsed log file data

        Raises:
            None

        Returns:
            None
        """
        for ip in data.keys():
            get_req = data[ip]["get"]
            last_time = data[ip]["ep_time"][0]
            if (self.payload_match(get_req) or self.regex_check(get_req)):
                if ip not in self.logged_IP:  # if not logged earlier
                    self.logged_IP.append(ip)
                    msg = "Possible SQL injection (sqli) detected from: " + str(ip) + \
                          " on: " + str(utils.epoch_to_date(last_time))
                    self.logger.log(msg, logtype="warning")
                    utils.write_ip(str(ip))
                    # Generate CSV report using OSINT tools
                    self.osint_obj.perform_osint_scan(ip.strip(" "))
                    # Write malicious IP to file, to teach Firewall about the IP
                    write_mal_ip(ip.strip(" "))
Exemplo n.º 7
0
    def check_ssh_bruteforce(self):
        """
        Check for SSH brute-force by comparing
        the calculated ratio with the set threshold.

        Args:
            None

        Raises:
            None

        Returns:
            None
        """
        for user in self.username_dict.keys():
            no_of_ip = len(self.username_dict[user]["ip"])
            count = self.username_dict[user]["count"]
            last_time = self.username_dict[user]["last_time"]
            current_time = time.time()

            try:
                delta_time = int(current_time - last_time)
                calc_threshold_ip = no_of_ip / delta_time
                calc_threshold_count = count / delta_time
            except ZeroDivisionError:
                calc_threshold_ip = int(no_of_ip)
                calc_threshold_count = int(count)

            if (calc_threshold_ip > self.THRESHOLD or
                calc_threshold_count > self.THRESHOLD):
                if no_of_ip == 1:  # if a single IP in user list
                    msg = "Possible SSH brute force detected for the user: "******" from: " + \
                           self.username_dict[user]["ip"][0] + " on: " + \
                           user.split(self.SALT)[1]
                    self.logger.log(
                        msg,
                        logtype="warning"
                    )
                    # Generate CSV report using OSINT tools
                    self.osint_obj.perform_osint_scan(self.username_dict[user]["ip"][0].strip(" "))
                    # Write malicious IP to file, to teach Firewall about the IP
                    write_mal_ip(self.username_dict[user]["ip"][0].strip(" "))
                else:
                    for ip in self.username_dict[user]["ip"]:
                        msg = "Possible SSH brute force detected for the user: "******" from: " + ip + " on: " + \
                               user.split(self.SALT)[1]
                        self.logger.log(
                            msg,
                            logtype="warning"
                        )
                        # Generate CSV report using OSINT tools
                        self.osint_obj.perform_osint_scan(ip.strip(" "))
                        # Write malicious IP to file, to teach Firewall about the IP
                        write_mal_ip(ip.strip(" "))
Exemplo n.º 8
0
    def detect_ddos(self, data):
        """
        Detect DoS attack. Classify DoS attack into two categories:
        - Single IP Single Port DoS Attack
        - Single IP Multiple Port DoS Attack
        Look for IP addresses having high number of GET request and
        a small time difference to predict SISP DoS attack.
        High number of alarms triggered for SISP DoS attack indicates
        MISP DoS attack.

        Args:
            data (dict): Parsed log file data

        Raises:
            None

        Returns:
            None
        """
        for ip in data.keys():
            count = data[ip]["count"]
            last_time = data[ip]["ep_time"][0]
            initial_time = data[ip]["ep_time"][int(
                len(data[ip]["ep_time"]) - 1)]
            delta = abs(int(last_time - initial_time))

            try:
                calc_count_thresh = int(count / delta)
            except ZeroDivisionError:
                calc_count_thresh = int(count)

            if calc_count_thresh > self._SISP_THRESHOLD:  # if crosses threshold, trigger alarm
                msg = "Possible Single IP DoS Attack Detected from: " + \
                       str(ip) + " on: " + utils.epoch_to_date(last_time)
                self.logger.log(msg, logtype="warning")
                if ip not in self.SISP_LIST:
                    self.SISP_LIST.append(ip)
                    # Generate CSV report using OSINT tools
                    self.osint_obj.perform_osint_scan(ip.strip(" "))
                    # Write malicious IP to file, to teach Firewall about the IP
                    write_mal_ip(ip.strip(" "))

            if len(self.SISP_LIST
                   ) > self._SIMP_THRESHOLD:  # if no. of SISP is huge
                for ip in self.SISP_LIST:
                    self.logger.log(
                        "Possible Multiple IP DoS Attack Detected from: " +
                        str(ip),
                        logtype="warning")
Exemplo n.º 9
0
    def detect_spider(self, data):
        """
        Detect possible Web Crawler / Spider / Bad user agents.
        High amount of unique GET request from an IP within a
        small period of time are likely to indicate a web crawler /
        spider.

        Look for bad user agents payload to guess a bad user agent.

        Args:
            data (dict): Parsed log file data

        Raises:
            None

        Returns:
            None
        """
        for ip in data.keys():
            count = data[ip]["count"]
            last_time = data[ip]["ep_time"][0]
            initial_time = data[ip]["ep_time"][int(
                len(data[ip]["ep_time"]) - 1)]
            delta = abs(int(last_time - initial_time))

            try:
                calc_count_thresh = count / delta
                calc_get_thresh = len(data[ip]["unique_get"]) / delta
            except ZeroDivisionError:
                calc_count_thresh = count
                calc_get_thresh = len(data[ip]["unique_get"])

            if (calc_count_thresh > self._THRESHOLD
                    or calc_get_thresh > self._THRESHOLD
                    or self.payload_match(data[ip]["ua"])):
                if ip not in self.logged_IP:
                    self.logged_IP.append(ip)
                    self.logger.log(
                        "Possible web crawler / spider / bad user agent detected from: "
                        + str(ip),
                        logtype="warning")
                    utils.write_ip(str(ip))
                    # Generate CSV report using OSINT tools
                    self.osint_obj.perform_osint_scan(ip.strip(" "))
                    # Write malicious IP to file, to teach Firewall about the IP
                    write_mal_ip(ip.strip(" "))
Exemplo n.º 10
0
    def detect_ssrf(self , data):
        """
                    Detects  SSRF
                    Args:
                        data (dict): Parsed Log File

                    Raises:
                        None

                    Returns:
                        None
                    """
        for ip in data.keys():
            get_req = data[ip]["get"]
            last_time = data[ip]["ep_time"][0]
            # extracting all the urls in path
            urls=re.findall(r"https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+", get_req[0])
            for url in urls:
                resolved_ip=utils.resolver(url)
                if resolved_ip:
                    if (self.rmatch(resolved_ip)):
                        if ip not in self.logged_IP:  # if not logged earlier
                            self.logged_IP.append(ip)
                            msg = "Possible SSRF detected From: " + str(ip) + \
                                  " on: " + str(utils.epoch_to_date(last_time))
                            self.logger.log(
                                msg,
                                logtype="warning"
                            )
                            utils.write_ip(str(ip))
                            # Generate CSV report using OSINT tools
                            self.osint_obj.perform_osint_scan(ip.strip(" "))
                            # Write malicious IP to file, to teach Firewall about the IP
                            write_mal_ip(ip.strip(" "))

                if(self.payload_match(url) or self.regex_match(get_req)):
                        if ip not in self.logged_IP:
                            self.logged_IP.append(ip)
                            msg = "Possible SSRF detected From  " + str(ip) + \
                                  " on: " + str(utils.epoch_to_date(last_time))
                            self.logger.log(msg,logtype="warning")
                            utils.write_ip(str(ip))
                            # Generate CSV report using OSINT tools
                            self.osint_obj.perform_osint_scan(ip.strip(" "))
                            # Write malicious IP to file, to teach Firewall about the IP
                            write_mal_ip(ip.strip(" "))
Exemplo n.º 11
0
    def detect_fuzzer(self, data):
        """
        Detect possible URL fuzzing attacks.
        High number of failure codes (400-500) range from an IP
        within a small period of time indicates a possible
        fuzzing attack.

        Args:
            data (dict): Parsed log file data

        Raises:
            None

        Returns:
            None
        """
        for ip in data.keys():
            status_code = data[ip]["status_code"]
            # Count failure attempts for that IP
            failure_count = self.count_failure(status_code)
            last_time = data[ip]["ep_time"][0]
            initial_time = data[ip]["ep_time"][int(
                len(data[ip]["ep_time"]) - 1)]
            delta = abs(int(last_time - initial_time))

            try:
                calc_count_thresh = failure_count / delta
                calc_get_thresh = len(data[ip]["get"]) / delta
            except ZeroDivisionError:
                calc_count_thresh = failure_count
                calc_get_thresh = len(data[ip]["get"])

            if (calc_count_thresh > self._THRESHOLD
                    or calc_get_thresh > self._THRESHOLD):
                if ip not in self.logged_IP:
                    self.logged_IP.append(ip)
                    msg = "Possible URL fuzzing detected from: " + str(ip) + \
                          " on: " + utils.epoch_to_date(data[ip]["ep_time"][0])
                    self.logger.log(msg, logtype="warning")
                utils.write_ip(str(ip))
                # Generate CSV report using OSINT tools
                self.osint_obj.perform_osint_scan(ip.strip(" "))
                # Write malicious IP to file, to teach Firewall about the IP
                write_mal_ip(ip.strip(" "))
Exemplo n.º 12
0
 def test_write_mal_ip(mck_open):
     """
     Test write_mal_ip.
     """
     common.write_mal_ip("10.0.0.0")
     mck_open.assert_called_with('/etc/securetea/mal_ip.txt', 'a')