BaseAttack.py 29 KB

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