BaseAttack_REMOTE_3007.py 18 KB

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