mal-simulator 2.2.0__tar.gz → 2.4.0__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 (89) hide show
  1. {mal_simulator-2.2.0/mal_simulator.egg-info → mal_simulator-2.4.0}/PKG-INFO +12 -4
  2. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/README.md +11 -3
  3. {mal_simulator-2.2.0 → mal_simulator-2.4.0/mal_simulator.egg-info}/PKG-INFO +12 -4
  4. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/mal_simulator.egg-info/SOURCES.txt +1 -1
  5. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/__init__.py +2 -3
  6. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/__main__.py +10 -6
  7. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/config/agent_settings.py +83 -24
  8. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/config/agent_settings_factories.py +38 -4
  9. mal_simulator-2.4.0/malsim/config/node_property_rule.py +158 -0
  10. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/config/sim_settings.py +24 -20
  11. mal_simulator-2.4.0/malsim/envs/base_classes.py +29 -0
  12. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/envs/graph/graph_env.py +30 -26
  13. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/envs/graph/mal_spaces.py +17 -2
  14. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/envs/graph/serialization.py +38 -3
  15. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/envs/graph/utils.py +20 -10
  16. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/envs/graph/wrapper.py +8 -2
  17. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/envs/legacy/gym_envs.py +13 -26
  18. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/envs/legacy/malsim_vectorized_obs_env.py +37 -46
  19. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/__init__.py +6 -6
  20. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/agent_state.py +10 -9
  21. mal_simulator-2.4.0/malsim/mal_simulator/agent_states.py +20 -0
  22. mal_simulator-2.4.0/malsim/mal_simulator/attack_surface.py +102 -0
  23. mal_simulator-2.4.0/malsim/mal_simulator/attacker_state.py +42 -0
  24. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/attacker_state_factories.py +83 -74
  25. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/attacker_step.py +16 -20
  26. mal_simulator-2.4.0/malsim/mal_simulator/defender_state.py +38 -0
  27. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/defender_state_factories.py +22 -46
  28. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/defender_step.py +13 -13
  29. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/defense_surface.py +5 -5
  30. mal_simulator-2.4.0/malsim/mal_simulator/false_alerts.py +59 -0
  31. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/graph_processing.py +20 -22
  32. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/graph_state.py +13 -10
  33. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/graph_utils.py +37 -36
  34. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/node_getters.py +11 -8
  35. mal_simulator-2.4.0/malsim/mal_simulator/observability.py +51 -0
  36. mal_simulator-2.4.0/malsim/mal_simulator/reset_agent.py +80 -0
  37. mal_simulator-2.4.0/malsim/mal_simulator/rewards.py +102 -0
  38. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/run_simulation.py +5 -8
  39. mal_simulator-2.4.0/malsim/mal_simulator/simulator.py +568 -0
  40. mal_simulator-2.4.0/malsim/mal_simulator/simulator_state.py +27 -0
  41. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/state_query.py +12 -14
  42. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/mal_simulator/ttc_utils.py +65 -38
  43. mal_simulator-2.4.0/malsim/policies/attackers/searchers.py +199 -0
  44. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/policies/attackers/shortest_path.py +4 -4
  45. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/policies/attackers/ttc_soft_min.py +4 -4
  46. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/policies/decision_agent.py +4 -4
  47. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/policies/defenders/heuristic_agent.py +13 -12
  48. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/policies/keyboard_input.py +5 -5
  49. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/policies/passive_agent.py +4 -4
  50. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/policies/random_agent.py +7 -5
  51. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/policies/utils/path_finding.py +6 -4
  52. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/scenario/scenario.py +103 -80
  53. mal_simulator-2.4.0/malsim/types.py +5 -0
  54. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/visualization/malsim_gui_client.py +2 -2
  55. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/pyproject.toml +3 -3
  56. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/tests/test_graph_processing.py +27 -17
  57. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/tests/test_main.py +2 -2
  58. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/tests/test_mal_simulator.py +511 -365
  59. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/tests/test_scenario.py +136 -80
  60. mal_simulator-2.2.0/malsim/config/node_property_rule.py +0 -84
  61. mal_simulator-2.2.0/malsim/envs/base_classes.py +0 -35
  62. mal_simulator-2.2.0/malsim/mal_simulator/attack_surface.py +0 -93
  63. mal_simulator-2.2.0/malsim/mal_simulator/attacker_state.py +0 -84
  64. mal_simulator-2.2.0/malsim/mal_simulator/defender_state.py +0 -59
  65. mal_simulator-2.2.0/malsim/mal_simulator/false_alerts.py +0 -77
  66. mal_simulator-2.2.0/malsim/mal_simulator/observability.py +0 -62
  67. mal_simulator-2.2.0/malsim/mal_simulator/register_agent.py +0 -163
  68. mal_simulator-2.2.0/malsim/mal_simulator/reset_agent.py +0 -105
  69. mal_simulator-2.2.0/malsim/mal_simulator/rewards.py +0 -74
  70. mal_simulator-2.2.0/malsim/mal_simulator/simulator.py +0 -764
  71. mal_simulator-2.2.0/malsim/mal_simulator/simulator_state.py +0 -52
  72. mal_simulator-2.2.0/malsim/policies/attackers/searchers.py +0 -113
  73. mal_simulator-2.2.0/malsim/types.py +0 -14
  74. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/AUTHORS +0 -0
  75. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/LICENSE +0 -0
  76. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/mal_simulator.egg-info/dependency_links.txt +0 -0
  77. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/mal_simulator.egg-info/entry_points.txt +0 -0
  78. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/mal_simulator.egg-info/requires.txt +0 -0
  79. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/mal_simulator.egg-info/top_level.txt +0 -0
  80. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/config/__init__.py +0 -0
  81. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/envs/__init__.py +0 -0
  82. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/envs/graph/__init__.py +0 -0
  83. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/envs/legacy/__init__.py +0 -0
  84. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/policies/__init__.py +0 -0
  85. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/policies/attackers/__init__.py +0 -0
  86. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/policies/defenders/__init__.py +0 -0
  87. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/malsim/scenario/__init__.py +0 -0
  88. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/setup.cfg +0 -0
  89. {mal_simulator-2.2.0 → mal_simulator-2.4.0}/tests/test_ttc_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mal-simulator
3
- Version: 2.2.0
3
+ Version: 2.4.0
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>, Sandor Berglund <sandorb@kth.se>
6
6
  License: Apache Software License
@@ -41,7 +41,7 @@ Dynamic: license-file
41
41
 
42
42
  ## Overview
43
43
 
44
- The **MAL Simulator** is a tool designed for running simulations on systems modeled in the **Modeling Attack Language (MAL)**.
44
+ The **MAL Simulator** is a tool designed for running simulations on systems modeled in the **Meta Attack Language (MAL)**.
45
45
 
46
46
  It allows you to:
47
47
  * Simulate the adversarial and defensive actions of intelligent agents (attackers and defenders).
@@ -49,12 +49,20 @@ It allows you to:
49
49
  * Develop machine learning agents (e.g., using Reinforcement Learning) in a safe, dynamic environment.
50
50
  * Incorporate stochastic modeling through Time-to-Compromise (TTC) distributions.
51
51
 
52
- For in-depth documentation please refer to the official **[Wiki](https://github.com/mal-lang/mal-simulator/wiki)**.
52
+ For in-depth documentation, refer to:
53
+ - The official **[Wiki](https://github.com/mal-lang/mal-simulator/wiki)**.
54
+ - The official MAL infrastructure **[tutorials](https://github.com/mal-lang/mal-tutorials)**.
53
55
 
54
56
  ## Contributing
55
57
 
56
58
  - Use [Conventional commits](https://www.conventionalcommits.org/en/v1.0.0/)
57
- - The CI pipeline runs `mypy` and `ruff` for linting and type checking, and PRs will only be merged if pipeline succeeds.
59
+ - The CI pipeline runs `pytest`, `mypy` and `ruff format && ruff check` for linting and type checking. PRs will only be merged if pipeline succeeds.
60
+
61
+ ## Making a release
62
+ - Make a PR where you change to the new version number in `pyproject.toml` and `malsim/__init__.py`.
63
+ - Merge the PR after the pipeline suceeds
64
+ - Tag the latest commit with the new version number
65
+ - Push the tag
58
66
 
59
67
  ---
60
68
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Overview
4
4
 
5
- The **MAL Simulator** is a tool designed for running simulations on systems modeled in the **Modeling Attack Language (MAL)**.
5
+ The **MAL Simulator** is a tool designed for running simulations on systems modeled in the **Meta Attack Language (MAL)**.
6
6
 
7
7
  It allows you to:
8
8
  * Simulate the adversarial and defensive actions of intelligent agents (attackers and defenders).
@@ -10,12 +10,20 @@ It allows you to:
10
10
  * Develop machine learning agents (e.g., using Reinforcement Learning) in a safe, dynamic environment.
11
11
  * Incorporate stochastic modeling through Time-to-Compromise (TTC) distributions.
12
12
 
13
- For in-depth documentation please refer to the official **[Wiki](https://github.com/mal-lang/mal-simulator/wiki)**.
13
+ For in-depth documentation, refer to:
14
+ - The official **[Wiki](https://github.com/mal-lang/mal-simulator/wiki)**.
15
+ - The official MAL infrastructure **[tutorials](https://github.com/mal-lang/mal-tutorials)**.
14
16
 
15
17
  ## Contributing
16
18
 
17
19
  - Use [Conventional commits](https://www.conventionalcommits.org/en/v1.0.0/)
18
- - The CI pipeline runs `mypy` and `ruff` for linting and type checking, and PRs will only be merged if pipeline succeeds.
20
+ - The CI pipeline runs `pytest`, `mypy` and `ruff format && ruff check` for linting and type checking. PRs will only be merged if pipeline succeeds.
21
+
22
+ ## Making a release
23
+ - Make a PR where you change to the new version number in `pyproject.toml` and `malsim/__init__.py`.
24
+ - Merge the PR after the pipeline suceeds
25
+ - Tag the latest commit with the new version number
26
+ - Push the tag
19
27
 
20
28
  ---
21
29
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mal-simulator
3
- Version: 2.2.0
3
+ Version: 2.4.0
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>, Sandor Berglund <sandorb@kth.se>
6
6
  License: Apache Software License
@@ -41,7 +41,7 @@ Dynamic: license-file
41
41
 
42
42
  ## Overview
43
43
 
44
- The **MAL Simulator** is a tool designed for running simulations on systems modeled in the **Modeling Attack Language (MAL)**.
44
+ The **MAL Simulator** is a tool designed for running simulations on systems modeled in the **Meta Attack Language (MAL)**.
45
45
 
46
46
  It allows you to:
47
47
  * Simulate the adversarial and defensive actions of intelligent agents (attackers and defenders).
@@ -49,12 +49,20 @@ It allows you to:
49
49
  * Develop machine learning agents (e.g., using Reinforcement Learning) in a safe, dynamic environment.
50
50
  * Incorporate stochastic modeling through Time-to-Compromise (TTC) distributions.
51
51
 
52
- For in-depth documentation please refer to the official **[Wiki](https://github.com/mal-lang/mal-simulator/wiki)**.
52
+ For in-depth documentation, refer to:
53
+ - The official **[Wiki](https://github.com/mal-lang/mal-simulator/wiki)**.
54
+ - The official MAL infrastructure **[tutorials](https://github.com/mal-lang/mal-tutorials)**.
53
55
 
54
56
  ## Contributing
55
57
 
56
58
  - Use [Conventional commits](https://www.conventionalcommits.org/en/v1.0.0/)
57
- - The CI pipeline runs `mypy` and `ruff` for linting and type checking, and PRs will only be merged if pipeline succeeds.
59
+ - The CI pipeline runs `pytest`, `mypy` and `ruff format && ruff check` for linting and type checking. PRs will only be merged if pipeline succeeds.
60
+
61
+ ## Making a release
62
+ - Make a PR where you change to the new version number in `pyproject.toml` and `malsim/__init__.py`.
63
+ - Merge the PR after the pipeline suceeds
64
+ - Tag the latest commit with the new version number
65
+ - Push the tag
58
66
 
59
67
  ---
60
68
 
@@ -29,6 +29,7 @@ malsim/envs/legacy/gym_envs.py
29
29
  malsim/envs/legacy/malsim_vectorized_obs_env.py
30
30
  malsim/mal_simulator/__init__.py
31
31
  malsim/mal_simulator/agent_state.py
32
+ malsim/mal_simulator/agent_states.py
32
33
  malsim/mal_simulator/attack_surface.py
33
34
  malsim/mal_simulator/attacker_state.py
34
35
  malsim/mal_simulator/attacker_state_factories.py
@@ -43,7 +44,6 @@ malsim/mal_simulator/graph_state.py
43
44
  malsim/mal_simulator/graph_utils.py
44
45
  malsim/mal_simulator/node_getters.py
45
46
  malsim/mal_simulator/observability.py
46
- malsim/mal_simulator/register_agent.py
47
47
  malsim/mal_simulator/reset_agent.py
48
48
  malsim/mal_simulator/rewards.py
49
49
  malsim/mal_simulator/run_simulation.py
@@ -1,5 +1,4 @@
1
- # -*- encoding: utf-8 -*-
2
- # MAL Simulator v2.2.0
1
+ # MAL Simulator v2.3.0
3
2
  # Copyright 2025, Andrei Buhaiu.
4
3
  #
5
4
  # Licensed under the Apache License, Version 2.0 (the "License");
@@ -27,7 +26,7 @@ from malsim.scenario import Scenario
27
26
  from malsim.config import AttackerSettings, DefenderSettings
28
27
 
29
28
  __title__ = 'malsim'
30
- __version__ = '2.2.0'
29
+ __version__ = '2.3.0'
31
30
  __authors__ = [
32
31
  'Andrei Buhaiu',
33
32
  'Joakim Loxdal',
@@ -4,6 +4,8 @@ from __future__ import annotations
4
4
  import argparse
5
5
  import logging
6
6
 
7
+ from malsim.config.sim_settings import AttackSurfaceSettings
8
+
7
9
  from .mal_simulator import MalSimulator, MalSimulatorSettings, run_simulation, TTCMode
8
10
  from .scenario.scenario import Scenario
9
11
 
@@ -47,21 +49,23 @@ def main() -> None:
47
49
  help='If set, simulator will send actions to malsim-gui',
48
50
  )
49
51
  args = parser.parse_args()
50
- scenario = Scenario.load_from_file(args.scenario_file)
51
- sim = MalSimulator.from_scenario(
52
- scenario,
53
- MalSimulatorSettings(
52
+ scenario = Scenario.load_from_file(
53
+ args.scenario_file,
54
+ sim_settings=MalSimulatorSettings(
54
55
  seed=args.seed,
55
56
  ttc_mode=TTCMode(args.ttc_mode),
56
- attack_surface_skip_unnecessary=False,
57
+ attack_surface=AttackSurfaceSettings(skip_unnecessary=False),
57
58
  ),
59
+ )
60
+ sim = MalSimulator.from_scenario(
61
+ scenario,
58
62
  send_to_api=args.send_to_gui,
59
63
  )
60
64
 
61
65
  if args.output_attack_graph:
62
66
  sim.sim_state.attack_graph.save_to_file(args.output_attack_graph)
63
67
 
64
- run_simulation(sim, scenario.agent_settings)
68
+ run_simulation(sim)
65
69
 
66
70
 
67
71
  if __name__ == '__main__':
@@ -1,11 +1,15 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from collections.abc import Set
3
4
  from dataclasses import dataclass, field
4
5
  from enum import Enum
5
- from typing import Any, Optional
6
+ from typing import Any, Generic, TypeVar
6
7
 
7
- from maltoolbox.attackgraph import AttackGraphNode
8
+ from maltoolbox.attackgraph import AttackGraph, AttackGraphNode
8
9
  from malsim.config.node_property_rule import NodePropertyRule
10
+ from malsim.config.sim_settings import RewardMode
11
+ from malsim.mal_simulator.node_getters import full_name_or_node_to_node
12
+ from malsim.mal_simulator.ttc_utils import TTCDist
9
13
 
10
14
 
11
15
  class AgentType(Enum):
@@ -18,11 +22,11 @@ class AgentType(Enum):
18
22
  class AgentRuntimeMixin:
19
23
  """Provides agent construction for attacker and defender."""
20
24
 
21
- policy: Optional[type]
25
+ policy: type | None
22
26
  config: dict[str, Any]
23
- _agent: Optional[Any] = None
27
+ _agent: Any | None = None
24
28
 
25
- def _create_agent(self) -> Optional[Any]:
29
+ def _create_agent(self) -> Any | None:
26
30
  if self.policy:
27
31
  return self.policy(self.config)
28
32
  return None
@@ -31,7 +35,7 @@ class AgentRuntimeMixin:
31
35
  self._agent = self._create_agent()
32
36
 
33
37
  @property
34
- def agent(self) -> Optional[Any]:
38
+ def agent(self) -> Any | None:
35
39
  if self._agent:
36
40
  return self._agent
37
41
  if self.policy is None:
@@ -40,23 +44,28 @@ class AgentRuntimeMixin:
40
44
  return self._agent
41
45
 
42
46
 
47
+ T = TypeVar('T', bound=AttackGraphNode | str, covariant=True)
48
+
49
+
43
50
  @dataclass
44
- class AttackerSettings(AgentRuntimeMixin):
51
+ class AttackerSettings(AgentRuntimeMixin, Generic[T]):
45
52
  """Settings for an attacker in a scenario."""
46
53
 
47
54
  name: str
48
- entry_points: set[str] | set[AttackGraphNode]
49
- goals: set[str] | set[AttackGraphNode] = field(default_factory=set)
50
- policy: Optional[type] = None
51
- actionable_steps: Optional[NodePropertyRule] = None
52
- rewards: Optional[NodePropertyRule] = None
53
- ttc_overrides: Optional[NodePropertyRule] = None
55
+ entry_points: Set[T]
56
+ policy: type | None = None
57
+ actionable_steps: NodePropertyRule[bool] | None = None
58
+ rewards: NodePropertyRule[float] | None = None
54
59
  config: dict[str, Any] = field(default_factory=dict)
55
60
  type: AgentType = AgentType.ATTACKER
61
+ reward_mode: RewardMode = RewardMode.CUMULATIVE
62
+ # Goals affect simulation termination but is optional
63
+ goals: Set[T] = field(default_factory=frozenset)
64
+ # TTC distributions that override TTCs set in language
65
+ ttc_dists: NodePropertyRule[TTCDist] | None = None
56
66
 
57
67
  def to_dict(self) -> dict[str, Any]:
58
68
  d: dict[str, Any] = {
59
- 'name': self.name,
60
69
  'type': AgentType.ATTACKER.value,
61
70
  'entry_points': {
62
71
  n.full_name if isinstance(n, AttackGraphNode) else n
@@ -77,24 +86,49 @@ class AttackerSettings(AgentRuntimeMixin):
77
86
  d['config'] = self.config
78
87
  return d
79
88
 
89
+ def __post_init__(self) -> None:
90
+ if isinstance(self.reward_mode, str):
91
+ self.reward_mode = RewardMode[self.reward_mode]
92
+
93
+ def convert_to_attack_graph_nodes(
94
+ self, attack_graph: AttackGraph
95
+ ) -> AttackerSettings[AttackGraphNode]:
96
+ """Convert entry points, goals, and impossible steps from full names to nodes"""
97
+ return AttackerSettings(
98
+ goals=frozenset(
99
+ full_name_or_node_to_node(attack_graph, g) for g in self.goals
100
+ ),
101
+ entry_points=frozenset(
102
+ full_name_or_node_to_node(attack_graph, ep) for ep in self.entry_points
103
+ ),
104
+ name=self.name,
105
+ policy=self.policy,
106
+ actionable_steps=self.actionable_steps,
107
+ rewards=self.rewards,
108
+ config=self.config,
109
+ type=self.type,
110
+ reward_mode=self.reward_mode,
111
+ ttc_dists=self.ttc_dists,
112
+ )
113
+
80
114
 
81
115
  @dataclass
82
116
  class DefenderSettings(AgentRuntimeMixin):
83
117
  """Settings for a defender in a scenario."""
84
118
 
85
119
  name: str
86
- policy: Optional[type] = None
87
- observable_steps: Optional[NodePropertyRule] = None
88
- actionable_steps: Optional[NodePropertyRule] = None
89
- rewards: Optional[NodePropertyRule] = None
90
- false_positive_rates: Optional[NodePropertyRule] = None
91
- false_negative_rates: Optional[NodePropertyRule] = None
120
+ policy: type | None = None
121
+ observable_steps: NodePropertyRule[bool] | None = None
122
+ actionable_steps: NodePropertyRule[bool] | None = None
123
+ rewards: NodePropertyRule[float] | None = None
124
+ false_positive_rates: NodePropertyRule[float] | None = None
125
+ false_negative_rates: NodePropertyRule[float] | None = None
92
126
  config: dict[str, Any] = field(default_factory=dict)
93
127
  type: AgentType = AgentType.DEFENDER
128
+ reward_mode: RewardMode = RewardMode.CUMULATIVE
94
129
 
95
130
  def to_dict(self) -> dict[str, Any]:
96
131
  d: dict[str, Any] = {
97
- 'name': self.name,
98
132
  'type': AgentType.DEFENDER.value,
99
133
  }
100
134
  if self.policy:
@@ -113,16 +147,41 @@ class DefenderSettings(AgentRuntimeMixin):
113
147
  d['config'] = self.config
114
148
  return d
115
149
 
150
+ def __post_init__(self) -> None:
151
+ if isinstance(self.reward_mode, str):
152
+ self.reward_mode = RewardMode[self.reward_mode]
153
+
116
154
 
117
155
  def get_defender_settings(
118
- agent_settings: dict[str, DefenderSettings | AttackerSettings],
156
+ agent_settings: dict[str, DefenderSettings | AttackerSettings[AttackGraphNode]],
119
157
  ) -> dict[str, DefenderSettings]:
120
158
  """Return the defender settings from agent_settings dict"""
121
159
  return {k: v for k, v in agent_settings.items() if isinstance(v, DefenderSettings)}
122
160
 
123
161
 
124
162
  def get_attacker_settings(
125
- agent_settings: dict[str, DefenderSettings | AttackerSettings],
126
- ) -> dict[str, AttackerSettings]:
163
+ agent_settings: dict[str, DefenderSettings | AttackerSettings[AttackGraphNode]],
164
+ ) -> dict[str, AttackerSettings[AttackGraphNode]]:
127
165
  """Return the attacker settings from agent_settings dict"""
128
166
  return {k: v for k, v in agent_settings.items() if isinstance(v, AttackerSettings)}
167
+
168
+
169
+ AgentSettings = dict[str, AttackerSettings[AttackGraphNode] | DefenderSettings]
170
+
171
+
172
+ def defender_settings(agent_settings: AgentSettings) -> dict[str, DefenderSettings]:
173
+ return {
174
+ name: settings
175
+ for name, settings in agent_settings.items()
176
+ if isinstance(settings, DefenderSettings)
177
+ }
178
+
179
+
180
+ def attacker_settings(
181
+ agent_settings: AgentSettings,
182
+ ) -> dict[str, AttackerSettings[AttackGraphNode]]:
183
+ return {
184
+ name: settings
185
+ for name, settings in agent_settings.items()
186
+ if isinstance(settings, AttackerSettings)
187
+ }
@@ -1,8 +1,10 @@
1
1
  from typing import Any
2
2
 
3
+
3
4
  from malsim.config.agent_settings import AgentType, AttackerSettings, DefenderSettings
4
5
 
5
6
  from malsim.config.node_property_rule import NodePropertyRule
7
+ from malsim.config.sim_settings import RewardMode
6
8
  from malsim.policies import (
7
9
  BreadthFirstAttacker,
8
10
  DepthFirstAttacker,
@@ -28,12 +30,42 @@ policy_name_to_class = {
28
30
  }
29
31
 
30
32
 
33
+ def _validate_agent_dict(d: dict[str, Any]) -> dict[str, Any]:
34
+ required_keys = {'type', 'policy'}
35
+ allowed_keys = {
36
+ 'type',
37
+ 'policy',
38
+ 'agent_class',
39
+ 'config',
40
+ 'rewards',
41
+ 'false_positive_rates',
42
+ 'false_negative_rates',
43
+ 'observable_steps',
44
+ 'actionable_steps',
45
+ 'entry_points',
46
+ 'goals',
47
+ 'reward_mode',
48
+ 'ttc_overrides',
49
+ }
50
+ illegal_keys = d.keys() - allowed_keys
51
+ missing_keys = required_keys - d.keys()
52
+
53
+ if illegal_keys:
54
+ raise ValueError(f'Illegal keys in agent scenario settings: {illegal_keys}')
55
+
56
+ if illegal_keys:
57
+ raise ValueError(f'Missing keys in agent scenario settings: {missing_keys}')
58
+
59
+ return d
60
+
61
+
31
62
  def agent_settings_from_dict(
32
63
  name: str,
33
64
  d: dict[str, Any],
34
- ) -> AttackerSettings | DefenderSettings:
65
+ ) -> AttackerSettings[str] | DefenderSettings:
35
66
  """Load agent settings from a dict"""
36
67
 
68
+ d = _validate_agent_dict(d)
37
69
  agent_type = AgentType(d['type'])
38
70
 
39
71
  # Resolve policy class if provided
@@ -52,15 +84,16 @@ def agent_settings_from_dict(
52
84
  if agent_type == AgentType.ATTACKER:
53
85
  return AttackerSettings(
54
86
  name=name,
55
- entry_points=set(d['entry_points']),
56
- goals=set(d.get('goals', [])),
57
- ttc_overrides=NodePropertyRule.from_optional_dict(d.get('ttc_overrides')),
87
+ entry_points=frozenset(d['entry_points']),
88
+ goals=frozenset(d.get('goals', [])),
89
+ ttc_dists=NodePropertyRule.from_optional_dict(d.get('ttc_overrides')),
58
90
  policy=policy,
59
91
  actionable_steps=NodePropertyRule.from_optional_dict(
60
92
  d.get('actionable_steps')
61
93
  ),
62
94
  rewards=NodePropertyRule.from_optional_dict(d.get('rewards')),
63
95
  config=config,
96
+ reward_mode=RewardMode[d.get('reward_mode', 'CUMULATIVE')],
64
97
  )
65
98
 
66
99
  # Defender
@@ -77,4 +110,5 @@ def agent_settings_from_dict(
77
110
  d.get('false_negative_rates')
78
111
  ),
79
112
  config=config,
113
+ reward_mode=RewardMode[d.get('reward_mode', 'CUMULATIVE')],
80
114
  )
@@ -0,0 +1,158 @@
1
+ from __future__ import annotations
2
+ from collections.abc import Callable
3
+ from dataclasses import dataclass
4
+ from typing import Any, Generic, TypeVar
5
+ from collections.abc import Mapping
6
+
7
+ from maltoolbox.attackgraph import AttackGraph, AttackGraphNode
8
+
9
+
10
+ T = TypeVar('T')
11
+ X = TypeVar('X')
12
+ Y = TypeVar('Y')
13
+ DefaultType = TypeVar('DefaultType')
14
+
15
+
16
+ def _lookup(subkey: str, key: str, by_dict: Mapping[str, Any]) -> Any | None:
17
+ sub_dict = by_dict.get(key, {})
18
+ if subkey in sub_dict:
19
+ if isinstance(sub_dict, list):
20
+ return True
21
+ return sub_dict[subkey]
22
+ return None
23
+
24
+
25
+ def optional(f: Callable[[X], Y]) -> Callable[[X | None], Y | None]:
26
+ def wrapper(x: X | None) -> Y | None:
27
+ if x is None:
28
+ return None
29
+ return f(x)
30
+
31
+ return wrapper
32
+
33
+
34
+ def get_asset_name(node: AttackGraphNode) -> str:
35
+ if not node.model_asset:
36
+ raise ValueError(
37
+ 'Can not create NodePropertyRule from nodes without model asset connection.'
38
+ )
39
+ return node.model_asset.name
40
+
41
+
42
+ @dataclass
43
+ class NodePropertyRule(Generic[T]):
44
+ """
45
+ Defines a mapping from nodes to values based on:
46
+ - asset_type filters
47
+ - asset_name filters
48
+ """
49
+
50
+ by_asset_type: Mapping[str, Mapping[str, T]] | None = None
51
+ by_asset_name: Mapping[str, Mapping[str, T]] | None = None
52
+ default: Any = None
53
+
54
+ def __len__(self) -> int:
55
+ return len(self.by_asset_type or {}) + len(self.by_asset_name or {})
56
+
57
+ def __getitem__(self, key: AttackGraphNode) -> T:
58
+ x = self.value(key, None)
59
+ if x is None:
60
+ raise KeyError(f'No value found for node {key}')
61
+ return x
62
+
63
+ def __post_init__(self) -> None:
64
+ if self.by_asset_type is None and self.by_asset_name is None:
65
+ raise ValueError('Expected either "by_asset_type" or "by_asset_name"')
66
+
67
+ def __contains__(self, item: AttackGraphNode) -> bool:
68
+ return self.value(item, None) is not None
69
+
70
+ @classmethod
71
+ def from_attack_step_dict(
72
+ cls, attack_step_dict: dict[AttackGraphNode, T]
73
+ ) -> NodePropertyRule[T]:
74
+ """Create a NodePropertyRule from a list of attack steps
75
+ For simplicitly it will only create 'by_asset_name' rules.
76
+ """
77
+ by_asset_name = {
78
+ asset_name: {
79
+ node.name: value
80
+ for node, value in attack_step_dict.items()
81
+ if node.model_asset and node.model_asset.name == asset_name
82
+ }
83
+ for asset_name in (
84
+ get_asset_name(node) for node in attack_step_dict if node.model_asset
85
+ )
86
+ }
87
+
88
+ return cls(by_asset_name=by_asset_name)
89
+
90
+ def value(self, node: AttackGraphNode, default: T | DefaultType) -> T | DefaultType:
91
+ """Get value for `node` based on this node property config"""
92
+ if not node.model_asset:
93
+ return default
94
+
95
+ node_name = node.name
96
+ asset_name = node.model_asset.name
97
+ asset_type = node.model_asset.type
98
+
99
+ by_asset_val = (
100
+ _lookup(node_name, asset_name, self.by_asset_name)
101
+ if self.by_asset_name
102
+ else None
103
+ )
104
+ asset_type_val = (
105
+ _lookup(node_name, asset_type, self.by_asset_type)
106
+ if self.by_asset_type
107
+ else None
108
+ )
109
+
110
+ # precedence: asset_name > asset_type > default
111
+ return by_asset_val or asset_type_val or default
112
+
113
+ def per_node(self, attack_graph: AttackGraph) -> dict[str, Any]:
114
+ """Return a dict mapping from each step full name to value given by config"""
115
+ per_node_dict = {}
116
+ for n in attack_graph.nodes.values():
117
+ value = self.value(n, None)
118
+ if value is not None:
119
+ per_node_dict[n.full_name] = value
120
+ return per_node_dict
121
+
122
+ @classmethod
123
+ def _validate_dict(
124
+ cls, node_property_dict: Mapping[str, Mapping[str, Mapping[str, T]]]
125
+ ) -> NodePropertyRule[T]:
126
+ allowed_fields = {'by_asset_type', 'by_asset_name'}
127
+ present_allowed_fields = allowed_fields & node_property_dict.keys()
128
+ forbidden_fields = node_property_dict.keys() - allowed_fields
129
+ if not present_allowed_fields:
130
+ raise ValueError(
131
+ "Node property dict need at least 'by_asset_type' or 'by_asset_name'"
132
+ )
133
+ if forbidden_fields:
134
+ raise ValueError(f'Node property fields not allowed: {forbidden_fields}')
135
+
136
+ return NodePropertyRule(
137
+ by_asset_type=node_property_dict.get('by_asset_type', None),
138
+ by_asset_name=node_property_dict.get('by_asset_name', None),
139
+ )
140
+
141
+ @classmethod
142
+ def from_optional_dict(
143
+ cls, node_property_dict: dict[str, dict[str, Any]] | None
144
+ ) -> NodePropertyRule[T] | None:
145
+ return optional(cls.from_dict)(node_property_dict)
146
+
147
+ @classmethod
148
+ def from_dict(
149
+ cls,
150
+ node_property_dict: Mapping[str, Mapping[str, Any]],
151
+ ) -> NodePropertyRule[T]:
152
+ return cls._validate_dict(node_property_dict)
153
+
154
+ def to_dict(self) -> Mapping[str, Mapping[str, Mapping[str, T]] | None]:
155
+ return {
156
+ 'by_asset_type': self.by_asset_type,
157
+ 'by_asset_name': self.by_asset_name,
158
+ }
@@ -1,6 +1,6 @@
1
+ from __future__ import annotations
1
2
  from enum import Enum
2
- from dataclasses import dataclass
3
- from typing import Optional
3
+ from dataclasses import dataclass, field
4
4
 
5
5
 
6
6
  class TTCMode(Enum):
@@ -24,6 +24,21 @@ class RewardMode(Enum):
24
24
  SAMPLE_TTC = 4 # Penalty calculated based on sampled TTC value
25
25
 
26
26
 
27
+ @dataclass
28
+ class AttackSurfaceSettings:
29
+ """Settings for how to calculate the attack surface"""
30
+
31
+ # attack_surface_skip_compromised
32
+ # - if true do not add already compromised nodes to the attack surface
33
+ skip_compromised: bool = True
34
+ # attack_surface_skip_unviable
35
+ # - if true do not add unviable nodes to the attack surface
36
+ skip_unviable: bool = True
37
+ # attack_surface_skip_unnecessary
38
+ # - if true do not add unnecessary nodes to the attack surface
39
+ skip_unnecessary: bool = True
40
+
41
+
27
42
  @dataclass
28
43
  class MalSimulatorSettings:
29
44
  """Contains settings used in MalSimulator"""
@@ -41,16 +56,10 @@ class MalSimulatorSettings:
41
56
 
42
57
  # seed
43
58
  # - optionally run deterministic simulations with seed
44
- seed: Optional[int] = None
45
- # attack_surface_skip_compromised
46
- # - if true do not add already compromised nodes to the attack surface
47
- attack_surface_skip_compromised: bool = True
48
- # attack_surface_skip_unviable
49
- # - if true do not add unviable nodes to the attack surface
50
- attack_surface_skip_unviable: bool = True
51
- # attack_surface_skip_unnecessary
52
- # - if true do not add unnecessary nodes to the attack surface
53
- attack_surface_skip_unnecessary: bool = True
59
+ seed: int | None = None
60
+
61
+ attack_surface: AttackSurfaceSettings = field(default_factory=AttackSurfaceSettings)
62
+
54
63
  # If set to True, each attacker compromises/performs their
55
64
  # entry point nodes at the start of the simulation
56
65
  compromise_entrypoints_at_start: bool = True
@@ -62,15 +71,10 @@ class MalSimulatorSettings:
62
71
  # - if true, sample attack step bernoullis to decide if they are impossible/exists
63
72
  run_attack_step_bernoullis: bool = True
64
73
 
65
- # Reward settings
66
- attacker_reward_mode: RewardMode = RewardMode.CUMULATIVE
67
- defender_reward_mode: RewardMode = RewardMode.CUMULATIVE
68
-
69
74
  def __post_init__(self) -> None:
70
75
  """Allow ttc/reward mode to be given as strings - convert to enums"""
71
76
  if isinstance(self.ttc_mode, str):
72
77
  self.ttc_mode = TTCMode[self.ttc_mode]
73
- if isinstance(self.attacker_reward_mode, str):
74
- self.attacker_reward_mode = RewardMode[self.attacker_reward_mode]
75
- if isinstance(self.defender_reward_mode, str):
76
- self.defender_reward_mode = RewardMode[self.defender_reward_mode]
78
+
79
+ if isinstance(self.attack_surface, dict):
80
+ self.attack_surface = AttackSurfaceSettings(**self.attack_surface)