3
0

BaseAttack.py 28 KB

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