BaseAttack.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import ipaddress
  2. import random
  3. import re
  4. from abc import abstractmethod, ABCMeta
  5. import ID2TLib.libpcapreader as pr
  6. from Attack import AttackParameters
  7. from Attack.AttackParameters import Parameter
  8. from Attack.AttackParameters import ParameterTypes
  9. class BaseAttack(metaclass=ABCMeta):
  10. """
  11. Abstract base class for all attack classes. Provides basic functionalities, like parameter validation.
  12. """
  13. def __init__(self, statistics, name, description, attack_type):
  14. """
  15. To be called within the individual attack class to initialize the required parameters.
  16. :param statistics: A reference to the Statistics class.
  17. :param name: The name of the attack class.
  18. :param description: A short description of the attack.
  19. :param attack_type: The type the attack belongs to, like probing/scanning, malware.
  20. """
  21. # Reference to statistics class
  22. self.statistics = statistics
  23. # Class fields
  24. self.attack_name = name
  25. self.attack_description = description
  26. self.attack_type = attack_type
  27. self.params = {}
  28. self.supported_params = {}
  29. self.attack_start_utime = 0
  30. self.attack_end_utime = 0
  31. @abstractmethod
  32. def get_packets(self):
  33. """
  34. Creates the packets containing the attack.
  35. :return: A list of packets ordered ascending by the packet's timestamp.
  36. """
  37. pass
  38. ################################################
  39. # HELPER VALIDATION METHODS
  40. # Used to validate the given parameter values
  41. ################################################
  42. @staticmethod
  43. def _is_mac_address(mac_address: str):
  44. """
  45. 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.
  46. :param mac_address: The MAC address as string.
  47. :return: True if the MAC address is valid, otherwise False.
  48. """
  49. pattern = re.compile('^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$', re.MULTILINE)
  50. if isinstance(mac_address, list):
  51. for mac in mac_address:
  52. if re.match(pattern, mac) is None:
  53. return False
  54. else:
  55. if re.match(pattern, mac_address) is None:
  56. return False
  57. return True
  58. @staticmethod
  59. def _is_ip_address(ip_address: str):
  60. """
  61. Verifies that the given string or list of IP addresses (strings) is a valid IPv4/IPv6 address.
  62. Accepts comma-separated lists of IP addresses, like "192.169.178.1, 192.168.178.2"
  63. :param ip_address: The IP address(es) as list of strings or comma-separated string.
  64. :return: True if all IP addresses are valid, otherwise False. And a list of IP addresses as string.
  65. """
  66. ip_address_output = []
  67. # a comma-separated list of IP addresses must be splitted first
  68. if isinstance(ip_address, str):
  69. ip_address = ip_address.split(',')
  70. for ip in ip_address:
  71. try:
  72. ipaddress.ip_address(ip)
  73. ip_address_output.append(ip)
  74. except ValueError:
  75. return False, ip_address_output
  76. if len(ip_address_output) == 1:
  77. return True, ip_address_output[0]
  78. else:
  79. return True, ip_address_output
  80. @staticmethod
  81. def _is_port(ports_input: str):
  82. """
  83. Verifies if the given value is a valid port. Accepts port ranges, like 80-90, 80..99, 80...99.
  84. :param ports_input: The port number as int or string.
  85. :return: True if the port number is valid, otherwise False. If a single port or a comma-separated list of ports
  86. was given, a list of int is returned. If a port range was given, the range is resolved
  87. and a list of int is returned.
  88. """
  89. def _is_invalid_port(num):
  90. """
  91. Checks whether the port number is invalid.
  92. :param num: The port number as int.
  93. :return: True if the port number is invalid, otherwise False.
  94. """
  95. return num < 0 or num > 65535
  96. if isinstance(ports_input, str):
  97. ports_input = ports_input.replace(' ', '').split(',')
  98. elif isinstance(ports_input, int):
  99. ports_input = [ports_input]
  100. ports_output = []
  101. for port_entry in ports_input:
  102. if isinstance(port_entry, int):
  103. if _is_invalid_port(port_entry):
  104. return False
  105. ports_output.append(port_entry)
  106. elif isinstance(port_entry, str) and port_entry.isdigit():
  107. # port_entry describes a single port
  108. port_entry = int(port_entry)
  109. if _is_invalid_port(port_entry):
  110. return False
  111. ports_output.append(port_entry)
  112. elif '-' in port_entry or '..' in port_entry:
  113. # port_entry describes a port range
  114. # allowed format: '1-49151', '1..49151', '1...49151'
  115. match = re.match('^([0-9]{1,5})(?:-|\.{2,3})([0-9]{1,5})$', port_entry)
  116. # check validity of port range
  117. # and create list of ports derived from given start and end port
  118. (port_start, port_end) = int(match.group(1)), int(match.group(2))
  119. if _is_invalid_port(port_start) or _is_invalid_port(port_end):
  120. return False
  121. else:
  122. ports_list = [i for i in range(port_start, port_end + 1)]
  123. # append ports at ports_output list
  124. ports_output += ports_list
  125. if len(ports_output) == 1:
  126. return True, ports_output[0]
  127. else:
  128. return True, ports_output
  129. @staticmethod
  130. def _is_timestamp(timestamp: str):
  131. """
  132. Checks whether the given value is in a valid timestamp format. The accepted format is:
  133. YYYY-MM-DD h:m:s, whereas h, m, s may be one or two digits.
  134. :param timestamp: The timestamp to be checked.
  135. :return: True if the timestamp is valid, otherwise False.
  136. """
  137. is_valid = re.match('[0-9]{4}(?:-[0-9]{1,2}){2} (?:[0-9]{1,2}:){2}[0-9]{1,2}', timestamp)
  138. return is_valid is not None
  139. @staticmethod
  140. def _is_boolean(value):
  141. """
  142. Checks whether the given value (string or bool) is a boolean. Strings are valid booleans if they are in:
  143. {y, yes, t, true, on, 1, n, no, f, false, off, 0}.
  144. :param value: The value to be checked.
  145. :return: True if the value is a boolean, otherwise false. And the casted boolean.
  146. """
  147. # If value is already a boolean
  148. if isinstance(value, bool):
  149. return True, value
  150. # If value is a string
  151. # True values are y, yes, t, true, on and 1;
  152. # False values are n, no, f, false, off and 0.
  153. # Raises ValueError if value is anything else.
  154. try:
  155. import distutils.core
  156. value = distutils.util.strtobool(value.lower())
  157. is_bool = True
  158. except ValueError:
  159. is_bool = False
  160. return is_bool, value
  161. @staticmethod
  162. def _is_float(value):
  163. """
  164. Checks whether the given value is a float.
  165. :param value: The value to be checked.
  166. :return: True if the value is a float, otherwise False. And the casted float.
  167. """
  168. try:
  169. value = float(value)
  170. return True, value
  171. except ValueError:
  172. return False, value
  173. #########################################
  174. # HELPER METHODS
  175. #########################################
  176. def add_param_value(self, param, value):
  177. """
  178. Adds the pair param : value to the dictionary of attack parameters. Prints and error message and skips the
  179. parameter if the validation fails.
  180. :param param: The parameter name.
  181. :param value: The parameter's value.
  182. :return: None.
  183. """
  184. # by default no param is valid
  185. is_valid = False
  186. # get AttackParameters instance associated with param
  187. # for default values assigned in attack classes, like Parameter.PORT_OPEN
  188. if isinstance(param, AttackParameters.Parameter):
  189. param_name = param
  190. # for values given by user input, like port.open
  191. else:
  192. # Get Enum key of given string identifier
  193. param_name = AttackParameters.Parameter(param)
  194. # Get parameter type of attack's required_params
  195. param_type = self.supported_params.get(param_name)
  196. # Verify validity of given value with respect to parameter type
  197. if param_type is None:
  198. print('Parameter ' + str(param_name) + ' not available for chosen attack. Skipping parameter.')
  199. # If value is query -> get value from database
  200. elif self.statistics.is_query(value):
  201. value = self.statistics.process_db_query(value, False)
  202. if value is not None and value is not "":
  203. is_valid = True
  204. else:
  205. print('Error in given parameter value: ' + value + '. Data could not be retrieved.')
  206. # Validate parameter depending on parameter's type
  207. elif param_type == ParameterTypes.TYPE_IP_ADDRESS:
  208. is_valid, value = self._is_ip_address(value)
  209. elif param_type == ParameterTypes.TYPE_PORT:
  210. is_valid, value = self._is_port(value)
  211. elif param_type == ParameterTypes.TYPE_MAC_ADDRESS:
  212. is_valid = self._is_mac_address(value)
  213. elif param_type == ParameterTypes.TYPE_INTEGER_POSITIVE:
  214. if isinstance(value, int) and int(value) >= 0:
  215. is_valid = True
  216. elif isinstance(value, str) and value.isdigit() and int(value) >= 0:
  217. is_valid = True
  218. value = int(value)
  219. elif param_type == ParameterTypes.TYPE_FLOAT:
  220. is_valid, value = self._is_float(value)
  221. # this is required to avoid that the timestamp's microseconds of the first attack packet is '000000'
  222. # but microseconds are only chosen randomly if the given parameter does not already specify it
  223. # e.g. inject.at-timestamp=123456.987654 -> is not changed
  224. # e.g. inject.at-timestamp=123456 -> is changed to: 123456.[random digits]
  225. if param_name == Parameter.INJECT_AT_TIMESTAMP and is_valid and ((value - int(value)) == 0):
  226. value = value + random.uniform(0, 0.999999)
  227. elif param_type == ParameterTypes.TYPE_TIMESTAMP:
  228. is_valid = self._is_timestamp(value)
  229. elif param_type == ParameterTypes.TYPE_BOOLEAN:
  230. is_valid, value = self._is_boolean(value)
  231. elif param_type == ParameterTypes.TYPE_PACKET_POSITION:
  232. ts = pr.pcap_processor(self.statistics.pcap_filepath).get_timestamp_mu_sec(int(value))
  233. if 0 <= int(value) <= self.statistics.get_packet_count() and ts >= 0:
  234. is_valid = True
  235. param_name = Parameter.INJECT_AT_TIMESTAMP
  236. value = (ts / 1000000) # convert microseconds from getTimestampMuSec into seconds
  237. # add value iff validation was successful
  238. if is_valid:
  239. self.params[param_name] = value
  240. else:
  241. print("ERROR: Parameter " + str(param) + " or parameter value " + str(value) +
  242. " not valid. Skipping parameter.")
  243. def get_param_value(self, param: Parameter):
  244. """
  245. Returns the parameter value for a given parameter.
  246. :param param: The parameter whose value is wanted.
  247. :return: The parameter's value.
  248. """
  249. return self.params.get(param)
  250. def check_parameters(self):
  251. """
  252. Checks whether all parameter values are defined. If a value is not defined, the application is terminated.
  253. However, this should not happen as all attack should define default parameter values.
  254. """
  255. # parameters which do not require default values
  256. non_obligatory_params = [Parameter.INJECT_AFTER_PACKET, Parameter.NUMBER_ATTACKERS]
  257. for param, type in self.supported_params.items():
  258. # checks whether all params have assigned values, INJECT_AFTER_PACKET must not be considered because the
  259. # timestamp derived from it is set to Parameter.INJECT_AT_TIMESTAMP
  260. if param not in self.params.keys() and param not in non_obligatory_params:
  261. print("\033[91mCRITICAL ERROR: Attack '" + self.attack_name + "' does not define the parameter '" +
  262. str(param) + "'.\n The attack must define default values for all parameters."
  263. + "\n Cannot continue attack generation.\033[0m")
  264. import sys
  265. sys.exit(0)
  266. @staticmethod
  267. def generate_random_ipv4_address(n: int = 1):
  268. """
  269. Generates n random IPv4 addresses.
  270. :param n: The number of IP addresses to be generated
  271. :return: A single IP address, or if n>1, a list of IP addresses
  272. """
  273. def is_invalid(ipAddress: ipaddress.IPv4Address):
  274. return ipAddress.is_multicast or ipAddress.is_unspecified or ipAddress.is_loopback or \
  275. ipAddress.is_link_local or ipAddress.is_private or ipAddress.is_reserved
  276. def generate_address():
  277. return ipaddress.IPv4Address(random.randint(0, 2 ** 32 - 1))
  278. ip_addresses = []
  279. for i in range(0, n):
  280. address = generate_address()
  281. while is_invalid(address):
  282. address = generate_address()
  283. ip_addresses.append(str(address))
  284. if n == 1:
  285. return ip_addresses[0]
  286. else:
  287. return ip_addresses
  288. @staticmethod
  289. def generate_random_ipv6_address(n: int = 1):
  290. """
  291. Generates n random IPv6 addresses.
  292. :param n: The number of IP addresses to be generated
  293. :return: A single IP address, or if n>1, a list of IP addresses
  294. """
  295. def is_invalid(ipAddress: ipaddress.IPv6Address):
  296. return ipAddress.is_multicast or ipAddress.is_unspecified or ipAddress.is_loopback or \
  297. ipAddress.is_link_local or ipAddress.is_private or ipAddress.is_reserved
  298. def generate_address():
  299. return ipaddress.IPv6Address(random.randint(0, 2 ** 128 - 1))
  300. ip_addresses = []
  301. for i in range(0, n):
  302. address = generate_address()
  303. while is_invalid(address):
  304. address = generate_address()
  305. ip_addresses.append(str(address))
  306. if n == 1:
  307. return ip_addresses[0]
  308. else:
  309. return ip_addresses
  310. @staticmethod
  311. def generate_random_mac_address(n: int = 1):
  312. """
  313. Generates n random MAC addresses.
  314. :param n: The number of MAC addresses to be generated.
  315. :return: A single MAC addres, or if n>1, a list of MAC addresses
  316. """
  317. def is_invalid(address: str):
  318. first_octet = int(address[0:2], 16)
  319. is_multicast_address = bool(first_octet & 0b01)
  320. is_locally_administered = bool(first_octet & 0b10)
  321. return is_multicast_address or is_locally_administered
  322. def generate_address():
  323. mac = [random.randint(0x00, 0xff) for i in range(0, 6)]
  324. return ':'.join(map(lambda x: "%02x" % x, mac))
  325. mac_addresses = []
  326. for i in range(0, n):
  327. address = generate_address()
  328. while is_invalid(address):
  329. address = generate_address()
  330. mac_addresses.append(address)
  331. if n == 1:
  332. return mac_addresses[0]
  333. else:
  334. return mac_addresses