Debian Codegraph @

greenbone/feed/sync/parser.py

raw ◀ ▶
1 Debian patch touch this file
1 # SPDX-FileCopyrightText: 2023-2024 Greenbone AG
2 #
3 # SPDX-License-Identifier: GPL-3.0-or-later
4 #
5
•6 import sys
7 from argparse import ArgumentParser, Namespace
8 from pathlib import Path
9 from typing import Any, Optional, Sequence
10
11 import shtab
12
13 from greenbone.feed.sync.__version__ import __version__
14 from greenbone.feed.sync.config import (
15 DEFAULT_CONFIG_FILE,
16 DEFAULT_USER_CONFIG_FILE,
17 Config,
18 ConfigDict,
19 EnterpriseSettings,
20 maybe_int,
21 )
22 from greenbone.feed.sync.errors import ConfigFileError
23
24
25 def _to_defaults(values: ConfigDict) -> dict[str, Any]:
26 defaults = {}
27
28 for key, value in values.items():
29 defaults[key.replace("-", "_")] = value
30
31 return defaults
32
33
34 def feed_type(value: str) -> str:
35 """
36 Converts to a specific feed type
37 """
38
39 value = value.replace("_", "-").lower()
40
41 if value in ("nvts", "report-formats", "port-lists", "scan-configs"):
42 return value[:-1]
43
44 return value
45
46
47 class CliParser:
48 """
49 An ArgumentParser for the feed sync CLI
50 """
51
52 def __init__(self) -> None:
•53 parser = ArgumentParser(prog=Path(sys.argv[0]).name, add_help=False)
54 shtab.add_argument_to(parser)
55 parser.add_argument(
56 "--version",
57 help="Print version then exit.",
58 action="version",
59 version=f"%(prog)s {__version__}",
60 )
61 parser.add_argument(
62 "-h",
63 "--help",
64 help="Show this help message and exit.",
65 action="store_true",
66 )
67 parser.add_argument(
68 "--selftest",
69 help="Perform self-test and set exit code",
70 action="store_true",
71 )
72 output_group = parser.add_mutually_exclusive_group()
73 output_group.add_argument(
74 "--verbose",
75 "-v",
76 action="count",
77 help="Set log verbosity. `-vvv` for maximum verbosity. "
78 "(Default: %(default)s)",
79 )
80 output_group.add_argument(
81 "--quiet", action="store_true", help="Disable all log output."
82 )
83
84 parser.add_argument(
85 "-c",
86 "--config",
87 help="Configuration file path. If not set %(prog)s "
88 f"tries to load {DEFAULT_USER_CONFIG_FILE} or "
89 f"{DEFAULT_CONFIG_FILE}.",
90 )
91 parser.add_argument(
92 "--private-directory",
93 help="(Sub-)Directory to exclude from the sync which will never "
94 "get deleted automatically.",
95 type=Path,
96 )
97 parser.add_argument(
98 "--compression-level",
99 type=int,
100 choices=range(0, 10),
101 help="Rsync compression level (0-9). (Default: %(default)s)",
102 )
103 parser.add_argument(
104 "--type",
105 choices=[
106 "all",
107 "nvt",
108 "gvmd-data",
109 "scap",
110 "cert",
111 "notus",
112 "nasl",
113 "report-format",
114 "scan-config",
115 "port-list",
116 ],
117 default="all",
118 type=feed_type,
119 help="Select which feed should be synced. (Default: %(default)s)",
120 )
121 parser.add_argument(
122 "--feed-version",
123 help="Deprecated. Use --feed-release instead.",
124 )
125 parser.add_argument(
126 "--feed-release",
127 help="Release series of the feed to download for example 22.04 or 24.10. (Default: %(default)s)",
128 )
129 parser.add_argument(
130 "--destination-prefix",
131 type=Path,
132 help="Prefix for the destination directories. (Default: %(default)s)",
133 )
134 parser.add_argument(
135 "--gvmd-data-destination",
136 type=Path,
137 help="Destination of the downloaded gvmd data. "
138 "(Default: %(default)s)",
139 )
140 parser.add_argument(
141 "--gvmd-data-url",
142 help="URL to download the gvmd data from. (Default: %(default)s)",
143 )
144 nvts_destination_group = parser.add_argument_group()
145 nvts_destination_group.add_argument(
146 "--notus-destination",
147 type=Path,
148 help="Destination of the downloaded notus data. "
149 "(Default: %(default)s)",
150 )
151 nvts_url_group = parser.add_argument_group()
152 nvts_url_group.add_argument(
153 "--notus-url",
154 help="URL to download the notus data from. (Default: %(default)s)",
155 )
156 nvts_destination_group.add_argument(
157 "--nasl-destination",
158 type=Path,
159 help="Destination of the downloaded nasl data. "
160 "(Default: %(default)s)",
161 )
162 nvts_url_group.add_argument(
163 "--nasl-url",
164 help="URL to download the nasl data from. (Default: %(default)s)",
165 )
166
167 secinfo_destination_group = parser.add_argument_group()
168 secinfo_destination_group.add_argument(
169 "--scap-data-destination",
170 type=Path,
171 help="Destination of the downloaded SCAP data. "
172 "(Default: %(default)s)",
173 )
174 secinfo_url_group = parser.add_argument_group()
175 secinfo_url_group.add_argument(
176 "--scap-data-url",
177 help="URL to download the SCAP data from. (Default: %(default)s)",
178 )
179 secinfo_destination_group.add_argument(
180 "--cert-data-destination",
181 type=Path,
182 help="Destination of the downloaded CERT data. "
183 "(Default: %(default)s)",
184 )
185 secinfo_url_group.add_argument(
186 "--cert-data-url",
187 help="URL to download the CERT data from. (Default: %(default)s)",
188 )
189
190 data_objects_destination_group = parser.add_argument_group()
191 data_objects_destination_group.add_argument(
192 "--report-formats-destination",
193 type=Path,
194 help="Destination of the downloaded report format data "
195 "(Default: %(default)s)",
196 )
197 data_objects_url_group = parser.add_argument_group()
198 data_objects_url_group.add_argument(
199 "--report-formats-url",
200 help="URL to download the report format data from. "
201 "(Default: %(default)s)",
202 )
203 data_objects_destination_group.add_argument(
204 "--scan-configs-destination",
205 type=Path,
206 help="Destination of the downloaded scan config data. "
207 "(Default: %(default)s)",
208 )
209 data_objects_url_group.add_argument(
210 "--scan-configs-url",
211 help="URL to download the scan config data from. "
212 "(Default: %(default)s)",
213 )
214 data_objects_destination_group.add_argument(
215 "--port-lists-destination",
216 type=Path,
217 help="Destination of the downloaded port list data. "
218 "(Default: %(default)s)",
219 )
220 data_objects_url_group.add_argument(
221 "--port-lists-url",
222 help="URL to download the port list data from. "
223 "(Default: %(default)s)",
224 )
225
226 lock_file_group = parser.add_argument_group()
227 lock_file_group.add_argument(
228 "--gvmd-lock-file",
229 type=Path,
230 help="File to use for locking the feed synchronization for data "
231 "loaded by the gvmd daemon. Used to avoid that more then one "
232 "process accesses the feed data at the same time. "
233 "(Default: %(default)s)",
234 )
235 lock_file_group.add_argument(
236 "--openvas-lock-file",
237 type=Path,
238 help="File to use for locking the feed synchronization for data "
239 "loaded by the openvas scanner. Used to avoid that more then one "
240 "process accesses the feed data at the same time. "
241 "(Default: %(default)s)",
242 )
243 parser.add_argument(
244 "--fail-fast",
245 "--failfast",
246 action="store_true",
247 help="Stop after a first error has occurred. Otherwise the script "
248 "tries to download additional data if specified.",
249 )
250
251 wait_group = parser.add_mutually_exclusive_group()
252 wait_group.add_argument(
253 "--no-wait",
254 action="store_true",
255 help="Fail directly if the lock file can't be acquired.",
256 )
257 wait_group.add_argument(
258 "--wait-interval",
259 type=int,
260 help="Time to wait in seconds after failed lock attempt before"
261 "re-trying to lock the file. (Default: %(default)s seconds)",
262 )
263
264 parser.add_argument(
265 "--rsync-timeout",
266 type=int,
267 help="Maximum I/O timeout in seconds used for rsync. If no data is "
268 "transferred for the specified time then rsync will exit. By "
269 "default no timeout is set and the rsync default will be used.",
270 )
271
272 permissions_group = parser.add_argument_group()
273 permissions_group.add_argument(
274 "--user",
275 type=maybe_int,
276 help="If started as root, use this user name or ID to run the "
277 "script. (Default: %(default)s)",
278 )
279 permissions_group.add_argument(
280 "--group",
281 type=maybe_int,
282 help="If started as root, use this group name or ID to run the "
283 "script. (Default: %(default)s)",
284 )
285
286 parser.add_argument(
287 "--greenbone-enterprise-feed-key",
288 type=Path,
289 help="File to read the Greenbone Enterprise Feed key from. "
290 "The key gives access to additional vulnerability tests for "
291 "enterprise software among other advantages. See "
292 "https://www.greenbone.net/en/feed-comparison/ for more details."
293 "The default URLs are adjusted according to the data in the key."
294 "If the key file does not exist it is ignored. "
295 "(Default: %(default)s)",
296 )
297
298 self.parser = parser
299
300 def _determine_enterprise_settings(
301 self, enterprise_key: Path
302 ) -> Optional[EnterpriseSettings]:
303 if not enterprise_key or not enterprise_key.exists():
304 return None
305
306 return EnterpriseSettings.from_key(enterprise_key)
307
308 def _load_config(self, config_file: str) -> Config:
309 config_path = None
310
311 if config_file is None:
312 for file in [DEFAULT_USER_CONFIG_FILE, DEFAULT_CONFIG_FILE]:
313 path = Path(file).expanduser().resolve()
314 if path.exists():
315 config_path = path
316 break
317
318 else:
319 config_path = Path(config_file).expanduser().resolve()
320 if not config_path.exists():
321 raise ConfigFileError(
322 f"Config file {config_file} does not exist."
323 )
324
325 config = Config()
326
327 if config_path:
328 config.load_from_config_file(config_path)
329
330 return config
331
332 def _set_defaults(self, config: ConfigDict) -> None:
333 self.parser.set_defaults(**_to_defaults(config))
334
335 def parse_arguments(
336 self, args: Optional[Sequence[str]] = None
337 ) -> Namespace:
338 """
339 Parse CLI arguments
340 """
341 # Parse args to get the config file path passed as option
342 known_args, _ = self.parser.parse_known_args(args)
343
344 # Load the defaults from the config file if it exists.
345 config = self._load_config(known_args.config)
346
347 # set greenbone enterprise feed key in config if user passed one to load
348 # desired key for determining the feed url
349 if known_args.greenbone_enterprise_feed_key:
350 config["greenbone-enterprise-feed-key"] = (
351 known_args.greenbone_enterprise_feed_key
352 )
353
354 if known_args.feed_version:
355 config["feed-release"] = known_args.feed_version
356
357 if known_args.feed_release:
358 config["feed-release"] = known_args.feed_release
359
360 if known_args.destination_prefix:
361 config["destination-prefix"] = known_args.destination_prefix
362
363 if self.parser.prog == "greenbone-nvt-sync":
364 config["type"] = "nvt"
365 elif self.parser.prog == "greenbone-scapdata-sync":
366 config["type"] = "scap"
367 elif self.parser.prog == "greenbone-certdata-sync":
368 config["type"] = "cert"
369
370 # apply defaults in config
371 config.apply_settings()
372
373 # check if a enterprise feed key is available
374 enterprise_settings = self._determine_enterprise_settings(
375 config["greenbone-enterprise-feed-key"]
376 )
377
378 # override feed url from key
379 if enterprise_settings:
380 config["feed-url"] = enterprise_settings.feed_url()
381
382 # apply other config defaults
383 config.apply_dependent_settings()
384
385 # set config as defaults for CLI to make them visible in --help
386 self._set_defaults(config)
387
388 if known_args.help:
389 self.parser.print_help()
390 self.parser.exit(0)
391
392 return self.parser.parse_args(args)