BaseAttack.py 19 KB

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