CommunicationProcessor.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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:list, mtypes:dict, nat:bool):
  11. self.packets = packets
  12. self.mtypes = mtypes
  13. self.nat = nat
  14. def set_mapping(self, packets: list, mapped_ids: dict):
  15. """
  16. Set the selected mapping for this communication processor.
  17. :param packets: all packets contained in the mapped time frame
  18. :param mapped_ids: the chosen IDs
  19. """
  20. self.packets = packets
  21. self.local_init_ids = set(mapped_ids.keys())
  22. def find_interval_most_comm(self, number_ids: int, max_int_time: float):
  23. """
  24. Finds a time interval of the given seconds where the given number of IDs commuicate the most.
  25. If NAT is active, the most communication is restricted to the most communication by the given number of initiating IDs.
  26. If NAT is inactive, the intervall the most overall communication, that has at least the given number of initiating IDs in it, is chosen.
  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. mtypes = self.mtypes
  33. def get_nez_comm_counts(comm_counts: dict):
  34. """
  35. Filters out all msg_counts that have 0 as value
  36. """
  37. nez_comm_counts = dict()
  38. for id_ in comm_counts.keys():
  39. count = comm_counts[id_]
  40. if count > 0:
  41. nez_comm_counts[id_] = count
  42. return nez_comm_counts
  43. def greater_than(a: float, b: float):
  44. """
  45. A greater than operator desgined to handle slight machine inprecision up to EPS_TOLERANCE.
  46. :return: True if a > b, otherwise False
  47. """
  48. return b - a < -EPS_TOLERANCE
  49. def change_comm_counts(comm_counts: dict, idx: int, add=True):
  50. """
  51. Changes the communication count, stored in comm_counts, of the initiating ID with respect to the
  52. packet specified by the given index. If add is True, 1 is added to the value, otherwise 1 is subtracted.
  53. """
  54. change = 1 if add else -1
  55. mtype = mtypes[int(packets[idx]["Type"])]
  56. id_src, id_dst = packets[idx]["Src"], packets[idx]["Dst"]
  57. if mtype in {MessageType.SALITY_HELLO, MessageType.SALITY_NL_REQUEST}:
  58. if id_src in comm_counts:
  59. comm_counts[id_src] += change
  60. elif change > 0:
  61. comm_counts[id_src] = 1
  62. elif mtype in {MessageType.SALITY_HELLO_REPLY, MessageType.SALITY_NL_REPLY}:
  63. if id_dst in comm_counts:
  64. comm_counts[id_dst] += change
  65. elif change > 0:
  66. comm_counts[id_dst] = 1
  67. def get_comm_count_first_ids(comm_counts: list):
  68. """
  69. Finds the IDs that communicate among themselves the most with respect to the given message counts.
  70. :param msg_counts: a sorted list of message counts where each entry is a tuple of key and value
  71. :return: The picked IDs and their total message count as a tuple
  72. """
  73. # if order of most messages is important, use an additional list
  74. picked_ids = {}
  75. total_comm_count = 0
  76. # iterate over every message count
  77. for i, comm in enumerate(comm_counts):
  78. count_picked_ids = len(picked_ids)
  79. # if enough IDs have been found, stop
  80. if count_picked_ids >= number_ids:
  81. break
  82. picked_ids[comm[0]] = comm[1]
  83. total_comm_count += comm[1]
  84. return picked_ids, total_comm_count
  85. # first find all possible intervals that contain enough IDs that initiate communication
  86. idx_low, idx_high = 0, 0
  87. comm_counts = {}
  88. possible_intervals = []
  89. general_comm_sum, cur_highest_sum = 0, 0
  90. # Iterate over all packets from start to finish and process the info of each packet
  91. # If time of packet within time interval, update the message count for this communication
  92. # If time of packet exceeds time interval, substract from the message count for this communication
  93. # Similar to a Sliding Window approach
  94. while True:
  95. if idx_high < len(packets):
  96. cur_int_time = float(packets[idx_high]["Time"]) - float(packets[idx_low]["Time"])
  97. # if current interval time exceeds time interval, save the message counts if appropriate, or stop if no more packets
  98. if greater_than(cur_int_time, max_int_time) or idx_high >= len(packets):
  99. # get all message counts for communications that took place in the current intervall
  100. nez_comm_counts = get_nez_comm_counts(comm_counts)
  101. # if we have enough IDs as specified by the caller, mark as possible interval
  102. if len(nez_comm_counts) >= number_ids:
  103. if self.nat:
  104. possible_intervals.append((nez_comm_counts, idx_low, idx_high-1))
  105. elif general_comm_sum >= cur_highest_sum:
  106. cur_highest_sum = general_comm_sum
  107. possible_intervals.append({"IDs": nez_comm_counts, "CommSum": general_comm_sum, "Start": idx_low, "End": idx_high-1})
  108. general_comm_sum = 0
  109. if idx_high >= len(packets):
  110. break
  111. # let idx_low "catch up" so that the current interval time fits into the interval time specified by the caller
  112. while greater_than(cur_int_time, max_int_time):
  113. change_comm_counts(comm_counts, idx_low, add=False)
  114. idx_low += 1
  115. cur_int_time = float(packets[idx_high]["Time"]) - float(packets[idx_low]["Time"])
  116. # consume the new packet at idx_high and process its information
  117. change_comm_counts(comm_counts, idx_high)
  118. idx_high += 1
  119. general_comm_sum += 1
  120. if self.nat:
  121. # now find the interval in which as many IDs as specified communicate the most in the given time interval
  122. summed_intervals = []
  123. sum_intervals_idxs = []
  124. cur_highest_sum = 0
  125. # for every interval compute the sum of id_counts of the first most communicative IDs and eventually find
  126. # the interval(s) with most communication and its IDs
  127. # on the side also store the communication count of the individual IDs
  128. for j, interval in enumerate(possible_intervals):
  129. comm_counts = interval[0].items()
  130. sorted_comm_counts = sorted(comm_counts, key=lambda x: x[1], reverse=True)
  131. picked_ids, comm_sum = get_comm_count_first_ids(sorted_comm_counts)
  132. if comm_sum == cur_highest_sum:
  133. summed_intervals.append({"IDs": picked_ids, "CommSum": comm_sum, "Start": interval[1], "End": interval[2]})
  134. elif comm_sum > cur_highest_sum:
  135. summed_intervals = []
  136. summed_intervals.append({"IDs": picked_ids, "CommSum": comm_sum, "Start": interval[1], "End": interval[2]})
  137. cur_highest_sum = comm_sum
  138. return summed_intervals
  139. else:
  140. return possible_intervals
  141. def det_id_roles_and_msgs(self):
  142. """
  143. Determine the role of every mapped ID. The role can be initiator, responder or both.
  144. On the side also connect corresponding messages together to quickly find out
  145. which reply belongs to which request and vice versa.
  146. :return: a triple as (initiator IDs, responder IDs, messages)
  147. """
  148. mtypes = self.mtypes
  149. # setup initial variables and their values
  150. respnd_ids = set()
  151. # msgs --> the filtered messages, msg_id --> an increasing ID to give every message an artificial primary key
  152. msgs, msg_id = [], 0
  153. # keep track of previous request to find connections
  154. prev_reqs = {}
  155. local_init_ids = self.local_init_ids
  156. external_init_ids = set()
  157. # process every packet individually
  158. for packet in self.packets:
  159. id_src, id_dst, msg_type, time = packet["Src"], packet["Dst"], int(packet["Type"]), float(packet["Time"])
  160. # if if either one of the IDs is not mapped, continue
  161. if (id_src not in local_init_ids) and (id_dst not in local_init_ids):
  162. continue
  163. # convert message type number to enum type
  164. msg_type = mtypes[msg_type]
  165. # process a request
  166. if msg_type in {MessageType.SALITY_HELLO, MessageType.SALITY_NL_REQUEST}:
  167. if not self.nat and id_dst in local_init_ids and id_src not in local_init_ids:
  168. external_init_ids.add(id_src)
  169. elif id_src not in local_init_ids:
  170. continue
  171. else:
  172. # process ID's role
  173. respnd_ids.add(id_dst)
  174. # convert the abstract message into a message object to handle it better
  175. msg_str = "{0}-{1}".format(id_src, id_dst)
  176. msg = Message(msg_id, id_src, id_dst, msg_type, time)
  177. msgs.append(msg)
  178. prev_reqs[msg_str] = msg_id
  179. msg_id += 1
  180. # process a reply
  181. elif msg_type in {MessageType.SALITY_HELLO_REPLY, MessageType.SALITY_NL_REPLY}:
  182. if not self.nat and id_src in local_init_ids and id_dst not in local_init_ids:
  183. # process ID's role
  184. external_init_ids.add(id_dst)
  185. elif id_dst not in local_init_ids:
  186. continue
  187. else:
  188. # process ID's role
  189. respnd_ids.add(id_src)
  190. # convert the abstract message into a message object to handle it better
  191. msg_str = "{0}-{1}".format(id_dst, id_src)
  192. # find the request message ID for this response and set its reference index
  193. refer_idx = prev_reqs[msg_str]
  194. msgs[refer_idx].refer_msg_id = msg_id
  195. msg = Message(msg_id, id_src, id_dst, msg_type, time, refer_idx)
  196. msgs.append(msg)
  197. # remove the request to this response from storage
  198. del(prev_reqs[msg_str])
  199. msg_id += 1
  200. # store the retrieved information in this object for later use
  201. self.respnd_ids = sorted(respnd_ids)
  202. self.external_init_ids = sorted(external_init_ids)
  203. self.messages = msgs
  204. # return the retrieved information
  205. return self.local_init_ids, self.external_init_ids, self.respnd_ids, self.messages
  206. def det_ext_and_local_ids(self, prob_rspnd_local: int):
  207. """
  208. Map the given IDs to a locality (i.e. local or external} considering the given probabilities.
  209. :param comm_type: the type of communication (i.e. local, external or mixed)
  210. :param prob_rspnd_local: the probabilty that a responder is local
  211. """
  212. external_ids = set()
  213. local_ids = self.local_init_ids.copy()
  214. # set up probabilistic chooser
  215. rspnd_locality = Lea.fromValFreqsDict({"local": prob_rspnd_local*100, "external": (1-prob_rspnd_local)*100})
  216. for id_ in self.external_init_ids:
  217. external_ids.add(id_)
  218. # determine responder localities
  219. for id_ in self.respnd_ids:
  220. if id_ in local_ids or id_ in external_ids:
  221. continue
  222. pos = rspnd_locality.random()
  223. if pos == "local":
  224. local_ids.add(id_)
  225. elif pos == "external":
  226. external_ids.add(id_)
  227. self.local_ids, self.external_ids = local_ids, external_ids
  228. return self.local_ids, self.external_ids