"Fossies" - the Fresh Open Source Software Archive

Member "ospd-2.0.1/ospd/parser.py" (12 May 2020, 7411 Bytes) of package /linux/misc/openvas/ospd-2.0.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "parser.py" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 2.0.0_vs_2.0.1.

    1 # Copyright (C) 2019 Greenbone Networks GmbH
    2 #
    3 # SPDX-License-Identifier: GPL-2.0-or-later
    4 #
    5 # This program is free software; you can redistribute it and/or
    6 # modify it under the terms of the GNU General Public License
    7 # as published by the Free Software Foundation; either version 2
    8 # of the License, or (at your option) any later version.
    9 #
   10 # This program is distributed in the hope that it will be useful,
   11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
   12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   13 # GNU General Public License for more details.
   14 #
   15 # You should have received a copy of the GNU General Public License
   16 # along with this program; if not, write to the Free Software
   17 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   18 
   19 import argparse
   20 import logging
   21 from pathlib import Path
   22 
   23 from ospd.config import Config
   24 
   25 # Default file locations as used by a OpenVAS default installation
   26 DEFAULT_KEY_FILE = "/usr/var/lib/gvm/private/CA/serverkey.pem"
   27 DEFAULT_CERT_FILE = "/usr/var/lib/gvm/CA/servercert.pem"
   28 DEFAULT_CA_FILE = "/usr/var/lib/gvm/CA/cacert.pem"
   29 
   30 DEFAULT_PORT = 0
   31 DEFAULT_ADDRESS = "0.0.0.0"
   32 DEFAULT_NICENESS = 10
   33 DEFAULT_UNIX_SOCKET_MODE = "0o700"
   34 DEFAULT_CONFIG_PATH = "~/.config/ospd.conf"
   35 DEFAULT_UNIX_SOCKET_PATH = "/var/run/ospd/ospd.sock"
   36 DEFAULT_PID_PATH = "/var/run/ospd.pid"
   37 DEFAULT_LOCKFILE_DIR_PATH = "/var/run/ospd"
   38 DEFAULT_STREAM_TIMEOUT = 10  # ten seconds
   39 DEFAULT_SCANINFO_STORE_TIME = 0  # in hours
   40 
   41 ParserType = argparse.ArgumentParser
   42 Arguments = argparse.Namespace
   43 
   44 logger = logging.getLogger(__name__)
   45 
   46 
   47 class CliParser:
   48     def __init__(self, description):
   49         """ Create a command-line arguments parser for OSPD. """
   50         self._name = description
   51         parser = argparse.ArgumentParser(description=description)
   52 
   53         parser.add_argument(
   54             '--version', action='store_true', help='Print version then exit.'
   55         )
   56 
   57         parser.add_argument(
   58             '-s',
   59             '--config',
   60             nargs='?',
   61             default=DEFAULT_CONFIG_PATH,
   62             help='Configuration file path (default: %(default)s)',
   63         )
   64 
   65         parser.add_argument(
   66             '-p',
   67             '--port',
   68             default=DEFAULT_PORT,
   69             type=self.network_port,
   70             help='TCP Port to listen on. Default: %(default)s',
   71         )
   72         parser.add_argument(
   73             '-b',
   74             '--bind-address',
   75             default=DEFAULT_ADDRESS,
   76             dest='address',
   77             help='Address to listen on. Default: %(default)s',
   78         )
   79         parser.add_argument(
   80             '-u',
   81             '--unix-socket',
   82             default=DEFAULT_UNIX_SOCKET_PATH,
   83             help='Unix file socket to listen on. Default: %(default)s',
   84         )
   85         parser.add_argument(
   86             '--pid-file',
   87             default=DEFAULT_PID_PATH,
   88             help='Unix file socket to listen on. Default: %(default)s.',
   89         )
   90         parser.add_argument(
   91             '--lock-file-dir',
   92             default=DEFAULT_LOCKFILE_DIR_PATH,
   93             help='Directory where lock files are placed. Default: %(default)s',
   94         )
   95         parser.add_argument(
   96             '-m',
   97             '--socket-mode',
   98             default=DEFAULT_UNIX_SOCKET_MODE,
   99             help='Unix file socket mode. Default: %(default)s',
  100         )
  101         parser.add_argument(
  102             '-k',
  103             '--key-file',
  104             default=DEFAULT_KEY_FILE,
  105             help='Server key file. Default: %(default)s',
  106         )
  107         parser.add_argument(
  108             '-c',
  109             '--cert-file',
  110             default=DEFAULT_CERT_FILE,
  111             help='Server cert file. Default: %(default)s',
  112         )
  113         parser.add_argument(
  114             '--ca-file',
  115             default=DEFAULT_CA_FILE,
  116             help='CA cert file. Default: %(default)s',
  117         )
  118         parser.add_argument(
  119             '-L',
  120             '--log-level',
  121             default='WARNING',
  122             type=self.log_level,
  123             help='Wished level of logging. Default: %(default)s',
  124         )
  125         parser.add_argument(
  126             '-f',
  127             '--foreground',
  128             action='store_true',
  129             help='Run in foreground and logs all messages to console.',
  130         )
  131         parser.add_argument(
  132             '-t',
  133             '--stream-timeout',
  134             default=DEFAULT_STREAM_TIMEOUT,
  135             type=int,
  136             help='Stream timeout. Default: %(default)s',
  137         )
  138         parser.add_argument(
  139             '-l', '--log-file', help='Path to the logging file.'
  140         )
  141         parser.add_argument(
  142             '--niceness',
  143             default=DEFAULT_NICENESS,
  144             type=int,
  145             help='Start the scan with the given niceness. Default %(default)s',
  146         )
  147         parser.add_argument(
  148             '--scaninfo-store-time',
  149             default=DEFAULT_SCANINFO_STORE_TIME,
  150             type=int,
  151             help='Time in hours a scan is stored before being considered '
  152             'forgotten and being delete from the scan table. '
  153             'Default %(default)s, disabled.',
  154         )
  155 
  156         self.parser = parser
  157 
  158     def network_port(self, string):
  159         """ Check if provided string is a valid network port. """
  160 
  161         value = int(string)
  162         if not 0 < value <= 65535:
  163             raise argparse.ArgumentTypeError(
  164                 'port must be in ]0,65535] interval'
  165             )
  166         return value
  167 
  168     def log_level(self, string):
  169         """ Check if provided string is a valid log level. """
  170 
  171         value = getattr(logging, string.upper(), None)
  172         if not isinstance(value, int):
  173             raise argparse.ArgumentTypeError(
  174                 'log level must be one of {debug,info,warning,error,critical}'
  175             )
  176         return value
  177 
  178     def _set_defaults(self, configfilename=None):
  179         self._config = self._load_config(configfilename)
  180         self.parser.set_defaults(**self._config.defaults())
  181 
  182     def _load_config(self, configfile):
  183         config = Config()
  184 
  185         if not configfile:
  186             return config
  187 
  188         configpath = Path(configfile)
  189 
  190         try:
  191             if not configpath.expanduser().resolve().exists():
  192                 logger.debug('Ignoring non existing config file %s', configfile)
  193                 return config
  194         except FileNotFoundError:
  195             # we are on python 3.5 and Path.resolve raised a FileNotFoundError
  196             logger.debug('Ignoring non existing config file %s', configfile)
  197             return config
  198 
  199         try:
  200             config.load(configpath, def_section=self._name)
  201             logger.debug('Loaded config %s', configfile)
  202         except Exception as e:  # pylint: disable=broad-except
  203             raise RuntimeError(
  204                 'Error while parsing config file {config}. Error was '
  205                 '{message}'.format(config=configfile, message=e)
  206             )
  207 
  208         return config
  209 
  210     def parse_arguments(self, args=None):
  211         # Parse args to get the config file path passed as option
  212         _args, _ = self.parser.parse_known_args(args)
  213 
  214         # Load the defaults from the config file if it exists.
  215         # This override also what it was passed as cmd option.
  216         self._set_defaults(_args.config)
  217         args, _ = self.parser.parse_known_args(args)
  218 
  219         return args
  220 
  221 
  222 def create_parser(description):
  223     return CliParser(description)