Checks if the last known request and current request are within the threshold limit for attempts being added and if so add an attempt. Args: ip: IP address as a string to be blacklisted if not already done so pattern_type: A string which selects the
(self, ip, pattern_type, time_object, ip_type="v4")
| 112 | self.check(ip, pattern_type, t, ip_type) |
| 113 | |
| 114 | def check(self, ip, pattern_type, time_object, ip_type="v4"): |
| 115 | """ |
| 116 | Checks if the last known request and current request are within the threshold limit for attempts being added |
| 117 | and if so add an attempt. |
| 118 | |
| 119 | Args: |
| 120 | ip: IP address as a string to be blacklisted if not already done so |
| 121 | pattern_type: A string which selects the correct dictionary to get the amount of failed attempts for that IP |
| 122 | time_object: A datetime object to check last request time |
| 123 | ip_type: Differentiates between the v4 and v6 protocols |
| 124 | """ |
| 125 | |
| 126 | old_time_object = self.ip_dict[pattern_type][ip]["last_request"] |
| 127 | |
| 128 | self.ip_dict[pattern_type][ip]["last_request"] = time_object |
| 129 | |
| 130 | if old_time_object is None: |
| 131 | return |
| 132 | |
| 133 | time_since_request = (time_object - old_time_object).total_seconds() |
| 134 | if time_since_request > self.settings["request_time"]: |
| 135 | return # Returns if the last request was more than the specified time |
| 136 | |
| 137 | self.ip_dict[pattern_type][ip]["amount"] += 1 |
| 138 | |
| 139 | if self.ip_dict[pattern_type][ip]["amount"] == self.settings["failed_attempts"]: |
| 140 | |
| 141 | if self.database_connection.select(ip) is not None: |
| 142 | return |
| 143 | |
| 144 | log_msg = "IP: {} has been blacklisted and the firewall rules have been updated." \ |
| 145 | " Acquired 5 bad connections via {}.\n".format(ip, pattern_type) |
| 146 | |
| 147 | if self.log_settings["active"]: |
| 148 | self.log(log_msg) |
| 149 | print(log_msg, end='') |
| 150 | |
| 151 | try: |
| 152 | del self.ip_dict[pattern_type][ip] # Delete IP from dictionary as it is getting blacklisted |
| 153 | except KeyError: |
| 154 | pass |
| 155 | |
| 156 | self.blacklist(ip, log_msg=log_msg, ip_type=ip_type) |
| 157 | |
| 158 | def blacklist(self, ip, save=True, log_msg="Unknown", ip_type="v4"): |
| 159 | """ |