Utility.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import calendar as cal
  2. import datetime as dt
  3. import ipaddress
  4. import os
  5. import random as rnd
  6. import matplotlib
  7. import scipy.stats as stats
  8. matplotlib.use('Agg', force=True)
  9. import lea
  10. import xdg.BaseDirectory as BaseDir
  11. import scapy.layers.inet as inet
  12. CACHE_DIR = os.path.join(BaseDir.xdg_cache_home, 'id2t')
  13. CODE_DIR = os.path.dirname(os.path.abspath(__file__)) + "/../"
  14. ROOT_DIR = CODE_DIR + "../"
  15. RESOURCE_DIR = ROOT_DIR + "resources/"
  16. TEST_DIR = RESOURCE_DIR + "test/"
  17. platforms = {"win7", "win10", "winxp", "win8.1", "macos", "linux", "win8", "winvista", "winnt", "win2000"}
  18. platform_probability = {"win7": 48.43, "win10": 27.99, "winxp": 6.07, "win8.1": 6.07, "macos": 5.94, "linux": 3.38,
  19. "win8": 1.35, "winvista": 0.46, "winnt": 0.31}
  20. x86_nops = {b'\x90', b'\xfc', b'\xfd', b'\xf8', b'\xf9', b'\xf5', b'\x9b'}
  21. x86_pseudo_nops = {b'\x97', b'\x96', b'\x95', b'\x93', b'\x92', b'\x91', b'\x99', b'\x4d', b'\x48', b'\x47', b'\x4f',
  22. b'\x40', b'\x41', b'\x37', b'\x3f', b'\x27', b'\x2f', b'\x46', b'\x4e', b'\x98', b'\x9f', b'\x4a',
  23. b'\x44', b'\x42', b'\x43', b'\x49', b'\x4b', b'\x45', b'\x4c', b'\x60', b'\x0e', b'\x1e', b'\x50',
  24. b'\x55', b'\x53', b'\x51', b'\x57', b'\x52', b'\x06', b'\x56', b'\x54', b'\x16', b'\x58', b'\x5d',
  25. b'\x5b', b'\x59', b'\x5f', b'\x5a', b'\x5e', b'\xd6'}
  26. forbidden_chars = [b'\x00', b'\x0a', b'\x0d']
  27. attacker_port_mapping = {}
  28. attacker_ttl_mapping = {}
  29. def update_timestamp(timestamp, pps, delay=0):
  30. """
  31. Calculates the next timestamp to be used based on the packet per second rate (pps) and the maximum delay.
  32. :return: Timestamp to be used for the next packet.
  33. """
  34. if delay == 0:
  35. # Calculate request timestamp
  36. # To imitate the bursty behavior of traffic
  37. randomdelay = lea.Lea.fromValFreqsDict({1 / pps: 70, 2 / pps: 20, 5 / pps: 7, 10 / pps: 3})
  38. return timestamp + rnd.uniform(1 / pps, randomdelay.random())
  39. else:
  40. # Calculate reply timestamp
  41. randomdelay = lea.Lea.fromValFreqsDict({2 * delay: 70, 3 * delay: 20, 5 * delay: 7, 10 * delay: 3})
  42. return timestamp + rnd.uniform(1 / pps + delay, 1 / pps + randomdelay.random())
  43. def get_interval_pps(complement_interval_pps, timestamp):
  44. """
  45. Gets the packet rate (pps) for a specific time interval.
  46. :param complement_interval_pps: an array of tuples (the last timestamp in the interval, the packet rate in the
  47. corresponding interval).
  48. :param timestamp: the timestamp at which the packet rate is required.
  49. :return: the corresponding packet rate (pps) .
  50. """
  51. for row in complement_interval_pps:
  52. if timestamp <= row[0]:
  53. return row[1]
  54. return complement_interval_pps[-1][1] # in case the timstamp > capture max timestamp
  55. def get_nth_random_element(*element_list):
  56. """
  57. Returns the n-th element of every list from an arbitrary number of given lists.
  58. For example, list1 contains IP addresses, list 2 contains MAC addresses. Use of this function ensures that
  59. the n-th IP address uses always the n-th MAC address.
  60. :param element_list: An arbitrary number of lists.
  61. :return: A tuple of the n-th element of every list.
  62. """
  63. if len(element_list) <= 0:
  64. return None
  65. elif len(element_list) == 1 and len(element_list[0]) > 0:
  66. return rnd.choice(element_list[0])
  67. else:
  68. range_max = min([len(x) for x in element_list])
  69. if range_max > 0:
  70. range_max -= 1
  71. n = rnd.randint(0, range_max)
  72. return tuple(x[n] for x in element_list)
  73. else:
  74. return None
  75. def get_rnd_os():
  76. """
  77. Chooses random platform over an operating system probability distribution
  78. :return: random platform as string
  79. """
  80. os_dist = lea.Lea.fromValFreqsDict(platform_probability)
  81. return os_dist.random()
  82. def check_platform(platform: str):
  83. """
  84. Checks if the given platform is currently supported
  85. if not exits with error
  86. :param platform: the platform, which should be validated
  87. """
  88. if platform not in platforms:
  89. print("\nERROR: Invalid platform: " + platform + "." +
  90. "\n Please select one of the following platforms: ", platforms)
  91. exit(1)
  92. def get_ip_range(start_ip: str, end_ip: str):
  93. """
  94. Generates a list of IPs of a given range. If the start_ip is greater than the end_ip, the reverse range is generated
  95. :param start_ip: the start_ip of the desired IP-range
  96. :param end_ip: the end_ip of the desired IP-range
  97. :return: a list of all IPs in the desired IP-range, including start-/end_ip
  98. """
  99. start = ipaddress.ip_address(start_ip)
  100. end = ipaddress.ip_address(end_ip)
  101. ips = []
  102. if start < end:
  103. while start <= end:
  104. ips.append(start.exploded)
  105. start = start + 1
  106. elif start > end:
  107. while start >= end:
  108. ips.append(start.exploded)
  109. start = start - 1
  110. else:
  111. ips.append(start_ip)
  112. return ips
  113. def generate_source_port_from_platform(platform: str, previous_port=0):
  114. """
  115. Generates the next source port according to the TCP-port-selection strategy of the given platform
  116. :param platform: the platform for which to generate source ports
  117. :param previous_port: the previously used/generated source port. Must be 0 if no port was generated before
  118. :return: the next source port for the given platform
  119. """
  120. check_platform(platform)
  121. if platform in {"winnt", "winxp", "win2000"}:
  122. if (previous_port == 0) or (previous_port + 1 > 5000):
  123. return rnd.randint(1024, 5000)
  124. else:
  125. return previous_port + 1
  126. elif platform == "linux":
  127. return rnd.randint(32768, 61000)
  128. else:
  129. if (previous_port == 0) or (previous_port + 1 > 65535):
  130. return rnd.randint(49152, 65535)
  131. else:
  132. return previous_port + 1
  133. def get_filetime_format(timestamp):
  134. """
  135. Converts a timestamp into MS FILETIME format
  136. :param timestamp: a timestamp in seconds
  137. :return: MS FILETIME timestamp
  138. """
  139. boot_datetime = dt.datetime.fromtimestamp(timestamp)
  140. if boot_datetime.tzinfo is None or boot_datetime.tzinfo.utcoffset(boot_datetime) is None:
  141. boot_datetime = boot_datetime.replace(tzinfo=boot_datetime.tzname())
  142. boot_filetime = 116444736000000000 + (cal.timegm(boot_datetime.timetuple()) * 10000000)
  143. return boot_filetime + (boot_datetime.microsecond * 10)
  144. def get_rnd_boot_time(timestamp, platform="winxp"):
  145. """
  146. Generates a random boot time based on a given timestamp and operating system
  147. :param timestamp: a timestamp in seconds
  148. :param platform: a platform as string as specified in check_platform above. default is winxp. this param is optional
  149. :return: timestamp of random boot time in seconds since EPOCH
  150. """
  151. check_platform(platform)
  152. if platform is "linux":
  153. uptime_in_days = lea.Lea.fromValFreqsDict({3: 50, 7: 25, 14: 12.5, 31: 6.25, 92: 3.125, 183: 1.5625,
  154. 365: 0.78125, 1461: 0.390625, 2922: 0.390625})
  155. elif platform is "macos":
  156. uptime_in_days = lea.Lea.fromValFreqsDict({7: 50, 14: 25, 31: 12.5, 92: 6.25, 183: 3.125, 365: 3.076171875,
  157. 1461: 0.048828125})
  158. else:
  159. uptime_in_days = lea.Lea.fromValFreqsDict({3: 50, 7: 25, 14: 12.5, 31: 6.25, 92: 3.125, 183: 1.5625,
  160. 365: 0.78125, 1461: 0.78125})
  161. timestamp -= rnd.randint(0, uptime_in_days.random() * 86400)
  162. return timestamp
  163. def get_rnd_x86_nop(count=1, side_effect_free=False, char_filter=set()):
  164. """
  165. Generates a specified number of x86 single-byte (pseudo-)NOPs
  166. :param count: The number of bytes to generate
  167. :param side_effect_free: Determines whether NOPs with side-effects (to registers or the stack) are allowed
  168. :param char_filter: A set of bytes which are forbidden to generate
  169. :return: Random x86 NOP bytestring
  170. """
  171. result = b''
  172. nops = x86_nops.copy()
  173. if not side_effect_free:
  174. nops |= x86_pseudo_nops.copy()
  175. if not isinstance(char_filter, set):
  176. char_filter = set(char_filter)
  177. nops = list(nops - char_filter)
  178. for i in range(0, count):
  179. result += nops[rnd.randint(0, len(nops) - 1)]
  180. return result
  181. def get_rnd_bytes(count=1, ignore=None):
  182. """
  183. Generates a specified number of random bytes while excluding unwanted bytes
  184. :param count: Number of wanted bytes
  185. :param ignore: The bytes, which should be ignored, as an array
  186. :return: Random bytestring
  187. """
  188. if ignore is None:
  189. ignore = []
  190. result = b''
  191. for i in range(0, count):
  192. char = os.urandom(1)
  193. while char in ignore:
  194. char = os.urandom(1)
  195. result += char
  196. return result
  197. def check_payload_len(payload_len: int, limit: int):
  198. """
  199. Checks if the len of the payload exceeds a given limit
  200. :param payload_len: The length of the payload
  201. :param limit: The limit of the length of the payload which is allowed
  202. """
  203. if payload_len > limit:
  204. print("\nCustom payload too long: ", payload_len, " bytes. Should be a maximum of ", limit, " bytes.")
  205. exit(1)
  206. def get_bytes_from_file(filepath):
  207. """
  208. Converts the content of a file into its byte representation
  209. The content of the file can either be a string or hexadecimal numbers/bytes (e.g. shellcode)
  210. The file must have the keyword "str" or "hex" in its first line to specify the rest of the content
  211. If the content is hex, whitespaces, backslashes, "x", quotation marks and "+" are removed
  212. Example for a hexadecimal input file:
  213. hex
  214. "abcd ef \xff10\ff 'xaa' x \ ab"
  215. Output: b'\xab\xcd\xef\xff\x10\xff\xaa\xab'
  216. :param filepath: The path of the file from which to get the bytes
  217. :return: The bytes of the file (either a byte representation of a string or the bytes contained in the file)
  218. """
  219. try:
  220. file = open(filepath)
  221. result_bytes = b''
  222. header = file.readline().strip()
  223. content = file.read()
  224. if header == "hex":
  225. content = content.replace(" ", "").replace("\n", "").replace("\\", "").replace("x", "").replace("\"", "") \
  226. .replace("'", "").replace("+", "").replace("\r", "")
  227. try:
  228. result_bytes = bytes.fromhex(content)
  229. except ValueError:
  230. print("\nERROR: Content of file is not all hexadecimal.")
  231. file.close()
  232. exit(1)
  233. elif header == "str":
  234. result_bytes = content.strip().encode()
  235. else:
  236. print("\nERROR: Invalid header found: " + header + ". Try 'hex' or 'str' followed by endline instead.")
  237. file.close()
  238. exit(1)
  239. for forbidden_char in forbidden_chars:
  240. if forbidden_char in result_bytes:
  241. print("\nERROR: Forbidden character found in payload: ", forbidden_char)
  242. file.close()
  243. exit(1)
  244. file.close()
  245. return result_bytes
  246. except FileNotFoundError:
  247. print("\nERROR: File not found: ", filepath)
  248. exit(1)
  249. def handle_most_used_outputs(most_used_x):
  250. """
  251. :param most_used_x: Element or list (e.g. from SQL-query output) which should only be one element
  252. :return: most_used_x if it's not a list. The first element of most_used_x after being sorted if it's a list.
  253. None if that list is empty.
  254. """
  255. if isinstance(most_used_x, list):
  256. if len(most_used_x) == 0:
  257. return None
  258. most_used_x.sort()
  259. return most_used_x[0]
  260. else:
  261. return most_used_x
  262. def get_attacker_config(ip_source_list, ip_address: str):
  263. """
  264. Returns the attacker configuration depending on the IP address, this includes the port for the next
  265. attacking packet and the previously used (fixed) TTL value.
  266. :param ip_source_list: List of source IPs
  267. :param ip_address: The IP address of the attacker
  268. :return: A tuple consisting of (port, ttlValue)
  269. """
  270. # Gamma distribution parameters derived from MAWI 13.8G dataset
  271. alpha, loc, beta = (2.3261710235, -0.188306914406, 44.4853123884)
  272. gd = stats.gamma.rvs(alpha, loc=loc, scale=beta, size=len(ip_source_list))
  273. # Determine port
  274. port = attacker_port_mapping.get(ip_address)
  275. if port is not None: # use next port
  276. next_port = attacker_port_mapping.get(ip_address) + 1
  277. if next_port > (2 ** 16 - 1):
  278. next_port = 1
  279. else: # generate starting port
  280. next_port = inet.RandShort()
  281. attacker_port_mapping[ip_address] = next_port
  282. # Determine TTL value
  283. ttl = attacker_ttl_mapping.get(ip_address)
  284. if ttl is None: # determine TTL value
  285. is_invalid = True
  286. pos = ip_source_list.index(ip_address)
  287. pos_max = len(gd)
  288. while is_invalid:
  289. ttl = int(round(gd[pos]))
  290. if 0 < ttl < 256: # validity check
  291. is_invalid = False
  292. else:
  293. pos = (pos + 1) % pos_max
  294. attacker_ttl_mapping[ip_address] = ttl
  295. # return port and TTL
  296. return next_port, ttl
  297. def rchop(string, endings):
  298. """"
  299. Returns the input string with it's ending cut off, in case it was part of 'endings'
  300. :param string: Input string
  301. :param endings: List of possible endings to be cut off
  302. :return: Input string with ending cut off
  303. """
  304. for end in endings:
  305. if string.endswith(end):
  306. return string[:-len(end)]
  307. return string