sniparinject 0.0.0.dev7__py3-none-any.whl → 0.0.0.dev9__py3-none-any.whl

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.
sniparinject/core/game.py CHANGED
@@ -57,7 +57,6 @@ class Game:
57
57
  error_message, error_location = self._extract_exception(error)
58
58
  error_location = f'Class Game{error_location}'
59
59
  self._print_error(error_message, error_location)
60
- return
61
60
 
62
61
  @staticmethod
63
62
  def _extract_exception(error: Exception) -> tuple[str, str]:
@@ -95,7 +94,7 @@ class Game:
95
94
  """
96
95
  message, extracted_location = self._extract_exception(error)
97
96
  full_location = f'{location}{extracted_location}'
98
- raise Exception(message, full_location)
97
+ raise RuntimeError(message, full_location)
99
98
 
100
99
  def _print_error(self, error: str, location: str) -> None:
101
100
  """
@@ -135,7 +134,7 @@ class Game:
135
134
  except Exception as error:
136
135
  self._raise_exception(error, exception_location)
137
136
 
138
- packet_id, = unpack('<h', self._get_data(2))
137
+ packet_id, = unpack('<H', self._get_data(2))
139
138
  actions = settings.get('actions') or {}
140
139
  if packet_id in actions.keys():
141
140
  action = actions.get(packet_id) or {}
@@ -164,8 +163,8 @@ class Game:
164
163
  :rtype: dict
165
164
  :return: The actions with the settings.
166
165
  """
167
- settings_exception = Exception('The Game settings are missing.',
168
- ' -> Settings(...).get(\'Game\')')
166
+ settings_exception = RuntimeError('The Game settings are missing.',
167
+ ' -> Settings(...).get(\'Game\')')
169
168
 
170
169
  general_settings = {}
171
170
  try:
@@ -3,6 +3,8 @@
3
3
  """
4
4
  Given a YAML file it get the settings and return a dictionary with them.
5
5
  """
6
+ from os import stat
7
+
6
8
  from yaml import load, FullLoader
7
9
 
8
10
 
@@ -10,8 +12,13 @@ from yaml import load, FullLoader
10
12
  class Settings:
11
13
  """
12
14
  Parse the configuration file and return the settings.
15
+
16
+ The parsed settings are cached by file path and modification time, so
17
+ the file is parsed again only after it changes on disk.
13
18
  """
14
19
 
20
+ _cache: dict[str, tuple[int, dict]] = {}
21
+
15
22
  def __init__(self, config_file: str) -> None:
16
23
  """
17
24
  Parse the configuration file and return the settings.
@@ -31,10 +38,30 @@ class Settings:
31
38
  :rtype: dict
32
39
  :return: The settings for Python usage.
33
40
  """
34
- with open(self.config_file) as file:
41
+ modified_time = self._get_modified_time()
42
+ cached = Settings._cache.get(self.config_file)
43
+ if modified_time is not None and cached and cached[0] == modified_time:
44
+ return cached[1]
45
+
46
+ with open(self.config_file, encoding='utf-8') as file:
35
47
  settings = load(file, Loader=FullLoader)
36
48
 
37
- if not settings:
38
- raise Exception(f'Error: Not found settings in the file `{self.config_file}`.')
49
+ if not settings:
50
+ raise ValueError(f'Error: Not found settings in the file `{self.config_file}`.')
51
+
52
+ if modified_time is not None:
53
+ Settings._cache[self.config_file] = (modified_time, settings)
39
54
 
40
- return settings
55
+ return settings
56
+
57
+ def _get_modified_time(self) -> int | None:
58
+ """
59
+ Return the modification time of the configuration file.
60
+
61
+ :rtype: int | None
62
+ :return: The modification time in nanoseconds, or None if it is unknown.
63
+ """
64
+ try:
65
+ return stat(self.config_file).st_mtime_ns
66
+ except OSError:
67
+ return None
@@ -3,6 +3,8 @@
3
3
  """
4
4
  Start the sniff of the network packets.
5
5
  """
6
+ from pathlib import Path
7
+
6
8
  from scapy.layers.inet import TCP, UDP, IP
7
9
  from scapy.layers.l2 import Ether
8
10
  from scapy.packet import Raw
@@ -35,14 +37,19 @@ class NetworkSniffer:
35
37
  settings = Settings(settings_path).get_dictionary()
36
38
  print(settings)
37
39
 
38
- self.interface = settings.get('Network').get('interface')
40
+ network = settings.get('Network') or {}
41
+ self.interface = network.get('interface')
42
+ self.offline = self._resolve_offline_path(settings_path, network.get('offline'))
39
43
  protocol = settings.get('Server').get('protocol') or 'tcp'
40
44
  self.protocol = protocol.lower()
41
45
  self.host_ip = settings.get('Server').get('ip') or None
42
46
  self.host_port = settings.get('Server').get('port') or None
43
47
  print()
44
48
  print('=== Network Sniffer ===')
45
- print(f'Interface: {self.interface}')
49
+ if self.offline:
50
+ print(f'Offline: {self.offline}')
51
+ else:
52
+ print(f'Interface: {self.interface}')
46
53
  print(f'Protocol: {self.protocol}')
47
54
  print(f'Host IP: {self.host_ip}')
48
55
  print(f'Host Port: {self.host_port}')
@@ -55,6 +62,17 @@ class NetworkSniffer:
55
62
  :rtype: None
56
63
  :return: Nothing.
57
64
  """
65
+ if self.offline:
66
+ # A BPF filter on a capture file needs tcpdump, so the packets
67
+ # read from the file are filtered in _sniff_data instead.
68
+ sniff(
69
+ offline=self.offline,
70
+ count=0,
71
+ store=False,
72
+ prn=self._sniff_data
73
+ )
74
+ return
75
+
58
76
  sniffer_filter = self.protocol
59
77
  if self.host_ip:
60
78
  sniffer_filter += f' and host {self.host_ip}'
@@ -65,12 +83,59 @@ class NetworkSniffer:
65
83
  iface=self.interface,
66
84
  filter=sniffer_filter,
67
85
  count=0,
86
+ store=False,
68
87
  prn=self._sniff_data
69
88
  )
70
89
 
90
+ @staticmethod
91
+ def _resolve_offline_path(settings_path: str, offline: str | None) -> str | None:
92
+ """
93
+ Resolve the capture file path, relative to the settings file.
94
+
95
+ :type settings_path: str
96
+ :param settings_path: The path of the YAML file with settings.
97
+
98
+ :type offline: str | None
99
+ :param offline: The capture file (pcap or pcapng) from the settings.
100
+
101
+ :rtype: str | None
102
+ :return: The capture file path, or None to sniff the network interface.
103
+ """
104
+ if not offline:
105
+ return None
106
+
107
+ offline_path = Path(offline)
108
+ if not offline_path.is_absolute():
109
+ offline_path = Path(settings_path).parent / offline_path
110
+
111
+ return str(offline_path)
112
+
113
+ def _is_server_packet(self, ip_layer: IP, layer_type: TCP | UDP) -> bool:
114
+ """
115
+ Check if the packet goes to or comes from the configured server.
116
+
117
+ :type ip_layer: IP
118
+ :param ip_layer: The IP layer of the packet.
119
+
120
+ :type layer_type: TCP | UDP
121
+ :param layer_type: The protocol layer of the packet.
122
+
123
+ :rtype: bool
124
+ :return: True if the packet matches the server IP and port.
125
+ """
126
+ if self.host_ip and self.host_ip not in (ip_layer.src, ip_layer.dst):
127
+ return False
128
+
129
+ if self.host_port and self.host_port not in (layer_type.sport, layer_type.dport):
130
+ return False
131
+
132
+ return True
133
+
71
134
  def _sniff_data(self, packet: Ether) -> None:
72
135
  """
73
136
  Process data provided by the Sniffer.
137
+ Packets without an IP layer or without the configured protocol layer
138
+ (TCP or UDP) are skipped, so they do not stop the sniffer.
74
139
 
75
140
  :type packet: Ether
76
141
  :param packet: The sniffed packet.
@@ -79,13 +144,12 @@ class NetworkSniffer:
79
144
  :return: Nothing.
80
145
  """
81
146
  ip_layer = packet.getlayer(IP)
82
- if not ip_layer:
83
- raise Exception('Error: The IP layer not exists in this package.')
84
-
85
- if not (packet.haslayer(TCP) or packet.haslayer(UDP)):
86
- raise Exception('Error: The protocol layer (TCP or UDP) not exists in this package.')
87
-
88
147
  layer_type = packet.getlayer(UDP) if self.protocol == 'udp' else packet.getlayer(TCP)
148
+ if not ip_layer or not layer_type:
149
+ return
150
+
151
+ if self.offline and not self._is_server_packet(ip_layer, layer_type):
152
+ return
89
153
 
90
154
  if self.host_ip and self.host_port:
91
155
  is_host = self.host_ip == ip_layer.src and self.host_port == layer_type.sport
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: sniparinject
3
- Version: 0.0.0.dev7
3
+ Version: 0.0.0.dev9
4
4
  Summary: Intercept and read the network packets to find useful information. Also, inject some data.
5
5
  Home-page: https://github.com/airvzxf/sniparinject
6
6
  Author: Israel Roldan
@@ -21,17 +21,17 @@ Classifier: Natural Language :: English
21
21
  Classifier: Operating System :: POSIX :: Linux
22
22
  Classifier: Operating System :: Unix
23
23
  Classifier: Programming Language :: Python :: 3
24
- Classifier: Programming Language :: Python :: 3.9
25
- Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
26
25
  Classifier: Programming Language :: Python :: Implementation :: PyPy
27
26
  Classifier: Topic :: Games/Entertainment
28
27
  Classifier: Topic :: Security
29
28
  Classifier: Topic :: System :: Networking
30
29
  Classifier: Topic :: System :: Networking :: Monitoring
31
- Requires-Python: >=3.9
30
+ Requires-Python: >=3.11
32
31
  Description-Content-Type: text/markdown
33
- Requires-Dist: PyYAML (>=5.4.1)
34
- Requires-Dist: scapy (>=2.4.5)
32
+ Requires-Dist: PyYAML>=6.0.3
33
+ Requires-Dist: scapy>=2.7.0
34
+ Dynamic: description
35
35
 
36
36
  # SniParInject
37
37
 
@@ -58,7 +58,7 @@ python3 -m pip install sniparinject
58
58
  ### As a developer
59
59
 
60
60
  The only two special Python's packages that you need are `scapy` and
61
- `PyYAML`, the suggested version of `Python` is `>= 3.9`. Follow the commands to
61
+ `PyYAML`, the suggested version of `Python` is `>= 3.11`. Follow the commands to
62
62
  set up and install this package.
63
63
 
64
64
  ```bash
@@ -199,6 +199,29 @@ Server:
199
199
 
200
200
  ---
201
201
 
202
+ Read the packets from a capture file (`pcap` or `pcapng`) instead of the
203
+ network interface with `offline`. A relative path is relative to the settings
204
+ file. It does not need root permissions, and only the packets to or from the
205
+ `Server` `ip` and `port` are parsed.
206
+
207
+ ```yaml
208
+ Network:
209
+ offline: capture.pcapng
210
+
211
+ Server:
212
+ ip: 52.174.196.146
213
+ port: 5122
214
+ ```
215
+
216
+ For example, record the game with `tshark`, which also does not need root when
217
+ your user is in the `wireshark` group.
218
+
219
+ ```bash
220
+ tshark -i enp4s0 -f 'tcp port 5122' -w capture.pcapng
221
+ ```
222
+
223
+ ---
224
+
202
225
  This is the basic structure without any rule.
203
226
 
204
227
  ```yaml
@@ -492,5 +515,3 @@ Enjoy!
492
515
  [ascii-mana-link]: https://asciinema.org/a/R0mxcmrpWHzX96NDJyc7kyTDB
493
516
 
494
517
  [structs]: https://docs.python.org/3/library/struct.html#format-characters
495
-
496
-
@@ -0,0 +1,11 @@
1
+ sniparinject/__init__.py,sha256=e6SXifSM2k8jxos7320W_19mIId1HR8VlK8Y3VL_U0w,69
2
+ sniparinject/network_sniffer.py,sha256=QEJtMEEryiQBtxwUzsHd9uc0miYal0LnXluiAAT9v_8,5049
3
+ sniparinject/core/__init__.py,sha256=e6SXifSM2k8jxos7320W_19mIId1HR8VlK8Y3VL_U0w,69
4
+ sniparinject/core/game.py,sha256=MJHybQsMb0au7i8HXLHfppUHwIVeZMGvqH5Ky2P3RJI,17664
5
+ sniparinject/core/settings.py,sha256=NAleP256sItJiGSwFKeGeGbBxbc3T9GVAYcwtmVXb8Q,1952
6
+ sniparinject/core/text_style.py,sha256=aK5aB_HT_qHIsTRGms1EcjRj8wJLofoloP20mzenMao,273
7
+ sniparinject/core/utility.py,sha256=hM7xO77KBqFHvM_wC4p57b_cLr-vxdGfcJzH6ymy_8Q,1607
8
+ sniparinject-0.0.0.dev9.dist-info/METADATA,sha256=EPT-PHZcvdKyX9Ya6w2o0et3jJTRsQVw7VNYazXEok8,13483
9
+ sniparinject-0.0.0.dev9.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ sniparinject-0.0.0.dev9.dist-info/top_level.txt,sha256=txiwH5zWpKjjp0CCQWnWpRBOnMO33DEzuuXd7DpFAlE,13
11
+ sniparinject-0.0.0.dev9.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: bdist_wheel (0.36.2)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,11 +0,0 @@
1
- sniparinject/__init__.py,sha256=e6SXifSM2k8jxos7320W_19mIId1HR8VlK8Y3VL_U0w,69
2
- sniparinject/network_sniffer.py,sha256=0qfybdNspvQ4pPIekL_Q2gQZ1lQeC2cQaNZNnynNSLw,2956
3
- sniparinject/core/__init__.py,sha256=e6SXifSM2k8jxos7320W_19mIId1HR8VlK8Y3VL_U0w,69
4
- sniparinject/core/game.py,sha256=V-KiwQ_AMJ0ms44VnuedieDLl9ZqtWfPCJqEOx9r9w0,17674
5
- sniparinject/core/settings.py,sha256=Fl8xgULJaAC8qkhsaZMtqbMcnJKaAE4V-U0WBXHDRGc,1054
6
- sniparinject/core/text_style.py,sha256=aK5aB_HT_qHIsTRGms1EcjRj8wJLofoloP20mzenMao,273
7
- sniparinject/core/utility.py,sha256=hM7xO77KBqFHvM_wC4p57b_cLr-vxdGfcJzH6ymy_8Q,1607
8
- sniparinject-0.0.0.dev7.dist-info/METADATA,sha256=miVUuObAUMUHo86mlcS3EwyGQVxLl32iaD2aLnKbQ-A,12970
9
- sniparinject-0.0.0.dev7.dist-info/WHEEL,sha256=OqRkF0eY5GHssMorFjlbTIq072vpHpF60fIQA6lS9xA,92
10
- sniparinject-0.0.0.dev7.dist-info/top_level.txt,sha256=txiwH5zWpKjjp0CCQWnWpRBOnMO33DEzuuXd7DpFAlE,13
11
- sniparinject-0.0.0.dev7.dist-info/RECORD,,