summaryrefslogtreecommitdiffstats
path: root/ipaserver/install/dogtaginstance.py
blob: b482d8e08c1dadc14c8f265bc28f95d4325a11b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# Authors: Ade Lee <alee@redhat.com>
#
# Copyright (C) 2014  Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import base64
import os
import shutil
import tempfile
import traceback

from ipapython import certmonger
from ipapython import dogtag
from ipapython import ipautil
from ipapython import services as ipaservices
from ipapython.dn import DN
from ipaserver.install import service
from ipaserver.install import installutils
from ipaserver.install.installutils import stopped_service
from ipapython.ipa_log_manager import *

HTTPD_CONFD = "/etc/httpd/conf.d/"
DEFAULT_DSPORT = dogtag.install_constants.DS_PORT

PKI_USER = "pkiuser"
PKI_DS_USER = dogtag.install_constants.DS_USER


def check_inst(subsystem):
    """
    Validate that the appropriate dogtag/RHCS packages have been installed.
    """

    # Check for a couple of binaries we need
    if not os.path.exists(dogtag.install_constants.SPAWN_BINARY):
        return False
    if not os.path.exists(dogtag.install_constants.DESTROY_BINARY):
        return False

    # This is the template tomcat file for a DRM
    if not os.path.exists('/usr/share/pki/%s/conf/server.xml' % subsystem):
        return False

    return True

class DogtagInstance(service.Service):
    """
    This is the base class for a Dogtag 10+ instance, which uses a
    shared tomcat instance and DS to host the relevant subsystems.

    It contains functions that will be common to installations of the
    CA, KRA, and eventually TKS and TPS.
    """

    def __init__(self, realm, subsystem, service_desc, dogtag_constants=None):
        if dogtag_constants is None:
            dogtag_constants = dogtag.configured_constants()

        service.Service.__init__(self,
                '%sd' % dogtag_constants.PKI_INSTANCE_NAME,
                service_desc=service_desc
                )

        self.dogtag_constants = dogtag_constants
        self.realm = realm
        self.dm_password = None
        self.admin_password = None
        self.fqdn = None
        self.domain = None
        self.pkcs12_info = None
        self.clone = False

        self.basedn = DN(('o', 'ipa%s' % subsystem.lower()))
        self.agent_db = tempfile.mkdtemp(prefix = "tmp-")
        self.ds_port = DEFAULT_DSPORT
        self.server_root = dogtag_constants.SERVER_ROOT
        self.subsystem = subsystem
        self.security_domain_name = "IPA"
        self.tracking_nicknames = None

    def __del__(self):
        shutil.rmtree(self.agent_db, ignore_errors=True)

    def is_installed(self):
        """
        Determine if subsystem instance has been installed.

        Returns True/False
        """
        return os.path.exists(os.path.join(
            self.server_root, self.dogtag_constants.PKI_INSTANCE_NAME,
                self.subsystem.lower()))

    def spawn_instance(self, cfg_file):
        """
        Create and configure a new Dogtag instance using pkispawn.
        Passes in a configuration file with IPA-specific
        parameters.
        """
        subsystem = self.subsystem

        # Define the things we don't want logged
        nolog = (self.admin_password, self.dm_password,)

        args = ["/usr/sbin/pkispawn",
                "-s", subsystem,
                "-f", cfg_file ]

        with open(cfg_file) as f:
            root_logger.debug(
                'Contents of pkispawn configuration file (%s):\n%s' %
                    (cfg_file, ipautil.nolog_replace(f.read(), nolog)))

        try:
            ipautil.run(args, nolog=nolog)
        except ipautil.CalledProcessError, e:
            root_logger.critical("failed to configure %s instance %s" %
                                 (subsystem, e))
            raise RuntimeError('Configuration of %s failed' % subsystem)

    def enable(self):
        self.backup_state("enabled", self.is_enabled())

    def restart_instance(self):
        try:
            self.restart(self.dogtag_constants.PKI_INSTANCE_NAME)
        except Exception:
            root_logger.debug(traceback.format_exc())
            root_logger.critical(
                "Failed to restart the Dogtag instance."
                "See the installation log for details.")

    def start_instance(self):
        try:
            self.start(self.dogtag_constants.PKI_INSTANCE_NAME)
        except Exception:
            root_logger.debug(traceback.format_exc())
            root_logger.critical(
                "Failed to restart the Dogtag instance."
                "See the installation log for details.")

    def stop_instance(self):
        try:
            self.stop(self.dogtag_constants.PKI_INSTANCE_NAME)
        except Exception:
            root_logger.debug(traceback.format_exc())
            root_logger.critical(
                "Failed to restart the Dogtag instance."
                "See the installation log for details.")

    def enable_client_auth_to_db(self, config):
        """
        Enable client auth connection to the internal db.
        Path to CS.cfg config file passed in.
        """

        with stopped_service(self.dogtag_constants.SERVICE_NAME,
                        instance_name=self.dogtag_constants.PKI_INSTANCE_NAME):

            installutils.set_directive(config,
                'authz.instance.DirAclAuthz.ldap.ldapauth.authtype',
                'SslClientAuth', quotes=False, separator='=')
            installutils.set_directive(config,
                'authz.instance.DirAclAuthz.ldap.ldapauth.bindDN',
                'uid=pkidbuser,ou=people,o=ipaca', quotes=False, separator='=')
            installutils.set_directive(config,
                'authz.instance.DirAclAuthz.ldap.ldapauth.clientCertNickname',
                'subsystemCert cert-pki-ca', quotes=False, separator='=')
            installutils.set_directive(config,
                'authz.instance.DirAclAuthz.ldap.ldapconn.port',
                str(dogtag.install_constants.DS_SECURE_PORT),
                quotes=False, separator='=')
            installutils.set_directive(config,
                'authz.instance.DirAclAuthz.ldap.ldapconn.secureConn',
                'true', quotes=False, separator='=')

            installutils.set_directive(config, 'internaldb.ldapauth.authtype',
                'SslClientAuth', quotes=False, separator='=')
            installutils.set_directive(config, 'internaldb.ldapauth.bindDN',
                'uid=pkidbuser,ou=people,o=ipaca', quotes=False, separator='=')
            installutils.set_directive(config,
                'internaldb.ldapauth.clientCertNickname',
                'subsystemCert cert-pki-ca', quotes=False, separator='=')
            installutils.set_directive(config, 'internaldb.ldapconn.port',
                str(dogtag.install_constants.DS_SECURE_PORT),
                quotes=False, separator='=')
            installutils.set_directive(config,
                 'internaldb.ldapconn.secureConn', 'true', quotes=False,
                 separator='=')

    def uninstall(self):
        if self.is_installed():
            self.print_msg("Unconfiguring %s" % self.subsystem)

        try:
            ipautil.run(["/usr/sbin/pkidestroy", "-i",
                         self.dogtag_constants.PKI_INSTANCE_NAME,
                         "-s", self.subsystem])
        except ipautil.CalledProcessError, e:
            root_logger.critical("failed to uninstall %s instance %s"
                                 % (self.subsystem,e))

    def http_proxy(self):
        ''' Update the http proxy file  '''
        template_filename = ipautil.SHARE_DIR + "ipa-pki-proxy.conf"
        sub_dict = dict(
            DOGTAG_PORT=self.dogtag_constants.AJP_PORT,
            CLONE='' if self.clone else '#',
            FQDN=self.fqdn,
        )
        template = ipautil.template_file(template_filename, sub_dict)
        with open(HTTPD_CONFD + "ipa-pki-proxy.conf", "w") as fd:
            fd.write(template)

    def __get_pin(self):
        try:
            return certmonger.get_pin('internal',
                dogtag_constants=self.dogtag_constants)
        except IOError, e:
            root_logger.debug(
                'Unable to determine PIN for DRM instance: %s' % str(e))
            raise RuntimeError(e)

    def configure_renewal(self, nicknames=None):
        ''' Configure certmonger to renew system certs

        @param nickname: list of nicknames
        '''
        cmonger = ipaservices.knownservices.certmonger
        cmonger.enable()
        ipaservices.knownservices.messagebus.start()
        cmonger.start()

        pin = self.__get_pin()

        if nicknames is None:
            nicknames = self.tracking_nicknames

        for nickname in nicknames:
            try:
                certmonger.dogtag_start_tracking(
                    ca='dogtag-ipa-ca-renew-agent',
                    nickname=nickname,
                    pin=pin,
                    pinfile=None,
                    secdir=self.dogtag_constants.ALIAS_DIR,
                    pre_command='stop_pkicad',
                    post_command='renew_ca_cert "%s"' % nickname)
            except (ipautil.CalledProcessError, RuntimeError), e:
                root_logger.error(
                    "certmonger failed to start tracking certificate: %s" %
                        str(e))

    def stop_tracking_certificates(self, dogtag_constants, nicknames = None):
        """Stop tracking our certificates. Called on uninstall.
        """
        cmonger = ipaservices.knownservices.certmonger
        ipaservices.knownservices.messagebus.start()
        cmonger.start()

        if nicknames is None:
            nicknames = self.tracking_nicknames

        for nickname in nicknames:
            try:
                certmonger.stop_tracking(
                    dogtag_constants.ALIAS_DIR, nickname=nickname)
            except (ipautil.CalledProcessError, RuntimeError), e:
                root_logger.error(
                    "certmonger failed to stop tracking certificate: %s"
                    % str(e))

        cmonger.stop()

    def update_cert_config(self, nickname, cert, directives, cs_cfg,
                           dogtag_constants=None):
        """
        When renewing a DRM subsystem certificate the configuration file
        needs to get the new certificate as well.

        nickname is one of the known nicknames.
        cert is a DER-encoded certificate.
        directives is the list of directives to be updated for the subsystem
        cs_cfg is the path to the CS.cfg file
        """

        if dogtag_constants is None:
            dogtag_constants = dogtag.configured_constants()

        with stopped_service(dogtag_constants.SERVICE_NAME,
                         instance_name=dogtag_constants.PKI_INSTANCE_NAME):
            installutils.set_directive(
                cs_cfg,
                directives[nickname],
                base64.b64encode(cert),
                quotes=False,
                separator='=')