mal-simulator 0.2.2__tar.gz → 0.2.4__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.
Files changed (30) hide show
  1. {mal_simulator-0.2.2/mal_simulator.egg-info → mal_simulator-0.2.4}/PKG-INFO +1 -1
  2. {mal_simulator-0.2.2 → mal_simulator-0.2.4/mal_simulator.egg-info}/PKG-INFO +1 -1
  3. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/mal_simulator.egg-info/SOURCES.txt +1 -0
  4. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/__init__.py +2 -2
  5. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/agents/__init__.py +6 -1
  6. mal_simulator-0.2.4/malsim/agents/heuristic_agent.py +125 -0
  7. mal_simulator-0.2.4/malsim/agents/searchers.py +117 -0
  8. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/envs/malsim_vectorized_obs_env.py +1 -1
  9. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/scenario.py +5 -1
  10. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/pyproject.toml +1 -1
  11. mal_simulator-0.2.2/malsim/agents/searchers.py +0 -99
  12. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/AUTHORS +0 -0
  13. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/LICENSE +0 -0
  14. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/README.md +0 -0
  15. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/mal_simulator.egg-info/dependency_links.txt +0 -0
  16. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/mal_simulator.egg-info/entry_points.txt +0 -0
  17. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/mal_simulator.egg-info/requires.txt +0 -0
  18. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/mal_simulator.egg-info/top_level.txt +0 -0
  19. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/__main__.py +0 -0
  20. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/agents/decision_agent.py +0 -0
  21. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/agents/keyboard_input.py +0 -0
  22. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/agents/passive_agent.py +0 -0
  23. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/envs/__init__.py +0 -0
  24. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/envs/base_classes.py +0 -0
  25. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/envs/gym_envs.py +0 -0
  26. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/malsim/mal_simulator.py +0 -0
  27. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/setup.cfg +0 -0
  28. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/tests/test_main.py +0 -0
  29. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/tests/test_mal_simulator.py +0 -0
  30. {mal_simulator-0.2.2 → mal_simulator-0.2.4}/tests/test_scenario.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: mal-simulator
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: A MAL compliant simulator.
5
5
  Author-email: Andrei Buhaiu <buhaiu@kth.se>, Joakim Loxdal <loxdal@kth.se>, Jakob Nyberg <jaknyb@kth.se>, Nikolaos Kakouros <nkak@kth.se>
6
6
  License: Apache Software License
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: mal-simulator
3
- Version: 0.2.2
3
+ Version: 0.2.4
4
4
  Summary: A MAL compliant simulator.
5
5
  Author-email: Andrei Buhaiu <buhaiu@kth.se>, Joakim Loxdal <loxdal@kth.se>, Jakob Nyberg <jaknyb@kth.se>, Nikolaos Kakouros <nkak@kth.se>
6
6
  License: Apache Software License
@@ -14,6 +14,7 @@ malsim/mal_simulator.py
14
14
  malsim/scenario.py
15
15
  malsim/agents/__init__.py
16
16
  malsim/agents/decision_agent.py
17
+ malsim/agents/heuristic_agent.py
17
18
  malsim/agents/keyboard_input.py
18
19
  malsim/agents/passive_agent.py
19
20
  malsim/agents/searchers.py
@@ -1,5 +1,5 @@
1
1
  # -*- encoding: utf-8 -*-
2
- # MAL Simulator v0.2.2
2
+ # MAL Simulator v0.2.4
3
3
  # Copyright 2025, Andrei Buhaiu.
4
4
  #
5
5
  # Licensed under the Apache License, Version 2.0 (the "License");
@@ -24,7 +24,7 @@ MAL Simulator
24
24
  """
25
25
 
26
26
  __title__ = "malsim"
27
- __version__ = "0.2.2"
27
+ __version__ = "0.2.4"
28
28
  __authors__ = ["Andrei Buhaiu", "Joakim Loxdal", "Jakob Nyberg", "Nikolaos Kakouros"]
29
29
  __license__ = "Apache 2.0"
30
30
  __docformat__ = "restructuredtext en"
@@ -2,11 +2,16 @@ from .decision_agent import DecisionAgent
2
2
  from .passive_agent import PassiveAgent
3
3
  from .keyboard_input import KeyboardAgent
4
4
  from .searchers import BreadthFirstAttacker, DepthFirstAttacker
5
+ from .heuristic_agent import (
6
+ DefendCompromisedDefender, DefendFutureCompromisedDefender
7
+ )
5
8
 
6
9
  __all__ = [
7
10
  'PassiveAgent',
8
11
  'DecisionAgent',
9
12
  'KeyboardAgent',
10
13
  'BreadthFirstAttacker',
11
- 'DepthFirstAttacker'
14
+ 'DepthFirstAttacker',
15
+ 'DefendCompromisedDefender',
16
+ 'DefendFutureCompromisedDefender'
12
17
  ]
@@ -0,0 +1,125 @@
1
+ from __future__ import annotations
2
+ from typing import Optional, TYPE_CHECKING
3
+ import logging
4
+ import math
5
+
6
+ import numpy as np
7
+
8
+ from .decision_agent import DecisionAgent
9
+
10
+ if TYPE_CHECKING:
11
+ from maltoolbox.attackgraph import AttackGraphNode
12
+ from ..mal_simulator import MalSimAgentStateView
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ class DefendCompromisedDefender(DecisionAgent):
17
+ """A defender that defends compromised assets using notPresent"""
18
+
19
+ def __init__(self, agent_config, **_):
20
+ # Seed and rng not currently used
21
+ seed = (
22
+ agent_config["seed"]
23
+ if agent_config.get("seed")
24
+ else np.random.SeedSequence().entropy
25
+ )
26
+ self.rng = (
27
+ np.random.default_rng(seed)
28
+ if agent_config.get("randomize")
29
+ else None
30
+ )
31
+
32
+ def get_next_action(
33
+ self, agent_state: MalSimAgentStateView, **kwargs
34
+ ) -> Optional[AttackGraphNode]:
35
+
36
+ """Return an action that disables a compromised node"""
37
+
38
+ selected_node_cost = math.inf
39
+ selected_node = None
40
+
41
+ # To make it deterministic
42
+ possible_choices = list(agent_state.action_surface)
43
+ possible_choices.sort(key=lambda n: n.id)
44
+
45
+ for node in possible_choices:
46
+
47
+ if node.is_enabled_defense():
48
+ continue
49
+
50
+ node_cost = node.extras.get('reward', 0)
51
+
52
+ # Strategy:
53
+ # - Enabled the cheapest defense node
54
+ # that has compromised child nodes
55
+ if node_cost < selected_node_cost:
56
+
57
+ node_has_compromised_child = (
58
+ any(
59
+ child_node.is_compromised()
60
+ for child_node in node.children
61
+ )
62
+ )
63
+
64
+ if node_has_compromised_child:
65
+ selected_node = node
66
+ selected_node_cost = node_cost
67
+
68
+ return selected_node
69
+
70
+
71
+ class DefendFutureCompromisedDefender(DecisionAgent):
72
+ """A defender that defends compromised assets using notPresent"""
73
+
74
+ def __init__(self, agent_config, **_):
75
+ # Seed and rng not currently used
76
+ seed = (
77
+ agent_config["seed"]
78
+ if agent_config.get("seed")
79
+ else np.random.SeedSequence().entropy
80
+ )
81
+ self.rng = (
82
+ np.random.default_rng(seed)
83
+ if agent_config.get("randomize")
84
+ else None
85
+ )
86
+
87
+ def get_next_action(
88
+ self, agent_state: MalSimAgentStateView, **kwargs
89
+ ) -> Optional[AttackGraphNode]:
90
+
91
+ """Return an action that disables a compromised node"""
92
+
93
+ selected_node_cost = math.inf
94
+ selected_node = None
95
+
96
+ # To make it deterministic
97
+ possible_choices = list(agent_state.action_surface)
98
+ possible_choices.sort(key=lambda n: n.id)
99
+
100
+ for node in possible_choices:
101
+
102
+ if node.is_enabled_defense():
103
+ continue
104
+
105
+ node_cost = node.extras.get('reward', 0)
106
+
107
+ # Strategy:
108
+ # - Enabled the cheapest defense node
109
+ # that has a non compromised child
110
+ # that has a compromised parent.
111
+ if node_cost < selected_node_cost:
112
+
113
+ node_has_child_that_can_be_compromised = (
114
+ any(
115
+ any(p.is_compromised() for p in child_node.parents)
116
+ and not child_node.is_compromised()
117
+ for child_node in node.children
118
+ )
119
+ )
120
+
121
+ if node_has_child_that_can_be_compromised:
122
+ selected_node = node
123
+ selected_node_cost = node_cost
124
+
125
+ return selected_node
@@ -0,0 +1,117 @@
1
+ from __future__ import annotations
2
+ import logging
3
+ import random
4
+
5
+ from collections import deque
6
+ from typing import Optional, TYPE_CHECKING, Any
7
+
8
+ from .decision_agent import DecisionAgent
9
+ from ..mal_simulator import MalSimAgentStateView
10
+
11
+ if TYPE_CHECKING:
12
+ from maltoolbox.attackgraph import AttackGraphNode
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class BreadthFirstAttacker(DecisionAgent):
18
+ """A Breadth-First agent, with possible randomization at each level."""
19
+
20
+ # A human-friendly name for the agent.
21
+ name = 'Breadth First Attacker'
22
+
23
+ # Controls where newly discovered steps will be appended to the deque of
24
+ # available actions. Differentiates between BFS and DFS agents.
25
+ _extend_method = 'extendleft'
26
+
27
+ _default_settings: dict[str, Any] = {
28
+ # Whether to randomize next target selection, still respecting the
29
+ # policy of the agent (BFS or DFS).
30
+ 'randomize': False,
31
+ # The random seed to initialize the randomness engine with.
32
+ # If set, the simulation will be deterministic.
33
+ 'seed': None,
34
+ }
35
+
36
+ def __init__(self, agent_config: dict) -> None:
37
+ """Initialize a BFS/DFS agent.
38
+
39
+ Args:
40
+ agent_config: Dict with settings to override defaults
41
+ """
42
+ self._targets: deque[AttackGraphNode] = deque()
43
+ self._current_target: Optional[AttackGraphNode] = None
44
+ self._settings = self._default_settings | agent_config
45
+
46
+ self._rng = random.Random(self._settings.get('seed'))
47
+ self._started = False
48
+
49
+ def get_next_action(
50
+ self, agent_state: MalSimAgentStateView, **kwargs
51
+ ) -> Optional[AttackGraphNode]:
52
+ """Receive the next action according to agent policy (bfs/dfs)"""
53
+
54
+ self._update_targets(
55
+ new_nodes=(
56
+ agent_state.step_action_surface_additions
57
+ if self._started else agent_state.action_surface
58
+ ),
59
+ disabled_nodes=(
60
+ agent_state.step_action_surface_removals
61
+ )
62
+ )
63
+
64
+ self._select_next_target()
65
+ self._started = True
66
+ return self._current_target
67
+
68
+ def _update_targets(
69
+ self,
70
+ new_nodes: set[AttackGraphNode],
71
+ disabled_nodes: set[AttackGraphNode],
72
+ ):
73
+ new_targets: list[AttackGraphNode] = []
74
+ if self._settings['seed']:
75
+ # If a seed is set, we assume the user wants determinism in the
76
+ # simulation. Thus, we sort to an ordered list to make sure the
77
+ # non-deterministic ordering of the action_surface set does not
78
+ # break simulation determinism.
79
+ new_targets = sorted(new_nodes, key=lambda n: n.id)
80
+ else:
81
+ # sorted above returns a list already
82
+ new_targets = list(new_nodes)
83
+
84
+ if self._settings['randomize']:
85
+ self._rng.shuffle(new_targets)
86
+
87
+ if (
88
+ self._current_target
89
+ and not self._current_target.is_compromised()
90
+ and self._current_target not in disabled_nodes
91
+ ):
92
+ # If self.current_target was not compromised, e.g. due to TTCs,
93
+ # it remains in action surface and should be added as a target.
94
+ self._targets.append(self._current_target)
95
+
96
+ # Enabled defenses may remove previously possible attack steps.
97
+ if disabled_nodes:
98
+ self._targets = deque(
99
+ n for n in self._targets if n not in disabled_nodes
100
+ )
101
+
102
+ # Use the extend method to add new targets
103
+ getattr(self._targets, self._extend_method)(new_targets)
104
+
105
+ def _select_next_target(self) -> None:
106
+ """
107
+ Implement the actual next target selection logic.
108
+ """
109
+ if self._targets:
110
+ self._current_target = self._targets.pop()
111
+ else:
112
+ self._current_target = None
113
+
114
+
115
+ class DepthFirstAttacker(BreadthFirstAttacker):
116
+ name = 'Depth First Attacker'
117
+ _extend_method = 'extend'
@@ -397,7 +397,7 @@ class MalSimVectorizedObsEnv(ParallelEnv, MalSimEnv):
397
397
  @property
398
398
  def possible_agents(self):
399
399
  """Required by ParallelEnv"""
400
- return list(self.sim._agents)
400
+ return list(self.sim._agent_states.keys())
401
401
 
402
402
  def _create_blank_observation(self, default_obs_state=-1):
403
403
  """Create the initial observation"""
@@ -22,7 +22,9 @@ from .agents import (
22
22
  BreadthFirstAttacker,
23
23
  DepthFirstAttacker,
24
24
  KeyboardAgent,
25
- PassiveAgent
25
+ PassiveAgent,
26
+ DefendCompromisedDefender,
27
+ DefendFutureCompromisedDefender
26
28
  )
27
29
 
28
30
  from .mal_simulator import AgentType, MalSimulator
@@ -32,6 +34,8 @@ agent_class_name_to_class = {
32
34
  'BreadthFirstAttacker': BreadthFirstAttacker,
33
35
  'KeyboardAgent': KeyboardAgent,
34
36
  'PassiveAgent': PassiveAgent,
37
+ 'DefendCompromisedDefender': DefendCompromisedDefender,
38
+ 'DefendFutureCompromisedDefender': DefendFutureCompromisedDefender
35
39
  }
36
40
 
37
41
  deprecated_fields = [
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mal-simulator"
3
- version = "0.2.2"
3
+ version = "0.2.4"
4
4
  authors = [
5
5
  { name="Andrei Buhaiu", email="buhaiu@kth.se" },
6
6
  { name="Joakim Loxdal", email="loxdal@kth.se" },
@@ -1,99 +0,0 @@
1
- from __future__ import annotations
2
- import logging
3
- import random
4
- import re
5
-
6
- from collections import deque
7
- from collections.abc import Iterable
8
- from typing import Optional, TYPE_CHECKING
9
-
10
- from .decision_agent import DecisionAgent
11
- from ..mal_simulator import MalSimAgentStateView
12
-
13
- if TYPE_CHECKING:
14
- from maltoolbox.attackgraph import AttackGraphNode
15
-
16
- logger = logging.getLogger(__name__)
17
-
18
-
19
- class BreadthFirstAttacker(DecisionAgent):
20
- """A Breadth-First agent, with possible randomization at each level."""
21
-
22
- _extend_method = 'extendleft'
23
- # Controls where newly discovered steps will be appended to the list of
24
- # available actions. Currently used to differentiate between BFS and DFS
25
- # agents.
26
-
27
- name = ' '.join(re.findall(r'[A-Z][^A-Z]*', __qualname__))
28
- # A human-friendly name for the agent.
29
-
30
- default_settings = {
31
- 'randomize': False,
32
- # Whether to randomize next target selection, still respecting the
33
- # policy of the agent (e.g. BFS or DFS).
34
- 'seed': None,
35
- # The random seed to initialize the randomness engine with. If set, the
36
- # simulation will be deterministic.
37
- }
38
-
39
- def __init__(self, agent_config: dict) -> None:
40
- """Initialize a BFS agent.
41
-
42
- Args:
43
- agent_config: Dict with settings to override defaults
44
- """
45
- self.targets: deque[AttackGraphNode] = deque()
46
- self.current_target: Optional[AttackGraphNode] = None
47
-
48
- self.settings = self.default_settings | agent_config
49
-
50
- self.rng = random.Random(self.settings.get('seed'))
51
-
52
- def get_next_action(
53
- self, agent_state: MalSimAgentStateView, **kwargs
54
- ) -> Optional[AttackGraphNode]:
55
- self._update_targets(agent_state.action_surface)
56
- self._select_next_target()
57
-
58
- return self.current_target
59
-
60
- def _update_targets(self, action_surface: Iterable[AttackGraphNode]):
61
- if self.settings['seed']:
62
- # If a seed is set, we assume the user wants determinism in the
63
- # simulation. Thus, we sort to an ordered list to make sure the
64
- # non-deterministic ordering of the action_surface set does not
65
- # break simulation determinism.
66
- action_surface = sorted(list(action_surface), key=lambda n: n.id)
67
-
68
- new_targets = [
69
- step
70
- for step in action_surface
71
- if step not in self.targets and not step.is_compromised()
72
- ]
73
-
74
- if self.settings['randomize']:
75
- self.rng.shuffle(new_targets)
76
-
77
- if self.current_target in new_targets:
78
- # If self.current_target is not yet compromised, e.g. due to TTCs,
79
- # keep using that as the target.
80
- new_targets.remove(self.current_target)
81
- new_targets.append(self.current_target)
82
-
83
- # Enabled defenses may remove previously possible attack steps.
84
- self.targets = deque(filter(lambda n: n.is_viable, self.targets))
85
-
86
- getattr(self.targets, self._extend_method)(new_targets)
87
-
88
- def _select_next_target(self) -> None:
89
- """
90
- Implement the actual next target selection logic.
91
- """
92
- try:
93
- self.current_target = self.targets.pop()
94
- except IndexError:
95
- self.current_target = None
96
-
97
-
98
- class DepthFirstAttacker(BreadthFirstAttacker):
99
- _extend_method = 'extend'
File without changes
File without changes
File without changes
File without changes