CommunicationProcessor.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. from lea import Lea
  2. from random import randrange
  3. from Attack.MembersMgmtCommAttack import MessageType
  4. from Attack.MembersMgmtCommAttack import Message
  5. class CommunicationProcessor():
  6. """
  7. Class to process parsed input CSV/XML data and retrieve a mapping or other information.
  8. """
  9. def __init__(self, mtypes:dict, nat:bool):
  10. """
  11. Creates an instance of CommunicationProcessor.
  12. :param mtypes: a dict containing an int to EnumType mapping of MessageTypes
  13. :param nat: whether NAT is present in this network
  14. """
  15. self.packets = []
  16. self.mtypes = mtypes
  17. self.nat = nat
  18. def set_mapping(self, packets: list, mapped_ids: dict):
  19. """
  20. Set the selected mapping for this communication processor.
  21. :param packets: all packets contained in the mapped time frame
  22. :param mapped_ids: the chosen IDs
  23. """
  24. self.packets = packets
  25. self.local_init_ids = set(mapped_ids)
  26. def get_comm_interval(self, cpp_comm_proc, strategy: str, number_ids: int, max_int_time: int, start_idx: int, end_idx: int):
  27. """
  28. Finds a communication interval with respect to the given strategy. The interval is maximum of the given seconds
  29. and has at least number_ids communicating initiators in it.
  30. :param cpp_comm_proc: An instance of the C++ communication processor that stores all the input messages and
  31. is responsible for retrieving the interval(s)
  32. :param strategy: The selection strategy (i.e. random, optimal, custom)
  33. :param number_ids: The number of initiator IDs that have to exist in the interval(s)
  34. :param max_int_time: The maximum time period of the interval
  35. :param start_idx: The message index the interval should start at (None if not specified)
  36. :param end_idx: The message index the interval should stop at (inclusive) (None if not specified)
  37. :return: A dict representing the communication interval. It contains the initiator IDs,
  38. the start index and end index of the respective interval. The respective keys
  39. are {IDs, Start, End}. If no interval is found, an empty dict is returned.
  40. """
  41. if strategy == "random":
  42. # try finding not-empty interval 5 times
  43. for i in range(5):
  44. start_idx = randrange(0, cpp_comm_proc.get_message_count())
  45. interval = cpp_comm_proc.find_interval_from_startidx(start_idx, number_ids, max_int_time)
  46. if interval and interval["IDs"]:
  47. return interval
  48. return {}
  49. elif strategy == "optimal":
  50. intervals = cpp_comm_proc.find_optimal_interval(number_ids, max_int_time)
  51. if not intervals:
  52. return {}
  53. else:
  54. for i in range(5):
  55. interval = intervals[randrange(0, len(intervals))]
  56. if interval and interval["IDs"]:
  57. return interval
  58. return {}
  59. elif strategy == "custom":
  60. if (not start_idx) and (not end_idx):
  61. print("Custom strategy was selected, but no (valid) start or end index was specified.")
  62. print("Because of this, a random interval is selected.")
  63. start_idx = randrange(0, cpp_comm_proc.get_message_count())
  64. interval = cpp_comm_proc.find_interval_from_startidx(start_idx, number_ids, max_int_time)
  65. elif (not start_idx) and end_idx:
  66. end_idx -= 1 # because message indices start with 1 (for the user)
  67. interval = cpp_comm_proc.find_interval_from_endidx(end_idx, number_ids, max_int_time)
  68. elif start_idx and (not end_idx):
  69. start_idx -= 1 # because message indices start with 1 (for the user)
  70. interval = cpp_comm_proc.find_interval_from_startidx(start_idx, number_ids, max_int_time)
  71. elif start_idx and end_idx:
  72. start_idx -= 1; end_idx -= 1
  73. ids = cpp_comm_proc.get_interval_init_ids(start_idx, end_idx)
  74. if not ids:
  75. return {}
  76. return {"IDs": ids, "Start": start_idx, "End": end_idx}
  77. if not interval or not interval["IDs"]:
  78. return {}
  79. return interval
  80. def det_id_roles_and_msgs(self):
  81. """
  82. Determine the role of every mapped ID. The role can be initiator, responder or both.
  83. On the side also connect corresponding messages together to quickly find out
  84. which reply belongs to which request and vice versa.
  85. :return: the selected messages
  86. """
  87. mtypes = self.mtypes
  88. # setup initial variables and their values
  89. respnd_ids = set()
  90. # msgs --> the filtered messages, msg_id --> an increasing ID to give every message an artificial primary key
  91. msgs, msg_id = [], 0
  92. # keep track of previous request to find connections
  93. prev_reqs = {}
  94. # used to determine whether a request has been seen yet, so that replies before the first request are skipped and do not throw an error by
  95. # accessing the empty dict prev_reqs (this is not a perfect solution, but it works most of the time)
  96. req_seen = False
  97. local_init_ids = self.local_init_ids
  98. external_init_ids = set()
  99. # process every packet individually
  100. for packet in self.packets:
  101. id_src, id_dst, msg_type, time = packet["Src"], packet["Dst"], int(packet["Type"]), float(packet["Time"])
  102. lineno = packet.get("LineNumber", -1)
  103. # if if either one of the IDs is not mapped, continue
  104. if (id_src not in local_init_ids) and (id_dst not in local_init_ids):
  105. continue
  106. # convert message type number to enum type
  107. msg_type = mtypes[msg_type]
  108. # process a request
  109. if msg_type in {MessageType.SALITY_HELLO, MessageType.SALITY_NL_REQUEST}:
  110. if not self.nat and id_dst in local_init_ids and id_src not in local_init_ids:
  111. external_init_ids.add(id_src)
  112. elif id_src not in local_init_ids:
  113. continue
  114. else:
  115. # process ID's role
  116. respnd_ids.add(id_dst)
  117. # convert the abstract message into a message object to handle it better
  118. msg_str = "{0}-{1}".format(id_src, id_dst)
  119. msg = Message(msg_id, id_src, id_dst, msg_type, time, line_no = lineno)
  120. msgs.append(msg)
  121. prev_reqs[msg_str] = msg_id
  122. msg_id += 1
  123. req_seen = True
  124. # process a reply
  125. elif msg_type in {MessageType.SALITY_HELLO_REPLY, MessageType.SALITY_NL_REPLY} and req_seen:
  126. if not self.nat and id_src in local_init_ids and id_dst not in local_init_ids:
  127. # process ID's role
  128. external_init_ids.add(id_dst)
  129. elif id_dst not in local_init_ids:
  130. continue
  131. else:
  132. # process ID's role
  133. respnd_ids.add(id_src)
  134. # convert the abstract message into a message object to handle it better
  135. msg_str = "{0}-{1}".format(id_dst, id_src)
  136. # find the request message ID for this response and set its reference index
  137. refer_idx = prev_reqs[msg_str]
  138. msgs[refer_idx].refer_msg_id = msg_id
  139. msg = Message(msg_id, id_src, id_dst, msg_type, time, refer_idx, lineno)
  140. msgs.append(msg)
  141. # remove the request to this response from storage
  142. del(prev_reqs[msg_str])
  143. msg_id += 1
  144. elif msg_type == MessageType.TIMEOUT and id_src in local_init_ids and not self.nat:
  145. # convert the abstract message into a message object to handle it better
  146. msg_str = "{0}-{1}".format(id_dst, id_src)
  147. # find the request message ID for this response and set its reference index
  148. refer_idx = prev_reqs.get(msg_str)
  149. if refer_idx is not None:
  150. msgs[refer_idx].refer_msg_id = msg_id
  151. if msgs[refer_idx].type == MessageType.SALITY_NL_REQUEST:
  152. msg = Message(msg_id, id_src, id_dst, MessageType.SALITY_NL_REPLY, time, refer_idx, lineno)
  153. else:
  154. msg = Message(msg_id, id_src, id_dst, MessageType.SALITY_HELLO_REPLY, time, refer_idx, lineno)
  155. msgs.append(msg)
  156. # remove the request to this response from storage
  157. del(prev_reqs[msg_str])
  158. msg_id += 1
  159. # store the retrieved information in this object for later use
  160. self.respnd_ids = sorted(respnd_ids)
  161. self.external_init_ids = sorted(external_init_ids)
  162. self.messages = msgs
  163. # return the selected messages
  164. return self.messages
  165. def det_ext_and_local_ids(self, prob_rspnd_local: int=0):
  166. """
  167. Map the given IDs to a locality (i.e. local or external} considering the given probabilities.
  168. :param comm_type: the type of communication (i.e. local, external or mixed)
  169. :param prob_rspnd_local: the probabilty that a responder is local
  170. """
  171. external_ids = set()
  172. local_ids = self.local_init_ids.copy()
  173. # set up probabilistic chooser
  174. rspnd_locality = Lea.fromValFreqsDict({"local": prob_rspnd_local*100, "external": (1-prob_rspnd_local)*100})
  175. for id_ in self.external_init_ids:
  176. external_ids.add(id_)
  177. # determine responder localities
  178. for id_ in self.respnd_ids:
  179. if id_ in local_ids or id_ in external_ids:
  180. continue
  181. pos = rspnd_locality.random()
  182. if pos == "local":
  183. local_ids.add(id_)
  184. elif pos == "external":
  185. external_ids.add(id_)
  186. self.local_ids, self.external_ids = local_ids, external_ids
  187. return self.local_ids, self.external_ids