CommunicationProcessor.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. from lea import Lea
  2. from Attack.MembersMgmtCommAttack import MessageType
  3. from Attack.MembersMgmtCommAttack import Message
  4. # needed because of machine inprecision. E.g A time difference of 0.1s is stored as >0.1s
  5. EPS_TOLERANCE = 1e-13 # works for a difference of 0.1, no less
  6. class CommunicationProcessor():
  7. """
  8. Class to process parsed input CSV/XML data and retrieve a mapping or other information.
  9. """
  10. def __init__(self, packets):
  11. self.packets = packets
  12. def set_mapping(self, packets, mapped_ids, id_comms):
  13. """
  14. Set the selected mapping for this communication processor.
  15. :param packets: all packets contained in the mapped time frame
  16. :param mapped_ids: the chosen IDs
  17. :param id_comms: the communications between the mapped IDs within the mapped interval
  18. """
  19. self.packets = packets
  20. self.ids = mapped_ids.keys()
  21. self.id_comms = id_comms
  22. self.indv_id_counts = mapped_ids
  23. def find_interval_with_most_comm(self, number_ids: int, max_int_time: float):
  24. """
  25. Finds a time interval of the given seconds where the given number of IDs communicate among themselves the most.
  26. :param packets: The packets containing the communication
  27. :param number_ids: The number of IDs that are to be considered
  28. :param max_int_time: A short description of the attack.
  29. :return: A triple consisting of the IDs, as well as start and end idx with respect to the given packets.
  30. """
  31. packets = self.packets
  32. def get_nez_msg_counts(msg_counts: dict):
  33. """
  34. Filters out all msg_counts that have 0 as value
  35. """
  36. nez_msg_counts = dict()
  37. for msg in msg_counts.keys():
  38. count = msg_counts[msg]
  39. if count > 0:
  40. nez_msg_counts[msg] = count
  41. return nez_msg_counts
  42. def greater_than(a: float, b: float):
  43. """
  44. A greater than operator desgined to handle slight machine inprecision up to EPS_TOLERANCE.
  45. :return: True if a > b, otherwise False
  46. """
  47. return b - a < -EPS_TOLERANCE
  48. def change_msg_counts(msg_counts: dict, idx: int, add=True):
  49. """
  50. Changes the value of the message count of the message occuring in the packet specified by the given index.
  51. Adds 1 if add is True and subtracts 1 otherwise.
  52. """
  53. change = 1 if add else -1
  54. id_src, id_dst = packets[idx]["Src"], packets[idx]["Dst"]
  55. src_to_dst = "{0}-{1}".format(id_src, id_dst)
  56. dst_to_src = "{0}-{1}".format(id_dst, id_src)
  57. if src_to_dst in msg_counts.keys():
  58. msg_counts[src_to_dst] += change
  59. elif dst_to_src in msg_counts.keys():
  60. msg_counts[dst_to_src] += change
  61. elif add:
  62. msg_counts[src_to_dst] = 1
  63. def count_ids_in_msg_counts(msg_counts: dict):
  64. """
  65. Counts all ids that are involved in messages with a non zero message count
  66. """
  67. ids = set()
  68. for msg in msg_counts.keys():
  69. src, dst = msg.split("-")
  70. ids.add(dst)
  71. ids.add(src)
  72. return len(ids)
  73. def get_msg_count_first_ids(msg_counts: list):
  74. """
  75. Finds the IDs that communicate among themselves the most with respect to the given message counts.
  76. :param msg_counts: a sorted list of message counts where each entry is a tuple of key and value
  77. :return: The picked IDs and their total message count as a tuple
  78. """
  79. # if order of most messages is important, use an additional list
  80. picked_ids = set()
  81. total_msg_count = 0
  82. # iterate over every message count
  83. for i, msg in enumerate(msg_counts):
  84. count_picked_ids = len(picked_ids)
  85. id_one, id_two = msg[0].split("-")
  86. # if enough IDs have been found, stop
  87. if count_picked_ids >= number_ids:
  88. break
  89. # if two IDs can be added without exceeding the desired number of IDs, add them
  90. if count_picked_ids - 2 <= number_ids:
  91. picked_ids.add(id_one)
  92. picked_ids.add(id_two)
  93. total_msg_count += msg[1]
  94. # if there is only room for one more id to be added,
  95. # find one that is already contained in the picked IDs
  96. else:
  97. for j, msg in enumerate(msg_counts[i:]):
  98. id_one, id_two = msg[0].split("-")
  99. if id_one in picked_ids:
  100. picked_ids.add(id_two)
  101. total_msg_count += msg[1]
  102. break
  103. elif id_two in picked_ids:
  104. picked_ids.add(id_one)
  105. total_msg_count += msg[1]
  106. break
  107. break
  108. return picked_ids, total_msg_count
  109. def get_indv_id_counts_and_comms(picked_ids: dict, msg_counts: dict):
  110. """
  111. Retrieves the total mentions of one ID in the communication pattern
  112. and all communication entries that include only picked IDs.
  113. """
  114. indv_id_counts = {}
  115. id_comms = set()
  116. for msg in msg_counts:
  117. ids = msg.split("-")
  118. if ids[0] in picked_ids and ids[1] in picked_ids:
  119. msg_other_dir = "{}-{}".format(ids[1], ids[0])
  120. if (not msg in id_comms) and (not msg_other_dir in id_comms):
  121. id_comms.add(msg)
  122. for id_ in ids:
  123. if id_ in indv_id_counts:
  124. indv_id_counts[id_] += msg_counts[msg]
  125. else:
  126. indv_id_counts[id_] = msg_counts[msg]
  127. return indv_id_counts, id_comms
  128. # first find all possible intervals that contain enough IDs that communicate among themselves
  129. idx_low, idx_high = 0, 0
  130. msg_counts = dict()
  131. possible_intervals = []
  132. # Iterate over all packets from start to finish and process the info of each packet
  133. # If time of packet within time interval, update the message count for this communication
  134. # If time of packet exceeds time interval, substract from the message count for this communication
  135. while True:
  136. if idx_high < len(packets):
  137. cur_int_time = float(packets[idx_high]["Time"]) - float(packets[idx_low]["Time"])
  138. # if current interval time exceeds time interval, save the message counts if appropriate, or stop if no more packets
  139. if greater_than(cur_int_time, max_int_time) or idx_high >= len(packets):
  140. # get all message counts for communications that took place in the current intervall
  141. nez_msg_counts = get_nez_msg_counts(msg_counts)
  142. # if we have enough IDs as specified by the caller, mark as possible interval
  143. if count_ids_in_msg_counts(nez_msg_counts) >= number_ids:
  144. # possible_intervals.append((nez_msg_counts, packets[idx_low]["Time"], packets[idx_high-1]["Time"]))
  145. possible_intervals.append((nez_msg_counts, idx_low, idx_high - 1))
  146. if idx_high >= len(packets):
  147. break
  148. # let idx_low "catch up" so that the current interval time fits into the interval time specified by the caller
  149. while greater_than(cur_int_time, max_int_time):
  150. change_msg_counts(msg_counts, idx_low, add=False)
  151. idx_low += 1
  152. cur_int_time = float(packets[idx_high]["Time"]) - float(packets[idx_low]["Time"])
  153. # consume the new packet at idx_high and process its information
  154. change_msg_counts(msg_counts, idx_high)
  155. idx_high += 1
  156. # now find the interval in which as many IDs as specified communicate the most in the given time interval
  157. summed_intervals = []
  158. sum_intervals_idxs = []
  159. cur_highest_sum = 0
  160. # for every interval compute the sum of msg_counts of the first most communicative IDs and eventually find
  161. # the interval(s) with most communication and its IDs
  162. # on the side also store the communication count of the individual IDs
  163. for j, interval in enumerate(possible_intervals):
  164. msg_counts = interval[0].items()
  165. sorted_msg_counts = sorted(msg_counts, key=lambda x: x[1], reverse=True)
  166. picked_ids, msg_sum = get_msg_count_first_ids(sorted_msg_counts)
  167. if msg_sum == cur_highest_sum:
  168. summed_intervals.append({"IDs": picked_ids, "MsgSum": msg_sum, "Start": interval[1], "End": interval[2]})
  169. sum_intervals_idxs.append(j)
  170. elif msg_sum > cur_highest_sum:
  171. summed_intervals = []
  172. sum_intervals_idxs = [j]
  173. summed_intervals.append({"IDs": picked_ids, "MsgSum": msg_sum, "Start": interval[1], "End": interval[2]})
  174. cur_highest_sum = msg_sum
  175. for j, interval in enumerate(summed_intervals):
  176. idx = sum_intervals_idxs[j]
  177. msg_counts_picked = possible_intervals[idx][0]
  178. indv_id_counts, id_comms = get_indv_id_counts_and_comms(interval["IDs"], msg_counts_picked)
  179. interval["IDs"] = indv_id_counts
  180. interval["Comms"] = id_comms
  181. return summed_intervals
  182. def det_id_roles_and_msgs(self, mtypes: dict):
  183. """
  184. Determine the role of every mapped ID. The role can be initiator, responder or both.
  185. On the side also connect corresponding messages together to quickly find out
  186. which reply belongs to which request and vice versa.
  187. :param mtypes: a dict for fast number to enum type lookup of message types
  188. :return: a 4-tuple as (initiator IDs, responder IDs, both IDs, messages)
  189. """
  190. # setup initial variables and their values
  191. init_ids, respnd_ids, both_ids = set(), set(), set()
  192. # msgs --> the filtered messages, msg_id --> an increasing ID to give every message an artificial primary key
  193. msgs, msg_id = [], 0
  194. # kepp track of previous request to find connections
  195. prev_reqs = {}
  196. all_ids = self.ids
  197. packets = self.packets
  198. def process_initiator(id_: str):
  199. """
  200. Process the given ID as initiator and update the above sets accordingly.
  201. """
  202. if id_ in both_ids:
  203. pass
  204. elif not id_ in respnd_ids:
  205. init_ids.add(id_)
  206. elif id_ in respnd_ids:
  207. respnd_ids.remove(id_)
  208. both_ids.add(id_)
  209. def process_responder(id_: str):
  210. """
  211. Process the given ID as responder and update the above sets accordingly.
  212. """
  213. if id_ in both_ids:
  214. pass
  215. elif not id_ in init_ids:
  216. respnd_ids.add(id_)
  217. elif id_ in init_ids:
  218. init_ids.remove(id_)
  219. both_ids.add(id_)
  220. # process every packet individually
  221. for packet in packets:
  222. id_src, id_dst, msg_type, time = packet["Src"], packet["Dst"], int(packet["Type"]), float(packet["Time"])
  223. # if if either one of the IDs is not mapped, continue
  224. if (not id_src in all_ids) or (not id_dst in all_ids):
  225. continue
  226. # convert message type number to enum type
  227. msg_type = mtypes[msg_type]
  228. # process a request
  229. if msg_type in {MessageType.SALITY_HELLO, MessageType.SALITY_NL_REQUEST}:
  230. # process each ID's role
  231. process_initiator(id_src)
  232. process_responder(id_dst)
  233. # convert the abstract message into a message object to handle it better
  234. msg_str = "{0}-{1}".format(id_src, id_dst)
  235. msg = Message(msg_id, id_src, id_dst, msg_type, time)
  236. msgs.append(msg)
  237. prev_reqs[msg_str] = msg_id
  238. # process a reply
  239. elif msg_type in {MessageType.SALITY_HELLO_REPLY, MessageType.SALITY_NL_REPLY}:
  240. # process each ID's role
  241. process_initiator(id_dst)
  242. process_responder(id_src)
  243. # convert the abstract message into a message object to handle it better
  244. msg_str = "{0}-{1}".format(id_dst, id_src)
  245. # find the request message ID for this response and set its reference index
  246. refer_idx = prev_reqs[msg_str]
  247. msgs[refer_idx].refer_msg_id = msg_id
  248. # print(msgs[refer_idx])
  249. msg = Message(msg_id, id_src, id_dst, msg_type, time, refer_idx)
  250. msgs.append(msg)
  251. # remove the request to this response from storage
  252. del(prev_reqs[msg_str])
  253. # for message ID only count actual messages
  254. if not msg_type == MessageType.TIMEOUT:
  255. msg_id += 1
  256. # store the retrieved information in this object for later use
  257. self.init_ids, self.respnd_ids, self.both_ids = init_ids, respnd_ids, both_ids
  258. self.messages = msgs
  259. # return the retrieved information
  260. return init_ids, respnd_ids, both_ids, msgs
  261. def det_ext_and_local_ids(self, comm_type: str, prob_init_local: int, prob_rspnd_local: int):
  262. """
  263. Map the given IDs to a locality (i.e. local or external} considering the given probabilities.
  264. :param comm_type: the type of communication (i.e. local, external or mixed)
  265. :param prob_init_local: the probabilty that an initiator ID is local
  266. :param prob_rspnd_local: the probabilty that a responder is local
  267. """
  268. init_ids, respnd_ids, both_ids = self.init_ids, self.respnd_ids, self.both_ids
  269. id_comms = self.id_comms
  270. external_ids = set()
  271. local_ids = set()
  272. def map_init_is_local(id_:str):
  273. """
  274. Map the given ID as local and handle its communication partners' locality
  275. """
  276. # loop over all communication entries
  277. for id_comm in id_comms:
  278. # if id_comm does not contain the ID to be mapped, continue
  279. if not (id_ == ids[0] or id_ == ids[1]):
  280. continue
  281. ids = id_comm.split("-")
  282. other = ids[0] if id_ == ids[1] else ids[1]
  283. # if other is already mapped, continue
  284. if other in local_ids or other in external_ids:
  285. continue
  286. # if comm_type is mixed, other ID can be local or external
  287. if comm_type == "mixed":
  288. other_pos = mixed_respnd_is_local.random()
  289. if other_pos == "local":
  290. local_ids.add(other)
  291. elif other_pos == "external":
  292. external_ids.add(other)
  293. # if comm_type is external, other ID must be external to fulfill type
  294. # exlude initiators not to throw away too much communication
  295. elif comm_type == "external":
  296. if not other in initiators:
  297. external_ids.add(other)
  298. def map_init_is_external(id_: int):
  299. """
  300. Map the given ID as external and handle its communication partners' locality
  301. """
  302. for id_comm in id_comms:
  303. # if id_comm does not contain the ID to be mapped, continue
  304. if not (id_ == ids[0] or id_ == ids[1]):
  305. continue
  306. ids = id_comm.split("-")
  307. other = ids[0] if id_ == ids[1] else ids[1]
  308. # if other is already mapped, continue
  309. if other in local_ids or other in external_ids:
  310. continue
  311. if not other in initiators:
  312. local_ids.add(other)
  313. # if comm_type is local, map all IDs to local
  314. if comm_type == "local":
  315. local_ids = set(mapped_ids.keys())
  316. else:
  317. # set up probabilistic chooser
  318. init_local_or_external = Lea.fromValFreqsDict({"local": prob_init_local*100, "external": (1-prob_init_local)*100})
  319. mixed_respnd_is_local = Lea.fromValFreqsDict({"local": prob_rspnd_local*100, "external": (1-prob_rspnd_local)*100})
  320. # assign IDs in 'both' local everytime for mixed?
  321. # sort initiators by some order, to gain determinism
  322. initiators = sorted(list(init_ids) + list(both_ids))
  323. # sort by individual communication count to increase final communication count
  324. # better to sort by highest count of 'shared' IDs in case of local comm_type?
  325. initiators = sorted(initiators, key=lambda id_:self.indv_id_counts[id_], reverse=True)
  326. for id_ in initiators:
  327. pos = init_local_or_external.random()
  328. if pos == "local":
  329. # if id_ has already been mapped differently, its communication partners still have to be mapped
  330. if id_ in external_ids:
  331. map_init_is_external(id_)
  332. # otherwise, map as chosen above
  333. else:
  334. local_ids.add(id_)
  335. map_init_is_local(id_)
  336. elif pos == "external":
  337. # if id_ has already been mapped differently, its communication partners still have to be mapped
  338. if id_ in local_ids:
  339. map_init_is_local(id_)
  340. # otherwise, map as chosen above
  341. else:
  342. external_ids.add(id_)
  343. map_init_is_external(id_)
  344. self.local_ids, self.external_ids = local_ids, external_ids
  345. return local_ids, external_ids