MembersMgmtCommAttack.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. from enum import Enum
  2. from random import randint, randrange, choice, uniform
  3. from collections import deque
  4. from scipy.stats import gamma
  5. from lea import Lea
  6. from datetime import datetime
  7. from Attack import BaseAttack
  8. from Attack.AttackParameters import Parameter as Param
  9. from Attack.AttackParameters import ParameterTypes
  10. class MessageType(Enum):
  11. """
  12. Defines possible botnet message types
  13. """
  14. TIMEOUT = 3
  15. SALITY_NL_REQUEST = 101
  16. SALITY_NL_REPLY = 102
  17. SALITY_HELLO = 103
  18. SALITY_HELLO_REPLY = 104
  19. def is_request(mtype):
  20. return mtype in {MessageType.SALITY_HELLO, MessageType.SALITY_NL_REQUEST}
  21. def is_response(mtype):
  22. return mtype in {MessageType.SALITY_HELLO_REPLY, MessageType.SALITY_NL_REPLY}
  23. class Message():
  24. INVALID_LINENO = -1
  25. """
  26. Defines a compact message type that contains all necessary information.
  27. """
  28. def __init__(self, msg_id: int, src, dst, type_: MessageType, time: float, refer_msg_id: int=-1, line_no = -1):
  29. """
  30. Constructs a message with the given parameters.
  31. :param msg_id: the ID of the message
  32. :param src: something identifiying the source, e.g. ID or configuration
  33. :param dst: something identifiying the destination, e.g. ID or configuration
  34. :param type_: the type of the message
  35. :param time: the timestamp of the message
  36. :param refer_msg_id: the ID this message is a request for or reply to. -1 if there is no related message.
  37. :param line_no: The line number this message appeared in the original file
  38. """
  39. self.msg_id = msg_id
  40. self.src = src
  41. self.dst = dst
  42. self.type = type_
  43. self.time = time
  44. self.refer_msg_id = refer_msg_id
  45. # if similar fields to line_no should be added consider a separate class
  46. self.line_no = line_no
  47. def __str__(self):
  48. str_ = "{0}. at {1}: {2}-->{3}, {4}, refer:{5}".format(self.msg_id, self.time, self.src, self.dst, self.type, self.refer_msg_id)
  49. return str_
  50. from ID2TLib import FileUtils, PaddingGenerator
  51. from ID2TLib.PacketGenerator import PacketGenerator
  52. from ID2TLib.IPGenerator import IPGenerator
  53. from ID2TLib.PcapAddressOperations import PcapAddressOperations
  54. from ID2TLib.CommunicationProcessor import CommunicationProcessor
  55. from ID2TLib.MacAddressGenerator import MacAddressGenerator
  56. from ID2TLib.PortGenerator import gen_random_server_port
  57. from ID2TLib.Botnet.MessageMapping import MessageMapping
  58. class MembersMgmtCommAttack(BaseAttack.BaseAttack):
  59. def __init__(self):
  60. """
  61. Creates a new instance of the Membership Management Communication.
  62. """
  63. # Initialize communication
  64. super(MembersMgmtCommAttack, self).__init__("Membership Management Communication Attack (MembersMgmtCommAttack)",
  65. "Injects Membership Management Communication", "Botnet communication")
  66. # Define allowed parameters and their type
  67. self.supported_params = {
  68. # parameters regarding attack
  69. Param.INJECT_AT_TIMESTAMP: ParameterTypes.TYPE_FLOAT,
  70. Param.INJECT_AFTER_PACKET: ParameterTypes.TYPE_PACKET_POSITION,
  71. Param.PACKETS_PER_SECOND: ParameterTypes.TYPE_FLOAT,
  72. Param.PACKETS_LIMIT: ParameterTypes.TYPE_INTEGER_POSITIVE,
  73. Param.ATTACK_DURATION: ParameterTypes.TYPE_INTEGER_POSITIVE,
  74. # use num_attackers to specify number of communicating devices?
  75. Param.NUMBER_INITIATOR_BOTS: ParameterTypes.TYPE_INTEGER_POSITIVE,
  76. # input file containing botnet communication
  77. Param.FILE_CSV: ParameterTypes.TYPE_FILEPATH,
  78. Param.FILE_XML: ParameterTypes.TYPE_FILEPATH,
  79. # the percentage of IP reuse (if total and other is specified, percentages are multiplied)
  80. Param.IP_REUSE_TOTAL: ParameterTypes.TYPE_PERCENTAGE,
  81. Param.IP_REUSE_LOCAL: ParameterTypes.TYPE_PERCENTAGE,
  82. Param.IP_REUSE_EXTERNAL: ParameterTypes.TYPE_PERCENTAGE,
  83. # the user-selected padding to add to every packet
  84. Param.PACKET_PADDING: ParameterTypes.TYPE_PADDING,
  85. # presence of NAT at the gateway of the network
  86. Param.NAT_PRESENT: ParameterTypes.TYPE_BOOLEAN
  87. }
  88. # create dict with MessageType values for fast name lookup
  89. self.msg_types = {}
  90. for msg_type in MessageType:
  91. self.msg_types[msg_type.value] = msg_type
  92. def init_params(self):
  93. """
  94. Initialize some parameters of this communication-attack using the user supplied command line parameters.
  95. The remaining parameters are implicitly set in the provided data file. Note: the timestamps in the file
  96. have to be sorted in ascending order
  97. :param statistics: Reference to a statistics object.
  98. """
  99. # set class constants
  100. self.DEFAULT_XML_PATH = "resources/MembersMgmtComm_example.xml"
  101. # probability for responder ID to be local if comm_type is mixed
  102. self.PROB_RESPND_IS_LOCAL = 0
  103. # PARAMETERS: initialize with default values
  104. # (values are overwritten if user specifies them)
  105. self.add_param_value(Param.INJECT_AFTER_PACKET, randint(1, int(self.statistics.get_packet_count()/5)))
  106. self.add_param_value(Param.PACKETS_PER_SECOND, 0)
  107. self.add_param_value(Param.FILE_XML, self.DEFAULT_XML_PATH)
  108. # Alternatively new attack parameter?
  109. duration = int(float(self._get_capture_duration()))
  110. self.add_param_value(Param.ATTACK_DURATION, duration)
  111. self.add_param_value(Param.NUMBER_INITIATOR_BOTS, 1)
  112. # NAT on by default
  113. self.add_param_value(Param.NAT_PRESENT, True)
  114. # default locality behavior
  115. # self.add_param_value(Param.COMM_TYPE, "mixed")
  116. # TODO: change 1 to something better
  117. self.add_param_value(Param.IP_REUSE_TOTAL, 1)
  118. self.add_param_value(Param.IP_REUSE_LOCAL, 0.5)
  119. self.add_param_value(Param.IP_REUSE_EXTERNAL, 0.5)
  120. # add default additional padding
  121. self.add_param_value(Param.PACKET_PADDING, 20)
  122. def generate_attack_pcap(self, context):
  123. # create the final messages that have to be sent, including all bot configurations
  124. messages = self._create_messages()
  125. if messages == []:
  126. return 0, []
  127. # Setup (initial) parameters for packet creation loop
  128. BUFFER_SIZE = 1000
  129. pkt_gen = PacketGenerator()
  130. file_timestamp_prv = messages[0].time
  131. pcap_timestamp = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  132. padding = self.get_param_value(Param.PACKET_PADDING)
  133. packets = deque(maxlen=BUFFER_SIZE)
  134. total_pkts = 0
  135. limit_packetcount = self.get_param_value(Param.PACKETS_LIMIT)
  136. limit_duration = self.get_param_value(Param.ATTACK_DURATION)
  137. duration = 0
  138. path_attack_pcap = None
  139. msg_packet_mapping = MessageMapping(messages)
  140. # create packets to write to PCAP file
  141. for msg in messages:
  142. # retrieve the source and destination configurations
  143. id_src, id_dst = msg.src["ID"], msg.dst["ID"]
  144. ip_src, ip_dst = msg.src["IP"], msg.dst["IP"]
  145. mac_src, mac_dst = msg.src["MAC"], msg.dst["MAC"]
  146. port_src, port_dst = msg.src["Port"], msg.dst["Port"]
  147. ttl = msg.src["TTL"]
  148. # update timestamps and duration
  149. file_timestamp = msg.time
  150. file_time_delta = file_timestamp - file_timestamp_prv
  151. pcap_timestamp += file_time_delta
  152. duration += file_time_delta
  153. file_timestamp_prv = file_timestamp
  154. # if total number of packets has been sent or the attack duration has been exceeded, stop
  155. if ((limit_packetcount is not None and total_pkts >= limit_packetcount) or
  156. (limit_duration is not None and duration >= limit_duration)):
  157. break
  158. # if the type of the message is a NL reply, determine the number of entries
  159. nl_size = 0
  160. if msg.type == MessageType.SALITY_NL_REPLY:
  161. nl_size = randint(1, 25) # what is max NL entries?
  162. # create suitable IP/UDP packet and add to packets list
  163. packet = pkt_gen.generate_mmcom_packet(ip_src=ip_src, ip_dst=ip_dst, ttl=ttl, mac_src=mac_src, mac_dst=mac_dst,
  164. port_src=port_src, port_dst=port_dst, message_type=msg.type, neighborlist_entries=nl_size)
  165. PaddingGenerator.add_padding(packet, padding,True, True)
  166. packet.time = pcap_timestamp
  167. packets.append(packet)
  168. msg_packet_mapping.map_message(msg, packet)
  169. total_pkts += 1
  170. # Store timestamp of first packet (for attack label)
  171. if total_pkts <= 1:
  172. self.attack_start_utime = packets[0].time
  173. elif total_pkts % BUFFER_SIZE == 0: # every 1000 packets write them to the PCAP file (append)
  174. packets = list(packets)
  175. PaddingGenerator.equal_length(packets, padding = padding)
  176. last_packet = packets[-1]
  177. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  178. packets = deque(maxlen=BUFFER_SIZE)
  179. # if there are unwritten packets remaining, write them to the PCAP file
  180. if len(packets) > 0:
  181. packets = list(packets)
  182. PaddingGenerator.equal_length(packets, padding = padding)
  183. path_attack_pcap = self.write_attack_pcap(packets, True, path_attack_pcap)
  184. last_packet = packets[-1]
  185. # write the mapping to a file
  186. msg_packet_mapping.write_to(context.allocate_file("_mapping.xml"))
  187. # Store timestamp of last packet
  188. self.attack_end_utime = last_packet.time
  189. # Return packets sorted by packet by timestamp and total number of packets (sent)
  190. return total_pkts , path_attack_pcap
  191. def _create_messages(self):
  192. def add_ids_to_config(ids_to_add: list, existing_ips: list, new_ips: list, bot_configs: dict, idtype:str="local", router_mac:str=""):
  193. """
  194. Creates IP and MAC configurations for the given IDs and adds them to the existing configurations object.
  195. :param ids_to_add: all sorted IDs that have to be configured and added
  196. :param existing_ips: the existing IPs in the PCAP file that should be assigned to some, or all, IDs
  197. :param new_ips: the newly generated IPs that should be assigned to some, or all, IDs
  198. :param bot_configs: the existing configurations for the bots
  199. :param idtype: the locality type of the IDs
  200. :param router_mac: the MAC address of the router in the PCAP
  201. """
  202. ids = ids_to_add.copy()
  203. # macgen only needed, when IPs are new local IPs (therefore creating the object here suffices for the current callers
  204. # to not end up with the same MAC paired with different IPs)
  205. macgen = MacAddressGenerator()
  206. # assign existing IPs and the corresponding MAC addresses in the PCAP to the IDs
  207. for ip in existing_ips:
  208. random_id = choice(ids)
  209. mac = self.statistics.process_db_query("macAddress(IPAddress=%s)" % ip)
  210. bot_configs[random_id] = {"Type": idtype, "IP": ip, "MAC": mac}
  211. ids.remove(random_id)
  212. # assign new IPs and for local IPs new MACs or for external IPs the router MAC to the IDs
  213. for ip in new_ips:
  214. random_id = choice(ids)
  215. if idtype == "local":
  216. mac = macgen.random_mac()
  217. elif idtype == "external":
  218. mac = router_mac
  219. bot_configs[random_id] = {"Type": idtype, "IP": ip, "MAC": mac}
  220. ids.remove(random_id)
  221. def index_increment(number: int, max: int):
  222. """
  223. Number increment with rollover.
  224. """
  225. if number + 1 < max:
  226. return number + 1
  227. else:
  228. return 0
  229. def assign_realistic_ttls(bot_configs):
  230. '''
  231. Assigns a realisitic ttl to each bot from @param: bot_configs. Uses statistics and distribution to be able
  232. to calculate a realisitc ttl.
  233. :param bot_configs:
  234. :return:
  235. '''
  236. ids = sorted(bot_configs.keys())
  237. for pos,bot in enumerate(ids):
  238. bot_type = bot_configs[bot]["Type"]
  239. # print(bot_type)
  240. if(bot_type == "local"): # Set fix TTL for local Bots
  241. bot_configs[bot]["TTL"] = 128
  242. # Set TTL based on TTL distribution of IP address
  243. else: # Set varying TTl for external Bots
  244. bot_ttl_dist = self.statistics.get_ttl_distribution(bot_configs[bot]["IP"])
  245. if len(bot_ttl_dist) > 0:
  246. source_ttl_prob_dict = Lea.fromValFreqsDict(bot_ttl_dist)
  247. bot_configs[bot]["TTL"] = source_ttl_prob_dict.random()
  248. else:
  249. bot_configs[bot]["TTL"] = self.statistics.process_db_query("most_used(ttlValue)")
  250. def add_delay(timestamp: float, minDelay: float, delay: float):
  251. '''
  252. Adds delay to a timestamp, with a minimum value of minDelay. But usually a value close to delay
  253. :param timestamp: the timestamp that is to be increased
  254. :param minDelay: the minimum value that is to be added to the timestamp
  255. :param delay: The general size of the delay. Statistically speaking: the expected value
  256. :return: the updated timestamp
  257. '''
  258. randomdelay = Lea.fromValFreqsDict({0.15*delay: 7, 0.3*delay: 10, 0.7*delay:20,
  259. delay:33, 1.2*delay:20, 1.6*delay: 10, 1.9*delay: 7, 2.5*delay: 3, 4*delay: 1})
  260. if 0.1*delay < minDelay:
  261. print("Warning: minDelay probably too big when computing time_stamps")
  262. # updated timestamps consist of the sum of the minimum delay, the magnitude of the delay
  263. # and a deviation by up to 10% in order to guarantee uniqueness
  264. general_offset = randomdelay.random()
  265. unique_offset = uniform(-0.1*general_offset, 0.1*general_offset)
  266. return timestamp + minDelay + general_offset + unique_offset
  267. # parse input CSV or XML
  268. filepath_xml = self.get_param_value(Param.FILE_XML)
  269. filepath_csv = self.get_param_value(Param.FILE_CSV)
  270. # prefer XML input over CSV input (in case both are given)
  271. if filepath_csv and filepath_xml == self.DEFAULT_XML_PATH:
  272. filepath_xml = FileUtils.parse_csv_to_xml(filepath_csv)
  273. abstract_packets = FileUtils.parse_xml(filepath_xml)
  274. # find a good communication mapping in the input file that matches the users parameters
  275. duration = self.get_param_value(Param.ATTACK_DURATION)
  276. number_init_bots = self.get_param_value(Param.NUMBER_INITIATOR_BOTS)
  277. nat = self.get_param_value(Param.NAT_PRESENT)
  278. comm_proc = CommunicationProcessor(abstract_packets, self.msg_types, nat)
  279. comm_intervals = comm_proc.find_interval_most_comm(number_init_bots, duration)
  280. if comm_intervals == []:
  281. print("Error: There is no interval in the given CSV/XML that has enough communication initiating bots.")
  282. return []
  283. comm_interval = comm_intervals[randrange(0, len(comm_intervals))]
  284. # retrieve the mapping information
  285. mapped_ids, packet_start_idx, packet_end_idx = comm_interval["IDs"], comm_interval["Start"], comm_interval["End"]
  286. while len(mapped_ids) > number_init_bots:
  287. rm_idx = randrange(0, len(mapped_ids))
  288. del mapped_ids[rm_idx]
  289. # assign the communication processor this mapping for further processing
  290. comm_proc.set_mapping(abstract_packets[packet_start_idx:packet_end_idx+1], mapped_ids)
  291. # print start and end time of mapped interval
  292. # print(abstract_packets[packet_start_idx]["Time"])
  293. # print(abstract_packets[packet_end_idx]["Time"])
  294. # print(mapped_ids)
  295. # determine number of reused local and external IPs
  296. reuse_percent_total = self.get_param_value(Param.IP_REUSE_TOTAL)
  297. reuse_percent_external = self.get_param_value(Param.IP_REUSE_EXTERNAL)
  298. reuse_percent_local = self.get_param_value(Param.IP_REUSE_LOCAL)
  299. reuse_count_external = int(reuse_percent_total * reuse_percent_external * len(mapped_ids))
  300. reuse_count_local = int(reuse_percent_total * reuse_percent_local * len(mapped_ids))
  301. # create locality, IP and MAC configurations for the IDs/Bots
  302. ipgen = IPGenerator()
  303. pcapops = PcapAddressOperations(self.statistics)
  304. router_mac = pcapops.get_probable_router_mac()
  305. bot_configs = {}
  306. # determine the roles of the IDs in the mapping communication-{initiator, responder}
  307. local_init_ids, external_init_ids, respnd_ids, messages = comm_proc.det_id_roles_and_msgs()
  308. # use these roles to determine which IDs are to be local and which external
  309. local_ids, external_ids = comm_proc.det_ext_and_local_ids(self.PROB_RESPND_IS_LOCAL)
  310. # retrieve and assign the IPs and MACs for the bots with respect to the given parameters
  311. # (IDs are always added to bot_configs in the same order under a given seed)
  312. number_local_ids, number_external_ids = len(local_ids), len(external_ids)
  313. # assign addresses for local IDs
  314. if number_local_ids > 0:
  315. reuse_count_local = int(reuse_percent_total * reuse_percent_local * number_local_ids)
  316. existing_local_ips = sorted(pcapops.get_existing_local_ips(reuse_count_local))
  317. new_local_ips = sorted(pcapops.get_new_local_ips(number_local_ids - len(existing_local_ips)))
  318. add_ids_to_config(sorted(local_ids), existing_local_ips, new_local_ips, bot_configs)
  319. # assign addresses for external IDs
  320. if number_external_ids > 0:
  321. reuse_count_external = int(reuse_percent_total * reuse_percent_external * number_external_ids)
  322. existing_external_ips = sorted(pcapops.get_existing_external_ips(reuse_count_external))
  323. remaining = len(external_ids) - len(existing_external_ips)
  324. new_external_ips = sorted([ipgen.random_ip() for _ in range(remaining)])
  325. add_ids_to_config(sorted(external_ids), existing_external_ips, new_external_ips, bot_configs, idtype="external", router_mac=router_mac)
  326. #### Set realistic timestamps for messages ####
  327. most_used_ip_address = self.statistics.get_most_used_ip_address()
  328. minDelay = self.get_reply_delay(most_used_ip_address)[0]
  329. next_timestamp = self.get_param_value(Param.INJECT_AT_TIMESTAMP)
  330. pcap_duration = float(self._get_capture_duration())
  331. equi_timeslice = pcap_duration/len(messages)
  332. # Dict, takes a tuple of 2 Bot_IDs as a key (ID with lower number first), returns the time when the Hello_reply came in
  333. hello_times = {}
  334. # msg_IDs with already updated timestamps
  335. updated_msgs = []
  336. for req_msg in messages:
  337. updated = 0
  338. if(req_msg.msg_id in updated_msgs):
  339. # message already updated
  340. continue
  341. if(req_msg.msg_id == -1):
  342. # message has no corresponding request/response
  343. req_msg.time = next_timestamp
  344. next_timestamp = add_delay(next_timestamp, minDelay, equi_timeslice)
  345. updated_msgs.append(req_msg.msg_id)
  346. continue
  347. elif req_msg.type != MessageType.SALITY_HELLO:
  348. # Hello messages must have preceded, so make sure the timestamp of this msg is after the HELLO_REPLY
  349. if int(req_msg.src) < int(req_msg.dst):
  350. hello_time = hello_times[(req_msg.src, req_msg.dst)]
  351. else:
  352. hello_time = hello_times[(req_msg.dst, req_msg.src)]
  353. if next_timestamp < hello_time:
  354. # use the time of the hello_reply instead of next_timestamp to update this pair of messages
  355. post_hello = add_delay(hello_time, minDelay, equi_timeslice)
  356. respns_msg = messages[req_msg.refer_msg_id]
  357. respns_msg.time = add_delay(post_hello, minDelay, equi_timeslice)
  358. req_msg.time = post_hello
  359. updated = 1
  360. if not updated:
  361. # update normally
  362. respns_msg = messages[req_msg.refer_msg_id]
  363. respns_msg.time = add_delay(next_timestamp, minDelay, equi_timeslice)
  364. req_msg.time = next_timestamp
  365. next_timestamp = add_delay(next_timestamp, minDelay, equi_timeslice)
  366. updated_msgs.append(req_msg.msg_id)
  367. updated_msgs.append(req_msg.refer_msg_id)
  368. if req_msg.type == MessageType.SALITY_HELLO:
  369. # if hello messages have been exchanged, save timestamp of the HELLO_REPLY
  370. if int(req_msg.src) < int(req_msg.dst):
  371. hello_times[(req_msg.src, req_msg.dst)] = respns_msg.time
  372. else:
  373. hello_times[(req_msg.dst, req_msg.src)] = respns_msg.time
  374. # create port configurations for the bots
  375. for bot in bot_configs:
  376. bot_configs[bot]["Port"] = gen_random_server_port()
  377. # print(local_init_ids)
  378. # print(bot_configs)
  379. # assign realistic TTL for every bot
  380. assign_realistic_ttls(bot_configs)
  381. # put together the final messages including the full sender and receiver
  382. # configurations (i.e. IP, MAC, port, ...) for easier later use
  383. final_messages = []
  384. messages = sorted(messages, key=lambda msg: msg.time)
  385. new_id = 0
  386. for msg in messages:
  387. type_src, type_dst = bot_configs[msg.src]["Type"], bot_configs[msg.dst]["Type"]
  388. id_src, id_dst = msg.src, msg.dst
  389. # sort out messages that do not have a suitable locality setting
  390. if type_src == "external" and type_dst == "external":
  391. continue
  392. msg.src, msg.dst = bot_configs[id_src], bot_configs[id_dst]
  393. msg.src["ID"], msg.dst["ID"] = id_src, id_dst
  394. msg.msg_id = new_id
  395. new_id += 1
  396. ### Important here to update refers, if needed later?
  397. final_messages.append(msg)
  398. return final_messages
  399. def _get_capture_duration(self):
  400. """
  401. Returns the duration of the input PCAP (since statistics duration seems to be incorrect)
  402. """
  403. ts_date_format = "%Y-%m-%d %H:%M:%S.%f"
  404. ts_first_date = datetime.strptime(self.statistics.get_pcap_timestamp_start(), ts_date_format)
  405. ts_last_date = datetime.strptime(self.statistics.get_pcap_timestamp_end(), ts_date_format)
  406. diff_date = ts_last_date - ts_first_date
  407. duration = "%d.%d" % (diff_date.total_seconds(), diff_date.microseconds)
  408. return duration