BaseAttack.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. import abc
  2. import csv
  3. import hashlib
  4. import ipaddress
  5. import math
  6. import os
  7. import random
  8. import random as rnd
  9. import re
  10. import socket
  11. import sys
  12. import tempfile
  13. import time
  14. import collections
  15. import typing as t
  16. import ID2TLib.libpcapreader as pr
  17. import lea
  18. import numpy as np
  19. import scapy.layers.inet as inet
  20. import scapy.utils
  21. import Attack.AttackParameters as atkParam
  22. import ID2TLib.Utility as Util
  23. class BaseAttack(metaclass=abc.ABCMeta):
  24. """
  25. Abstract base class for all attack classes. Provides basic functionalities, like parameter validation.
  26. """
  27. ValuePair = collections.namedtuple('ValuePair', ['value', 'user_specified'])
  28. def __init__(self, name, description, attack_type):
  29. """
  30. To be called within the individual attack class to initialize the required parameters.
  31. :param name: The name of the attack class.
  32. :param description: A short description of the attack.
  33. :param attack_type: The type the attack belongs to, like probing/scanning, malware.
  34. """
  35. # Reference to statistics class
  36. self.statistics = None
  37. # Class fields
  38. self.attack_name = name
  39. self.attack_description = description
  40. self.attack_type = attack_type
  41. self.params = {}
  42. self.supported_params = {}
  43. self.attack_start_utime = 0
  44. self.attack_end_utime = 0
  45. self.start_time = 0
  46. self.finish_time = 0
  47. self.packets = []
  48. self.path_attack_pcap = ""
  49. # get_reply_delay
  50. self.all_min_delays = None
  51. self.all_max_delays = None
  52. self.most_used_mss_value = None
  53. self.most_used_ttl_value = None
  54. self.most_used_win_size = None
  55. def set_statistics(self, statistics):
  56. """
  57. Specify the statistics object that will be used to calculate the parameters of this attack.
  58. The statistics are used to calculate default parameters and to process user supplied
  59. queries.
  60. :param statistics: Reference to a statistics object.
  61. """
  62. self.statistics = statistics
  63. # get_reply_delay
  64. self.all_min_delays = self.statistics.process_db_query("SELECT minDelay FROM conv_statistics LIMIT 500;")
  65. self.all_max_delays = self.statistics.process_db_query("SELECT maxDelay FROM conv_statistics LIMIT 500;")
  66. self.most_used_mss_value = self.statistics.get_most_used_mss_value()
  67. self.most_used_ttl_value = self.statistics.get_most_used_ttl_value()
  68. self.most_used_win_size = self.statistics.get_most_used_win_size()
  69. @abc.abstractmethod
  70. def init_params(self):
  71. """
  72. Initialize all required parameters taking into account user supplied values. If no value is supplied,
  73. or if a user defined query is supplied, use a statistics object to do the calculations.
  74. A call to this function requires a call to 'set_statistics' first.
  75. """
  76. pass
  77. @abc.abstractmethod
  78. def generate_attack_packets(self):
  79. """
  80. Creates the attack packets.
  81. """
  82. pass
  83. @abc.abstractmethod
  84. def generate_attack_pcap(self):
  85. """
  86. Creates a pcap containing the attack packets.
  87. :return: The location of the generated pcap file.
  88. """
  89. pass
  90. ################################################
  91. # HELPER VALIDATION METHODS
  92. # Used to validate the given parameter values
  93. ################################################
  94. @staticmethod
  95. def _is_mac_address(mac_address: t.Union[str, t.List[str]]) -> bool:
  96. """
  97. Verifies if the given string is a valid MAC address.
  98. Accepts the formats 00:80:41:ae:fd:7e and 00-80-41-ae-fd-7e.
  99. :param mac_address: The MAC address as string.
  100. :return: True if the MAC address is valid, otherwise False.
  101. """
  102. pattern = re.compile('^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$', re.MULTILINE)
  103. if isinstance(mac_address, list):
  104. for mac in mac_address:
  105. if re.match(pattern, mac) is None:
  106. return False
  107. else:
  108. if re.match(pattern, mac_address) is None:
  109. return False
  110. return True
  111. @staticmethod
  112. def _is_ip_address(ip_address: t.Union[str, t.List[str]]) -> t.Tuple[bool, t.Union[str, t.List[str]]]:
  113. """
  114. Verifies that the given string or list of IP addresses (strings) is a valid IPv4/IPv6 address.
  115. Accepts comma-separated lists of IP addresses, like "192.169.178.1, 192.168.178.2"
  116. :param ip_address: The IP address(es) as list of strings, comma-separated or dash-separated string.
  117. :return: True if all IP addresses are valid, otherwise False. And a list of IP addresses as string.
  118. """
  119. def append_ips(ip_address_input: t.List[str]) -> t.Tuple[bool, t.List[str]]:
  120. """
  121. Recursive appending function to handle lists and ranges of IP addresses.
  122. :param ip_address_input: The IP address(es) as list of strings, comma-separated or dash-separated string.
  123. :return: List of all given IP addresses.
  124. """
  125. ip_list = []
  126. is_valid = True
  127. for ip in ip_address_input:
  128. if '-' in ip:
  129. ip_range = ip.split('-')
  130. ip_range = Util.get_ip_range(ip_range[0], ip_range[1])
  131. is_valid, ips = append_ips(ip_range)
  132. ip_list.extend(ips)
  133. else:
  134. try:
  135. ipaddress.ip_address(ip)
  136. ip_list.append(ip)
  137. except ValueError:
  138. return False, ip_list
  139. return is_valid, ip_list
  140. # a comma-separated list of IP addresses must be split first
  141. if isinstance(ip_address, str):
  142. ip_address = ip_address.split(',')
  143. result, ip_address_output = append_ips(ip_address)
  144. if len(ip_address_output) == 1:
  145. return result, ip_address_output[0]
  146. else:
  147. return result, ip_address_output
  148. @staticmethod
  149. def _is_port(ports_input: t.Union[t.List[str], t.List[int], str, int])\
  150. -> t.Union[bool, t.Tuple[bool, t.List[t.Union[int, str]]]]:
  151. """
  152. Verifies if the given value is a valid port. Accepts port ranges, like 80-90, 80..99, 80...99.
  153. :param ports_input: The port number as int or string.
  154. :return: True if the port number is valid, otherwise False. If a single port or a comma-separated list of ports
  155. was given, a list of int is returned. If a port range was given, the range is resolved
  156. and a list of int is returned.
  157. """
  158. def _is_invalid_port(num: int) -> bool:
  159. """
  160. Checks whether the port number is invalid.
  161. :param num: The port number as int.
  162. :return: True if the port number is invalid, otherwise False.
  163. """
  164. return num < 1 or num > 65535
  165. if ports_input is None or ports_input is "":
  166. return False
  167. if isinstance(ports_input, str):
  168. ports_input = ports_input.replace(' ', '').split(',')
  169. elif isinstance(ports_input, int):
  170. ports_input = [ports_input]
  171. elif len(ports_input) is 0:
  172. return False
  173. ports_output = []
  174. for port_entry in ports_input:
  175. if isinstance(port_entry, int):
  176. if _is_invalid_port(port_entry):
  177. return False
  178. ports_output.append(port_entry)
  179. # TODO: validate last condition
  180. elif isinstance(port_entry, str) and port_entry.isdigit():
  181. # port_entry describes a single port
  182. port_entry = int(port_entry)
  183. if _is_invalid_port(port_entry):
  184. return False
  185. ports_output.append(port_entry)
  186. elif '-' in port_entry or '..' in port_entry:
  187. # port_entry describes a port range
  188. # allowed format: '1-49151', '1..49151', '1...49151'
  189. match = re.match(r'^([0-9]{1,5})(?:-|\.{2,3})([0-9]{1,5})$', str(port_entry))
  190. # check validity of port range
  191. # and create list of ports derived from given start and end port
  192. (port_start, port_end) = int(match.group(1)), int(match.group(2))
  193. if _is_invalid_port(port_start) or _is_invalid_port(port_end):
  194. return False
  195. else:
  196. ports_list = [i for i in range(port_start, port_end + 1)]
  197. # append ports at ports_output list
  198. ports_output += ports_list
  199. if len(ports_output) == 1:
  200. return True, ports_output[0]
  201. else:
  202. return True, ports_output
  203. @staticmethod
  204. def _is_timestamp(timestamp: str) -> bool:
  205. """
  206. Checks whether the given value is in a valid timestamp format. The accepted format is:
  207. YYYY-MM-DD h:m:s, whereas h, m, s may be one or two digits.
  208. :param timestamp: The timestamp to be checked.
  209. :return: True if the timestamp is valid, otherwise False.
  210. """
  211. is_valid = re.match(r'[0-9]{4}(?:-[0-9]{1,2}){2} (?:[0-9]{1,2}:){2}[0-9]{1,2}', timestamp)
  212. return is_valid is not None
  213. @staticmethod
  214. def _is_boolean(value):
  215. """
  216. Checks whether the given value (string or bool) is a boolean. Strings are valid booleans if they are in:
  217. {y, yes, t, true, on, 1, n, no, f, false, off, 0}.
  218. :param value: The value to be checked.
  219. :return: True if the value is a boolean, otherwise false. And the casted boolean.
  220. """
  221. # If value is already a boolean
  222. if isinstance(value, bool):
  223. return True, value
  224. # If value is a string
  225. # True values are y, yes, t, true, on and 1;
  226. # False values are n, no, f, false, off and 0.
  227. # Raises ValueError if value is anything else.
  228. try:
  229. import distutils.core
  230. import distutils.util
  231. value = bool(distutils.util.strtobool(value.lower()))
  232. is_bool = True
  233. except ValueError:
  234. is_bool = False
  235. return is_bool, value
  236. @staticmethod
  237. def _is_float(value):
  238. """
  239. Checks whether the given value is a float.
  240. :param value: The value to be checked.
  241. :return: True if the value is a float, otherwise False. And the casted float.
  242. """
  243. try:
  244. value = float(value)
  245. return True, value
  246. except ValueError:
  247. return False, value
  248. @staticmethod
  249. def _is_domain(val: str) -> bool:
  250. """
  251. Verifies that the given string is a valid URI.
  252. :param val: The URI as string.
  253. :return: True if URI is valid, otherwise False.
  254. """
  255. domain = re.match(r'^(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+$', val)
  256. return domain is not None
  257. #########################################
  258. # HELPER METHODS
  259. #########################################
  260. @staticmethod
  261. def set_seed(seed):
  262. """
  263. :param seed: The random seed to be set.
  264. """
  265. seed_final = None
  266. if isinstance(seed, int):
  267. seed_final = seed
  268. elif isinstance(seed, str):
  269. if seed.isdigit():
  270. seed_final = int(seed)
  271. else:
  272. hashed_seed = hashlib.sha1(seed.encode()).digest()
  273. seed_final = int.from_bytes(hashed_seed, byteorder="little")
  274. if seed_final:
  275. random.seed(seed_final)
  276. np.random.seed(seed_final & 0xFFFFFFFF)
  277. def set_start_time(self) -> None:
  278. """
  279. Set the current time as global starting time.
  280. """
  281. self.start_time = time.time()
  282. def set_finish_time(self) -> None:
  283. """
  284. Set the current time as global finishing time.
  285. """
  286. self.finish_time = time.time()
  287. def get_packet_generation_time(self) -> float:
  288. """
  289. :return difference between starting and finishing time.
  290. """
  291. return self.finish_time - self.start_time
  292. def add_param_value(self, param, value, user_specified: bool = True) -> None:
  293. """
  294. Adds the pair param : value to the dictionary of attack parameters. Prints and error message and skips the
  295. parameter if the validation fails.
  296. :param param: Name of the parameter that we wish to modify.
  297. :param value: The value we wish to assign to the specified parameter.
  298. :param user_specified: Whether the value was specified by the user (or left default)
  299. :return: None.
  300. """
  301. # by default no param is valid
  302. is_valid = False
  303. # get AttackParameters instance associated with param
  304. # for default values assigned in attack classes, like Parameter.PORT_OPEN
  305. if isinstance(param, atkParam.Parameter):
  306. param_name = param
  307. # for values given by user input, like port.open
  308. else:
  309. # Get Enum key of given string identifier
  310. param_name = atkParam.Parameter(param)
  311. # Get parameter type of attack's required_params
  312. param_type = self.supported_params.get(param_name)
  313. # Verify validity of given value with respect to parameter type
  314. if param_type is None:
  315. print('Parameter ' + str(param_name) + ' not available for chosen attack. Skipping parameter.')
  316. # If value is query -> get value from database
  317. elif param_name != atkParam.Parameter.INTERVAL_SELECT_STRATEGY and self.statistics.is_query(value):
  318. value = self.statistics.process_db_query(value, False)
  319. if value is not None and value is not "":
  320. is_valid = True
  321. else:
  322. print('Error in given parameter value: ' + str(value) + '. Data could not be retrieved.')
  323. # Validate parameter depending on parameter's type
  324. elif param_type == atkParam.ParameterTypes.TYPE_IP_ADDRESS:
  325. is_valid, value = self._is_ip_address(value)
  326. elif param_type == atkParam.ParameterTypes.TYPE_PORT:
  327. is_valid, value = self._is_port(value)
  328. elif param_type == atkParam.ParameterTypes.TYPE_MAC_ADDRESS:
  329. is_valid = self._is_mac_address(value)
  330. elif param_type == atkParam.ParameterTypes.TYPE_INTEGER_POSITIVE:
  331. if isinstance(value, int) and int(value) >= 0:
  332. is_valid = True
  333. elif isinstance(value, str) and value.isdigit() and int(value) >= 0:
  334. is_valid = True
  335. value = int(value)
  336. elif param_type == atkParam.ParameterTypes.TYPE_STRING:
  337. if isinstance(value, str):
  338. is_valid = True
  339. elif param_type == atkParam.ParameterTypes.TYPE_FLOAT:
  340. is_valid, value = self._is_float(value)
  341. # this is required to avoid that the timestamp's microseconds of the first attack packet is '000000'
  342. # but microseconds are only chosen randomly if the given parameter does not already specify it
  343. # e.g. inject.at-timestamp=123456.987654 -> is not changed
  344. # e.g. inject.at-timestamp=123456 -> is changed to: 123456.[random digits]
  345. if param_name == atkParam.Parameter.INJECT_AT_TIMESTAMP and is_valid and ((value - int(value)) == 0):
  346. value = value + random.uniform(0, 0.999999)
  347. elif param_type == atkParam.ParameterTypes.TYPE_TIMESTAMP:
  348. is_valid = self._is_timestamp(value)
  349. elif param_type == atkParam.ParameterTypes.TYPE_BOOLEAN:
  350. is_valid, value = self._is_boolean(value)
  351. elif param_type == atkParam.ParameterTypes.TYPE_PACKET_POSITION:
  352. # This function call is valid only if there is a statistics object available.
  353. if self.statistics is None:
  354. print('Error: Statistics-dependent attack parameter added without setting a statistics object first.')
  355. exit(1)
  356. ts = pr.pcap_processor(self.statistics.pcap_filepath, "False").get_timestamp_mu_sec(int(value))
  357. if 0 <= int(value) <= self.statistics.get_packet_count() and ts >= 0:
  358. is_valid = True
  359. param_name = atkParam.Parameter.INJECT_AT_TIMESTAMP
  360. value = (ts / 1000000) # convert microseconds from getTimestampMuSec into seconds
  361. elif param_type == atkParam.ParameterTypes.TYPE_DOMAIN:
  362. is_valid = self._is_domain(value)
  363. elif param_type == atkParam.ParameterTypes.TYPE_FILEPATH:
  364. is_valid = os.path.isfile(value)
  365. elif param_type == atkParam.ParameterTypes.TYPE_PERCENTAGE:
  366. is_valid_float, value = self._is_float(value)
  367. if is_valid_float:
  368. is_valid = 0 <= value <= 1
  369. else:
  370. is_valid = False
  371. elif param_type == atkParam.ParameterTypes.TYPE_PADDING:
  372. if isinstance(value, int):
  373. is_valid = 0 <= value <= 100
  374. elif isinstance(value, str) and value.isdigit():
  375. value = int(value)
  376. is_valid = 0 <= value <= 100
  377. elif param_type == atkParam.ParameterTypes.TYPE_INTERVAL_SELECT_STRAT:
  378. is_valid = value in {"random", "optimal", "custom"}
  379. # add value iff validation was successful
  380. if is_valid:
  381. self.params[param_name] = self.ValuePair(value, user_specified)
  382. else:
  383. print("ERROR: Parameter " + str(param) + " or parameter value " + str(value) +
  384. " not valid. Skipping parameter.")
  385. def get_param_value(self, param: atkParam.Parameter):
  386. """
  387. Returns the parameter value for a given parameter.
  388. :param param: The parameter whose value is wanted.
  389. :return: The parameter's value.
  390. """
  391. parameter = self.params.get(param)
  392. if parameter is not None:
  393. return parameter.value
  394. else:
  395. return None
  396. def get_param_user_specified(self, param: atkParam.Parameter) -> bool:
  397. """
  398. Returns whether the parameter value was specified by the user for a given parameter.
  399. :param param: The parameter whose user-specified flag is wanted.
  400. :return: The parameter's user-specified flag.
  401. """
  402. parameter = self.params.get(param)
  403. if parameter is not None:
  404. return parameter.user_specified
  405. else:
  406. return False
  407. def check_parameters(self):
  408. """
  409. Checks whether all parameter values are defined. If a value is not defined, the application is terminated.
  410. However, this should not happen as all attack should define default parameter values.
  411. """
  412. # parameters which do not require default values
  413. non_obligatory_params = [atkParam.Parameter.INJECT_AFTER_PACKET, atkParam.Parameter.NUMBER_ATTACKERS]
  414. for param, param_type in self.supported_params.items():
  415. # checks whether all params have assigned values, INJECT_AFTER_PACKET must not be considered because the
  416. # timestamp derived from it is set to Parameter.INJECT_AT_TIMESTAMP
  417. if param not in self.params.keys() and param not in non_obligatory_params:
  418. print("\033[91mCRITICAL ERROR: Attack '" + self.attack_name + "' does not define the parameter '" +
  419. str(param) + "'.\n The attack must define default values for all parameters."
  420. + "\n Cannot continue attack generation.\033[0m")
  421. import sys
  422. sys.exit(0)
  423. def write_attack_pcap(self, packets: list, append_flag: bool = False, destination_path: str = None):
  424. """
  425. Writes the attack's packets into a PCAP file with a temporary filename.
  426. :return: The path of the written PCAP file.
  427. """
  428. # Only check params initially when attack generation starts
  429. if append_flag is False and destination_path is None:
  430. # Check if all req. parameters are set
  431. self.check_parameters()
  432. # Determine destination path
  433. if destination_path is not None and os.path.exists(destination_path):
  434. destination = destination_path
  435. else:
  436. temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.pcap')
  437. destination = temp_file.name
  438. # Write packets into pcap file
  439. pktdump = scapy.utils.PcapWriter(destination, append=append_flag)
  440. pktdump.write(packets)
  441. # Store pcap path and close file objects
  442. pktdump.close()
  443. return destination
  444. def get_reply_delay(self, ip_dst, default=2000):
  445. """
  446. Gets the minimum and the maximum reply delay for all the connections of a specific IP.
  447. :param ip_dst: The IP to reterive its reply delay.
  448. :param default: The default value to return if no delay could be fount. If < 0 raise an exception instead
  449. :return minDelay: minimum delay
  450. :return maxDelay: maximum delay
  451. """
  452. result = self.statistics.process_db_query(
  453. "SELECT AVG(minDelay), AVG(maxDelay) FROM conv_statistics WHERE ipAddressB='" + ip_dst + "';")
  454. if result[0][0] and result[0][1]:
  455. min_delay = result[0][0]
  456. max_delay = result[0][1]
  457. else:
  458. min_delay = np.median(self.all_min_delays)
  459. max_delay = np.median(self.all_max_delays)
  460. if math.isnan(min_delay): # max_delay is nan too then
  461. if default < 0:
  462. raise ValueError("Could not calculate min/max_delay")
  463. min_delay = default
  464. max_delay = default
  465. min_delay = int(min_delay) * 10 ** -6 # convert from micro to seconds
  466. max_delay = int(max_delay) * 10 ** -6
  467. return min_delay, max_delay
  468. @staticmethod
  469. def packets_to_convs(exploit_raw_packets):
  470. """
  471. Classifies a bunch of packets to conversations groups. A conversation is a set of packets go between host A
  472. (IP,port) to host B (IP,port)
  473. :param exploit_raw_packets: A set of packets contains several conversations.
  474. :return conversations: A set of arrays, each array contains the packet of specific conversation
  475. :return orderList_conversations: An array contains the conversations ids (IP_A,port_A, IP_b,port_B) in the
  476. order they appeared in the original packets.
  477. """
  478. conversations = {}
  479. order_list_conversations = []
  480. for pkt_num, pkt in enumerate(exploit_raw_packets):
  481. eth_frame = inet.Ether(pkt[0])
  482. ip_pkt = eth_frame.payload
  483. ip_dst = ip_pkt.getfieldval("dst")
  484. ip_src = ip_pkt.getfieldval("src")
  485. tcp_pkt = ip_pkt.payload
  486. port_dst = tcp_pkt.getfieldval("dport")
  487. port_src = tcp_pkt.getfieldval("sport")
  488. conv_req = (ip_src, port_src, ip_dst, port_dst)
  489. conv_rep = (ip_dst, port_dst, ip_src, port_src)
  490. if conv_req not in conversations and conv_rep not in conversations:
  491. pkt_list = [pkt]
  492. conversations[conv_req] = pkt_list
  493. # Order list of conv
  494. order_list_conversations.append(conv_req)
  495. else:
  496. if conv_req in conversations:
  497. pkt_list = conversations[conv_req]
  498. pkt_list.append(pkt)
  499. conversations[conv_req] = pkt_list
  500. else:
  501. pkt_list = conversations[conv_rep]
  502. pkt_list.append(pkt)
  503. conversations[conv_rep] = pkt_list
  504. return conversations, order_list_conversations
  505. @staticmethod
  506. def is_valid_ip_address(addr):
  507. """
  508. Checks if the IP address family is supported.
  509. :param addr: IP address to be checked.
  510. :return: Boolean
  511. """
  512. try:
  513. socket.inet_aton(addr)
  514. return True
  515. except socket.error:
  516. return False
  517. @staticmethod
  518. def ip_src_dst_equal_check(ip_source, ip_destination):
  519. """
  520. Checks if the source IP and destination IP are equal.
  521. :param ip_source: source IP address.
  522. :param ip_destination: destination IP address.
  523. """
  524. equal = False
  525. if isinstance(ip_source, list) and isinstance(ip_destination, list):
  526. for ip in ip_source:
  527. if ip in ip_destination:
  528. equal = True
  529. elif isinstance(ip_source, list):
  530. if ip_destination in ip_source:
  531. equal = True
  532. elif isinstance(ip_destination, list):
  533. if ip_source in ip_destination:
  534. equal = True
  535. else:
  536. if ip_source == ip_destination:
  537. equal = True
  538. if equal:
  539. print("\nERROR: Invalid IP addresses; source IP is the same as destination IP: " + ip_destination + ".")
  540. sys.exit(0)
  541. @staticmethod
  542. def get_inter_arrival_time(packets, distribution: bool = False):
  543. """
  544. Gets the inter-arrival times array and its distribution of a set of packets.
  545. :param packets: the packets to extract their inter-arrival time.
  546. :param distribution: build distribution dictionary or not
  547. :return inter_arrival_times: array of the inter-arrival times
  548. :return dict: the inter-arrival time distribution as a histogram {inter-arrival time:frequency}
  549. """
  550. inter_arrival_times = []
  551. prvs_pkt_time = 0
  552. for index, pkt in enumerate(packets):
  553. timestamp = pkt[2][0] + pkt[2][1] / 10 ** 6
  554. if index == 0:
  555. prvs_pkt_time = timestamp
  556. inter_arrival_times.append(0)
  557. else:
  558. inter_arrival_times.append(timestamp - prvs_pkt_time)
  559. prvs_pkt_time = timestamp
  560. if distribution:
  561. # Build a distribution dictionary
  562. freq, values = np.histogram(inter_arrival_times, bins=20)
  563. dist_dict = {}
  564. for i, val in enumerate(values):
  565. if i < len(freq):
  566. dist_dict[str(val)] = freq[i]
  567. return inter_arrival_times, dist_dict
  568. else:
  569. return inter_arrival_times
  570. @staticmethod
  571. def clean_white_spaces(str_param):
  572. """
  573. Delete extra backslash from white spaces. This function is used to process the payload of packets.
  574. :param str_param: the payload to be processed.
  575. """
  576. str_param = str_param.replace("\\n", "\n")
  577. str_param = str_param.replace("\\r", "\r")
  578. str_param = str_param.replace("\\t", "\t")
  579. str_param = str_param.replace("\\\'", "\'")
  580. return str_param
  581. def modify_http_header(self, str_tcp_seg, orig_target_uri, target_uri, orig_ip_dst, target_host):
  582. """
  583. Substitute the URI and HOST in a HTTP header with new values.
  584. :param str_tcp_seg: the payload to be processed.
  585. :param orig_target_uri: old URI
  586. :param target_uri: new URI
  587. :param orig_ip_dst: old host
  588. :param target_host: new host
  589. """
  590. if len(str_tcp_seg) > 0:
  591. # convert payload bytes to str => str = "b'..\\r\\n..'"
  592. str_tcp_seg = str_tcp_seg[2:-1]
  593. str_tcp_seg = str_tcp_seg.replace(orig_target_uri, target_uri)
  594. str_tcp_seg = str_tcp_seg.replace(orig_ip_dst, target_host)
  595. str_tcp_seg = self.clean_white_spaces(str_tcp_seg)
  596. return str_tcp_seg
  597. def get_ip_data(self, ip_address: str):
  598. """
  599. :param ip_address: the ip of which (packet-)data shall be returned
  600. :return: MSS, TTL and Window Size values of the given IP
  601. """
  602. # Set MSS (Maximum Segment Size) based on MSS distribution of IP address
  603. mss_dist = self.statistics.get_mss_distribution(ip_address)
  604. if len(mss_dist) > 0:
  605. mss_prob_dict = lea.Lea.fromValFreqsDict(mss_dist)
  606. mss_value = mss_prob_dict.random()
  607. else:
  608. mss_value = Util.handle_most_used_outputs(self.most_used_mss_value)
  609. # Set TTL based on TTL distribution of IP address
  610. ttl_dist = self.statistics.get_ttl_distribution(ip_address)
  611. if len(ttl_dist) > 0:
  612. ttl_prob_dict = lea.Lea.fromValFreqsDict(ttl_dist)
  613. ttl_value = ttl_prob_dict.random()
  614. else:
  615. ttl_value = Util.handle_most_used_outputs(self.most_used_ttl_value)
  616. # Set Window Size based on Window Size distribution of IP address
  617. win_dist = self.statistics.get_win_distribution(ip_address)
  618. if len(win_dist) > 0:
  619. win_prob_dict = lea.Lea.fromValFreqsDict(win_dist)
  620. win_value = win_prob_dict.random()
  621. else:
  622. win_value = Util.handle_most_used_outputs(self.most_used_win_size)
  623. return mss_value, ttl_value, win_value
  624. #########################################
  625. # RANDOM IP/MAC ADDRESS GENERATORS
  626. #########################################
  627. @staticmethod
  628. def generate_random_ipv4_address(ip_class, n: int = 1):
  629. # TODO: document ip_class
  630. """
  631. Generates n random IPv4 addresses.
  632. :param ip_class:
  633. :param n: The number of IP addresses to be generated
  634. :return: A single IP address, or if n>1, a list of IP addresses
  635. """
  636. def is_invalid(ip_address_param: ipaddress.IPv4Address):
  637. """
  638. TODO FILL ME
  639. :param ip_address_param:
  640. :return:
  641. """
  642. return ip_address_param.is_multicast or ip_address_param.is_unspecified or ip_address_param.is_loopback or \
  643. ip_address_param.is_link_local or ip_address_param.is_reserved or ip_address_param.is_private
  644. # Generate a random IP from specific class
  645. def generate_address(ip_class_param):
  646. """
  647. TODO FILL ME
  648. :param ip_class_param:
  649. :return:
  650. """
  651. if ip_class_param == "Unknown":
  652. return ipaddress.IPv4Address(random.randint(0, 2 ** 32 - 1))
  653. else:
  654. # For DDoS attack, we do not generate private IPs
  655. if "private" in ip_class_param:
  656. ip_class_param = ip_class_param[0] # convert A-private to A
  657. ip_classes_byte1 = {"A": {1, 126}, "B": {128, 191}, "C": {192, 223}, "D": {224, 239}, "E": {240, 254}}
  658. temp = list(ip_classes_byte1[ip_class_param])
  659. min_b1 = temp[0]
  660. max_b1 = temp[1]
  661. b1 = random.randint(min_b1, max_b1)
  662. b2 = random.randint(1, 255)
  663. b3 = random.randint(1, 255)
  664. b4 = random.randint(1, 255)
  665. ip_address = ipaddress.IPv4Address(str(b1) + "." + str(b2) + "." + str(b3) + "." + str(b4))
  666. return ip_address
  667. ip_addresses = []
  668. for i in range(0, n):
  669. address = generate_address(ip_class)
  670. while is_invalid(address):
  671. address = generate_address(ip_class)
  672. ip_addresses.append(str(address))
  673. if n == 1:
  674. return ip_addresses[0]
  675. else:
  676. return ip_addresses
  677. @staticmethod
  678. def generate_random_ipv6_address(n: int = 1):
  679. """
  680. Generates n random IPv6 addresses.
  681. :param n: The number of IP addresses to be generated
  682. :return: A single IP address, or if n>1, a list of IP addresses
  683. """
  684. def is_invalid(ip_address: ipaddress.IPv6Address):
  685. """
  686. TODO FILL ME
  687. :param ip_address:
  688. :return:
  689. """
  690. return ip_address.is_multicast or ip_address.is_unspecified or ip_address.is_loopback or \
  691. ip_address.is_link_local or ip_address.is_private or ip_address.is_reserved
  692. def generate_address():
  693. """
  694. TODO FILL ME
  695. :return:
  696. """
  697. return ipaddress.IPv6Address(random.randint(0, 2 ** 128 - 1))
  698. ip_addresses = []
  699. for i in range(0, n):
  700. address = generate_address()
  701. while is_invalid(address):
  702. address = generate_address()
  703. ip_addresses.append(str(address))
  704. if n == 1:
  705. return ip_addresses[0]
  706. else:
  707. return ip_addresses
  708. @staticmethod
  709. def generate_random_mac_address(n: int = 1):
  710. """
  711. Generates n random MAC addresses.
  712. :param n: The number of MAC addresses to be generated.
  713. :return: A single MAC address, or if n>1, a list of MAC addresses
  714. """
  715. def is_invalid(address_param: str):
  716. first_octet = int(address_param[0:2], 16)
  717. is_multicast_address = bool(first_octet & 0b01)
  718. is_locally_administered = bool(first_octet & 0b10)
  719. return is_multicast_address or is_locally_administered
  720. def generate_address():
  721. # FIXME: cleanup
  722. mac = [random.randint(0x00, 0xff) for i in range(0, 6)]
  723. return ':'.join(map(lambda x: "%02x" % x, mac))
  724. mac_addresses = []
  725. for i in range(0, n):
  726. address = generate_address()
  727. while is_invalid(address):
  728. address = generate_address()
  729. mac_addresses.append(address)
  730. if n == 1:
  731. return mac_addresses[0]
  732. else:
  733. return mac_addresses
  734. @staticmethod
  735. def get_ports_from_nmap_service_dst(ports_num):
  736. """
  737. Read the most ports_num frequently open ports from nmap-service-tcp file to be used in the port scan.
  738. :return: Ports numbers to be used as default destination ports or default open ports in the port scan.
  739. """
  740. ports_dst = []
  741. file = open(Util.RESOURCE_DIR + 'nmap-services-tcp.csv', 'rt')
  742. spamreader = csv.reader(file, delimiter=',')
  743. for count in range(ports_num):
  744. # escape first row (header)
  745. next(spamreader)
  746. # save ports numbers
  747. ports_dst.append(next(spamreader)[0])
  748. file.close()
  749. # rnd.shuffle ports numbers partially
  750. if ports_num == 1000: # used for port.dst
  751. # FIXME: cleanup
  752. temp_array = [[0 for i in range(10)] for i in range(100)]
  753. port_dst_shuffled = []
  754. for count in range(0, 10):
  755. temp_array[count] = ports_dst[count * 100:(count + 1) * 100]
  756. rnd.shuffle(temp_array[count])
  757. port_dst_shuffled += temp_array[count]
  758. else: # used for port.open
  759. rnd.shuffle(ports_dst)
  760. port_dst_shuffled = ports_dst
  761. return port_dst_shuffled