BaseAttack.py 31 KB

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