Skip to content

Commit c721190

Browse files
committed
refactor: added communicationattacks class
1 parent 287708d commit c721190

File tree

2 files changed

+79
-51
lines changed

2 files changed

+79
-51
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
from abc import abstractmethod
2+
import logging
3+
import types
4+
from nebula.addons.attacks.attacks import Attack
5+
6+
7+
class CommunicationAttack(Attack):
8+
def __init__(self, engine, target_class, target_method, round_start_attack, round_stop_attack, decorator_args=None):
9+
super().__init__()
10+
self.engine = engine
11+
self.target_class = target_class
12+
self.target_method = target_method
13+
self.decorator_args = decorator_args
14+
self.round_start_attack = round_start_attack
15+
self.round_stop_attack = round_stop_attack
16+
self.original_method = getattr(target_class, target_method, None)
17+
18+
if not self.original_method:
19+
raise AttributeError(f"Method {target_method} not found in class {target_class}")
20+
21+
@abstractmethod
22+
def decorator(self, *args):
23+
"""Decorator that adds malicious behavior to the execution of the original method."""
24+
pass
25+
26+
async def _inject_malicious_behaviour(self):
27+
"""Inject malicious behavior into the target method."""
28+
logging.info("Injecting malicious behavior")
29+
30+
decorated_method = self.decorator(self.decorator_args)(self.original_method)
31+
32+
setattr(
33+
self.target_class,
34+
self.target_method,
35+
types.MethodType(decorated_method, self.target_class),
36+
)
37+
38+
async def _restore_original_behaviour(self):
39+
"""Restore the original behavior of the target method."""
40+
logging.info(f"Restoring original behavior of {self.target_class}.{self.target_method}")
41+
setattr(self.target_class, self.target_method, self.original_method)
42+
43+
async def attack(self):
44+
"""Perform the attack logic based on the current round."""
45+
if self.engine.round == self.round_stop_attack:
46+
logging.info(f"[{self.__class__.__name__}] Restoring original behavior")
47+
await self._restore_original_behaviour()
48+
elif self.engine.round == self.round_start_attack:
49+
logging.info(f"[{self.__class__.__name__}] Injecting malicious behavior")
50+
await self._inject_malicious_behaviour()
51+
Lines changed: 28 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,79 +1,56 @@
11
import asyncio
22
from functools import wraps
33
import logging
4-
import types
5-
from nebula.addons.attacks.attacks import Attack
4+
from nebula.addons.attacks.communications.communicationattack import CommunicationAttack
65

76

8-
class DelayerAttack(Attack):
7+
class DelayerAttack(CommunicationAttack):
98
"""
109
Implements an attack that delays the execution of a target method by a specified amount of time.
11-
12-
This attack dynamically modifies the `propagate` method of the propagator to
13-
introduce a delay during its execution.
1410
"""
15-
def __init__(self, engine, attack_params):
11+
12+
def __init__(self, engine, attack_params: dict):
1613
"""
1714
Initializes the DelayerAttack with the engine and attack parameters.
1815
1916
Args:
2017
engine: The engine managing the attack context.
2118
attack_params (dict): Parameters for the attack, including the delay duration.
2219
"""
23-
super().__init__()
24-
self.engine = engine
25-
self.propagator = self.engine._cm._propagator
26-
self.original_propagate = self.propagator.propagate
27-
self.delay = int(attack_params["delay"])
28-
self.round_start_attack = int(attack_params["round_start_attack"])
29-
self.round_stop_attack = int(attack_params["round_stop_attack"])
30-
31-
def delay_decorator(self, delay):
20+
try:
21+
self.delay = int(attack_params["delay"])
22+
round_start = int(attack_params["round_start_attack"])
23+
round_stop = int(attack_params["round_stop_attack"])
24+
except KeyError as e:
25+
raise ValueError(f"Missing required attack parameter: {e}")
26+
except ValueError:
27+
raise ValueError("Invalid value in attack_params. Ensure all values are integers.")
28+
29+
super().__init__(
30+
engine,
31+
engine._cm._propagator,
32+
"propagate",
33+
round_start,
34+
round_stop,
35+
self.delay,
36+
)
37+
38+
def decorator(self, delay: int):
3239
"""
3340
Decorator that adds a delay to the execution of the original method.
3441
3542
Args:
36-
delay (int or float): The time in seconds to delay the method execution.
43+
delay (int): The time in seconds to delay the method execution.
3744
3845
Returns:
3946
function: A decorator function that wraps the target method with the delay logic.
4047
"""
41-
# The actual decorator function that will be applied to the target method
4248
def decorator(func):
43-
@wraps(func) # Preserves the metadata of the original function
44-
async def wrapper(*args):
45-
logging.info(f"[DelayerAttack] Adding delay of {delay} seconds")
46-
49+
@wraps(func)
50+
async def wrapper(*args, **kwargs):
51+
logging.info(f"[DelayerAttack] Adding delay of {delay} seconds to {func.__name__}")
4752
await asyncio.sleep(delay)
4853
_, *new_args = args # Exclude self argument
4954
return await func(*new_args)
5055
return wrapper
51-
return decorator
52-
53-
async def _inject_malicious_behaviour(self):
54-
"""
55-
Modifies the `propagate` method of the propagator to include a delay.
56-
"""
57-
decorated_propagate = self.delay_decorator(self.delay)(self.propagator.propagate)
58-
59-
self.propagator.propagate = types.MethodType(decorated_propagate, self.propagator)
60-
61-
async def _restore_original_behaviour(self):
62-
"""
63-
Restores the original behaviour of the `propagate` method.
64-
"""
65-
self.propagator.propagate = self.original_propagate
66-
67-
async def attack(self):
68-
"""
69-
Starts the attack by injecting the malicious behaviour.
70-
71-
If the current round matches the attack start round, the malicious behavior
72-
is injected. If it matches the stop round, the original behavior is restored.
73-
"""
74-
if self.engine.round == self.round_stop_attack:
75-
logging.info(f"[DelayerAttack] Stopping Delayer attack")
76-
await self._restore_original_behaviour()
77-
elif self.engine.round == self.round_start_attack:
78-
logging.info("[DelayerAttack] Injecting malicious behaviour")
79-
await self._inject_malicious_behaviour()
56+
return decorator

0 commit comments

Comments
 (0)