예제 #1
0
def list_certificates():
    """Display information about certs configured with Certbot

    :param config: Configuration.
    :type config: :class:`certbot._internal.configuration.NamespaceConfig`
    """
    
    plugins = plugins_disco.PluginsRegistry.find_all()
    
    args = cli.prepare_and_parse_args(plugins, [
        "certificates", 
        "--config-dir=" + constants.CONFIG_DIR, 
        "--work-dir=" + constants.WORK_DIR, 
        "--logs=" + constants.LOGS_DIR
    ])
    config = configuration.NamespaceConfig(args)
    
    parsed_certs = []
    parse_failures = []
    for renewal_file in storage.renewal_conf_files(config):
        try:
            renewal_candidate = storage.RenewableCert(renewal_file, config)
            crypto_util.verify_renewable_cert(renewal_candidate)
            parsed_certs.append(renewal_candidate)
        except Exception as e:  # pylint: disable=broad-except
            logger.warning("Renewal configuration file %s produced an "
                           "unexpected error: %s. Skipping.", renewal_file, e)
            logger.debug("Traceback was:\n%s", traceback.format_exc())
            parse_failures.append(renewal_file)
    
    return (parsed_certs, parse_failures)
예제 #2
0
파일: common.py 프로젝트: swipswaps/certbot
    def _prepare_configurator(self):
        """Prepares the Nginx plugin for testing"""
        for k in constants.CLI_DEFAULTS:
            setattr(self.le_config, "nginx_" + k, constants.os_constant(k))

        conf = configuration.NamespaceConfig(self.le_config)
        self._configurator = configurator.NginxConfigurator(config=conf,
                                                            name="nginx")
        self._configurator.prepare()
예제 #3
0
    def _prepare_configurator(self):
        """Prepares the Apache plugin for testing"""
        for k in entrypoint.ENTRYPOINT.OS_DEFAULTS.__dict__.keys():
            setattr(self.le_config, "apache_" + k,
                    getattr(entrypoint.ENTRYPOINT.OS_DEFAULTS, k))

        self._configurator = entrypoint.ENTRYPOINT(
            config=configuration.NamespaceConfig(self.le_config),
            name="apache")
        self._configurator.prepare()
예제 #4
0
파일: certbot_utils.py 프로젝트: itsvs/dna
    def _config(self, args=[]):
        """Generate a ``certbot`` configuration with the given arguments

        :param args: the arguments to use
        :type args: list[str]

        :return: a :class:`~certbot.interfaces.IConfig` object
        """
        args = args + self.args
        args = cli.prepare_and_parse_args(self.plugins, args)
        return configuration.NamespaceConfig(args)
예제 #5
0
 def setUp(self):
     super(ConfigTestCase, self).setUp()
     self.config = configuration.NamespaceConfig(
         mock.MagicMock(**constants.CLI_DEFAULTS))
     self.config.verb = "certonly"
     self.config.config_dir = os.path.join(self.tempdir, 'config')
     self.config.work_dir = os.path.join(self.tempdir, 'work')
     self.config.logs_dir = os.path.join(self.tempdir, 'logs')
     self.config.cert_path = constants.CLI_DEFAULTS['auth_cert_path']
     self.config.fullchain_path = constants.CLI_DEFAULTS['auth_chain_path']
     self.config.chain_path = constants.CLI_DEFAULTS['auth_chain_path']
     self.config.server = "https://example.com"
    def test_certificates_no_files(self, mock_utility, mock_logger):
        empty_tempdir = tempfile.mkdtemp()
        empty_config = configuration.NamespaceConfig(
            mock.MagicMock(config_dir=os.path.join(empty_tempdir, "config"),
                           work_dir=os.path.join(empty_tempdir, "work"),
                           logs_dir=os.path.join(empty_tempdir, "logs"),
                           quiet=False))

        filesystem.makedirs(empty_config.renewal_configs_dir)
        self._certificates(empty_config)
        self.assertFalse(mock_logger.warning.called)
        self.assertTrue(mock_utility.called)
        shutil.rmtree(empty_tempdir)
예제 #7
0
def main(cli_args=None):
    """Run Certbot.

    :param cli_args: command line to Certbot, defaults to ``sys.argv[1:]``
    :type cli_args: `list` of `str`

    :returns: value for `sys.exit` about the exit status of Certbot
    :rtype: `str` or `int` or `None`

    """
    if not cli_args:
        cli_args = sys.argv[1:]

    log.pre_arg_parse_setup()

    plugins = plugins_disco.PluginsRegistry.find_all()
    logger.debug("certbot version: %s", certbot.__version__)
    # do not log `config`, as it contains sensitive data (e.g. revoke --key)!
    logger.debug("Arguments: %r", cli_args)
    logger.debug("Discovered plugins: %r", plugins)

    # note: arg parser internally handles --help (and exits afterwards)
    args = cli.prepare_and_parse_args(plugins, cli_args)
    config = configuration.NamespaceConfig(args)
    zope.component.provideUtility(config)

    # On windows, shell without administrative right cannot create symlinks required by certbot.
    # So we check the rights before continuing.
    misc.raise_for_non_administrative_windows_rights()

    try:
        log.post_arg_parse_setup(config)
        make_or_verify_needed_dirs(config)
    except errors.Error:
        # Let plugins_cmd be run as un-privileged user.
        if config.func != plugins_cmd:  # pylint: disable=comparison-with-callable
            raise

    if sys.version_info[:2] == (3, 4):
        logger.warning(
            "Python 3.4 support will be dropped in the next release "
            "of Certbot - please upgrade your Python version to 3.5+.")

    set_displayer(config)

    # Reporter
    report = reporter.Reporter(config)
    zope.component.provideUtility(report)
    util.atexit_register(report.print_messages)

    return config.func(config, plugins)
예제 #8
0
 def test_ancient_webroot_renewal_conf(self, mock_set_by_cli):
     mock_set_by_cli.return_value = False
     rc_path = test_util.make_lineage(self.config.config_dir,
                                      'sample-renewal-ancient.conf')
     self.config.account = None
     self.config.email = None
     self.config.webroot_path = None
     config = configuration.NamespaceConfig(self.config)
     lineage = storage.RenewableCert(rc_path, config)
     renewalparams = lineage.configuration['renewalparams']
     # pylint: disable=protected-access
     from certbot._internal import renewal
     renewal._restore_webroot_config(config, renewalparams)
     self.assertEqual(config.webroot_path, ['/var/www/'])
예제 #9
0
    def test_remove_deprecated_config_elements(self, mock_set_by_cli, unused_mock_get_utility):
        mock_set_by_cli.return_value = False
        config = configuration.NamespaceConfig(self.config)
        config.certname = "sample-renewal-deprecated-option"

        rc_path = test_util.make_lineage(
            self.config.config_dir, 'sample-renewal-deprecated-option.conf')

        from certbot._internal import renewal
        lineage_config = copy.deepcopy(self.config)
        renewal_candidate = renewal._reconstitute(lineage_config, rc_path)
        # This means that manual_public_ip_logging_ok was not modified in the config based on its
        # value in the renewal conf file
        self.assertTrue(isinstance(lineage_config.manual_public_ip_logging_ok, mock.MagicMock))
예제 #10
0
 def setup_method(self, method):
     # Setup fake redis for testing.
     self.r = fakeredis.FakeStrictRedis()
     self.name = 'certbot-redis-auth'
     self.name_cfg = self.name.replace('-', '_') + '_'
     self.tempdir = tempfile.mkdtemp(dir=tempfile.gettempdir())
     self.config = configuration.NamespaceConfig(
         mock.MagicMock(**constants.CLI_DEFAULTS))
     self.config.verb = "certonly"
     self.config.config_dir = os.path.join(self.tempdir, 'config')
     self.config.work_dir = os.path.join(self.tempdir, 'work')
     self.config.logs_dir = os.path.join(self.tempdir, 'logs')
     self.config.cert_path = constants.CLI_DEFAULTS['auth_cert_path']
     self.config.fullchain_path = constants.CLI_DEFAULTS['auth_chain_path']
     self.config.chain_path = constants.CLI_DEFAULTS['auth_chain_path']
     self.config.server = "example.com"
     self.http_chall = acme_util.ACHALLENGES[0]  # Http Chall
예제 #11
0
def main(cli_args=None):
    """Command line argument parsing and main script execution.

    :returns: result of requested command

    :raises errors.Error: OS errors triggered by wrong permissions
    :raises errors.Error: error if plugin command is not supported

    """
    if not cli_args:
        cli_args = sys.argv[1:]

    log.pre_arg_parse_setup()

    plugins = plugins_disco.PluginsRegistry.find_all()
    logger.debug("certbot version: %s", certbot.__version__)
    # do not log `config`, as it contains sensitive data (e.g. revoke --key)!
    logger.debug("Arguments: %r", cli_args)
    logger.debug("Discovered plugins: %r", plugins)

    # note: arg parser internally handles --help (and exits afterwards)
    args = cli.prepare_and_parse_args(plugins, cli_args)
    config = configuration.NamespaceConfig(args)
    zope.component.provideUtility(config)

    # On windows, shell without administrative right cannot create symlinks required by certbot.
    # So we check the rights before continuing.
    misc.raise_for_non_administrative_windows_rights()

    try:
        log.post_arg_parse_setup(config)
        make_or_verify_needed_dirs(config)
    except errors.Error:
        # Let plugins_cmd be run as un-privileged user.
        if config.func != plugins_cmd:
            raise

    set_displayer(config)

    # Reporter
    report = reporter.Reporter(config)
    zope.component.provideUtility(report)
    util.atexit_register(report.print_messages)

    return config.func(config, plugins)
예제 #12
0
    def test_reuse_key_renewal_params(self):
        self.config.rsa_key_size = 'INVALID_VALUE'
        self.config.reuse_key = True
        self.config.dry_run = True
        config = configuration.NamespaceConfig(self.config)

        rc_path = test_util.make_lineage(self.config.config_dir,
                                         'sample-renewal.conf')
        lineage = storage.RenewableCert(rc_path, config)

        le_client = mock.MagicMock()
        le_client.obtain_certificate.return_value = (None, None, None, None)

        from certbot._internal import renewal

        with mock.patch('certbot._internal.renewal.hooks.renew_hook'):
            renewal.renew_cert(self.config, None, le_client, lineage)

        assert self.config.rsa_key_size == 2048
예제 #13
0
    def setUp(self):
        self.redis_client_mock = patch("hvac.Client").start().return_value
        self.name = "certbot-vault-installer"
        self.name_cfg = self.name.replace("-", "_") + "_"
        self.tempdir = tempfile.mkdtemp(dir=tempfile.gettempdir())
        self.config = configuration.NamespaceConfig(
            MagicMock(**constants.CLI_DEFAULTS))
        self.config.verb = "certonly"
        self.config.config_dir = os.path.join(self.tempdir, "config")
        self.config.work_dir = os.path.join(self.tempdir, "work")
        self.config.logs_dir = os.path.join(self.tempdir, "logs")
        self.config.cert_path = constants.CLI_DEFAULTS["auth_cert_path"]
        self.config.fullchain_path = constants.CLI_DEFAULTS["auth_chain_path"]
        self.config.chain_path = constants.CLI_DEFAULTS["auth_chain_path"]
        self.config.server = "example.com"
        self.config.certbot_vault_installer_vault_engine_name = "certificates"

        self.config.__setattr__(self.name_cfg + "vault-url",
                                "http://localhost:8200")
        self.config.__setattr__(self.name_cfg + "vault-url", "testike")
        self.subject = VaultInstaller(self.config, self.name)
예제 #14
0
    def test_reuse_ec_key_renewal_params(self):
        self.config.elliptic_curve = 'INVALID_CURVE'
        self.config.reuse_key = True
        self.config.dry_run = True
        self.config.key_type = 'ecdsa'
        config = configuration.NamespaceConfig(self.config)

        rc_path = test_util.make_lineage(
            self.config.config_dir,
            'sample-renewal-ec.conf',
            ec=True,
        )
        lineage = storage.RenewableCert(rc_path, config)

        le_client = mock.MagicMock()
        le_client.obtain_certificate.return_value = (None, None, None, None)

        from certbot._internal import renewal

        with mock.patch('certbot._internal.renewal.hooks.renew_hook'):
            renewal.renew_cert(self.config, None, le_client, lineage)

        assert self.config.elliptic_curve == 'secp256r1'