Skip to content

Game components

netsecgame.game_components

Action(action_type, parameters=dict()) dataclass

Immutable dataclass representing an Action.

Attributes:

Name Type Description
action_type ActionType

The type of action.

parameters Dict[str, Any]

Parameters for the action.

as_dict property

Return a dictionary representation of the Action.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The action as a dictionary.

type property

Return the action type.

Returns:

Name Type Description
ActionType ActionType

The action type.

__eq__(other)

Check equality with another Action object.

Parameters:

Name Type Description Default
other object

Another Action object.

required

Returns:

Name Type Description
bool bool

True if equal, False otherwise.

Source code in netsecgame/game_components.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
def __eq__(self, other: object) -> bool:
    """
    Check equality with another Action object.

    Args:
        other (object): Another Action object.

    Returns:
        bool: True if equal, False otherwise.
    """
    if not isinstance(other, Action):
        return NotImplemented
    return (
        self.action_type == other.action_type and
        self.parameters == other.parameters
    )

__hash__()

Compute the hash of the Action.

Returns:

Name Type Description
int int

The hash value.

Source code in netsecgame/game_components.py
519
520
521
522
523
524
525
526
527
528
def __hash__(self) -> int:
    """
    Compute the hash of the Action.

    Returns:
        int: The hash value.
    """
    # Convert parameters to a sorted tuple of key-value pairs for consistency
    sorted_params = tuple(sorted((k, hash(v)) for k, v in self.parameters.items()))
    return hash((self.action_type, sorted_params))

__repr__()

Return the string representation of the Action.

Returns:

Name Type Description
str str

The action as a string.

Source code in netsecgame/game_components.py
484
485
486
487
488
489
490
491
def __repr__(self) -> str:
    """
    Return the string representation of the Action.

    Returns:
        str: The action as a string.
    """
    return f"Action <{self.action_type}|{self.parameters}>"

__str__()

Return the string representation of the Action.

Returns:

Name Type Description
str str

The action as a string.

Source code in netsecgame/game_components.py
493
494
495
496
497
498
499
500
def __str__(self) -> str:
    """
    Return the string representation of the Action.

    Returns:
        str: The action as a string.
    """
    return f"Action <{self.action_type}|{self.parameters}>"

from_dict(data_dict) classmethod

Create an Action from a dictionary.

Parameters:

Name Type Description Default
data_dict Dict[str, Any]

The action as a dictionary.

required

Returns:

Name Type Description
Action Action

The created Action object.

Raises:

Type Description
ValueError

If an unsupported parameter is encountered.

Source code in netsecgame/game_components.py
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
@classmethod
def from_dict(cls, data_dict: Dict[str, Any]) -> Action:
    """
    Create an Action from a dictionary.

    Args:
        data_dict (Dict[str, Any]): The action as a dictionary.

    Returns:
        Action: The created Action object.

    Raises:
        ValueError: If an unsupported parameter is encountered.
    """
    action_type = ActionType.from_string(data_dict["action_type"])
    params: Dict[str, Any] = {}
    for k, v in data_dict["parameters"].items():
        match k:
            case "source_host" | "target_host" | "blocked_host":
                params[k] = IP.from_dict(v)
            case "target_network":
                params[k] = Network.from_dict(v)
            case "target_service":
                params[k] = Service.from_dict(v)
            case "data":
                params[k] = Data.from_dict(v)
            case "agent_info":
                params[k] = AgentInfo.from_dict(v)
            case "request_trajectory" | "randomize_topology":
                if isinstance(v, bool):
                    params[k] = v
                else:
                    params[k] = ast.literal_eval(v)
            case _:
                raise ValueError(f"Unsupported value in {k}: {v}")
    return cls(action_type=action_type, parameters=params)

from_json(json_string) classmethod

Create an Action from a JSON string.

Parameters:

Name Type Description Default
json_string str

The JSON string representation.

required

Returns:

Name Type Description
Action Action

The created Action object.

Source code in netsecgame/game_components.py
470
471
472
473
474
475
476
477
478
479
480
481
482
@classmethod
def from_json(cls, json_string: str) -> Action:
    """
    Create an Action from a JSON string.

    Args:
        json_string (str): The JSON string representation.

    Returns:
        Action: The created Action object.
    """
    data_dict = json.loads(json_string)
    return cls.from_dict(data_dict)

to_json()

Serialize the Action to a JSON string.

Returns:

Name Type Description
str str

The JSON string representation.

Source code in netsecgame/game_components.py
424
425
426
427
428
429
430
431
def to_json(self) -> str:
    """
    Serialize the Action to a JSON string.

    Returns:
        str: The JSON string representation.
    """
    return json.dumps(self.as_dict)

ActionType

Bases: Enum

Enum representing possible action types in the NetSecGame.

__eq__(other)

Compare ActionType with another ActionType or string.

Parameters:

Name Type Description Default
other object

The object to compare.

required

Returns:

Name Type Description
bool bool

True if equal, False otherwise.

Source code in netsecgame/game_components.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def __eq__(self, other: object) -> bool:
    """
    Compare ActionType with another ActionType or string.

    Args:
        other (object): The object to compare.

    Returns:
        bool: True if equal, False otherwise.
    """
    # Compare with another ActionType
    if isinstance(other, ActionType):
        return self.value == other.value
    # Compare with a string
    elif isinstance(other, str):
       return self.value == other.replace("ActionType.", "")
    return False

__hash__()

Compute the hash of the ActionType.

Returns:

Name Type Description
int int

The hash value.

Source code in netsecgame/game_components.py
311
312
313
314
315
316
317
318
319
def __hash__(self) -> int:
    """
    Compute the hash of the ActionType.

    Returns:
        int: The hash value.
    """
    # Use the hash of the value for consistent behavior
    return hash(self.value)

from_string(name) classmethod

Convert a string to an ActionType enum. Strips 'ActionType.' if present.

Parameters:

Name Type Description Default
name str

The string representation.

required

Returns:

Name Type Description
ActionType ActionType

The corresponding ActionType.

Raises:

Type Description
ValueError

If the string does not match any ActionType.

Source code in netsecgame/game_components.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
@classmethod
def from_string(cls, name: str) -> ActionType:
    """
    Convert a string to an ActionType enum. Strips 'ActionType.' if present.

    Args:
        name (str): The string representation.

    Returns:
        ActionType: The corresponding ActionType.

    Raises:
        ValueError: If the string does not match any ActionType.
    """
    if name.startswith("ActionType."):
        name = name.split("ActionType.")[1]
    try:
        return cls[name]
    except KeyError:
        raise ValueError(f"Invalid ActionType: {name}")

to_string()

Convert the ActionType enum to string.

Returns:

Name Type Description
str str

The string representation.

Source code in netsecgame/game_components.py
284
285
286
287
288
289
290
291
def to_string(self) -> str:
    """
    Convert the ActionType enum to string.

    Returns:
        str: The string representation.
    """
    return self.value

AgentInfo(name, role) dataclass

Represents agent information.

Attributes:

Name Type Description
name str

Name of the agent.

role str

Role of the agent.

__repr__()

Return the string representation of the AgentInfo.

Returns:

Name Type Description
str str

The agent info as a string.

Source code in netsecgame/game_components.py
354
355
356
357
358
359
360
361
def __repr__(self) -> str:
    """
    Return the string representation of the AgentInfo.

    Returns:
        str: The agent info as a string.
    """
    return f"{self.name}({self.role})"

from_dict(data) classmethod

Build the AgentInfo object from a dictionary.

Parameters:

Name Type Description Default
data Dict[str, Any]

Dictionary with agent info attributes.

required

Returns:

Name Type Description
AgentInfo AgentInfo

The created AgentInfo object.

Source code in netsecgame/game_components.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> AgentInfo:
    """
    Build the AgentInfo object from a dictionary.

    Args:
        data (Dict[str, Any]): Dictionary with agent info attributes.

    Returns:
        AgentInfo: The created AgentInfo object.
    """
    if isinstance(data, str):
        data = ast.literal_eval(data)
    processed = {"name": data["name"], "role": AgentRole.from_string(data["role"])}
    return cls(**processed)   

AgentRole

Bases: str, Enum

Enum representing possible roles of agents.

__eq__(other)

Compare AgentRole with another AgentRole or string.

Parameters:

Name Type Description Default
other object

The object to compare.

required

Returns:

Name Type Description
bool bool

True if equal, False otherwise.

Source code in netsecgame/game_components.py
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
def __eq__(self, other: object) -> bool:
    """
    Compare AgentRole with another AgentRole or string.

    Args:
         other (object): The object to compare.

    Returns:
         bool: True if equal, False otherwise.
    """
    if isinstance(other, AgentRole):
         return self.value == other.value
    elif isinstance(other, str):
         return self.value.lower() == other.lower().replace("agentrole.", "")
    return False

__hash__()

Compute the hash of the AgentRole.

Returns:

Name Type Description
int int

The hash value.

Source code in netsecgame/game_components.py
880
881
882
883
884
885
886
887
def __hash__(self) -> int:
    """
    Compute the hash of the AgentRole.

    Returns:
        int: The hash value.
    """
    return hash(self.value)

__repr__()

Return the string representation of the AgentRole.

Returns:

Name Type Description
str str

The agent role as a string.

Source code in netsecgame/game_components.py
846
847
848
849
850
851
852
853
def __repr__(self) -> str:
    """
    Return the string representation of the AgentRole.

    Returns:
        str: The agent role as a string.
    """
    return self.value

from_string(name) classmethod

Convert a string to an AgentRole enum.

Parameters:

Name Type Description Default
name str

The string representation.

required

Returns:

Name Type Description
AgentRole AgentRole

The corresponding AgentRole.

Raises:

Type Description
ValueError

If the string does not match any AgentRole.

Source code in netsecgame/game_components.py
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
@classmethod
def from_string(cls, name: str) -> AgentRole:
    """
    Convert a string to an AgentRole enum.

    Args:
        name (str): The string representation.

    Returns:
        AgentRole: The corresponding AgentRole.

    Raises:
        ValueError: If the string does not match any AgentRole.
    """
    # Clean up input string
    name = name.split(".")[-1] # Remove prefix if present

    # Try case-insensitive matching
    for role in cls:
        if role.value.lower() == name.lower():
            return role

    raise ValueError(f"Invalid AgentRole: {name}")

to_string()

Convert the AgentRole enum to string.

Returns:

Name Type Description
str str

The string representation.

Source code in netsecgame/game_components.py
855
856
857
858
859
860
861
862
def to_string(self) -> str:
    """
    Convert the AgentRole enum to string.

    Returns:
        str: The string representation.
    """
    return self.value

AgentStatus

Bases: Enum

Enum representing possible agent statuses.

__eq__(other)

Compare AgentStatus with another AgentStatus or string.

Parameters:

Name Type Description Default
other object

The object to compare.

required

Returns:

Name Type Description
bool bool

True if equal, False otherwise.

Source code in netsecgame/game_components.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
def __eq__(self, other: object) -> bool:
    """
    Compare AgentStatus with another AgentStatus or string.

    Args:
        other (object): The object to compare.

    Returns:
        bool: True if equal, False otherwise.
    """
    # Compare with another ActionType
    if isinstance(other, AgentStatus):
        return self.value == other.value
    # Compare with a string
    elif isinstance(other, str):
       return self.value == other.replace("AgentStatus.", "")
    return False

__hash__()

Compute the hash of the AgentStatus.

Returns:

Name Type Description
int int

The hash value.

Source code in netsecgame/game_components.py
806
807
808
809
810
811
812
813
814
def __hash__(self) -> int:
    """
    Compute the hash of the AgentStatus.

    Returns:
        int: The hash value.
    """
    # Use the hash of the value for consistent behavior
    return hash(self.value)

from_string(name) classmethod

Convert a string to an AgentStatus enum.

Parameters:

Name Type Description Default
name str

The string representation.

required

Returns:

Name Type Description
AgentStatus AgentStatus

The corresponding AgentStatus.

Raises:

Type Description
ValueError

If the string does not match any AgentStatus.

Source code in netsecgame/game_components.py
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
@classmethod
def from_string(cls, name: str) -> AgentStatus:
    """
    Convert a string to an AgentStatus enum.

    Args:
        name (str): The string representation.

    Returns:
        AgentStatus: The corresponding AgentStatus.

    Raises:
        ValueError: If the string does not match any AgentStatus.
    """
    if name.startswith("AgentStatus."):
        name = name.split("AgentStatus.")[1]
    try:
        return cls[name]
    except KeyError:
        raise ValueError(f"Invalid AgentStatus: {name}")

to_string()

Convert the AgentStatus enum to string.

Returns:

Name Type Description
str str

The string representation.

Source code in netsecgame/game_components.py
779
780
781
782
783
784
785
786
def to_string(self) -> str:
    """
    Convert the AgentStatus enum to string.

    Returns:
        str: The string representation.
    """
    return self.value

Data(owner, id, size=0, type='', content=str()) dataclass

Represents a data object in the NetSecGame.

Attributes:

Name Type Description
owner str

Owner of the data.

id str

Identifier of the data.

size int

Size of the data. Default = 0

type str

Type of the data. Default = ""

content str

Content of the data. Default = ""

__hash__()

Compute the hash of the Data object.

Returns:

Name Type Description
int int

The hash value.

Source code in netsecgame/game_components.py
247
248
249
250
251
252
253
254
def __hash__(self) -> int:
    """
    Compute the hash of the Data object.

    Returns:
        int: The hash value.
    """
    return hash((self.owner, self.id, self.type))

from_dict(data) classmethod

Build the Data object from a dictionary.

Parameters:

Name Type Description Default
data Dict[str, Any]

Dictionary with data attributes.

required

Returns:

Name Type Description
Data Data

The created Data object.

Source code in netsecgame/game_components.py
256
257
258
259
260
261
262
263
264
265
266
267
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> Data:
    """
    Build the Data object from a dictionary.

    Args:
        data (Dict[str, Any]): Dictionary with data attributes.

    Returns:
        Data: The created Data object.
    """
    return cls(**data)

GameState(controlled_hosts=set(), known_hosts=set(), known_services=dict(), known_data=dict(), known_networks=set(), known_blocks=dict()) dataclass

Represents the state of the game.

Attributes:

Name Type Description
controlled_hosts Set[IP]

Controlled hosts.

known_hosts Set[IP]

Known hosts.

known_services Dict[IP, Set[Service]]

Known services.

known_data Dict[IP, Set[Data]]

Known data.

known_networks Set[Network]

Known networks.

known_blocks Dict[IP, Set[IP]]

Known blocks.

as_dict property

Return the dictionary representation of the GameState.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: The game state as a dictionary.

as_graph property

Build a graph representation of the game state.

Returns:

Type Description
List[int]

Tuple[List[int], List[int], List[Tuple[int, int]], Dict[Any, int]]:

List[int]

(node_features, controlled, edges, node_index_map)

__str__()

Return the string representation of the GameState.

Returns:

Name Type Description
str str

The game state as a string.

Source code in netsecgame/game_components.py
619
620
621
622
623
624
625
626
def __str__(self) -> str:
    """
    Return the string representation of the GameState.

    Returns:
        str: The game state as a string.
    """
    return f"State<nets:{self.known_networks}; known:{self.known_hosts}; owned:{self.controlled_hosts}; services:{self.known_services}; data:{self.known_data}; blocks:{self.known_blocks}>"    

as_json()

Return the JSON representation of the GameState.

Returns:

Name Type Description
str str

The JSON string.

Source code in netsecgame/game_components.py
628
629
630
631
632
633
634
635
636
def as_json(self) -> str:
    """
    Return the JSON representation of the GameState.

    Returns:
        str: The JSON string.
    """
    ret_dict = self.as_dict
    return json.dumps(ret_dict)

from_dict(data_dict) classmethod

Create a GameState from a dictionary.

Parameters:

Name Type Description Default
data_dict Dict[str, Any]

The game state as a dictionary.

required

Returns:

Name Type Description
GameState GameState

The created GameState object.

Source code in netsecgame/game_components.py
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
@classmethod
def from_dict(cls, data_dict: Dict[str, Any]) -> GameState:
    """
    Create a GameState from a dictionary.

    Args:
        data_dict (Dict[str, Any]): The game state as a dictionary.

    Returns:
        GameState: The created GameState object.
    """
    if "known_blocks" in data_dict:
        known_blocks = {}
        for target_host, blocked_hosts in data_dict["known_blocks"].items():
            blocked_ips = set()
            for blocked_host in blocked_hosts:
                ip_val = blocked_host["ip"]
                if isinstance(ip_val, dict):
                     ip_val = ip_val["ip"]
                blocked_ips.add(IP(ip_val))
            known_blocks[IP(target_host)] = blocked_ips
    else:
        known_blocks = {}
    state = GameState(
        known_networks = {Network(x["ip"], x["mask"]) for x in data_dict["known_networks"]},
        known_hosts = {IP(x["ip"]) for x in data_dict["known_hosts"]},
        controlled_hosts = {IP(x["ip"]) for x in data_dict["controlled_hosts"]},
        known_services = {IP(k):{Service(s["name"], s["type"], s["version"], s["is_local"])
            for s in services} for k,services in data_dict["known_services"].items()},  
        known_data = {IP(k):{Data(v["owner"], v["id"], v["size"], v["type"], v["content"]) for v in values} for k,values in data_dict["known_data"].items()},
        known_blocks = known_blocks
            )
    return state

from_json(json_string) classmethod

Create a GameState from a JSON string.

Parameters:

Name Type Description Default
json_string str

The JSON string.

required

Returns:

Name Type Description
GameState GameState

The created GameState object.

Source code in netsecgame/game_components.py
690
691
692
693
694
695
696
697
698
699
700
701
702
@classmethod
def from_json(cls, json_string: str) -> GameState:
    """
    Create a GameState from a JSON string.

    Args:
        json_string (str): The JSON string.

    Returns:
        GameState: The created GameState object.
    """
    data_dict = json.loads(json_string)
    return cls.from_dict(data_dict)

GameStatus

Bases: Enum

Enum representing possible game statuses.

__repr__()

Return the string representation of the GameStatus.

Returns:

Name Type Description
str str

The game status as a string.

Source code in netsecgame/game_components.py
757
758
759
760
761
762
763
764
def __repr__(self) -> str:
    """
    Return the string representation of the GameStatus.

    Returns:
        str: The game status as a string.
    """
    return str(self)

from_string(string) classmethod

Convert a string to a GameStatus enum.

Parameters:

Name Type Description Default
string str

The string representation.

required

Returns:

Name Type Description
GameStatus GameStatus

The corresponding GameStatus.

Source code in netsecgame/game_components.py
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
@classmethod
def from_string(cls, string: str) -> GameStatus:
    """
    Convert a string to a GameStatus enum.

    Args:
        string (str): The string representation.

    Returns:
        GameStatus: The corresponding GameStatus.
    """
    match string:
        case "GameStatus.OK":
            return GameStatus.OK
        case "GameStatus.CREATED":
            return GameStatus.CREATED
        case "GameStatus.BAD_REQUEST":
            return GameStatus.BAD_REQUEST
        case "GameStatus.FORBIDDEN":
            return GameStatus.FORBIDDEN
        case "GameStatus.RESET_DONE":
            return GameStatus.RESET_DONE
        case _:
            raise ValueError(f"Invalid GameStatus string: {string}")

IP(ip) dataclass

Immutable object representing an IPv4 address in the NetSecGame.

Attributes:

Name Type Description
ip str

The IP address in dot-decimal notation.

__eq__(other)

Check equality with another IP object.

Parameters:

Name Type Description Default
other object

Another object to compare with.

required

Returns:

Name Type Description
bool bool

True if equal, False otherwise.

Source code in netsecgame/game_components.py
75
76
77
78
79
80
81
82
83
84
85
86
87
def __eq__(self, other: object) -> bool:
    """
    Check equality with another IP object.

    Args:
        other (object): Another object to compare with.

    Returns:
        bool: True if equal, False otherwise.
    """
    if not isinstance(other, IP):
        return NotImplemented
    return self.ip == other.ip

__hash__()

Compute the hash of the IP.

Returns:

Name Type Description
hash int

The hash value.

Source code in netsecgame/game_components.py
118
119
120
121
122
123
124
125
def __hash__(self)->int:
    """
    Compute the hash of the IP.

    Returns:
        hash: The hash value.
    """
    return hash(self.ip)

__post_init__()

Verify if the provided IP is valid.

Raises:

Type Description
ValueError

If the IP address is invalid.

Source code in netsecgame/game_components.py
54
55
56
57
58
59
60
61
62
63
64
def __post_init__(self):
    """
    Verify if the provided IP is valid.

    Raises:
        ValueError: If the IP address is invalid.
    """
    try:
        ipaddress.ip_address(self.ip)
    except ValueError:
        raise ValueError(f"Invalid IP address provided: {self.ip}")

__repr__()

Return the string representation of the IP.

Returns:

Name Type Description
str str

The IP address.

Source code in netsecgame/game_components.py
66
67
68
69
70
71
72
73
def __repr__(self) -> str:
    """
    Return the string representation of the IP.

    Returns:
        str: The IP address.
    """
    return self.ip

from_dict(data) classmethod

Build the IP object from a dictionary representation.

Parameters:

Name Type Description Default
data Dict[str, Any]

Dictionary with IP attributes.

required

Returns:

Name Type Description
IP IP

The created IP object.

Source code in netsecgame/game_components.py
105
106
107
108
109
110
111
112
113
114
115
116
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> IP:
    """
    Build the IP object from a dictionary representation.

    Args:
        data (Dict[str, Any]): Dictionary with IP attributes.

    Returns:
        IP: The created IP object.
    """
    return cls(**data)

is_private()

Check if the IP address is private. Uses ipaddress module.

Returns:

Name Type Description
bool bool

True if the IP is private, False otherwise.

Source code in netsecgame/game_components.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def is_private(self) -> bool:
    """
    Check if the IP address is private. Uses ipaddress module.

    Returns:
        bool: True if the IP is private, False otherwise.
    """
    try:
        return ipaddress.IPv4Network(self.ip).is_private
    except ipaddress.AddressValueError:
        # The IP is a string 
        # In the concepts, 'external' is the string used for external hosts.
        if self.ip != 'external':
            return True
        return False

Network(ip, mask) dataclass

Immutable object representing an IPv4 network in the NetSecGame.

Attributes:

Name Type Description
ip str

IP address of the network.

mask int

CIDR mask of the network.

__gt__(other)

Greater-than comparison for networks.

Parameters:

Name Type Description Default
other Network

Another network.

required

Returns:

Name Type Description
bool bool

True if self > other, False otherwise.

Source code in netsecgame/game_components.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def __gt__(self, other: Network) -> bool:
    """
    Greater-than comparison for networks.

    Args:
        other (Network): Another network.

    Returns:
        bool: True if self > other, False otherwise.
    """
    try:
        return netaddr.IPNetwork(str(self)) > netaddr.IPNetwork(str(other))
    except netaddr.AddrFormatError:
        return str(self.ip) > str(other.ip)

__le__(other)

Less-than-or-equal comparison for networks.

Parameters:

Name Type Description Default
other Network

Another network.

required

Returns:

Name Type Description
bool bool

True if self <= other, False otherwise.

Source code in netsecgame/game_components.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def __le__(self, other: Network) -> bool:
    """
    Less-than-or-equal comparison for networks.

    Args:
        other (Network): Another network.

    Returns:
        bool: True if self <= other, False otherwise.
    """
    try:
        return netaddr.IPNetwork(str(self)) <= netaddr.IPNetwork(str(other))
    except netaddr.AddrFormatError:
        return str(self.ip) <= str(other.ip)

__lt__(other)

Less-than comparison for networks.

Parameters:

Name Type Description Default
other Network

Another network.

required

Returns:

Name Type Description
bool bool

True if self < other, False otherwise.

Source code in netsecgame/game_components.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
def __lt__(self, other: Network) -> bool:
    """
    Less-than comparison for networks.

    Args:
        other (Network): Another network.

    Returns:
        bool: True if self < other, False otherwise.
    """
    try:
        return netaddr.IPNetwork(str(self)) < netaddr.IPNetwork(str(other))
    except netaddr.AddrFormatError:
        return str(self.ip) < str(other.ip)

__repr__()

Return the string representation of the network.

Returns:

Name Type Description
str str

The network in CIDR notation.

Source code in netsecgame/game_components.py
139
140
141
142
143
144
145
146
def __repr__(self) -> str:
    """
    Return the string representation of the network.

    Returns:
        str: The network in CIDR notation.
    """
    return f"{self.ip}/{self.mask}"

__str__()

Return the string representation of the network.

Returns:

Name Type Description
str str

The network in CIDR notation.

Source code in netsecgame/game_components.py
148
149
150
151
152
153
154
155
def __str__(self) -> str:
    """
    Return the string representation of the network.

    Returns:
        str: The network in CIDR notation.
    """
    return f"{self.ip}/{self.mask}"

from_dict(data) classmethod

Build the Network object from a dictionary.

Parameters:

Name Type Description Default
data Dict[str, Any]

Dictionary with network attributes.

required

Returns:

Name Type Description
Network Network

The created Network object.

Source code in netsecgame/game_components.py
215
216
217
218
219
220
221
222
223
224
225
226
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> Network:
    """
    Build the Network object from a dictionary.

    Args:
        data (Dict[str, Any]): Dictionary with network attributes.

    Returns:
        Network: The created Network object.
    """
    return cls(**data)

is_private()

Check if the network is private. Uses ipaddress module.

Returns:

Name Type Description
bool bool

True if the network is private, False otherwise.

Source code in netsecgame/game_components.py
202
203
204
205
206
207
208
209
210
211
212
213
def is_private(self) -> bool:
    """
    Check if the network is private. Uses ipaddress module.

    Returns:
        bool: True if the network is private, False otherwise.
    """
    try:
        return ipaddress.IPv4Network(f'{self.ip}/{self.mask}',strict=False).is_private
    except ipaddress.AddressValueError:
        # If we are dealing with strings, assume they are local networks
        return True

Observation

Bases: NamedTuple

Observations are given when making a step in the environment.

Attributes:

Name Type Description
state GameState

Current state of the environment.

reward float

Value with immediate reward for last step.

end bool

True if the game ended.

info Dict[str, Any]

Dictionary with additional information about the reason for ending.

ProtocolConfig(END_OF_MESSAGE=b'EOF', BUFFER_SIZE=8192) dataclass

Configuration for protocol constants.

Attributes:

Name Type Description
END_OF_MESSAGE bytes

End-of-message marker.

BUFFER_SIZE int

Buffer size for messages.

Service(name, type='unknown', version='unknown', is_local=True) dataclass

Represents a service in the NetSecGame.

Attributes:

Name Type Description
name str

Name of the service.

type str

Type of the service. Default unknown.

version str

Version of the service. Default unknown.

is_local bool

Whether the service is local. Default True.

from_dict(data) classmethod

Create a Service object from a dictionary.

Parameters:

Name Type Description Default
data Dict[str, Any]

Dictionary with service attributes.

required

Returns:

Name Type Description
Service Service

The created Service object.

Source code in netsecgame/game_components.py
30
31
32
33
34
35
36
37
38
39
40
41
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> Service:
    """
    Create a Service object from a dictionary.

    Args:
        data (Dict[str, Any]): Dictionary with service attributes.

    Returns:
        Service: The created Service object.
    """
    return cls(**data)