CommunicationProcessor.py 10 KB

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