BaseAttack.py 29 KB

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