sniparinject 0.0.0.dev7__tar.gz → 0.0.0.dev9__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.
@@ -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,15 +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
32
+ Requires-Dist: PyYAML>=6.0.3
33
+ Requires-Dist: scapy>=2.7.0
34
+ Dynamic: description
33
35
 
34
36
  # SniParInject
35
37
 
@@ -56,7 +58,7 @@ python3 -m pip install sniparinject
56
58
  ### As a developer
57
59
 
58
60
  The only two special Python's packages that you need are `scapy` and
59
- `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
60
62
  set up and install this package.
61
63
 
62
64
  ```bash
@@ -197,6 +199,29 @@ Server:
197
199
 
198
200
  ---
199
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
+
200
225
  This is the basic structure without any rule.
201
226
 
202
227
  ```yaml
@@ -490,5 +515,3 @@ Enjoy!
490
515
  [ascii-mana-link]: https://asciinema.org/a/R0mxcmrpWHzX96NDJyc7kyTDB
491
516
 
492
517
  [structs]: https://docs.python.org/3/library/struct.html#format-characters
493
-
494
-
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = sniparinject
3
- version = 0.0.0.dev7
3
+ version = 0.0.0.dev9
4
4
  author = Israel Roldan
5
5
  author_email = israel.alberto.rv@gmail.com
6
6
  description = Intercept and read the network packets to find useful information. Also, inject some data.
@@ -23,8 +23,7 @@ classifiers =
23
23
  Operating System :: POSIX :: Linux
24
24
  Operating System :: Unix
25
25
  Programming Language :: Python :: 3
26
- Programming Language :: Python :: 3.9
27
- Programming Language :: Python :: 3.10
26
+ Programming Language :: Python :: 3.11
28
27
  Programming Language :: Python :: Implementation :: PyPy
29
28
  Topic :: Games/Entertainment
30
29
  Topic :: Security
@@ -34,9 +33,9 @@ classifiers =
34
33
  [options]
35
34
  packages = find:
36
35
  install_requires =
37
- PyYAML>=5.4.1
38
- scapy>=2.4.5
39
- python_requires = >=3.9
36
+ PyYAML>=6.0.3
37
+ scapy>=2.7.0
38
+ python_requires = >=3.11
40
39
 
41
40
  [flake8]
42
41
  max-line-length = 127
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: UTF-8 -*-
3
+ """
4
+ Set up tools.
5
+ """
6
+
7
+ from email import message_from_string
8
+ from pathlib import Path
9
+
10
+ import setuptools
11
+
12
+ HERE = Path(__file__).resolve().parent
13
+
14
+
15
+ def read_long_description():
16
+ """
17
+ Read the README from the repository root. It is outside the sdist, so
18
+ when building from the sdist reuse the description stored in PKG-INFO.
19
+ """
20
+ readme = HERE.parent / 'README.md'
21
+ if readme.is_file():
22
+ return readme.read_text(encoding='utf-8')
23
+
24
+ pkg_info = HERE / 'PKG-INFO'
25
+ if pkg_info.is_file():
26
+ return message_from_string(
27
+ pkg_info.read_text(encoding='utf-8')
28
+ ).get_payload()
29
+
30
+ return ''
31
+
32
+
33
+ setuptools.setup(
34
+ long_description=read_long_description(),
35
+ )
@@ -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:
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: UTF-8 -*-
3
+ """
4
+ Given a YAML file it get the settings and return a dictionary with them.
5
+ """
6
+ from os import stat
7
+
8
+ from yaml import load, FullLoader
9
+
10
+
11
+ # pylint: disable=too-few-public-methods
12
+ class Settings:
13
+ """
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.
18
+ """
19
+
20
+ _cache: dict[str, tuple[int, dict]] = {}
21
+
22
+ def __init__(self, config_file: str) -> None:
23
+ """
24
+ Parse the configuration file and return the settings.
25
+
26
+ :type config_file: str
27
+ :param config_file: Configuration file in YAML format.
28
+
29
+ :rtype: None
30
+ :return: Nothing.
31
+ """
32
+ self.config_file = config_file
33
+
34
+ def get_dictionary(self) -> dict:
35
+ """
36
+ Return the settings as a Python's dictionary.
37
+
38
+ :rtype: dict
39
+ :return: The settings for Python usage.
40
+ """
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:
47
+ settings = load(file, Loader=FullLoader)
48
+
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)
54
+
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,15 +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
32
+ Requires-Dist: PyYAML>=6.0.3
33
+ Requires-Dist: scapy>=2.7.0
34
+ Dynamic: description
33
35
 
34
36
  # SniParInject
35
37
 
@@ -56,7 +58,7 @@ python3 -m pip install sniparinject
56
58
  ### As a developer
57
59
 
58
60
  The only two special Python's packages that you need are `scapy` and
59
- `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
60
62
  set up and install this package.
61
63
 
62
64
  ```bash
@@ -197,6 +199,29 @@ Server:
197
199
 
198
200
  ---
199
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
+
200
225
  This is the basic structure without any rule.
201
226
 
202
227
  ```yaml
@@ -490,5 +515,3 @@ Enjoy!
490
515
  [ascii-mana-link]: https://asciinema.org/a/R0mxcmrpWHzX96NDJyc7kyTDB
491
516
 
492
517
  [structs]: https://docs.python.org/3/library/struct.html#format-characters
493
-
494
-
@@ -0,0 +1,2 @@
1
+ PyYAML>=6.0.3
2
+ scapy>=2.7.0
@@ -1,14 +0,0 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: UTF-8 -*-
3
- """
4
- Set up tools.
5
- """
6
-
7
- import setuptools
8
-
9
- with open('../README.md', 'r', encoding='utf-8') as file_handler:
10
- long_description = file_handler.read()
11
-
12
- setuptools.setup(
13
- long_description=long_description,
14
- )
@@ -1,40 +0,0 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: UTF-8 -*-
3
- """
4
- Given a YAML file it get the settings and return a dictionary with them.
5
- """
6
- from yaml import load, FullLoader
7
-
8
-
9
- # pylint: disable=too-few-public-methods
10
- class Settings:
11
- """
12
- Parse the configuration file and return the settings.
13
- """
14
-
15
- def __init__(self, config_file: str) -> None:
16
- """
17
- Parse the configuration file and return the settings.
18
-
19
- :type config_file: str
20
- :param config_file: Configuration file in YAML format.
21
-
22
- :rtype: None
23
- :return: Nothing.
24
- """
25
- self.config_file = config_file
26
-
27
- def get_dictionary(self) -> dict:
28
- """
29
- Return the settings as a Python's dictionary.
30
-
31
- :rtype: dict
32
- :return: The settings for Python usage.
33
- """
34
- with open(self.config_file) as file:
35
- settings = load(file, Loader=FullLoader)
36
-
37
- if not settings:
38
- raise Exception(f'Error: Not found settings in the file `{self.config_file}`.')
39
-
40
- return settings
@@ -1,2 +0,0 @@
1
- PyYAML>=5.4.1
2
- scapy>=2.4.5