csle-attack-profiler 0.6.0__tar.gz → 0.6.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of csle-attack-profiler might be problematic. Click here for more details.

Files changed (20) hide show
  1. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/PKG-INFO +1 -1
  2. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/setup.cfg +2 -2
  3. csle_attack_profiler-0.6.2/src/csle_attack_profiler/__version__.py +1 -0
  4. csle_attack_profiler-0.6.2/src/csle_attack_profiler/hmm_profiling.py +448 -0
  5. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/src/csle_attack_profiler.egg-info/PKG-INFO +1 -1
  6. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/src/csle_attack_profiler.egg-info/requires.txt +2 -2
  7. csle_attack_profiler-0.6.0/src/csle_attack_profiler/__version__.py +0 -1
  8. csle_attack_profiler-0.6.0/src/csle_attack_profiler/hmm_profiling.py +0 -904
  9. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/README.md +0 -0
  10. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/pyproject.toml +0 -0
  11. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/setup.py +0 -0
  12. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/src/csle_attack_profiler/__init__.py +0 -0
  13. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/src/csle_attack_profiler/attack_profiler.py +0 -0
  14. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/src/csle_attack_profiler.egg-info/SOURCES.txt +0 -0
  15. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/src/csle_attack_profiler.egg-info/dependency_links.txt +0 -0
  16. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/src/csle_attack_profiler.egg-info/not-zip-safe +0 -0
  17. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/src/csle_attack_profiler.egg-info/top_level.txt +0 -0
  18. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/tests/test_attack_profiler.py +0 -0
  19. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/tests/test_hmm_profiler.py +0 -0
  20. {csle_attack_profiler-0.6.0 → csle_attack_profiler-0.6.2}/tests/test_kullback.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: csle_attack_profiler
3
- Version: 0.6.0
3
+ Version: 0.6.2
4
4
  Summary: Library with MITRE attack profiler for CSLE
5
5
  Author: Bength Pappila
6
6
  Author-email: brpa@kth.se
@@ -25,8 +25,8 @@ packages = find:
25
25
  zip_safe = no
26
26
  install_requires =
27
27
  mitreattack-python==2.0.14
28
- csle-base==0.6.0
29
- csle-common==0.6.0
28
+ csle-base==0.6.2
29
+ csle-common==0.6.2
30
30
 
31
31
  [options.packages.find]
32
32
  where = src
@@ -0,0 +1 @@
1
+ __version__ = '0.6.2'
@@ -0,0 +1,448 @@
1
+ from typing import List, Union, Tuple, Any
2
+ import numpy as np
3
+ import sys
4
+ from csle_common.dao.system_identification.emulation_statistics import EmulationStatistics
5
+ from csle_common.dao.emulation_action.attacker.emulation_attacker_action_id import EmulationAttackerActionId
6
+ from csle_common.dao.emulation_action.attacker.emulation_attacker_action_type import EmulationAttackerActionType
7
+ from csle_common.dao.emulation_action.attacker.emulation_attacker_action_outcome import EmulationAttackerActionOutcome
8
+ from csle_common.dao.emulation_action.attacker.emulation_attacker_action import EmulationAttackerAction
9
+ from csle_attack_profiler.attack_profiler import AttackProfiler
10
+
11
+
12
+ class HMMProfiler:
13
+ """
14
+ The HMMProfiler class is used to profile a sequence of observations based on a Hidden Markov Model (HMM).
15
+ """
16
+
17
+ def __init__(self, statistics: List[EmulationStatistics], model_name: Union[str, None] = None) -> None:
18
+ """
19
+ Class constructor
20
+
21
+ :param statistics: The list of EmulationStatistics objects
22
+ :param model_name: The name of the model
23
+ :return: None
24
+ """
25
+ self.statistics = statistics
26
+ self.transition_matrix: List[List[float]] = []
27
+ self.emission_matrix: List[List[float]] = []
28
+ self.hidden_states: List[str] = []
29
+ self.emission_matrix_observations: List[int] = []
30
+ self.start_state_probs: List[float] = []
31
+ self.model_name = None
32
+
33
+ def create_model(self, transition_matrix: List[List[float]],
34
+ hidden_states: List[str], metric: str,
35
+ save_model: bool = False, location: str = ".") -> None:
36
+ """
37
+ Creates the HMM model based on the given transition matrix, states and metrics.
38
+ If save = True, matrices are saved to given location
39
+
40
+ :param transition_matrix: The transition matrix
41
+ :param states: The list of states of the HMM (format: 'A:attack_name' or
42
+ 'no_intrusion' based on emulation statistics file)
43
+ :param metrics: The list of metrics to profile
44
+ :param save: Whether to save the matrices to a file
45
+ :param location: The location to save the matrices, if save = True, e.g "./resources",
46
+ default is current directory
47
+ :return: None
48
+ """
49
+ emission_matrix, emission_matrix_observations = self.get_matrices_of_observation(self.statistics,
50
+ metric, hidden_states)
51
+ self.emission_matrix = emission_matrix
52
+ self.emission_matrix_observations = emission_matrix_observations
53
+ self.transition_matrix = transition_matrix
54
+ self.start_state_probs = self.calculate_initial_states(self.transition_matrix)
55
+ self.hidden_states = hidden_states
56
+ if save_model and location:
57
+ np.save(f'{location}/transition_matrix.npy', transition_matrix)
58
+ np.save(f'{location}/hidden_states.npy', hidden_states)
59
+ np.save(f'{location}/start_state_probs.npy', self.start_state_probs)
60
+ np.save(f'{location}/emission_matrix_{metric}.npy', emission_matrix)
61
+ np.save(f'{location}/emission_matrix_observations_{metric}.npy', emission_matrix_observations)
62
+
63
+ def load_model(self, location: str, metric: str) -> None:
64
+ """
65
+ Loads the HMM model from the given location.
66
+
67
+ :param location: The location of the model files, default is current directory
68
+ :return: None
69
+ """
70
+ self.transition_matrix = np.load(f'{location}/transition_matrix.npy')
71
+ self.hidden_states = np.load(f'{location}/hidden_states.npy')
72
+ self.start_state_probs = np.load(f'{location}/start_state_probs.npy')
73
+ self.emission_matrix = np.load(f'{location}/emission_matrix_{metric}.npy')
74
+ self.emission_matrix_observations = np.load(f'{location}/emission_matrix_observations_{metric}.npy')
75
+
76
+ def profile_sequence(self, sequence: List[int]) -> List[str]:
77
+ """
78
+ Profiles a sequence of observations based on the HMM model.
79
+
80
+ :param sequence: The sequence of observations
81
+ :return: The most likely sequence of states
82
+ """
83
+
84
+ path = HMMProfiler.viterbi(self.hidden_states, self.start_state_probs,
85
+ self.transition_matrix, self.emission_matrix,
86
+ sequence, self.emission_matrix_observations)
87
+ profiled_sequence = []
88
+ for i in range(len(path)):
89
+ profiled_sequence.append(self.hidden_states[int(path[i])])
90
+
91
+ return profiled_sequence
92
+
93
+ def get_matrices_of_observation(self, statistics: List[EmulationStatistics],
94
+ metric: str, states: List[str]) -> Tuple[List[List[float]], List[int]]:
95
+ """
96
+ Creates the emission matrix for a given metric based on the statistics from the EmulationStatistics objects.
97
+
98
+ :param statistics: The list of EmulationStatistics objects
99
+ :param metric: The metric to get the emission matrix for
100
+ :param states: The list of states
101
+ :return: The emission matrix, the list of observations, the list of states
102
+ """
103
+ emission_matrix = []
104
+ attack_observations = {}
105
+ attack_observations_total_counts = {}
106
+ all_keys = set()
107
+
108
+ for stats in statistics:
109
+ for condition, metric_distribution in stats.conditionals_counts.items():
110
+ action = condition.split('_')
111
+ if action[0] == 'no':
112
+ action[0] = 'no_intrusion'
113
+ if action[0] not in attack_observations:
114
+ # We are not intrested in the observations from 'intrusion' or 'A:Continue'
115
+ if action[0] == 'intrusion' or action[0] == 'A:Continue':
116
+ continue
117
+ else:
118
+ # Add the observations of the attack to the dictionary
119
+ if metric in metric_distribution:
120
+ attack_observations[action[0]] = metric_distribution[metric]
121
+ # Sum the total counts of the observations
122
+ attack_observations_total_counts[action[0]] = sum(attack_observations[action[0]].values())
123
+ # Aggregate the counts from the metric distribution
124
+ else:
125
+ counts_observation = metric_distribution[metric]
126
+ for element in counts_observation:
127
+ if element in attack_observations[action[0]]:
128
+ # Aggregate the counts if the element is already in the dictionary
129
+ attack_observations[action[0]][element] += counts_observation[element]
130
+ else:
131
+ attack_observations[action[0]][element] = counts_observation[element]
132
+ # Sum the total counts of the observations
133
+ attack_observations_total_counts[action[0]] += sum(attack_observations[action[0]].values())
134
+
135
+ # Store all possible values for the observation
136
+ if action[0] in attack_observations:
137
+ all_keys.update(attack_observations[action[0]])
138
+
139
+ # Normalize the counts
140
+ for attack, _ in attack_observations.items():
141
+ attack_observations_total_counts[attack] = sum(attack_observations[attack].values())
142
+ for key in all_keys:
143
+ int_key = int(key)
144
+ if key in attack_observations[attack]:
145
+ count = attack_observations[attack].pop(key, 0)
146
+ attack_observations[attack][int_key] = count / attack_observations_total_counts[attack]
147
+ else:
148
+ attack_observations[attack][int_key] = 0
149
+ # Sort the dictionary by key
150
+ attack_observations[attack] = dict(sorted(attack_observations[attack].items()))
151
+
152
+ # Take any attack as the reference to get the keys
153
+ emission_matrix_observations = []
154
+ emission_matrix_states = []
155
+ # Create the emission matrix
156
+ for state in states:
157
+ if state in attack_observations:
158
+ # Normalize the and then append
159
+ emission_matrix.append(list(attack_observations[state].values()))
160
+ # Get the keys of all observations
161
+ emission_matrix_observations = list(attack_observations[state].keys())
162
+ emission_matrix_states.append(state)
163
+ else:
164
+ # LaPlace smoothing for missing observations
165
+ num_keys = len(all_keys)
166
+ laplace_probability = 1 / (num_keys + 2)
167
+ laplace_sum = laplace_probability * num_keys
168
+ laplace_probability_adj = laplace_probability / laplace_sum
169
+ emission_matrix.append([laplace_probability_adj] * num_keys)
170
+ emission_matrix_states.append(state)
171
+
172
+ # Check if the sum of the probabilities is 1
173
+ for i in range(len(emission_matrix)):
174
+ sum_prob = round(sum(emission_matrix[i]), 10)
175
+ if sum_prob != 1:
176
+ print(f'Sum of probabilities for state {emission_matrix_states[i]} is {sum_prob}')
177
+
178
+ return (emission_matrix, emission_matrix_observations)
179
+
180
+ def convert_states_to_profiles(self, states: List[str]) -> List[Union[AttackProfiler, str]]:
181
+ """
182
+ Converts a list of states to a list of AttackProfiles.
183
+
184
+ :param states: The list of states to convert
185
+ :return: The list of EmulationAttackerActionId
186
+ """
187
+
188
+ new_states: List[Union[AttackProfiler, str]] = []
189
+ for state in states:
190
+ if state == 'A:Continue':
191
+ action = EmulationAttackerAction(id=EmulationAttackerActionId.CONTINUE, name="Continue", cmds=[],
192
+ type=None, descr="CONTINUE", ips=[], index=0, action_outcome='')
193
+ p = AttackProfiler.get_attack_profile(action)
194
+ new_states.append(p)
195
+ elif state == 'A:CVE-2015-1427 exploit':
196
+ action = EmulationAttackerAction(
197
+ id=EmulationAttackerActionId.CVE_2015_1427_EXPLOIT, name="CVE-2015-1427 exploit", cmds=None,
198
+ type=EmulationAttackerActionType.EXPLOIT,
199
+ descr="Uses the CVE-2015-1427 vulnerability to "
200
+ "get remote code execution and then sets up a SSH backdoor"
201
+ "to upgrade the channel", index=None, ips=[],
202
+ action_outcome=EmulationAttackerActionOutcome.SHELL_ACCESS)
203
+ p = AttackProfiler.get_attack_profile(action)
204
+ new_states.append(p)
205
+ elif state == 'A:DVWA SQL Injection Exploit':
206
+ action = EmulationAttackerAction(
207
+ id=EmulationAttackerActionId.DVWA_SQL_INJECTION, name="DVWA SQL Injection Exploit",
208
+ cmds=None, type=EmulationAttackerActionType.EXPLOIT,
209
+ descr="Uses the DVWA SQL Injection exploit to extract secret passwords",
210
+ index=None, ips=[], action_outcome=EmulationAttackerActionOutcome.SHELL_ACCESS)
211
+ p = AttackProfiler.get_attack_profile(action)
212
+ new_states.append(p)
213
+ elif state == 'A:Install tools':
214
+ action = EmulationAttackerAction(
215
+ id=EmulationAttackerActionId.INSTALL_TOOLS, name="Install tools", cmds=None,
216
+ type=EmulationAttackerActionType.POST_EXPLOIT,
217
+ descr="If taken root on remote machine, installs pentest tools, e.g. nmap",
218
+ index=None, ips=[], action_outcome=EmulationAttackerActionOutcome.PIVOTING)
219
+ p = AttackProfiler.get_attack_profile(action)
220
+ new_states.append(p)
221
+ elif state == 'A:Network service login':
222
+ action = EmulationAttackerAction(
223
+ id=EmulationAttackerActionId.NETWORK_SERVICE_LOGIN, name="Network service login",
224
+ cmds=[], type=EmulationAttackerActionType.POST_EXPLOIT,
225
+ descr="Uses known credentials to login to network services on a server",
226
+ index=None, ips=None, action_outcome=EmulationAttackerActionOutcome.LOGIN)
227
+ p = AttackProfiler.get_attack_profile(action)
228
+ new_states.append(p)
229
+ elif state == 'A:Ping Scan':
230
+ action = EmulationAttackerAction(
231
+ id=EmulationAttackerActionId.PING_SCAN_HOST, name="Ping Scan",
232
+ cmds=None, type=EmulationAttackerActionType.RECON,
233
+ descr="A host discovery scan, it is quick because it only checks of hosts "
234
+ "are up with Ping, without scanning the ports.", ips=None, index=None,
235
+ action_outcome=EmulationAttackerActionOutcome.INFORMATION_GATHERING, backdoor=False)
236
+ p = AttackProfiler.get_attack_profile(action)
237
+ new_states.append(p)
238
+ elif state == 'A:Sambacry Explolit':
239
+ action = EmulationAttackerAction(
240
+ id=EmulationAttackerActionId.SAMBACRY_EXPLOIT, name="Sambacry Explolit", cmds=None,
241
+ type=EmulationAttackerActionType.EXPLOIT,
242
+ descr="Uses the sambacry shell to get remote code execution and then"
243
+ "sets up a SSH backdoor to upgrade the channel",
244
+ index=None, ips=[], action_outcome=EmulationAttackerActionOutcome.SHELL_ACCESS)
245
+ p = AttackProfiler.get_attack_profile(action)
246
+ new_states.append(p)
247
+ elif state == 'A:ShellShock Explolit':
248
+ action = EmulationAttackerAction(
249
+ id=EmulationAttackerActionId.SHELLSHOCK_EXPLOIT, name="ShellShock Explolit",
250
+ cmds=None, type=EmulationAttackerActionType.EXPLOIT,
251
+ descr="Uses the Shellshock exploit and curl to do remote code execution and create a backdoor",
252
+ index=None, ips=[], action_outcome=EmulationAttackerActionOutcome.SHELL_ACCESS)
253
+ p = AttackProfiler.get_attack_profile(action)
254
+ new_states.append(p)
255
+ elif state == 'A:SSH dictionary attack for username=pw':
256
+ action = EmulationAttackerAction(
257
+ id=EmulationAttackerActionId.SSH_SAME_USER_PASS_DICTIONARY_HOST,
258
+ name="SSH dictionary attack for username=pw", cmds=None,
259
+ type=EmulationAttackerActionType.EXPLOIT, index=None,
260
+ descr="A dictionary attack that tries common passwords and usernames for SSH"
261
+ "where username=password", ips=None,
262
+ action_outcome=EmulationAttackerActionOutcome.SHELL_ACCESS)
263
+ p = AttackProfiler.get_attack_profile(action)
264
+ new_states.append(p)
265
+ elif state == 'A:FTP dictionary attack for username=pw':
266
+ action = EmulationAttackerAction(
267
+ id=EmulationAttackerActionId.FTP_SAME_USER_PASS_DICTIONARY_HOST,
268
+ name="FTP dictionary attack for username=pw", cmds=None, type=EmulationAttackerActionType.EXPLOIT,
269
+ index=None, descr="A dictionary attack that tries common passwords and"
270
+ "usernames for FTP where username=password", ips=None,
271
+ action_outcome=EmulationAttackerActionOutcome.SHELL_ACCESS)
272
+ p = AttackProfiler.get_attack_profile(action)
273
+ new_states.append(p)
274
+ elif state == 'A:Telnet dictionary attack for username=pw':
275
+ action = EmulationAttackerAction(
276
+ id=EmulationAttackerActionId.TELNET_SAME_USER_PASS_DICTIONARY_HOST,
277
+ name="Telnet dictionary attack for username=pw", cmds=None,
278
+ type=EmulationAttackerActionType.EXPLOIT, index=None,
279
+ descr="A dictionary attack that tries common passwords and usernames for"
280
+ "Telnet where username=password", ips=None,
281
+ action_outcome=EmulationAttackerActionOutcome.SHELL_ACCESS)
282
+ p = AttackProfiler.get_attack_profile(action)
283
+ new_states.append(p)
284
+ elif state == 'A:CVE-2010-0426 exploit':
285
+ action = EmulationAttackerAction(
286
+ id=EmulationAttackerActionId.CVE_2010_0426_PRIV_ESC,
287
+ name="CVE-2010-0426 exploit", cmds=None, type=EmulationAttackerActionType.PRIVILEGE_ESCALATION,
288
+ descr="Uses the CVE-2010-0426 vulnerability to perform privilege escalation to get root access",
289
+ index=None, ips=[], action_outcome=EmulationAttackerActionOutcome.PRIVILEGE_ESCALATION_ROOT)
290
+ p = AttackProfiler.get_attack_profile(action)
291
+ new_states.append(p)
292
+ elif state == 'A:TCP SYN (Stealth) Scan':
293
+ action = EmulationAttackerAction(
294
+ id=EmulationAttackerActionId.TCP_SYN_STEALTH_SCAN_HOST, name="TCP SYN (Stealth) Scan",
295
+ cmds=None, type=EmulationAttackerActionType.RECON,
296
+ descr="A stealthy and fast TCP SYN scan to detect open TCP ports on the subnet", ips=None,
297
+ index=None, action_outcome=EmulationAttackerActionOutcome.INFORMATION_GATHERING, backdoor=False)
298
+ p = AttackProfiler.get_attack_profile(action)
299
+ new_states.append(p)
300
+ elif state == 'ssh backdoor':
301
+ action = EmulationAttackerAction(
302
+ id=EmulationAttackerActionId.SSH_BACKDOOR, name="Install SSH backdoor",
303
+ cmds=None, type=EmulationAttackerActionType.POST_EXPLOIT,
304
+ descr="If taken root on remote machine, installs a ssh backdoor useful for"
305
+ "upgrading telnetor weaker channels", index=None, ips=[],
306
+ action_outcome=EmulationAttackerActionOutcome.PIVOTING, alt_cmds=None, backdoor=True)
307
+ p = AttackProfiler.get_attack_profile(action)
308
+ new_states.append(p)
309
+ else:
310
+ new_states.append(state)
311
+
312
+ return new_states
313
+
314
+ def calculate_initial_states(self, transition_matrix: List[List[float]]) -> List[float]:
315
+ """
316
+ Calculates the initial states probabilities based on the transition matrix.
317
+
318
+ 1 / (# of states)
319
+
320
+ :param transition_matrix: The transition matrix
321
+ :return: The start states probabilities
322
+ """
323
+ start_states = []
324
+ total_states = len(transition_matrix)
325
+ for _ in range(total_states):
326
+ start_states.append(1 / total_states)
327
+
328
+ return start_states
329
+
330
+ @staticmethod
331
+ def viterbi(hidden_states: List[EmulationAttackerActionId], init_probs: List[float],
332
+ trans_matrix: List[List[float]], emission_matrix: List[List[float]],
333
+ obs: List[int], emissions_list: List[int]) -> List[float]:
334
+ """
335
+ Viterbi algorithm for Hidden Markov Models (HMM).
336
+
337
+ :param hidden_states: The hidden states
338
+ :param init_probs: The initial probabilities of the hidden states
339
+ :param trans_matrix: The transition matrix
340
+ :param emission_matrix: The emission matrix
341
+ :param obs: The observation sequence
342
+ :param emissions_list: The list of possible observations
343
+ :return: The most likely sequence of hidden states
344
+ """
345
+ # Convert the emissions list to a numpy array, to use the where function
346
+ emissions_list_typed: np.ndarray[int, Any] = np.array(emissions_list)
347
+
348
+ # Check that the sum equals 1
349
+ for i in range(len(emission_matrix)):
350
+ if round(sum(emission_matrix[i]), 10) != 1:
351
+ print(f'Sum of probabilities for state {hidden_states[i]} is not 1')
352
+ print(f'Sum of probabilities: {sum(emission_matrix[i])}')
353
+
354
+ # The number of hidden states
355
+ S = len(hidden_states)
356
+ # The number of observations
357
+ T = len(obs)
358
+
359
+ # The Viterbi matrix (prob) T x S matrix of zeroes
360
+ prob = np.zeros((T, S))
361
+ # The backpointer matrix (prev)
362
+ prev = np.empty((T, S))
363
+ # Initialization
364
+ for i in range(S):
365
+ # Fetch the index of the observation in the emission_matrix
366
+ index, = np.where(emissions_list_typed == obs[0])
367
+ if index[0].size > 0:
368
+ prob[0][i] = init_probs[i] * emission_matrix[i][index[0]]
369
+ else:
370
+ print(f'Observation {obs[0]} not found in the emission matrix')
371
+ sys.exit(1)
372
+
373
+ # Recursion
374
+ for t in range(1, T):
375
+ index, = np.where(emissions_list_typed == obs[t])
376
+ for i in range(S):
377
+ max_prob = -1
378
+ max_state = -1
379
+ for j in range(S):
380
+ new_prob = prob[t - 1][j] * trans_matrix[j][i] * emission_matrix[i][index[0]]
381
+ if new_prob > max_prob:
382
+ max_prob = new_prob
383
+ max_state = j
384
+ prob[t][i] = max_prob
385
+ prev[t][i] = max_state
386
+
387
+ path = np.zeros(T)
388
+ path[T - 1] = np.argmax(prob[T - 1])
389
+ for t in range(T - 2, -1, -1):
390
+ path[t] = prev[t + 1][int(path[t + 1])]
391
+ # Convert the path to a list
392
+ typed_path: List[float] = path.tolist()
393
+
394
+ return typed_path
395
+
396
+ def generate_sequence(self, intrusion_length: int, initial_state_index: int,
397
+ seed: Union[int, None] = None) -> Tuple[List[str], List[int]]:
398
+ """
399
+ Generates a sequence of states and corresponding observations based on the given emission matrix,
400
+ and transition matrix. First, a sequence of observation from 'no intrusion' is generated
401
+ based on the geometric distribution of the initial state. Then, a sequence observations and states are
402
+ generated based on emission matrix and transition matrix. The length of this intrusion
403
+ sequence is given by the intrusion_length parameter.
404
+
405
+ :param intrusion_length: The length of the intrusion
406
+ :param initial_state_index: The index of the initial state
407
+ :param seed: The seed for the random number generator
408
+ return: The sequence of states and observations
409
+ """
410
+
411
+ P_obs = self.emission_matrix
412
+ P_states = self.transition_matrix
413
+ states = self.hidden_states
414
+ observations = self.emission_matrix_observations
415
+
416
+ if seed:
417
+ np.random.seed(seed)
418
+ obs_len = len(observations)
419
+ states_len = len(states)
420
+ # Return the geometric distribution of the initial state
421
+ dist = np.random.geometric(p=P_states[initial_state_index][0], size=1000)
422
+ T_i = round(sum(dist) / len(dist))
423
+
424
+ state_seq = [states[initial_state_index]] * T_i
425
+ obs_seq = []
426
+ for i in range(T_i):
427
+ o_i = np.random.choice(obs_len, p=P_obs[initial_state_index])
428
+ obs_seq.append(observations[o_i])
429
+
430
+ recon_states_sum = np.sum(P_states[initial_state_index][1:])
431
+ recon_states = P_states[initial_state_index][1:] / recon_states_sum
432
+
433
+ intrusion_start_state = np.random.choice(states_len - 1, p=recon_states) + 1
434
+ intrusion_start_observation = np.random.choice(obs_len, p=P_obs[intrusion_start_state])
435
+ state_seq.append(states[intrusion_start_state])
436
+ obs_seq.append(observations[intrusion_start_observation])
437
+
438
+ s_i = intrusion_start_state
439
+ if intrusion_length == 1:
440
+ return state_seq, obs_seq
441
+ for i in range(intrusion_length - 1):
442
+ # si ~ Ps(si | si-1)
443
+ s_i = np.random.choice(states_len, p=P_states[s_i])
444
+ # oi ~ Po(oi | si)
445
+ o_i = np.random.choice(obs_len, p=P_obs[s_i])
446
+ state_seq.append(states[s_i])
447
+ obs_seq.append(observations[o_i])
448
+ return state_seq, obs_seq
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: csle-attack-profiler
3
- Version: 0.6.0
3
+ Version: 0.6.2
4
4
  Summary: Library with MITRE attack profiler for CSLE
5
5
  Author: Bength Pappila
6
6
  Author-email: brpa@kth.se
@@ -1,6 +1,6 @@
1
1
  mitreattack-python==2.0.14
2
- csle-base==0.6.0
3
- csle-common==0.6.0
2
+ csle-base==0.6.2
3
+ csle-common==0.6.2
4
4
 
5
5
  [testing]
6
6
  pytest>=6.0
@@ -1 +0,0 @@
1
- __version__ = '0.6.0'