CommunicationProcessor.py 10 KB

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