MembersMgmtCommAttack.py 24 KB

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