BaseAttack.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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.attackName = name
  24. self.attackDescription = description
  25. self.attackType = 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. return True, ip_address_output
  66. @staticmethod
  67. def _is_port(ports_input: str):
  68. """
  69. Verifies if the given value is a valid port. Accepts port ranges, like 80-90, 80..99, 80...99.
  70. :param ports_input: The port number as int or string.
  71. :return: True if the port number is valid, otherwise False. If a port range was given, the range is resolved
  72. and a list of ports is additionally returned.
  73. """
  74. def _is_invalid_port(num):
  75. """
  76. Checks whether the port number is invalid.
  77. :param num: The port number as int.
  78. :return: True if the port number is invalid, otherwise False.
  79. """
  80. return num < 1 or num > 65535
  81. ports_input = ports_input.replace(' ', '').split(',')
  82. ports_output = []
  83. for port_entry in ports_input:
  84. if isinstance(port_entry, int):
  85. if _is_invalid_port(port_entry):
  86. return False
  87. ports_output.append(port_entry)
  88. elif isinstance(port_entry, str) and port_entry.isdigit():
  89. # port_entry describes a single port
  90. port_entry = int(port_entry)
  91. if _is_invalid_port(port_entry):
  92. return False
  93. ports_output.append(port_entry)
  94. elif '-' in port_entry or '..' in port_entry:
  95. # port_entry describes a port range
  96. # allowed format: '12-123', '12..123', '12...123'
  97. match = re.match('^([0-9]{1,5})(?:-|\.{2,3})([0-9]{1,5})$', port_entry)
  98. # check validity of port range
  99. # and create list of ports derived from given start and end port
  100. (port_start, port_end) = int(match.group(1)), int(match.group(2))
  101. if _is_invalid_port(port_start) or _is_invalid_port(port_end):
  102. return False
  103. else:
  104. ports_list = [i for i in range(port_start, port_end + 1)]
  105. # append ports at ports_output list
  106. ports_output += ports_list
  107. return True, ports_output
  108. @staticmethod
  109. def _is_timestamp(timestamp: str):
  110. """
  111. Checks whether the given value is in a valid timestamp format. The accepted format is:
  112. YYYY-MM-DD h:m:s, whereas h, m, s may be one or two digits.
  113. :param timestamp: The timestamp to be checked.
  114. :return: True if the timestamp is valid, otherwise False.
  115. """
  116. is_valid = re.match('[0-9]{4}(?:-[0-9]{1,2}){2} (?:[0-9]{1,2}:){2}[0-9]{1,2}', timestamp)
  117. return is_valid is not None
  118. @staticmethod
  119. def _is_boolean(value):
  120. """
  121. Checks whether the given value (string or bool) is a boolean. Strings are valid booleans if they are in:
  122. {y, yes, t, true, on, 1, n, no, f, false, off, 0}.
  123. :param value: The value to be checked.
  124. :return: True if the value is a boolean, otherwise false. And the casted boolean.
  125. """
  126. # If value is already a boolean
  127. if isinstance(value, bool):
  128. return True, value
  129. # If value is a string
  130. # True values are y, yes, t, true, on and 1;
  131. # False values are n, no, f, false, off and 0.
  132. # Raises ValueError if value is anything else.
  133. try:
  134. import distutils.core
  135. value = distutils.util.strtobool(value.lower())
  136. is_bool = True
  137. except ValueError:
  138. is_bool = False
  139. return is_bool, value
  140. @staticmethod
  141. def _is_float(value):
  142. """
  143. Checks whether the given value is a float.
  144. :param value: The value to be checked.
  145. :return: True if the value is a float, otherwise False. And the casted float.
  146. """
  147. try:
  148. value = float(value)
  149. return True, value
  150. except ValueError:
  151. return False, value
  152. #########################################
  153. # HELPER METHODS
  154. #########################################
  155. def add_param_value(self, param, value: str):
  156. """
  157. Adds the pair param : value to the dictionary of attack parameters. Prints and error message and skips the
  158. parameter if the validation fails.
  159. :param param: The parameter name.
  160. :param value: The parameter's value.
  161. :return: None.
  162. """
  163. # by default no param is valid
  164. is_valid = False
  165. # get AttackParameters instance associated with param
  166. # for default values assigned in attack classes, like Parameter.PORT_OPEN
  167. if isinstance(param, AttackParameters.Parameter):
  168. param_name = param
  169. # for values given by user input, like port.open
  170. else:
  171. # Get Enum key of given string identifier
  172. param_name = AttackParameters.Parameter(param)
  173. # Get parameter type of attack's required_params
  174. param_type = self.supported_params.get(param_name)
  175. # Verify validity of given value with respect to parameter type
  176. if param_type is None:
  177. print('Parameter ' + str(param_name) + ' not available for chosen attack. Skipping parameter.')
  178. # If value is query -> get value from database
  179. elif self.statistics.is_query(value):
  180. value = self.statistics.process_db_query(value, False)
  181. if value is not None and value is not "":
  182. is_valid = True
  183. else:
  184. print('Error in given parameter value: ' + value + '. Data could not be retrieved.')
  185. # Validate parameter depending on parameter's type
  186. elif param_type == ParameterTypes.TYPE_IP_ADDRESS:
  187. is_valid, value = self._is_ip_address(value)
  188. elif param_type == ParameterTypes.TYPE_PORT:
  189. is_valid, value = self._is_port(value)
  190. elif param_type == ParameterTypes.TYPE_MAC_ADDRESS:
  191. is_valid = self._is_mac_address(value)
  192. elif param_type == ParameterTypes.TYPE_INTEGER_POSITIVE:
  193. is_valid = value is None or (value.isdigit() and int(value) >= 0)
  194. elif param_type == ParameterTypes.TYPE_FLOAT:
  195. is_valid, value = self._is_float(value)
  196. elif param_type == ParameterTypes.TYPE_TIMESTAMP:
  197. is_valid = self._is_timestamp(value)
  198. elif param_type == ParameterTypes.TYPE_BOOLEAN:
  199. is_valid, value = self._is_boolean(value)
  200. elif param_type == ParameterTypes.TYPE_PACKET_POSITION:
  201. ts = pr.pcap_processor(self.pcap_filepath).get_timestamp_mu_sec(int(value))
  202. if 0 <= int(value) <= self.statistics.get_packet_count() and ts >= 0:
  203. is_valid = True
  204. param_name = Parameter.INJECT_AT_TIMESTAMP
  205. value = (ts / 1000000) # convert microseconds from getTimestampMuSec into seconds
  206. # add value iff validation was successful
  207. if is_valid:
  208. self.params[param_name] = value
  209. else:
  210. print("ERROR: Parameter " + str(param) + " or parameter value " + str(value) +
  211. " not valid. Skipping parameter.")
  212. def get_param_value(self, param: Parameter):
  213. """
  214. Returns the parameter value for a given parameter.
  215. :param param: The parameter whose value is wanted.
  216. :return: The parameter's value.
  217. """
  218. return self.params[param]