pgreco / rpms / ipa

Forked from forks/areguera/rpms/ipa 4 years ago
Clone
b01884
From 468bcf90cb985e2b1eb394bd752dc39aa4b75582 Mon Sep 17 00:00:00 2001
b01884
From: Rob Crittenden <rcritten@redhat.com>
b01884
Date: Thu, 19 Jul 2018 18:37:18 -0400
b01884
Subject: [PATCH] Remove csrgen
b01884
b01884
This reverts commits:
b01884
* 72de679eb445c975ec70cd265d37d4927823ce5b
b01884
* 177f07e163d6d591a1e609d35e0a6f6f5347551e
b01884
* 80be18162921268be9c8981495c9e8a4de0c85cd
b01884
* 83e2c2b65eeb5a3aa4a59c0535e9177aac5e4637
b01884
* ada91c20588046bb147fc701718d3da4d2c080ca
b01884
* 4350dcdea22fd2284836315d0ae7d38733a7620e
b01884
* 39a5d9c5aae77687f67d9be02457733bdfb99ead
b01884
* a26cf0d7910dd4c0a4da08682b4be8d3d94ba520
b01884
* afd7c05d11432304bfdf183832a21d419f363689
b01884
* f1a1c6eca1b294f24174d7b0e1f78de46d9d5b05
b01884
* fc58eff6a3d7fe805e612b8b002304d8b9cd4ba9
b01884
* 10ef5947860f5098182b1f95c08c1158e2da15f9
b01884
b01884
https://bugzilla.redhat.com/show_bug.cgi?id=1432630
b01884
---
b01884
 freeipa.spec.in                                    |  14 -
b01884
 ipaclient/csrgen.py                                | 488 ---------------------
b01884
 ipaclient/csrgen/profiles/caIPAserviceCert.json    |  15 -
b01884
 ipaclient/csrgen/profiles/userCert.json            |  15 -
b01884
 ipaclient/csrgen/rules/dataDNS.json                |   8 -
b01884
 ipaclient/csrgen/rules/dataEmail.json              |   8 -
b01884
 ipaclient/csrgen/rules/dataHostCN.json             |   8 -
b01884
 ipaclient/csrgen/rules/dataSubjectBase.json        |   8 -
b01884
 ipaclient/csrgen/rules/dataUsernameCN.json         |   8 -
b01884
 ipaclient/csrgen/rules/syntaxSAN.json              |   8 -
b01884
 ipaclient/csrgen/rules/syntaxSubject.json          |   9 -
b01884
 ipaclient/csrgen/templates/openssl_base.tmpl       |  17 -
b01884
 ipaclient/csrgen/templates/openssl_macros.tmpl     |  29 --
b01884
 ipaclient/csrgen_ffi.py                            | 331 --------------
b01884
 ipaclient/plugins/cert.py                          |  80 ----
b01884
 ipaclient/plugins/csrgen.py                        | 128 ------
b01884
 ipaclient/setup.py                                 |   8 -
b01884
 .../data/test_csrgen/configs/caIPAserviceCert.conf |  16 -
b01884
 .../data/test_csrgen/configs/userCert.conf         |  16 -
b01884
 .../data/test_csrgen/profiles/profile.json         |   8 -
b01884
 .../data/test_csrgen/rules/basic.json              |   5 -
b01884
 .../data/test_csrgen/rules/options.json            |   8 -
b01884
 .../data/test_csrgen/templates/identity_base.tmpl  |   1 -
b01884
 ipatests/test_ipaclient/test_csrgen.py             | 304 -------------
b01884
 24 files changed, 1540 deletions(-)
b01884
 delete mode 100644 ipaclient/csrgen.py
b01884
 delete mode 100644 ipaclient/csrgen/profiles/caIPAserviceCert.json
b01884
 delete mode 100644 ipaclient/csrgen/profiles/userCert.json
b01884
 delete mode 100644 ipaclient/csrgen/rules/dataDNS.json
b01884
 delete mode 100644 ipaclient/csrgen/rules/dataEmail.json
b01884
 delete mode 100644 ipaclient/csrgen/rules/dataHostCN.json
b01884
 delete mode 100644 ipaclient/csrgen/rules/dataSubjectBase.json
b01884
 delete mode 100644 ipaclient/csrgen/rules/dataUsernameCN.json
b01884
 delete mode 100644 ipaclient/csrgen/rules/syntaxSAN.json
b01884
 delete mode 100644 ipaclient/csrgen/rules/syntaxSubject.json
b01884
 delete mode 100644 ipaclient/csrgen/templates/openssl_base.tmpl
b01884
 delete mode 100644 ipaclient/csrgen/templates/openssl_macros.tmpl
b01884
 delete mode 100644 ipaclient/csrgen_ffi.py
b01884
 delete mode 100644 ipaclient/plugins/csrgen.py
b01884
 delete mode 100644 ipatests/test_ipaclient/data/test_csrgen/configs/caIPAserviceCert.conf
b01884
 delete mode 100644 ipatests/test_ipaclient/data/test_csrgen/configs/userCert.conf
b01884
 delete mode 100644 ipatests/test_ipaclient/data/test_csrgen/profiles/profile.json
b01884
 delete mode 100644 ipatests/test_ipaclient/data/test_csrgen/rules/basic.json
b01884
 delete mode 100644 ipatests/test_ipaclient/data/test_csrgen/rules/options.json
b01884
 delete mode 100644 ipatests/test_ipaclient/data/test_csrgen/templates/identity_base.tmpl
b01884
 delete mode 100644 ipatests/test_ipaclient/test_csrgen.py
b01884
b01884
diff --git a/freeipa.spec.in b/freeipa.spec.in
b01884
index a01fae7..cd1773a 100644
b01884
--- a/freeipa.spec.in
b01884
+++ b/freeipa.spec.in
b01884
@@ -1538,13 +1538,6 @@ fi
b01884
 %{python2_sitelib}/ipaclient/remote_plugins/*.py*
b01884
 %dir %{python2_sitelib}/ipaclient/remote_plugins/2_*
b01884
 %{python2_sitelib}/ipaclient/remote_plugins/2_*/*.py*
b01884
-%dir %{python2_sitelib}/ipaclient/csrgen
b01884
-%dir %{python2_sitelib}/ipaclient/csrgen/profiles
b01884
-%{python2_sitelib}/ipaclient/csrgen/profiles/*.json
b01884
-%dir %{python2_sitelib}/ipaclient/csrgen/rules
b01884
-%{python2_sitelib}/ipaclient/csrgen/rules/*.json
b01884
-%dir %{python2_sitelib}/ipaclient/csrgen/templates
b01884
-%{python2_sitelib}/ipaclient/csrgen/templates/*.tmpl
b01884
 %{python2_sitelib}/ipaclient-*.egg-info
b01884
 
b01884
 %endif # with_python2
b01884
@@ -1567,13 +1560,6 @@ fi
b01884
 %dir %{python3_sitelib}/ipaclient/remote_plugins/2_*
b01884
 %{python3_sitelib}/ipaclient/remote_plugins/2_*/*.py
b01884
 %{python3_sitelib}/ipaclient/remote_plugins/2_*/__pycache__/*.py*
b01884
-%dir %{python3_sitelib}/ipaclient/csrgen
b01884
-%dir %{python3_sitelib}/ipaclient/csrgen/profiles
b01884
-%{python3_sitelib}/ipaclient/csrgen/profiles/*.json
b01884
-%dir %{python3_sitelib}/ipaclient/csrgen/rules
b01884
-%{python3_sitelib}/ipaclient/csrgen/rules/*.json
b01884
-%dir %{python3_sitelib}/ipaclient/csrgen/templates
b01884
-%{python3_sitelib}/ipaclient/csrgen/templates/*.tmpl
b01884
 %{python3_sitelib}/ipaclient-*.egg-info
b01884
 
b01884
 
b01884
diff --git a/ipaclient/csrgen.py b/ipaclient/csrgen.py
b01884
deleted file mode 100644
b01884
index e7573be..0000000
b01884
--- a/ipaclient/csrgen.py
b01884
+++ /dev/null
b01884
@@ -1,488 +0,0 @@
b01884
-#
b01884
-# Copyright (C) 2016  FreeIPA Contributors see COPYING for license
b01884
-#
b01884
-
b01884
-import base64
b01884
-import collections
b01884
-import errno
b01884
-import json
b01884
-import logging
b01884
-import os
b01884
-import os.path
b01884
-import pipes
b01884
-import subprocess
b01884
-import traceback
b01884
-import codecs
b01884
-
b01884
-import pkg_resources
b01884
-
b01884
-from cryptography.hazmat.backends import default_backend
b01884
-from cryptography.hazmat.primitives.asymmetric import padding
b01884
-from cryptography.hazmat.primitives import hashes
b01884
-from cryptography.hazmat.primitives.serialization import (
b01884
-    load_pem_private_key, Encoding, PublicFormat)
b01884
-from cryptography.x509 import load_pem_x509_certificate
b01884
-import jinja2
b01884
-import jinja2.ext
b01884
-import jinja2.sandbox
b01884
-from pyasn1.codec.der import decoder, encoder
b01884
-from pyasn1.type import univ
b01884
-from pyasn1_modules import rfc2314
b01884
-import six
b01884
-
b01884
-from ipalib import api
b01884
-from ipalib import errors
b01884
-from ipalib.text import _
b01884
-
b01884
-if six.PY3:
b01884
-    unicode = str
b01884
-
b01884
-__doc__ = _("""
b01884
-Routines for constructing certificate signing requests using IPA data and
b01884
-stored templates.
b01884
-""")
b01884
-
b01884
-logger = logging.getLogger(__name__)
b01884
-
b01884
-
b01884
-class IndexableUndefined(jinja2.Undefined):
b01884
-    def __getitem__(self, key):
b01884
-        return jinja2.Undefined(
b01884
-            hint=self._undefined_hint, obj=self._undefined_obj,
b01884
-            name=self._undefined_name, exc=self._undefined_exception)
b01884
-
b01884
-
b01884
-class IPAExtension(jinja2.ext.Extension):
b01884
-    """Jinja2 extension providing useful features for CSR generation rules."""
b01884
-
b01884
-    def __init__(self, environment):
b01884
-        super(IPAExtension, self).__init__(environment)
b01884
-
b01884
-        environment.filters.update(
b01884
-            quote=self.quote,
b01884
-            required=self.required,
b01884
-        )
b01884
-
b01884
-    def quote(self, data):
b01884
-        return pipes.quote(data)
b01884
-
b01884
-    def required(self, data, name):
b01884
-        if not data:
b01884
-            raise errors.CSRTemplateError(
b01884
-                reason=_(
b01884
-                    'Required CSR generation rule %(name)s is missing data') %
b01884
-                {'name': name})
b01884
-        return data
b01884
-
b01884
-
b01884
-class Formatter(object):
b01884
-    """
b01884
-    Class for processing a set of CSR generation rules into a template.
b01884
-
b01884
-    The template can be rendered with user and database data to produce a
b01884
-    config, which specifies how to build a CSR.
b01884
-
b01884
-    Subclasses of Formatter should set the value of base_template_name to the
b01884
-    filename of a base template with spaces for the processed rules.
b01884
-    Additionally, they should override the _get_template_params method to
b01884
-    produce the correct output for the base template.
b01884
-    """
b01884
-    base_template_name = None
b01884
-
b01884
-    def __init__(self, csr_data_dir=None):
b01884
-        # chain loaders:
b01884
-        # 1) csr_data_dir/templates
b01884
-        # 2) /etc/ipa/csrgen/templates
b01884
-        # 3) ipaclient/csrgen/templates
b01884
-        loaders = []
b01884
-        if csr_data_dir is not None:
b01884
-            loaders.append(jinja2.FileSystemLoader(
b01884
-                os.path.join(csr_data_dir, 'templates'))
b01884
-            )
b01884
-        loaders.append(jinja2.FileSystemLoader(
b01884
-            os.path.join(api.env.confdir, 'csrgen/templates'))
b01884
-        )
b01884
-        loaders.append(jinja2.PackageLoader('ipaclient', 'csrgen/templates'))
b01884
-
b01884
-        self.jinja2 = jinja2.sandbox.SandboxedEnvironment(
b01884
-            loader=jinja2.ChoiceLoader(loaders),
b01884
-            extensions=[jinja2.ext.ExprStmtExtension, IPAExtension],
b01884
-            keep_trailing_newline=True, undefined=IndexableUndefined)
b01884
-
b01884
-        self.passthrough_globals = {}
b01884
-
b01884
-    def _define_passthrough(self, call):
b01884
-        """Some macros are meant to be interpreted during the final render, not
b01884
-        when data rules are interpolated into syntax rules. This method allows
b01884
-        those macros to be registered so that calls to them are passed through
b01884
-        to the prepared rule rather than interpreted.
b01884
-        """
b01884
-
b01884
-        def passthrough(caller):
b01884
-            return u'{%% call %s() %%}%s{%% endcall %%}' % (call, caller())
b01884
-
b01884
-        parts = call.split('.')
b01884
-        current_level = self.passthrough_globals
b01884
-        for part in parts[:-1]:
b01884
-            if part not in current_level:
b01884
-                current_level[part] = {}
b01884
-            current_level = current_level[part]
b01884
-        current_level[parts[-1]] = passthrough
b01884
-
b01884
-    def build_template(self, rules):
b01884
-        """
b01884
-        Construct a template that can produce CSR generator strings.
b01884
-
b01884
-        :param rules: list of FieldMapping to use to populate the template.
b01884
-
b01884
-        :returns: jinja2.Template that can be rendered to produce the CSR data.
b01884
-        """
b01884
-        syntax_rules = []
b01884
-        for field_mapping in rules:
b01884
-            data_rules_prepared = [
b01884
-                self._prepare_data_rule(rule)
b01884
-                for rule in field_mapping.data_rules]
b01884
-
b01884
-            data_sources = []
b01884
-            for xrule in field_mapping.data_rules:
b01884
-                data_source = xrule.options.get('data_source')
b01884
-                if data_source:
b01884
-                    data_sources.append(data_source)
b01884
-
b01884
-            syntax_rules.append(self._prepare_syntax_rule(
b01884
-                field_mapping.syntax_rule, data_rules_prepared,
b01884
-                field_mapping.description, data_sources))
b01884
-
b01884
-        template_params = self._get_template_params(syntax_rules)
b01884
-        base_template = self.jinja2.get_template(
b01884
-            self.base_template_name, globals=self.passthrough_globals)
b01884
-
b01884
-        try:
b01884
-            combined_template_source = base_template.render(**template_params)
b01884
-        except jinja2.UndefinedError:
b01884
-            logger.debug(traceback.format_exc())
b01884
-            raise errors.CSRTemplateError(reason=_(
b01884
-                'Template error when formatting certificate data'))
b01884
-
b01884
-        logger.debug(
b01884
-            'Formatting with template: %s', combined_template_source)
b01884
-        combined_template = self.jinja2.from_string(combined_template_source)
b01884
-
b01884
-        return combined_template
b01884
-
b01884
-    def _wrap_conditional(self, rule, condition):
b01884
-        rule = '{%% if %s %%}%s{%% endif %%}' % (condition, rule)
b01884
-        return rule
b01884
-
b01884
-    def _wrap_required(self, rule, description):
b01884
-        template = '{%% filter required("%s") %%}%s{%% endfilter %%}' % (
b01884
-            description, rule)
b01884
-
b01884
-        return template
b01884
-
b01884
-    def _prepare_data_rule(self, data_rule):
b01884
-        template = data_rule.template
b01884
-
b01884
-        data_source = data_rule.options.get('data_source')
b01884
-        if data_source:
b01884
-            template = self._wrap_conditional(template, data_source)
b01884
-
b01884
-        return template
b01884
-
b01884
-    def _prepare_syntax_rule(
b01884
-            self, syntax_rule, data_rules, description, data_sources):
b01884
-        logger.debug('Syntax rule template: %s', syntax_rule.template)
b01884
-        template = self.jinja2.from_string(
b01884
-            syntax_rule.template, globals=self.passthrough_globals)
b01884
-        is_required = syntax_rule.options.get('required', False)
b01884
-        try:
b01884
-            prepared_template = template.render(datarules=data_rules)
b01884
-        except jinja2.UndefinedError:
b01884
-            logger.debug(traceback.format_exc())
b01884
-            raise errors.CSRTemplateError(reason=_(
b01884
-                'Template error when formatting certificate data'))
b01884
-
b01884
-        if data_sources:
b01884
-            combinator = ' %s ' % syntax_rule.options.get(
b01884
-                'data_source_combinator', 'or')
b01884
-            condition = combinator.join(data_sources)
b01884
-            prepared_template = self._wrap_conditional(
b01884
-                prepared_template, condition)
b01884
-
b01884
-        if is_required:
b01884
-            prepared_template = self._wrap_required(
b01884
-                prepared_template, description)
b01884
-
b01884
-        return prepared_template
b01884
-
b01884
-    def _get_template_params(self, syntax_rules):
b01884
-        """
b01884
-        Package the syntax rules into fields expected by the base template.
b01884
-
b01884
-        :param syntax_rules: list of prepared syntax rules to be included in
b01884
-            the template.
b01884
-
b01884
-        :returns: dict of values needed to render the base template.
b01884
-        """
b01884
-        raise NotImplementedError('Formatter class must be subclassed')
b01884
-
b01884
-
b01884
-class OpenSSLFormatter(Formatter):
b01884
-    """Formatter class generating the openssl config-file format."""
b01884
-
b01884
-    base_template_name = 'openssl_base.tmpl'
b01884
-
b01884
-    # Syntax rules are wrapped in this data structure, to keep track of whether
b01884
-    # each goes in the extension or the root section
b01884
-    SyntaxRule = collections.namedtuple(
b01884
-        'SyntaxRule', ['template', 'is_extension'])
b01884
-
b01884
-    def __init__(self, *args, **kwargs):
b01884
-        super(OpenSSLFormatter, self).__init__(*args, **kwargs)
b01884
-        self._define_passthrough('openssl.section')
b01884
-
b01884
-    def _get_template_params(self, syntax_rules):
b01884
-        parameters = [rule.template for rule in syntax_rules
b01884
-                      if not rule.is_extension]
b01884
-        extensions = [rule.template for rule in syntax_rules
b01884
-                      if rule.is_extension]
b01884
-
b01884
-        return {'parameters': parameters, 'extensions': extensions}
b01884
-
b01884
-    def _prepare_syntax_rule(
b01884
-            self, syntax_rule, data_rules, description, data_sources):
b01884
-        """Overrides method to pull out whether rule is an extension or not."""
b01884
-        prepared_template = super(OpenSSLFormatter, self)._prepare_syntax_rule(
b01884
-            syntax_rule, data_rules, description, data_sources)
b01884
-        is_extension = syntax_rule.options.get('extension', False)
b01884
-        return self.SyntaxRule(prepared_template, is_extension)
b01884
-
b01884
-
b01884
-class FieldMapping(object):
b01884
-    """Representation of the rules needed to construct a complete cert field.
b01884
-
b01884
-    Attributes:
b01884
-        description: str, a name or description of this field, to be used in
b01884
-            messages
b01884
-        syntax_rule: Rule, the rule defining the syntax of this field
b01884
-        data_rules: list of Rule, the rules that produce data to be stored in
b01884
-            this field
b01884
-    """
b01884
-    __slots__ = ['description', 'syntax_rule', 'data_rules']
b01884
-
b01884
-    def __init__(self, description, syntax_rule, data_rules):
b01884
-        self.description = description
b01884
-        self.syntax_rule = syntax_rule
b01884
-        self.data_rules = data_rules
b01884
-
b01884
-
b01884
-class Rule(object):
b01884
-    __slots__ = ['name', 'template', 'options']
b01884
-
b01884
-    def __init__(self, name, template, options):
b01884
-        self.name = name
b01884
-        self.template = template
b01884
-        self.options = options
b01884
-
b01884
-
b01884
-class RuleProvider(object):
b01884
-    def rules_for_profile(self, profile_id):
b01884
-        """
b01884
-        Return the rules needed to build a CSR using the given profile.
b01884
-
b01884
-        :param profile_id: str, name of the CSR generation profile to use
b01884
-
b01884
-        :returns: list of FieldMapping, filled out with the appropriate rules
b01884
-        """
b01884
-        raise NotImplementedError('RuleProvider class must be subclassed')
b01884
-
b01884
-
b01884
-class FileRuleProvider(RuleProvider):
b01884
-    def __init__(self, csr_data_dir=None):
b01884
-        self.rules = {}
b01884
-        self._csrgen_data_dirs = []
b01884
-        if csr_data_dir is not None:
b01884
-            self._csrgen_data_dirs.append(csr_data_dir)
b01884
-        self._csrgen_data_dirs.append(
b01884
-            os.path.join(api.env.confdir, 'csrgen')
b01884
-        )
b01884
-        self._csrgen_data_dirs.append(
b01884
-            pkg_resources.resource_filename('ipaclient', 'csrgen')
b01884
-        )
b01884
-
b01884
-    def _open(self, subdir, filename):
b01884
-        for data_dir in self._csrgen_data_dirs:
b01884
-            path = os.path.join(data_dir, subdir, filename)
b01884
-            try:
b01884
-                return open(path)
b01884
-            except IOError as e:
b01884
-                if e.errno != errno.ENOENT:
b01884
-                    raise
b01884
-        raise IOError(
b01884
-            errno.ENOENT,
b01884
-            "'{}' not found in {}".format(
b01884
-                os.path.join(subdir, filename),
b01884
-                ", ".join(self._csrgen_data_dirs)
b01884
-            )
b01884
-        )
b01884
-
b01884
-    def _rule(self, rule_name):
b01884
-        if rule_name not in self.rules:
b01884
-            try:
b01884
-                with self._open('rules', '%s.json' % rule_name) as f:
b01884
-                    ruleconf = json.load(f)
b01884
-            except IOError:
b01884
-                raise errors.NotFound(
b01884
-                    reason=_('No generation rule %(rulename)s found.') %
b01884
-                    {'rulename': rule_name})
b01884
-
b01884
-            try:
b01884
-                rule = ruleconf['rule']
b01884
-            except KeyError:
b01884
-                raise errors.EmptyResult(
b01884
-                    reason=_('Generation rule "%(rulename)s" is missing the'
b01884
-                             ' "rule" key') % {'rulename': rule_name})
b01884
-
b01884
-            options = ruleconf.get('options', {})
b01884
-
b01884
-            self.rules[rule_name] = Rule(
b01884
-                rule_name, rule['template'], options)
b01884
-
b01884
-        return self.rules[rule_name]
b01884
-
b01884
-    def rules_for_profile(self, profile_id):
b01884
-        try:
b01884
-            with self._open('profiles', '%s.json' % profile_id) as f:
b01884
-                profile = json.load(f)
b01884
-        except IOError:
b01884
-            raise errors.NotFound(
b01884
-                reason=_('No CSR generation rules are defined for profile'
b01884
-                         ' %(profile_id)s') % {'profile_id': profile_id})
b01884
-
b01884
-        field_mappings = []
b01884
-        for field in profile:
b01884
-            syntax_rule = self._rule(field['syntax'])
b01884
-            data_rules = [self._rule(name) for name in field['data']]
b01884
-            field_mappings.append(FieldMapping(
b01884
-                syntax_rule.name, syntax_rule, data_rules))
b01884
-        return field_mappings
b01884
-
b01884
-
b01884
-class CSRGenerator(object):
b01884
-    def __init__(self, rule_provider, formatter_class=OpenSSLFormatter):
b01884
-        self.rule_provider = rule_provider
b01884
-        self.formatter = formatter_class()
b01884
-
b01884
-    def csr_config(self, principal, config, profile_id):
b01884
-        render_data = {'subject': principal, 'config': config}
b01884
-
b01884
-        rules = self.rule_provider.rules_for_profile(profile_id)
b01884
-        template = self.formatter.build_template(rules)
b01884
-
b01884
-        try:
b01884
-            config = template.render(render_data)
b01884
-        except jinja2.UndefinedError:
b01884
-            logger.debug(traceback.format_exc())
b01884
-            raise errors.CSRTemplateError(reason=_(
b01884
-                'Template error when formatting certificate data'))
b01884
-
b01884
-        return config
b01884
-
b01884
-
b01884
-class CSRLibraryAdaptor(object):
b01884
-    def get_subject_public_key_info(self):
b01884
-        raise NotImplementedError('Use a subclass of CSRLibraryAdaptor')
b01884
-
b01884
-    def sign_csr(self, certification_request_info):
b01884
-        """Sign a CertificationRequestInfo.
b01884
-
b01884
-        :returns: bytes, a DER-encoded signed CSR.
b01884
-        """
b01884
-        raise NotImplementedError('Use a subclass of CSRLibraryAdaptor')
b01884
-
b01884
-
b01884
-class OpenSSLAdaptor(object):
b01884
-    def __init__(self, key=None, key_filename=None, password_filename=None):
b01884
-        """
b01884
-        Must provide either ``key_filename`` or ``key``.
b01884
-
b01884
-        """
b01884
-        if key_filename is not None:
b01884
-            with open(key_filename, 'rb') as key_file:
b01884
-                key_bytes = key_file.read()
b01884
-
b01884
-            password = None
b01884
-            if password_filename is not None:
b01884
-                with open(password_filename, 'rb') as password_file:
b01884
-                    password = password_file.read().strip()
b01884
-
b01884
-            self._key = load_pem_private_key(
b01884
-                key_bytes, password, default_backend())
b01884
-
b01884
-        elif key is not None:
b01884
-            self._key = key
b01884
-
b01884
-        else:
b01884
-            raise ValueError("Must provide 'key' or 'key_filename'")
b01884
-
b01884
-    def key(self):
b01884
-        return self._key
b01884
-
b01884
-    def get_subject_public_key_info(self):
b01884
-        pubkey_info = self.key().public_key().public_bytes(
b01884
-            Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
b01884
-        return pubkey_info
b01884
-
b01884
-    def sign_csr(self, certification_request_info):
b01884
-        reqinfo = decoder.decode(
b01884
-            certification_request_info, rfc2314.CertificationRequestInfo())[0]
b01884
-        csr = rfc2314.CertificationRequest()
b01884
-        csr.setComponentByName('certificationRequestInfo', reqinfo)
b01884
-
b01884
-        algorithm = rfc2314.SignatureAlgorithmIdentifier()
b01884
-        algorithm.setComponentByName(
b01884
-            'algorithm', univ.ObjectIdentifier(
b01884
-                '1.2.840.113549.1.1.11'))  # sha256WithRSAEncryption
b01884
-        csr.setComponentByName('signatureAlgorithm', algorithm)
b01884
-
b01884
-        signature = self.key().sign(
b01884
-            certification_request_info,
b01884
-            padding.PKCS1v15(),
b01884
-            hashes.SHA256()
b01884
-        )
b01884
-        asn1sig = univ.BitString("'{sig}'H".format(
b01884
-                                    sig=codecs.encode(signature, 'hex')
b01884
-                                    .decode('ascii'))
b01884
-                                 )
b01884
-        csr.setComponentByName('signature', asn1sig)
b01884
-        return encoder.encode(csr)
b01884
-
b01884
-
b01884
-class NSSAdaptor(object):
b01884
-    def __init__(self, database, password_filename):
b01884
-        self.database = database
b01884
-        self.password_filename = password_filename
b01884
-        self.nickname = base64.b32encode(os.urandom(40))
b01884
-
b01884
-    def get_subject_public_key_info(self):
b01884
-        temp_cn = base64.b32encode(os.urandom(40)).decode('ascii')
b01884
-
b01884
-        password_args = []
b01884
-        if self.password_filename is not None:
b01884
-            password_args = ['-f', self.password_filename]
b01884
-
b01884
-        subprocess.check_call(
b01884
-            ['certutil', '-S', '-n', self.nickname, '-s', 'CN=%s' % temp_cn,
b01884
-             '-x', '-t', ',,', '-d', self.database] + password_args)
b01884
-        cert_pem = subprocess.check_output(
b01884
-            ['certutil', '-L', '-n', self.nickname, '-a',
b01884
-             '-d', self.database] + password_args)
b01884
-
b01884
-        cert = load_pem_x509_certificate(cert_pem, default_backend())
b01884
-        pubkey_info = cert.public_key().public_bytes(
b01884
-            Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
b01884
-
b01884
-        return pubkey_info
b01884
-
b01884
-    def sign_csr(self, certification_request_info):
b01884
-        raise NotImplementedError('NSS is not yet supported')
b01884
diff --git a/ipaclient/csrgen/profiles/caIPAserviceCert.json b/ipaclient/csrgen/profiles/caIPAserviceCert.json
b01884
deleted file mode 100644
b01884
index 114d2ff..0000000
b01884
--- a/ipaclient/csrgen/profiles/caIPAserviceCert.json
b01884
+++ /dev/null
b01884
@@ -1,15 +0,0 @@
b01884
-[
b01884
-    {
b01884
-        "syntax": "syntaxSubject",
b01884
-        "data": [
b01884
-            "dataHostCN",
b01884
-            "dataSubjectBase"
b01884
-        ]
b01884
-    },
b01884
-    {
b01884
-        "syntax": "syntaxSAN",
b01884
-        "data": [
b01884
-            "dataDNS"
b01884
-        ]
b01884
-    }
b01884
-]
b01884
diff --git a/ipaclient/csrgen/profiles/userCert.json b/ipaclient/csrgen/profiles/userCert.json
b01884
deleted file mode 100644
b01884
index d6cf5cf..0000000
b01884
--- a/ipaclient/csrgen/profiles/userCert.json
b01884
+++ /dev/null
b01884
@@ -1,15 +0,0 @@
b01884
-[
b01884
-    {
b01884
-        "syntax": "syntaxSubject",
b01884
-        "data": [
b01884
-            "dataUsernameCN",
b01884
-            "dataSubjectBase"
b01884
-        ]
b01884
-    },
b01884
-    {
b01884
-        "syntax": "syntaxSAN",
b01884
-        "data": [
b01884
-            "dataEmail"
b01884
-        ]
b01884
-    }
b01884
-]
b01884
diff --git a/ipaclient/csrgen/rules/dataDNS.json b/ipaclient/csrgen/rules/dataDNS.json
b01884
deleted file mode 100644
b01884
index a79a3d7..0000000
b01884
--- a/ipaclient/csrgen/rules/dataDNS.json
b01884
+++ /dev/null
b01884
@@ -1,8 +0,0 @@
b01884
-{
b01884
-  "rule": {
b01884
-    "template": "DNS = {{subject.krbprincipalname.0.partition('/')[2].partition('@')[0]}}"
b01884
-  },
b01884
-  "options": {
b01884
-    "data_source": "subject.krbprincipalname.0.partition('/')[2].partition('@')[0]"
b01884
-  }
b01884
-}
b01884
diff --git a/ipaclient/csrgen/rules/dataEmail.json b/ipaclient/csrgen/rules/dataEmail.json
b01884
deleted file mode 100644
b01884
index 4be6cec..0000000
b01884
--- a/ipaclient/csrgen/rules/dataEmail.json
b01884
+++ /dev/null
b01884
@@ -1,8 +0,0 @@
b01884
-{
b01884
-  "rule": {
b01884
-    "template": "email = {{subject.mail.0}}"
b01884
-  },
b01884
-  "options": {
b01884
-    "data_source": "subject.mail.0"
b01884
-  }
b01884
-}
b01884
diff --git a/ipaclient/csrgen/rules/dataHostCN.json b/ipaclient/csrgen/rules/dataHostCN.json
b01884
deleted file mode 100644
b01884
index f30c50f..0000000
b01884
--- a/ipaclient/csrgen/rules/dataHostCN.json
b01884
+++ /dev/null
b01884
@@ -1,8 +0,0 @@
b01884
-{
b01884
-  "rule": {
b01884
-    "template": "CN={{subject.krbprincipalname.0.partition('/')[2].partition('@')[0]}}"
b01884
-  },
b01884
-  "options": {
b01884
-    "data_source": "subject.krbprincipalname.0.partition('/')[2].partition('@')[0]"
b01884
-  }
b01884
-}
b01884
diff --git a/ipaclient/csrgen/rules/dataSubjectBase.json b/ipaclient/csrgen/rules/dataSubjectBase.json
b01884
deleted file mode 100644
b01884
index 31a38b4..0000000
b01884
--- a/ipaclient/csrgen/rules/dataSubjectBase.json
b01884
+++ /dev/null
b01884
@@ -1,8 +0,0 @@
b01884
-{
b01884
-  "rule": {
b01884
-    "template": "{{config.ipacertificatesubjectbase.0}}"
b01884
-  },
b01884
-  "options": {
b01884
-    "data_source": "config.ipacertificatesubjectbase.0"
b01884
-  }
b01884
-}
b01884
diff --git a/ipaclient/csrgen/rules/dataUsernameCN.json b/ipaclient/csrgen/rules/dataUsernameCN.json
b01884
deleted file mode 100644
b01884
index acbb524..0000000
b01884
--- a/ipaclient/csrgen/rules/dataUsernameCN.json
b01884
+++ /dev/null
b01884
@@ -1,8 +0,0 @@
b01884
-{
b01884
-  "rule": {
b01884
-    "template": "CN={{subject.uid.0}}"
b01884
-  },
b01884
-  "options": {
b01884
-    "data_source": "subject.uid.0"
b01884
-  }
b01884
-}
b01884
diff --git a/ipaclient/csrgen/rules/syntaxSAN.json b/ipaclient/csrgen/rules/syntaxSAN.json
b01884
deleted file mode 100644
b01884
index c6943ed..0000000
b01884
--- a/ipaclient/csrgen/rules/syntaxSAN.json
b01884
+++ /dev/null
b01884
@@ -1,8 +0,0 @@
b01884
-{
b01884
-  "rule": {
b01884
-    "template": "subjectAltName = @{% call openssl.section() %}{{ datarules|join('\n') }}{% endcall %}"
b01884
-  },
b01884
-  "options": {
b01884
-    "extension": true
b01884
-  }
b01884
-}
b01884
diff --git a/ipaclient/csrgen/rules/syntaxSubject.json b/ipaclient/csrgen/rules/syntaxSubject.json
b01884
deleted file mode 100644
b01884
index c609e01..0000000
b01884
--- a/ipaclient/csrgen/rules/syntaxSubject.json
b01884
+++ /dev/null
b01884
@@ -1,9 +0,0 @@
b01884
-{
b01884
-  "rule": {
b01884
-    "template": "distinguished_name = {% call openssl.section() %}{{ datarules|reverse|join('\n') }}{% endcall %}"
b01884
-  },
b01884
-  "options": {
b01884
-    "required": true,
b01884
-    "data_source_combinator": "and"
b01884
-  }
b01884
-}
b01884
diff --git a/ipaclient/csrgen/templates/openssl_base.tmpl b/ipaclient/csrgen/templates/openssl_base.tmpl
b01884
deleted file mode 100644
b01884
index 8d37994..0000000
b01884
--- a/ipaclient/csrgen/templates/openssl_base.tmpl
b01884
+++ /dev/null
b01884
@@ -1,17 +0,0 @@
b01884
-{% raw -%}
b01884
-{% import "openssl_macros.tmpl" as openssl -%}
b01884
-{% endraw -%}
b01884
-[ req ]
b01884
-prompt = no
b01884
-encrypt_key = no
b01884
-
b01884
-{{ parameters|join('\n') }}
b01884
-{% raw %}{% set rendered_extensions -%}{% endraw %}
b01884
-{{ extensions|join('\n') }}
b01884
-{% raw -%}
b01884
-{%- endset -%}
b01884
-{% if rendered_extensions -%}
b01884
-req_extensions = {% call openssl.section() %}{{ rendered_extensions }}{% endcall %}
b01884
-{% endif %}
b01884
-{{ openssl.openssl_sections|join('\n\n') }}
b01884
-{%- endraw %}
b01884
diff --git a/ipaclient/csrgen/templates/openssl_macros.tmpl b/ipaclient/csrgen/templates/openssl_macros.tmpl
b01884
deleted file mode 100644
b01884
index d31b8fe..0000000
b01884
--- a/ipaclient/csrgen/templates/openssl_macros.tmpl
b01884
+++ /dev/null
b01884
@@ -1,29 +0,0 @@
b01884
-{# List containing rendered sections to be included at end #}
b01884
-{% set openssl_sections = [] %}
b01884
-
b01884
-{#
b01884
-List containing one entry for each section name allocated. Because of
b01884
-scoping rules, we need to use a list so that it can be a "per-render global"
b01884
-that gets updated in place. Real globals are shared by all templates with the
b01884
-same environment, and variables defined in the macro don't persist after the
b01884
-macro invocation ends.
b01884
-#}
b01884
-{% set openssl_section_num = [] %}
b01884
-
b01884
-{% macro section() -%}
b01884
-{% set name -%}
b01884
-sec{{ openssl_section_num|length -}}
b01884
-{% endset -%}
b01884
-{% do openssl_section_num.append('') -%}
b01884
-{% set contents %}{{ caller() }}{% endset -%}
b01884
-{% if contents -%}
b01884
-{% set sectiondata = formatsection(name, contents) -%}
b01884
-{% do openssl_sections.append(sectiondata) -%}
b01884
-{% endif -%}
b01884
-{{ name -}}
b01884
-{% endmacro %}
b01884
-
b01884
-{% macro formatsection(name, contents) -%}
b01884
-[ {{ name }} ]
b01884
-{{ contents -}}
b01884
-{% endmacro %}
b01884
diff --git a/ipaclient/csrgen_ffi.py b/ipaclient/csrgen_ffi.py
b01884
deleted file mode 100644
b01884
index 10a20bd..0000000
b01884
--- a/ipaclient/csrgen_ffi.py
b01884
+++ /dev/null
b01884
@@ -1,331 +0,0 @@
b01884
-from cffi import FFI
b01884
-import ctypes.util
b01884
-
b01884
-from ipalib import errors
b01884
-
b01884
-_ffi = FFI()
b01884
-
b01884
-_ffi.cdef('''
b01884
-typedef ... CONF;
b01884
-typedef ... CONF_METHOD;
b01884
-typedef ... BIO;
b01884
-typedef ... ipa_STACK_OF_CONF_VALUE;
b01884
-
b01884
-/* openssl/conf.h */
b01884
-typedef struct {
b01884
-    char *section;
b01884
-    char *name;
b01884
-    char *value;
b01884
-} CONF_VALUE;
b01884
-
b01884
-CONF *NCONF_new(CONF_METHOD *meth);
b01884
-void NCONF_free(CONF *conf);
b01884
-int NCONF_load_bio(CONF *conf, BIO *bp, long *eline);
b01884
-ipa_STACK_OF_CONF_VALUE *NCONF_get_section(const CONF *conf,
b01884
-                                        const char *section);
b01884
-char *NCONF_get_string(const CONF *conf, const char *group, const char *name);
b01884
-
b01884
-/* openssl/safestack.h */
b01884
-// int sk_CONF_VALUE_num(ipa_STACK_OF_CONF_VALUE *);
b01884
-// CONF_VALUE *sk_CONF_VALUE_value(ipa_STACK_OF_CONF_VALUE *, int);
b01884
-
b01884
-/* openssl/stack.h */
b01884
-typedef ... _STACK;
b01884
-
b01884
-int OPENSSL_sk_num(const _STACK *);
b01884
-void *OPENSSL_sk_value(const _STACK *, int);
b01884
-
b01884
-int sk_num(const _STACK *);
b01884
-void *sk_value(const _STACK *, int);
b01884
-
b01884
-/* openssl/bio.h */
b01884
-BIO *BIO_new_mem_buf(const void *buf, int len);
b01884
-int BIO_free(BIO *a);
b01884
-
b01884
-/* openssl/asn1.h */
b01884
-typedef struct ASN1_ENCODING_st {
b01884
-    unsigned char *enc;         /* DER encoding */
b01884
-    long len;                   /* Length of encoding */
b01884
-    int modified;               /* set to 1 if 'enc' is invalid */
b01884
-} ASN1_ENCODING;
b01884
-
b01884
-/* openssl/evp.h */
b01884
-typedef ... EVP_PKEY;
b01884
-
b01884
-void EVP_PKEY_free(EVP_PKEY *pkey);
b01884
-
b01884
-/* openssl/x509.h */
b01884
-typedef ... ASN1_INTEGER;
b01884
-typedef ... ASN1_BIT_STRING;
b01884
-typedef ... ASN1_OBJECT;
b01884
-typedef ... X509;
b01884
-typedef ... X509_ALGOR;
b01884
-typedef ... X509_CRL;
b01884
-typedef ... X509_NAME;
b01884
-typedef ... X509_PUBKEY;
b01884
-typedef ... ipa_STACK_OF_X509_ATTRIBUTE;
b01884
-
b01884
-typedef struct X509_req_info_st {
b01884
-    ASN1_ENCODING enc;
b01884
-    ASN1_INTEGER *version;
b01884
-    X509_NAME *subject;
b01884
-    X509_PUBKEY *pubkey;
b01884
-    /*  d=2 hl=2 l=  0 cons: cont: 00 */
b01884
-    ipa_STACK_OF_X509_ATTRIBUTE *attributes; /* [ 0 ] */
b01884
-} X509_REQ_INFO;
b01884
-
b01884
-typedef struct X509_req_st {
b01884
-    X509_REQ_INFO *req_info;
b01884
-    X509_ALGOR *sig_alg;
b01884
-    ASN1_BIT_STRING *signature;
b01884
-    int references;
b01884
-} X509_REQ;
b01884
-
b01884
-X509_REQ *X509_REQ_new(void);
b01884
-void X509_REQ_free(X509_REQ *);
b01884
-EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a);
b01884
-int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey);
b01884
-int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type,
b01884
-                               const unsigned char *bytes, int len, int loc,
b01884
-                               int set);
b01884
-int X509_NAME_entry_count(X509_NAME *name);
b01884
-int i2d_X509_REQ_INFO(X509_REQ_INFO *a, unsigned char **out);
b01884
-
b01884
-/* openssl/objects.h */
b01884
-ASN1_OBJECT *OBJ_txt2obj(const char *s, int no_name);
b01884
-
b01884
-/* openssl/x509v3.h */
b01884
-typedef ... X509V3_CONF_METHOD;
b01884
-
b01884
-typedef struct v3_ext_ctx {
b01884
-    int flags;
b01884
-    X509 *issuer_cert;
b01884
-    X509 *subject_cert;
b01884
-    X509_REQ *subject_req;
b01884
-    X509_CRL *crl;
b01884
-    X509V3_CONF_METHOD *db_meth;
b01884
-    void *db;
b01884
-} X509V3_CTX;
b01884
-
b01884
-void X509V3_set_ctx(X509V3_CTX *ctx, X509 *issuer, X509 *subject,
b01884
-                    X509_REQ *req, X509_CRL *crl, int flags);
b01884
-void X509V3_set_nconf(X509V3_CTX *ctx, CONF *conf);
b01884
-int X509V3_EXT_REQ_add_nconf(CONF *conf, X509V3_CTX *ctx, char *section,
b01884
-                             X509_REQ *req);
b01884
-
b01884
-/* openssl/x509v3.h */
b01884
-unsigned long ERR_get_error(void);
b01884
-char *ERR_error_string(unsigned long e, char *buf);
b01884
-''')  # noqa: E501
b01884
-
b01884
-_libcrypto = _ffi.dlopen(ctypes.util.find_library('crypto'))
b01884
-
b01884
-NULL = _ffi.NULL
b01884
-
b01884
-# openssl/conf.h
b01884
-NCONF_new = _libcrypto.NCONF_new
b01884
-NCONF_free = _libcrypto.NCONF_free
b01884
-NCONF_load_bio = _libcrypto.NCONF_load_bio
b01884
-NCONF_get_section = _libcrypto.NCONF_get_section
b01884
-NCONF_get_string = _libcrypto.NCONF_get_string
b01884
-
b01884
-# openssl/stack.h
b01884
-try:
b01884
-    sk_num = _libcrypto.OPENSSL_sk_num
b01884
-    sk_value = _libcrypto.OPENSSL_sk_value
b01884
-except AttributeError:
b01884
-    sk_num = _libcrypto.sk_num
b01884
-    sk_value = _libcrypto.sk_value
b01884
-
b01884
-
b01884
-def sk_CONF_VALUE_num(sk):
b01884
-    return sk_num(_ffi.cast("_STACK *", sk))
b01884
-
b01884
-
b01884
-def sk_CONF_VALUE_value(sk, i):
b01884
-    return _ffi.cast("CONF_VALUE *", sk_value(_ffi.cast("_STACK *", sk), i))
b01884
-
b01884
-
b01884
-# openssl/bio.h
b01884
-BIO_new_mem_buf = _libcrypto.BIO_new_mem_buf
b01884
-BIO_free = _libcrypto.BIO_free
b01884
-
b01884
-# openssl/x509.h
b01884
-X509_REQ_new = _libcrypto.X509_REQ_new
b01884
-X509_REQ_free = _libcrypto.X509_REQ_free
b01884
-X509_REQ_set_pubkey = _libcrypto.X509_REQ_set_pubkey
b01884
-d2i_PUBKEY_bio = _libcrypto.d2i_PUBKEY_bio
b01884
-i2d_X509_REQ_INFO = _libcrypto.i2d_X509_REQ_INFO
b01884
-X509_NAME_add_entry_by_OBJ = _libcrypto.X509_NAME_add_entry_by_OBJ
b01884
-X509_NAME_entry_count = _libcrypto.X509_NAME_entry_count
b01884
-
b01884
-
b01884
-def X509_REQ_get_subject_name(req):
b01884
-    return req.req_info.subject
b01884
-
b01884
-
b01884
-# openssl/objects.h
b01884
-OBJ_txt2obj = _libcrypto.OBJ_txt2obj
b01884
-
b01884
-# openssl/evp.h
b01884
-EVP_PKEY_free = _libcrypto.EVP_PKEY_free
b01884
-
b01884
-# openssl/asn1.h
b01884
-MBSTRING_UTF8 = 0x1000
b01884
-
b01884
-# openssl/x509v3.h
b01884
-X509V3_set_ctx = _libcrypto.X509V3_set_ctx
b01884
-X509V3_set_nconf = _libcrypto.X509V3_set_nconf
b01884
-X509V3_EXT_REQ_add_nconf = _libcrypto.X509V3_EXT_REQ_add_nconf
b01884
-
b01884
-# openssl/err.h
b01884
-ERR_get_error = _libcrypto.ERR_get_error
b01884
-ERR_error_string = _libcrypto.ERR_error_string
b01884
-
b01884
-
b01884
-def _raise_openssl_errors():
b01884
-    msgs = []
b01884
-
b01884
-    code = ERR_get_error()
b01884
-    while code != 0:
b01884
-        msg = _ffi.string(ERR_error_string(code, NULL))
b01884
-        try:
b01884
-            strmsg = msg.decode('utf-8')
b01884
-        except UnicodeDecodeError:
b01884
-            strmsg = repr(msg)
b01884
-        msgs.append(strmsg)
b01884
-        code = ERR_get_error()
b01884
-
b01884
-    raise errors.CSRTemplateError(reason='\n'.join(msgs))
b01884
-
b01884
-
b01884
-def _parse_dn_section(subj, dn_sk):
b01884
-    for i in range(sk_CONF_VALUE_num(dn_sk)):
b01884
-        v = sk_CONF_VALUE_value(dn_sk, i)
b01884
-        rdn_type = _ffi.string(v.name)
b01884
-
b01884
-        # Skip past any leading X. X: X, etc to allow for multiple instances
b01884
-        for idx, c in enumerate(rdn_type):
b01884
-            if c in b':,.':
b01884
-                if idx+1 < len(rdn_type):
b01884
-                    rdn_type = rdn_type[idx+1:]
b01884
-                break
b01884
-        if rdn_type.startswith(b'+'):
b01884
-            rdn_type = rdn_type[1:]
b01884
-            mval = -1
b01884
-        else:
b01884
-            mval = 0
b01884
-
b01884
-        # convert rdn_type to an OID
b01884
-        #
b01884
-        # OpenSSL is fussy about the case of the string.  For example,
b01884
-        # lower-case 'o' (for "organization name") is not recognised.
b01884
-        # Therefore, try to convert the given string into an OID.  If
b01884
-        # that fails, convert it upper case and try again.
b01884
-        #
b01884
-        oid = OBJ_txt2obj(rdn_type, 0)
b01884
-        if oid == NULL:
b01884
-            oid = OBJ_txt2obj(rdn_type.upper(), 0)
b01884
-        if oid == NULL:
b01884
-            raise errors.CSRTemplateError(
b01884
-                reason='unrecognised attribute type: {}'
b01884
-                .format(rdn_type.decode('utf-8')))
b01884
-
b01884
-        if not X509_NAME_add_entry_by_OBJ(
b01884
-                subj, oid, MBSTRING_UTF8,
b01884
-                _ffi.cast("unsigned char *", v.value), -1, -1, mval):
b01884
-            _raise_openssl_errors()
b01884
-
b01884
-    if not X509_NAME_entry_count(subj):
b01884
-        raise errors.CSRTemplateError(
b01884
-            reason='error, subject in config file is empty')
b01884
-
b01884
-
b01884
-def build_requestinfo(config, public_key_info):
b01884
-    '''
b01884
-    Return a cffi buffer containing a DER-encoded CertificationRequestInfo.
b01884
-
b01884
-    The returned object implements the buffer protocol.
b01884
-
b01884
-    '''
b01884
-    reqdata = NULL
b01884
-    req = NULL
b01884
-    nconf_bio = NULL
b01884
-    pubkey_bio = NULL
b01884
-    pubkey = NULL
b01884
-
b01884
-    try:
b01884
-        reqdata = NCONF_new(NULL)
b01884
-        if reqdata == NULL:
b01884
-            _raise_openssl_errors()
b01884
-
b01884
-        nconf_bio = BIO_new_mem_buf(config, len(config))
b01884
-        errorline = _ffi.new('long[1]', [-1])
b01884
-        i = NCONF_load_bio(reqdata, nconf_bio, errorline)
b01884
-        if i < 0:
b01884
-            if errorline[0] < 0:
b01884
-                raise errors.CSRTemplateError(reason="Can't load config file")
b01884
-            else:
b01884
-                raise errors.CSRTemplateError(
b01884
-                    reason='Error on line %d of config file' % errorline[0])
b01884
-
b01884
-        dn_sect = NCONF_get_string(reqdata, b'req', b'distinguished_name')
b01884
-        if dn_sect == NULL:
b01884
-            raise errors.CSRTemplateError(
b01884
-                reason='Unable to find "distinguished_name" key in config')
b01884
-
b01884
-        dn_sk = NCONF_get_section(reqdata, dn_sect)
b01884
-        if dn_sk == NULL:
b01884
-            raise errors.CSRTemplateError(
b01884
-                reason='Unable to find "%s" section in config' %
b01884
-                _ffi.string(dn_sect))
b01884
-
b01884
-        pubkey_bio = BIO_new_mem_buf(public_key_info, len(public_key_info))
b01884
-        pubkey = d2i_PUBKEY_bio(pubkey_bio, NULL)
b01884
-        if pubkey == NULL:
b01884
-            _raise_openssl_errors()
b01884
-
b01884
-        req = X509_REQ_new()
b01884
-        if req == NULL:
b01884
-            _raise_openssl_errors()
b01884
-
b01884
-        subject = X509_REQ_get_subject_name(req)
b01884
-
b01884
-        _parse_dn_section(subject, dn_sk)
b01884
-
b01884
-        if not X509_REQ_set_pubkey(req, pubkey):
b01884
-            _raise_openssl_errors()
b01884
-
b01884
-        ext_ctx = _ffi.new("X509V3_CTX[1]")
b01884
-        X509V3_set_ctx(ext_ctx, NULL, NULL, req, NULL, 0)
b01884
-        X509V3_set_nconf(ext_ctx, reqdata)
b01884
-
b01884
-        extn_section = NCONF_get_string(reqdata, b"req", b"req_extensions")
b01884
-        if extn_section != NULL:
b01884
-            if not X509V3_EXT_REQ_add_nconf(
b01884
-                    reqdata, ext_ctx, extn_section, req):
b01884
-                _raise_openssl_errors()
b01884
-
b01884
-        der_len = i2d_X509_REQ_INFO(req.req_info, NULL)
b01884
-        if der_len < 0:
b01884
-            _raise_openssl_errors()
b01884
-
b01884
-        der_buf = _ffi.new("unsigned char[%d]" % der_len)
b01884
-        der_out = _ffi.new("unsigned char **", der_buf)
b01884
-        der_len = i2d_X509_REQ_INFO(req.req_info, der_out)
b01884
-        if der_len < 0:
b01884
-            _raise_openssl_errors()
b01884
-
b01884
-        return _ffi.buffer(der_buf, der_len)
b01884
-
b01884
-    finally:
b01884
-        if reqdata != NULL:
b01884
-            NCONF_free(reqdata)
b01884
-        if req != NULL:
b01884
-            X509_REQ_free(req)
b01884
-        if nconf_bio != NULL:
b01884
-            BIO_free(nconf_bio)
b01884
-        if pubkey_bio != NULL:
b01884
-            BIO_free(pubkey_bio)
b01884
-        if pubkey != NULL:
b01884
-            EVP_PKEY_free(pubkey)
b01884
diff --git a/ipaclient/plugins/cert.py b/ipaclient/plugins/cert.py
b01884
index 6d453d0..8a4db81 100644
b01884
--- a/ipaclient/plugins/cert.py
b01884
+++ b/ipaclient/plugins/cert.py
b01884
@@ -21,8 +21,6 @@
b01884
 
b01884
 import base64
b01884
 
b01884
-import six
b01884
-
b01884
 from ipaclient.frontend import MethodOverride
b01884
 from ipalib import errors
b01884
 from ipalib import x509
b01884
@@ -31,9 +29,6 @@ from ipalib.parameters import BinaryFile, File, Flag, Str
b01884
 from ipalib.plugable import Registry
b01884
 from ipalib.text import _
b01884
 
b01884
-if six.PY3:
b01884
-    unicode = str
b01884
-
b01884
 register = Registry()
b01884
 
b01884
 
b01884
@@ -74,87 +69,12 @@ class CertRetrieveOverride(MethodOverride):
b01884
 
b01884
 @register(override=True, no_fail=True)
b01884
 class cert_request(CertRetrieveOverride):
b01884
-    takes_options = CertRetrieveOverride.takes_options + (
b01884
-        Str(
b01884
-            'database?',
b01884
-            label=_('Path to NSS database'),
b01884
-            doc=_('Path to NSS database to use for private key'),
b01884
-        ),
b01884
-        Str(
b01884
-            'private_key?',
b01884
-            label=_('Path to private key file'),
b01884
-            doc=_('Path to PEM file containing a private key'),
b01884
-        ),
b01884
-        Str(
b01884
-            'password_file?',
b01884
-            label=_(
b01884
-                'File containing a password for the private key or database'),
b01884
-        ),
b01884
-        Str(
b01884
-            'csr_profile_id?',
b01884
-            label=_('Name of CSR generation profile (if not the same as'
b01884
-                    ' profile_id)'),
b01884
-        ),
b01884
-    )
b01884
-
b01884
     def get_args(self):
b01884
         for arg in super(cert_request, self).get_args():
b01884
             if arg.name == 'csr':
b01884
                 arg = arg.clone_retype(arg.name, File, required=False)
b01884
             yield arg
b01884
 
b01884
-    def forward(self, csr=None, **options):
b01884
-        database = options.pop('database', None)
b01884
-        private_key = options.pop('private_key', None)
b01884
-        csr_profile_id = options.pop('csr_profile_id', None)
b01884
-        password_file = options.pop('password_file', None)
b01884
-
b01884
-        if csr is None:
b01884
-            # Deferred import, ipaclient.csrgen is expensive to load.
b01884
-            # see https://pagure.io/freeipa/issue/7484
b01884
-            from ipaclient import csrgen
b01884
-
b01884
-            if database:
b01884
-                adaptor = csrgen.NSSAdaptor(database, password_file)
b01884
-            elif private_key:
b01884
-                adaptor = csrgen.OpenSSLAdaptor(
b01884
-                    key_filename=private_key, password_filename=password_file)
b01884
-            else:
b01884
-                raise errors.InvocationError(
b01884
-                    message=u"One of 'database' or 'private_key' is required")
b01884
-
b01884
-            pubkey_info = adaptor.get_subject_public_key_info()
b01884
-            pubkey_info_b64 = base64.b64encode(pubkey_info)
b01884
-
b01884
-            # If csr_profile_id is passed, that takes precedence.
b01884
-            # Otherwise, use profile_id. If neither are passed, the default
b01884
-            # in cert_get_requestdata will be used.
b01884
-            profile_id = csr_profile_id
b01884
-            if profile_id is None:
b01884
-                profile_id = options.get('profile_id')
b01884
-
b01884
-            response = self.api.Command.cert_get_requestdata(
b01884
-                profile_id=profile_id,
b01884
-                principal=options.get('principal'),
b01884
-                public_key_info=pubkey_info_b64)
b01884
-
b01884
-            req_info_b64 = response['result']['request_info']
b01884
-            req_info = base64.b64decode(req_info_b64)
b01884
-
b01884
-            csr = adaptor.sign_csr(req_info)
b01884
-
b01884
-            if not csr:
b01884
-                raise errors.CertificateOperationError(
b01884
-                    error=(_('Generated CSR was empty')))
b01884
-
b01884
-        else:
b01884
-            if database is not None or private_key is not None:
b01884
-                raise errors.MutuallyExclusiveError(reason=_(
b01884
-                    "Options 'database' and 'private_key' are not compatible"
b01884
-                    " with 'csr'"))
b01884
-
b01884
-        return super(cert_request, self).forward(csr, **options)
b01884
-
b01884
 
b01884
 @register(override=True, no_fail=True)
b01884
 class cert_show(CertRetrieveOverride):
b01884
diff --git a/ipaclient/plugins/csrgen.py b/ipaclient/plugins/csrgen.py
b01884
deleted file mode 100644
b01884
index 5aad636..0000000
b01884
--- a/ipaclient/plugins/csrgen.py
b01884
+++ /dev/null
b01884
@@ -1,128 +0,0 @@
b01884
-#
b01884
-# Copyright (C) 2016  FreeIPA Contributors see COPYING for license
b01884
-#
b01884
-
b01884
-import base64
b01884
-
b01884
-import six
b01884
-
b01884
-from ipalib import api
b01884
-from ipalib import errors
b01884
-from ipalib import output
b01884
-from ipalib import util
b01884
-from ipalib.frontend import Local, Str
b01884
-from ipalib.parameters import Bytes, Principal
b01884
-from ipalib.plugable import Registry
b01884
-from ipalib.text import _
b01884
-from ipapython import dogtag
b01884
-
b01884
-
b01884
-if six.PY3:
b01884
-    unicode = str
b01884
-
b01884
-register = Registry()
b01884
-
b01884
-__doc__ = _("""
b01884
-Commands to build certificate requests automatically
b01884
-""")
b01884
-
b01884
-
b01884
-@register()
b01884
-class cert_get_requestdata(Local):
b01884
-    __doc__ = _('Gather data for a certificate signing request.')
b01884
-
b01884
-    NO_CLI = True
b01884
-
b01884
-    takes_options = (
b01884
-        Principal(
b01884
-            'principal',
b01884
-            label=_('Principal'),
b01884
-            doc=_('Principal for this certificate (e.g.'
b01884
-                  ' HTTP/test.example.com)'),
b01884
-        ),
b01884
-        Str(
b01884
-            'profile_id?',
b01884
-            label=_('Profile ID'),
b01884
-            doc=_('CSR Generation Profile to use'),
b01884
-        ),
b01884
-        Bytes(
b01884
-            'public_key_info',
b01884
-            label=_('Subject Public Key Info'),
b01884
-            doc=_('DER-encoded SubjectPublicKeyInfo structure'),
b01884
-        ),
b01884
-        Str(
b01884
-            'out?',
b01884
-            doc=_('Write CertificationRequestInfo to file'),
b01884
-        ),
b01884
-    )
b01884
-
b01884
-    has_output = (
b01884
-        output.Output(
b01884
-            'result',
b01884
-            type=dict,
b01884
-            doc=_('Dictionary mapping variable name to value'),
b01884
-        ),
b01884
-    )
b01884
-
b01884
-    has_output_params = (
b01884
-        Str(
b01884
-            'request_info',
b01884
-            label=_('CertificationRequestInfo structure'),
b01884
-        )
b01884
-    )
b01884
-
b01884
-    def execute(self, *args, **options):
b01884
-        # Deferred import, ipaclient.csrgen is expensive to load.
b01884
-        # see https://pagure.io/freeipa/issue/7484
b01884
-        from ipaclient import csrgen
b01884
-        from ipaclient import csrgen_ffi
b01884
-
b01884
-        if 'out' in options:
b01884
-            util.check_writable_file(options['out'])
b01884
-
b01884
-        principal = options.get('principal')
b01884
-        profile_id = options.get('profile_id')
b01884
-        if profile_id is None:
b01884
-            profile_id = dogtag.DEFAULT_PROFILE
b01884
-        public_key_info = options.get('public_key_info')
b01884
-        public_key_info = base64.b64decode(public_key_info)
b01884
-
b01884
-        if self.api.env.in_server:
b01884
-            backend = self.api.Backend.ldap2
b01884
-        else:
b01884
-            backend = self.api.Backend.rpcclient
b01884
-        if not backend.isconnected():
b01884
-            backend.connect()
b01884
-
b01884
-        try:
b01884
-            if principal.is_host:
b01884
-                principal_obj = api.Command.host_show(
b01884
-                    principal.hostname, all=True)
b01884
-            elif principal.is_service:
b01884
-                principal_obj = api.Command.service_show(
b01884
-                    unicode(principal), all=True)
b01884
-            elif principal.is_user:
b01884
-                principal_obj = api.Command.user_show(
b01884
-                    principal.username, all=True)
b01884
-        except errors.NotFound:
b01884
-            raise errors.NotFound(
b01884
-                reason=_("The principal for this request doesn't exist."))
b01884
-        principal_obj = principal_obj['result']
b01884
-        config = api.Command.config_show()['result']
b01884
-
b01884
-        generator = csrgen.CSRGenerator(csrgen.FileRuleProvider())
b01884
-
b01884
-        csr_config = generator.csr_config(principal_obj, config, profile_id)
b01884
-        request_info = base64.b64encode(csrgen_ffi.build_requestinfo(
b01884
-            csr_config.encode('utf8'), public_key_info))
b01884
-
b01884
-        result = {}
b01884
-        if 'out' in options:
b01884
-            with open(options['out'], 'wb') as f:
b01884
-                f.write(request_info)
b01884
-        else:
b01884
-            result = dict(request_info=request_info)
b01884
-
b01884
-        return dict(
b01884
-            result=result
b01884
-        )
b01884
diff --git a/ipaclient/setup.py b/ipaclient/setup.py
b01884
index 8eb9aee..cd03685 100644
b01884
--- a/ipaclient/setup.py
b01884
+++ b/ipaclient/setup.py
b01884
@@ -41,13 +41,6 @@ if __name__ == '__main__':
b01884
             "ipaclient.remote_plugins.2_156",
b01884
             "ipaclient.remote_plugins.2_164",
b01884
         ],
b01884
-        package_data={
b01884
-            'ipaclient': [
b01884
-                'csrgen/profiles/*.json',
b01884
-                'csrgen/rules/*.json',
b01884
-                'csrgen/templates/*.tmpl',
b01884
-            ],
b01884
-        },
b01884
         install_requires=[
b01884
             "cryptography",
b01884
             "ipalib",
b01884
@@ -63,7 +56,6 @@ if __name__ == '__main__':
b01884
         extras_require={
b01884
             "install": ["ipaplatform"],
b01884
             "otptoken_yubikey": ["python-yubico", "pyusb"],
b01884
-            "csrgen": ["cffi", "jinja2"],
b01884
         },
b01884
         zip_safe=False,
b01884
     )
b01884
diff --git a/ipatests/test_ipaclient/data/test_csrgen/configs/caIPAserviceCert.conf b/ipatests/test_ipaclient/data/test_csrgen/configs/caIPAserviceCert.conf
b01884
deleted file mode 100644
b01884
index 3724bdc..0000000
b01884
--- a/ipatests/test_ipaclient/data/test_csrgen/configs/caIPAserviceCert.conf
b01884
+++ /dev/null
b01884
@@ -1,16 +0,0 @@
b01884
-[ req ]
b01884
-prompt = no
b01884
-encrypt_key = no
b01884
-
b01884
-distinguished_name = sec0
b01884
-req_extensions = sec2
b01884
-
b01884
-[ sec0 ]
b01884
-O=DOMAIN.EXAMPLE.COM
b01884
-CN=machine.example.com
b01884
-
b01884
-[ sec1 ]
b01884
-DNS = machine.example.com
b01884
-
b01884
-[ sec2 ]
b01884
-subjectAltName = @sec1
b01884
diff --git a/ipatests/test_ipaclient/data/test_csrgen/configs/userCert.conf b/ipatests/test_ipaclient/data/test_csrgen/configs/userCert.conf
b01884
deleted file mode 100644
b01884
index 00d63de..0000000
b01884
--- a/ipatests/test_ipaclient/data/test_csrgen/configs/userCert.conf
b01884
+++ /dev/null
b01884
@@ -1,16 +0,0 @@
b01884
-[ req ]
b01884
-prompt = no
b01884
-encrypt_key = no
b01884
-
b01884
-distinguished_name = sec0
b01884
-req_extensions = sec2
b01884
-
b01884
-[ sec0 ]
b01884
-O=DOMAIN.EXAMPLE.COM
b01884
-CN=testuser
b01884
-
b01884
-[ sec1 ]
b01884
-email = testuser@example.com
b01884
-
b01884
-[ sec2 ]
b01884
-subjectAltName = @sec1
b01884
diff --git a/ipatests/test_ipaclient/data/test_csrgen/profiles/profile.json b/ipatests/test_ipaclient/data/test_csrgen/profiles/profile.json
b01884
deleted file mode 100644
b01884
index 676f91b..0000000
b01884
--- a/ipatests/test_ipaclient/data/test_csrgen/profiles/profile.json
b01884
+++ /dev/null
b01884
@@ -1,8 +0,0 @@
b01884
-[
b01884
-    {
b01884
-        "syntax": "basic",
b01884
-        "data": [
b01884
-            "options"
b01884
-        ]
b01884
-    }
b01884
-]
b01884
diff --git a/ipatests/test_ipaclient/data/test_csrgen/rules/basic.json b/ipatests/test_ipaclient/data/test_csrgen/rules/basic.json
b01884
deleted file mode 100644
b01884
index 094ef71..0000000
b01884
--- a/ipatests/test_ipaclient/data/test_csrgen/rules/basic.json
b01884
+++ /dev/null
b01884
@@ -1,5 +0,0 @@
b01884
-{
b01884
-  "rule": {
b01884
-    "template": "openssl_rule"
b01884
-  }
b01884
-}
b01884
diff --git a/ipatests/test_ipaclient/data/test_csrgen/rules/options.json b/ipatests/test_ipaclient/data/test_csrgen/rules/options.json
b01884
deleted file mode 100644
b01884
index 393ed8c..0000000
b01884
--- a/ipatests/test_ipaclient/data/test_csrgen/rules/options.json
b01884
+++ /dev/null
b01884
@@ -1,8 +0,0 @@
b01884
-{
b01884
-  "rule": {
b01884
-    "template": "openssl_rule"
b01884
-  },
b01884
-  "options": {
b01884
-    "rule_option": true
b01884
-  }
b01884
-}
b01884
diff --git a/ipatests/test_ipaclient/data/test_csrgen/templates/identity_base.tmpl b/ipatests/test_ipaclient/data/test_csrgen/templates/identity_base.tmpl
b01884
deleted file mode 100644
b01884
index 79111ab..0000000
b01884
--- a/ipatests/test_ipaclient/data/test_csrgen/templates/identity_base.tmpl
b01884
+++ /dev/null
b01884
@@ -1 +0,0 @@
b01884
-{{ options|join(";") }}
b01884
diff --git a/ipatests/test_ipaclient/test_csrgen.py b/ipatests/test_ipaclient/test_csrgen.py
b01884
deleted file mode 100644
b01884
index b58596b..0000000
b01884
--- a/ipatests/test_ipaclient/test_csrgen.py
b01884
+++ /dev/null
b01884
@@ -1,304 +0,0 @@
b01884
-#
b01884
-# Copyright (C) 2016  FreeIPA Contributors see COPYING for license
b01884
-#
b01884
-
b01884
-import os
b01884
-import pytest
b01884
-
b01884
-from cryptography.hazmat.backends import default_backend
b01884
-from cryptography.hazmat.primitives.asymmetric import rsa
b01884
-from cryptography import x509
b01884
-
b01884
-from ipaclient import csrgen, csrgen_ffi
b01884
-from ipalib import errors
b01884
-
b01884
-BASE_DIR = os.path.dirname(__file__)
b01884
-CSR_DATA_DIR = os.path.join(BASE_DIR, 'data', 'test_csrgen')
b01884
-
b01884
-
b01884
-@pytest.fixture
b01884
-def formatter():
b01884
-    return csrgen.Formatter(csr_data_dir=CSR_DATA_DIR)
b01884
-
b01884
-
b01884
-@pytest.fixture
b01884
-def rule_provider():
b01884
-    return csrgen.FileRuleProvider(csr_data_dir=CSR_DATA_DIR)
b01884
-
b01884
-
b01884
-@pytest.fixture
b01884
-def generator():
b01884
-    return csrgen.CSRGenerator(csrgen.FileRuleProvider())
b01884
-
b01884
-
b01884
-class StubRuleProvider(csrgen.RuleProvider):
b01884
-    def __init__(self):
b01884
-        self.syntax_rule = csrgen.Rule(
b01884
-            'syntax', '{{datarules|join(",")}}', {})
b01884
-        self.data_rule = csrgen.Rule('data', 'data_template', {})
b01884
-        self.field_mapping = csrgen.FieldMapping(
b01884
-            'example', self.syntax_rule, [self.data_rule])
b01884
-        self.rules = [self.field_mapping]
b01884
-
b01884
-    def rules_for_profile(self, profile_id):
b01884
-        return self.rules
b01884
-
b01884
-
b01884
-class IdentityFormatter(csrgen.Formatter):
b01884
-    base_template_name = 'identity_base.tmpl'
b01884
-
b01884
-    def __init__(self):
b01884
-        super(IdentityFormatter, self).__init__(csr_data_dir=CSR_DATA_DIR)
b01884
-
b01884
-    def _get_template_params(self, syntax_rules):
b01884
-        return {'options': syntax_rules}
b01884
-
b01884
-
b01884
-class test_Formatter(object):
b01884
-    def test_prepare_data_rule_with_data_source(self, formatter):
b01884
-        data_rule = csrgen.Rule('uid', '{{subject.uid.0}}',
b01884
-                                {'data_source': 'subject.uid.0'})
b01884
-        prepared = formatter._prepare_data_rule(data_rule)
b01884
-        assert prepared == '{% if subject.uid.0 %}{{subject.uid.0}}{% endif %}'
b01884
-
b01884
-    def test_prepare_data_rule_no_data_source(self, formatter):
b01884
-        """Not a normal case, but we should handle it anyway"""
b01884
-        data_rule = csrgen.Rule('uid', 'static_text', {})
b01884
-        prepared = formatter._prepare_data_rule(data_rule)
b01884
-        assert prepared == 'static_text'
b01884
-
b01884
-    def test_prepare_syntax_rule_with_data_sources(self, formatter):
b01884
-        syntax_rule = csrgen.Rule(
b01884
-            'example', '{{datarules|join(",")}}', {})
b01884
-        data_rules = ['{{subject.field1}}', '{{subject.field2}}']
b01884
-        data_sources = ['subject.field1', 'subject.field2']
b01884
-        prepared = formatter._prepare_syntax_rule(
b01884
-            syntax_rule, data_rules, 'example', data_sources)
b01884
-
b01884
-        assert prepared == (
b01884
-            '{% if subject.field1 or subject.field2 %}{{subject.field1}},'
b01884
-            '{{subject.field2}}{% endif %}')
b01884
-
b01884
-    def test_prepare_syntax_rule_with_combinator(self, formatter):
b01884
-        syntax_rule = csrgen.Rule('example', '{{datarules|join(",")}}',
b01884
-                                  {'data_source_combinator': 'and'})
b01884
-        data_rules = ['{{subject.field1}}', '{{subject.field2}}']
b01884
-        data_sources = ['subject.field1', 'subject.field2']
b01884
-        prepared = formatter._prepare_syntax_rule(
b01884
-            syntax_rule, data_rules, 'example', data_sources)
b01884
-
b01884
-        assert prepared == (
b01884
-            '{% if subject.field1 and subject.field2 %}{{subject.field1}},'
b01884
-            '{{subject.field2}}{% endif %}')
b01884
-
b01884
-    def test_prepare_syntax_rule_required(self, formatter):
b01884
-        syntax_rule = csrgen.Rule('example', '{{datarules|join(",")}}',
b01884
-                                  {'required': True})
b01884
-        data_rules = ['{{subject.field1}}']
b01884
-        data_sources = ['subject.field1']
b01884
-        prepared = formatter._prepare_syntax_rule(
b01884
-            syntax_rule, data_rules, 'example', data_sources)
b01884
-
b01884
-        assert prepared == (
b01884
-            '{% filter required("example") %}{% if subject.field1 %}'
b01884
-            '{{subject.field1}}{% endif %}{% endfilter %}')
b01884
-
b01884
-    def test_prepare_syntax_rule_passthrough(self, formatter):
b01884
-        """
b01884
-        Calls to macros defined as passthrough are still call tags in the final
b01884
-        template.
b01884
-        """
b01884
-        formatter._define_passthrough('example.macro')
b01884
-
b01884
-        syntax_rule = csrgen.Rule(
b01884
-            'example',
b01884
-            '{% call example.macro() %}{{datarules|join(",")}}{% endcall %}',
b01884
-            {})
b01884
-        data_rules = ['{{subject.field1}}']
b01884
-        data_sources = ['subject.field1']
b01884
-        prepared = formatter._prepare_syntax_rule(
b01884
-            syntax_rule, data_rules, 'example', data_sources)
b01884
-
b01884
-        assert prepared == (
b01884
-            '{% if subject.field1 %}{% call example.macro() %}'
b01884
-            '{{subject.field1}}{% endcall %}{% endif %}')
b01884
-
b01884
-    def test_prepare_syntax_rule_no_data_sources(self, formatter):
b01884
-        """Not a normal case, but we should handle it anyway"""
b01884
-        syntax_rule = csrgen.Rule(
b01884
-            'example', '{{datarules|join(",")}}', {})
b01884
-        data_rules = ['rule1', 'rule2']
b01884
-        data_sources = []
b01884
-        prepared = formatter._prepare_syntax_rule(
b01884
-            syntax_rule, data_rules, 'example', data_sources)
b01884
-
b01884
-        assert prepared == 'rule1,rule2'
b01884
-
b01884
-
b01884
-class test_FileRuleProvider(object):
b01884
-    def test_rule_basic(self, rule_provider):
b01884
-        rule_name = 'basic'
b01884
-
b01884
-        rule = rule_provider._rule(rule_name)
b01884
-
b01884
-        assert rule.template == 'openssl_rule'
b01884
-
b01884
-    def test_rule_global_options(self, rule_provider):
b01884
-        rule_name = 'options'
b01884
-
b01884
-        rule = rule_provider._rule(rule_name)
b01884
-
b01884
-        assert rule.options['rule_option'] is True
b01884
-
b01884
-    def test_rule_nosuchrule(self, rule_provider):
b01884
-        with pytest.raises(errors.NotFound):
b01884
-            rule_provider._rule('nosuchrule')
b01884
-
b01884
-    def test_rules_for_profile_success(self, rule_provider):
b01884
-        rules = rule_provider.rules_for_profile('profile')
b01884
-
b01884
-        assert len(rules) == 1
b01884
-        field_mapping = rules[0]
b01884
-        assert field_mapping.syntax_rule.name == 'basic'
b01884
-        assert len(field_mapping.data_rules) == 1
b01884
-        assert field_mapping.data_rules[0].name == 'options'
b01884
-
b01884
-    def test_rules_for_profile_nosuchprofile(self, rule_provider):
b01884
-        with pytest.raises(errors.NotFound):
b01884
-            rule_provider.rules_for_profile('nosuchprofile')
b01884
-
b01884
-
b01884
-class test_CSRGenerator(object):
b01884
-    def test_userCert_OpenSSL(self, generator):
b01884
-        principal = {
b01884
-            'uid': ['testuser'],
b01884
-            'mail': ['testuser@example.com'],
b01884
-        }
b01884
-        config = {
b01884
-            'ipacertificatesubjectbase': [
b01884
-                'O=DOMAIN.EXAMPLE.COM'
b01884
-            ],
b01884
-        }
b01884
-
b01884
-        script = generator.csr_config(principal, config, 'userCert')
b01884
-        with open(os.path.join(
b01884
-                CSR_DATA_DIR, 'configs', 'userCert.conf')) as f:
b01884
-            expected_script = f.read()
b01884
-        assert script == expected_script
b01884
-
b01884
-    def test_caIPAserviceCert_OpenSSL(self, generator):
b01884
-        principal = {
b01884
-            'krbprincipalname': [
b01884
-                'HTTP/machine.example.com@DOMAIN.EXAMPLE.COM'
b01884
-            ],
b01884
-        }
b01884
-        config = {
b01884
-            'ipacertificatesubjectbase': [
b01884
-                'O=DOMAIN.EXAMPLE.COM'
b01884
-            ],
b01884
-        }
b01884
-
b01884
-        script = generator.csr_config(
b01884
-            principal, config, 'caIPAserviceCert')
b01884
-        with open(os.path.join(
b01884
-                CSR_DATA_DIR, 'configs', 'caIPAserviceCert.conf')) as f:
b01884
-            expected_script = f.read()
b01884
-        assert script == expected_script
b01884
-
b01884
-    def test_works_with_lowercase_attr_type_shortname(self, generator):
b01884
-        principal = {
b01884
-            'uid': ['testuser'],
b01884
-            'mail': ['testuser@example.com'],
b01884
-        }
b01884
-        template_env = {
b01884
-            'ipacertificatesubjectbase': [
b01884
-                'o=DOMAIN.EXAMPLE.COM'  # lower-case attr type shortname
b01884
-            ],
b01884
-        }
b01884
-        config = generator.csr_config(principal, template_env, 'userCert')
b01884
-
b01884
-        key = rsa.generate_private_key(
b01884
-            public_exponent=65537,
b01884
-            key_size=2048,
b01884
-            backend=default_backend(),
b01884
-        )
b01884
-        adaptor = csrgen.OpenSSLAdaptor(key=key)
b01884
-
b01884
-        reqinfo = bytes(csrgen_ffi.build_requestinfo(
b01884
-            config.encode('utf-8'), adaptor.get_subject_public_key_info()))
b01884
-        csr_der = adaptor.sign_csr(reqinfo)
b01884
-        csr = x509.load_der_x509_csr(csr_der, default_backend())
b01884
-        assert (
b01884
-            csr.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)
b01884
-            == [x509.NameAttribute(x509.NameOID.COMMON_NAME, u'testuser')]
b01884
-        )
b01884
-        assert (
b01884
-            csr.subject.get_attributes_for_oid(x509.NameOID.ORGANIZATION_NAME)
b01884
-            == [x509.NameAttribute(
b01884
-                x509.NameOID.ORGANIZATION_NAME, u'DOMAIN.EXAMPLE.COM')]
b01884
-        )
b01884
-
b01884
-    def test_unrecognised_attr_type_raises(self, generator):
b01884
-        principal = {
b01884
-            'uid': ['testuser'],
b01884
-            'mail': ['testuser@example.com'],
b01884
-        }
b01884
-        template_env = {
b01884
-            'ipacertificatesubjectbase': [
b01884
-                'X=DOMAIN.EXAMPLE.COM'  # unrecognised attr type
b01884
-            ],
b01884
-        }
b01884
-        config = generator.csr_config(principal, template_env, 'userCert')
b01884
-
b01884
-        key = rsa.generate_private_key(
b01884
-            public_exponent=65537,
b01884
-            key_size=2048,
b01884
-            backend=default_backend(),
b01884
-        )
b01884
-        adaptor = csrgen.OpenSSLAdaptor(key=key)
b01884
-
b01884
-        with pytest.raises(
b01884
-                errors.CSRTemplateError,
b01884
-                message='unrecognised attribute type: X'):
b01884
-            csrgen_ffi.build_requestinfo(
b01884
-                config.encode('utf-8'), adaptor.get_subject_public_key_info())
b01884
-
b01884
-
b01884
-class test_rule_handling(object):
b01884
-    def test_optionalAttributeMissing(self, generator):
b01884
-        principal = {'uid': 'testuser'}
b01884
-        rule_provider = StubRuleProvider()
b01884
-        rule_provider.data_rule.template = '{{subject.mail}}'
b01884
-        rule_provider.data_rule.options = {'data_source': 'subject.mail'}
b01884
-        generator = csrgen.CSRGenerator(
b01884
-            rule_provider, formatter_class=IdentityFormatter)
b01884
-
b01884
-        script = generator.csr_config(
b01884
-            principal, {}, 'example')
b01884
-        assert script == '\n'
b01884
-
b01884
-    def test_twoDataRulesOneMissing(self, generator):
b01884
-        principal = {'uid': 'testuser'}
b01884
-        rule_provider = StubRuleProvider()
b01884
-        rule_provider.data_rule.template = '{{subject.mail}}'
b01884
-        rule_provider.data_rule.options = {'data_source': 'subject.mail'}
b01884
-        rule_provider.field_mapping.data_rules.append(csrgen.Rule(
b01884
-            'data2', '{{subject.uid}}', {'data_source': 'subject.uid'}))
b01884
-        generator = csrgen.CSRGenerator(
b01884
-            rule_provider, formatter_class=IdentityFormatter)
b01884
-
b01884
-        script = generator.csr_config(principal, {}, 'example')
b01884
-        assert script == ',testuser\n'
b01884
-
b01884
-    def test_requiredAttributeMissing(self):
b01884
-        principal = {'uid': 'testuser'}
b01884
-        rule_provider = StubRuleProvider()
b01884
-        rule_provider.data_rule.template = '{{subject.mail}}'
b01884
-        rule_provider.data_rule.options = {'data_source': 'subject.mail'}
b01884
-        rule_provider.syntax_rule.options = {'required': True}
b01884
-        generator = csrgen.CSRGenerator(
b01884
-            rule_provider, formatter_class=IdentityFormatter)
b01884
-
b01884
-        with pytest.raises(errors.CSRTemplateError):
b01884
-            _script = generator.csr_config(
b01884
-                principal, {}, 'example')
b01884
-- 
b01884
2.13.6
b01884