2023-11-24 16:32:04 +00:00
|
|
|
import random
|
2024-02-08 09:19:18 +00:00
|
|
|
from typing import Dict, Tuple
|
2023-11-24 16:32:04 +00:00
|
|
|
|
|
|
|
|
from gymnasium.core import ObsType
|
|
|
|
|
|
|
|
|
|
from primaite.game.agent.interface import AbstractScriptedAgent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class DataManipulationAgent(AbstractScriptedAgent):
|
|
|
|
|
"""Agent that uses a DataManipulationBot to perform an SQL injection attack."""
|
|
|
|
|
|
|
|
|
|
next_execution_timestep: int = 0
|
2024-02-08 09:19:18 +00:00
|
|
|
starting_node_idx: int = 0
|
2023-11-24 16:32:04 +00:00
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
super().__init__(*args, **kwargs)
|
2024-02-08 09:19:18 +00:00
|
|
|
self.reset_agent_for_episode()
|
2023-11-24 16:32:04 +00:00
|
|
|
|
|
|
|
|
def _set_next_execution_timestep(self, timestep: int) -> None:
|
|
|
|
|
"""Set the next execution timestep with a configured random variance.
|
|
|
|
|
|
|
|
|
|
:param timestep: The timestep to add variance to.
|
|
|
|
|
"""
|
|
|
|
|
random_timestep_increment = random.randint(
|
|
|
|
|
-self.agent_settings.start_settings.variance, self.agent_settings.start_settings.variance
|
|
|
|
|
)
|
|
|
|
|
self.next_execution_timestep = timestep + random_timestep_increment
|
|
|
|
|
|
|
|
|
|
def get_action(self, obs: ObsType, reward: float = None) -> Tuple[str, Dict]:
|
|
|
|
|
"""Randomly sample an action from the action space.
|
|
|
|
|
|
|
|
|
|
:param obs: _description_
|
|
|
|
|
:type obs: ObsType
|
|
|
|
|
:param reward: _description_, defaults to None
|
|
|
|
|
:type reward: float, optional
|
|
|
|
|
:return: _description_
|
|
|
|
|
:rtype: Tuple[str, Dict]
|
|
|
|
|
"""
|
2023-11-26 23:29:14 +00:00
|
|
|
current_timestep = self.action_manager.game.step_counter
|
2023-11-24 16:32:04 +00:00
|
|
|
|
|
|
|
|
if current_timestep < self.next_execution_timestep:
|
|
|
|
|
return "DONOTHING", {"dummy": 0}
|
|
|
|
|
|
|
|
|
|
self._set_next_execution_timestep(current_timestep + self.agent_settings.start_settings.frequency)
|
|
|
|
|
|
2024-02-08 09:19:18 +00:00
|
|
|
return "NODE_APPLICATION_EXECUTE", {"node_id": self.starting_node_idx, "application_id": 0}
|
2024-01-09 14:53:15 +00:00
|
|
|
|
|
|
|
|
def reset_agent_for_episode(self) -> None:
|
|
|
|
|
"""Set the next execution timestep when the episode resets."""
|
|
|
|
|
super().reset_agent_for_episode()
|
2024-02-08 09:19:18 +00:00
|
|
|
self._select_start_node()
|
2024-01-09 14:53:15 +00:00
|
|
|
self._set_next_execution_timestep(self.agent_settings.start_settings.start_step)
|
2024-02-08 09:19:18 +00:00
|
|
|
|
|
|
|
|
def _select_start_node(self) -> None:
|
|
|
|
|
"""Set the starting starting node of the agent to be a random node from this agent's action manager."""
|
|
|
|
|
# we are assuming that every node in the node manager has a data manipulation application at idx 0
|
|
|
|
|
num_nodes = len(self.action_manager.node_names)
|
|
|
|
|
self.starting_node_idx = random.randint(0, num_nodes - 1)
|