Utility.py 13 KB

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