BaseAttack.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. import ipaddress
  2. import re
  3. from abc import abstractmethod, ABCMeta
  4. import ID2TLib.libpcapreader as pr
  5. from Attack import AttackParameters
  6. from Attack.AttackParameters import Parameter
  7. from Attack.AttackParameters import ParameterTypes
  8. class BaseAttack(metaclass=ABCMeta):
  9. """
  10. Abstract base class for all attack classes. Provides basic functionalities, like parameter validation.
  11. """
  12. def __init__(self, statistics, name, description, attack_type):
  13. """
  14. To be called within the individual attack class to initialize the required parameters.
  15. :param statistics: A reference to the Statistics class.
  16. :param name: The name of the attack class.
  17. :param description: A short description of the attack.
  18. :param attack_type: The type the attack belongs to, like probing/scanning, malware.
  19. """
  20. # Reference to statistics class
  21. self.statistics = statistics
  22. # Class fields
  23. self.attack_name = name
  24. self.attack_description = description
  25. self.attack_type = attack_type
  26. self.params = {}
  27. self.supported_params = {}
  28. self.attack_start_utime = 0
  29. self.attack_end_utime = 0
  30. @abstractmethod
  31. def get_packets(self):
  32. """
  33. Creates the packets containing the attack.
  34. :return: A list of packets ordered ascending by the packet's timestamp.
  35. """
  36. pass
  37. ################################################
  38. # HELPER VALIDATION METHODS
  39. # Used to validate the given parameter values
  40. ################################################
  41. @staticmethod
  42. def _is_mac_address(mac_address: str):
  43. """
  44. Verifies if the given string is a valid MAC address. Accepts the formats 00:80:41:ae:fd:7e and 00-80-41-ae-fd-7e.
  45. :param mac_address: The MAC address as string.
  46. :return: True if the MAC address is valid, otherwise False.
  47. """
  48. result = re.match('^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$', mac_address, re.MULTILINE)
  49. return result is not None
  50. @staticmethod
  51. def _is_ip_address(ip_address: str):
  52. """
  53. Verifies if the given string is a valid IPv4/IPv6 address. Accepts comma-separated lists of IP addresses,
  54. like "192.169.178.1, 192.168.178.2"
  55. :param ip_address: The IP address as string.
  56. :return: True if all IP addresses are valid, otherwise False. And a list of IP addresses as string.
  57. """
  58. ip_address_output = []
  59. for ip in ip_address.split(','):
  60. try:
  61. ipaddress.ip_address(ip)
  62. ip_address_output.append(ip)
  63. except ValueError:
  64. return False, ip_address_output
  65. if len(ip_address_output) == 1:
  66. return True, ip_address_output[0]
  67. else:
  68. return True, ip_address_output
  69. @staticmethod
  70. def _is_port(ports_input: str):
  71. """
  72. Verifies if the given value is a valid port. Accepts port ranges, like 80-90, 80..99, 80...99.
  73. :param ports_input: The port number as int or string.
  74. :return: True if the port number is valid, otherwise False. If a single port or a comma-separated list of ports
  75. was given, a list of int is returned. If a port range was given, the range is resolved
  76. and a list of int is returned.
  77. """
  78. def _is_invalid_port(num):
  79. """
  80. Checks whether the port number is invalid.
  81. :param num: The port number as int.
  82. :return: True if the port number is invalid, otherwise False.
  83. """
  84. return num < 0 or num > 65535
  85. ports_input = ports_input.replace(' ', '').split(',')
  86. ports_output = []
  87. for port_entry in ports_input:
  88. if isinstance(port_entry, int):
  89. if _is_invalid_port(port_entry):
  90. return False
  91. ports_output.append(port_entry)
  92. elif isinstance(port_entry, str) and port_entry.isdigit():
  93. # port_entry describes a single port
  94. port_entry = int(port_entry)
  95. if _is_invalid_port(port_entry):
  96. return False
  97. ports_output.append(port_entry)
  98. elif '-' in port_entry or '..' in port_entry:
  99. # port_entry describes a port range
  100. # allowed format: '12-123', '12..123', '12...123'
  101. match = re.match('^([0-9]{1,4})(?:-|\.{2,3})([0-9]{1,4})$', port_entry)
  102. # check validity of port range
  103. # and create list of ports derived from given start and end port
  104. (port_start, port_end) = int(match.group(1)), int(match.group(2))
  105. if _is_invalid_port(port_start) or _is_invalid_port(port_end):
  106. return False
  107. else:
  108. ports_list = [i for i in range(port_start, port_end + 1)]
  109. # append ports at ports_output list
  110. ports_output += ports_list
  111. return True, ports_output
  112. @staticmethod
  113. def _is_timestamp(timestamp: str):
  114. """
  115. Checks whether the given value is in a valid timestamp format. The accepted format is:
  116. YYYY-MM-DD h:m:s, whereas h, m, s may be one or two digits.
  117. :param timestamp: The timestamp to be checked.
  118. :return: True if the timestamp is valid, otherwise False.
  119. """
  120. is_valid = re.match('[0-9]{4}(?:-[0-9]{1,2}){2} (?:[0-9]{1,2}:){2}[0-9]{1,2}', timestamp)
  121. return is_valid is not None
  122. @staticmethod
  123. def _is_boolean(value):
  124. """
  125. Checks whether the given value (string or bool) is a boolean. Strings are valid booleans if they are in:
  126. {y, yes, t, true, on, 1, n, no, f, false, off, 0}.
  127. :param value: The value to be checked.
  128. :return: True if the value is a boolean, otherwise false. And the casted boolean.
  129. """
  130. # If value is already a boolean
  131. if isinstance(value, bool):
  132. return True, value
  133. # If value is a string
  134. # True values are y, yes, t, true, on and 1;
  135. # False values are n, no, f, false, off and 0.
  136. # Raises ValueError if value is anything else.
  137. try:
  138. import distutils.core
  139. value = distutils.util.strtobool(value.lower())
  140. is_bool = True
  141. except ValueError:
  142. is_bool = False
  143. return is_bool, value
  144. @staticmethod
  145. def _is_float(value):
  146. """
  147. Checks whether the given value is a float.
  148. :param value: The value to be checked.
  149. :return: True if the value is a float, otherwise False. And the casted float.
  150. """
  151. try:
  152. value = float(value)
  153. return True, value
  154. except ValueError:
  155. return False, value
  156. #########################################
  157. # HELPER METHODS
  158. #########################################
  159. def add_param_value(self, param, value: str):
  160. """
  161. Adds the pair param : value to the dictionary of attack parameters. Prints and error message and skips the
  162. parameter if the validation fails.
  163. :param param: The parameter name.
  164. :param value: The parameter's value.
  165. :return: None.
  166. """
  167. # by default no param is valid
  168. is_valid = False
  169. # get AttackParameters instance associated with param
  170. # for default values assigned in attack classes, like Parameter.PORT_OPEN
  171. if isinstance(param, AttackParameters.Parameter):
  172. param_name = param
  173. # for values given by user input, like port.open
  174. else:
  175. # Get Enum key of given string identifier
  176. param_name = AttackParameters.Parameter(param)
  177. # Get parameter type of attack's required_params
  178. param_type = self.supported_params.get(param_name)
  179. # Verify validity of given value with respect to parameter type
  180. if param_type is None:
  181. print('Parameter ' + str(param_name) + ' not available for chosen attack. Skipping parameter.')
  182. # If value is query -> get value from database
  183. elif self.statistics.is_query(value):
  184. value = self.statistics.process_db_query(value, False)
  185. if value is not None and value is not "":
  186. is_valid = True
  187. else:
  188. print('Error in given parameter value: ' + value + '. Data could not be retrieved.')
  189. # Validate parameter depending on parameter's type
  190. elif param_type == ParameterTypes.TYPE_IP_ADDRESS:
  191. is_valid, value = self._is_ip_address(value)
  192. elif param_type == ParameterTypes.TYPE_PORT:
  193. is_valid, value = self._is_port(value)
  194. elif param_type == ParameterTypes.TYPE_MAC_ADDRESS:
  195. is_valid = self._is_mac_address(value)
  196. elif param_type == ParameterTypes.TYPE_INTEGER_POSITIVE:
  197. is_valid = value is None or (value.isdigit() and int(value) >= 0)
  198. elif param_type == ParameterTypes.TYPE_FLOAT:
  199. is_valid, value = self._is_float(value)
  200. elif param_type == ParameterTypes.TYPE_TIMESTAMP:
  201. is_valid = self._is_timestamp(value)
  202. elif param_type == ParameterTypes.TYPE_BOOLEAN:
  203. is_valid, value = self._is_boolean(value)
  204. elif param_type == ParameterTypes.TYPE_PACKET_POSITION:
  205. ts = pr.pcap_processor(self.pcap_filepath).get_timestamp_mu_sec(int(value))
  206. if 0 <= int(value) <= self.statistics.get_packet_count() and ts >= 0:
  207. is_valid = True
  208. param_name = Parameter.INJECT_AT_TIMESTAMP
  209. value = (ts / 1000000) # convert microseconds from getTimestampMuSec into seconds
  210. # add value iff validation was successful
  211. if is_valid:
  212. self.params[param_name] = value
  213. else:
  214. print("ERROR: Parameter " + str(param) + " or parameter value " + str(value) +
  215. " not valid. Skipping parameter.")
  216. def get_param_value(self, param: Parameter):
  217. """
  218. Returns the parameter value for a given parameter.
  219. :param param: The parameter whose value is wanted.
  220. :return: The parameter's value.
  221. """
  222. return self.params[param]