3
0

Utility.py 14 KB

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