summaryrefslogtreecommitdiffstats
path: root/ipaserver/install/ipa_server_certinstall.py
blob: a9563e09522179a1a1c46078858324fd3fc4ab57 (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
#! /usr/bin/python
# Authors: Karl MacMillan <kmacmillan@mentalrootkit.com>
#          Jan Cholasta <jcholast@redhat.com>
#
# Copyright (C) 2007-2013  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 sys
import os
import os.path
import pwd
import optparse

from ipapython import admintool
from ipapython.dn import DN
from ipapython.ipautil import user_input, write_tmp_file
from ipalib import api, errors
from ipaserver.install import certs, dsinstance, httpinstance, installutils
from ipaserver.plugins.ldap2 import ldap2

CACERT = "/etc/ipa/ca.crt"

class ServerCertInstall(admintool.AdminTool):
    command_name = 'ipa-server-certinstall'

    usage = "%prog <-d|-w> [options] <PKCS#12 file>"

    description = "Install new SSL server certificates."

    @classmethod
    def add_options(cls, parser):
        super(ServerCertInstall, cls).add_options(parser)

        parser.add_option(
            "-d", "--dirsrv",
            dest="dirsrv", action="store_true", default=False,
            help="install certificate for the directory server")
        parser.add_option(
            "-w", "--http",
            dest="http", action="store_true", default=False,
            help="install certificate for the http server")
        parser.add_option(
            "--pin",
            dest="pin",
            help="The password of the PKCS#12 file")
        parser.add_option(
            "--dirsrv_pin", "--http_pin",
            dest="pin",
            help=optparse.SUPPRESS_HELP)
        parser.add_option(
            "-p", "--dirman-password",
            dest="dirman_password",
            help="Directory Manager password")

    def validate_options(self):
        super(ServerCertInstall, self).validate_options(needs_root=True)

        installutils.check_server_configuration()

        if not self.options.dirsrv and not self.options.http:
            self.option_parser.error("you must specify dirsrv and/or http")

        if len(self.args) != 1:
            self.option_parser.error("you must provide a pkcs12 filename")

    def ask_for_options(self):
        super(ServerCertInstall, self).ask_for_options()

        if self.options.dirsrv and not self.options.dirman_password:
            self.options.dirman_password = installutils.read_password(
                "Directory Manager", confirm=False, validate=False, retry=False)
            if self.options.dirman_password is None:
                raise admintool.ScriptError(
                    "Directory Manager password required")

        if not self.options.pin:
            self.options.pin = installutils.read_password(
                "Enter %s unlock" % self.args[0], confirm=False, validate=False)
            if self.options.pin is None:
                raise admintool.ScriptError(
                    "%s unlock password required" % self.args[0])

    def run(self):
        api.bootstrap(in_server=True)
        api.finalize()

        self.pkcs12_fname = self.args[0]

        if self.options.dirsrv:
            self.install_dirsrv_cert()

        if self.options.http:
            self.install_http_cert()

    def install_dirsrv_cert(self):
        serverid = dsinstance.realm_to_serverid(api.env.realm)
        dirname = dsinstance.config_dirname(serverid)

        conn = ldap2(shared_instance=False, base_dn='')
        conn.connect(bind_dn=DN(('cn', 'directory manager')),
                     bind_pw=self.options.dirman_password)

        entry = conn.get_entry(DN(('cn', 'RSA'), ('cn', 'encryption'),
                                  ('cn', 'config')),
                               ['nssslpersonalityssl'])
        old_cert = entry.single_value('nssslpersonalityssl')

        server_cert = self.import_cert(dirname, self.options.pin,
                                       old_cert, 'ldap/%s' % api.env.host,
                                       'restart_dirsrv %s' % serverid)

        entry['nssslpersonalityssl'] = [server_cert]
        try:
            conn.update_entry(entry)
        except errors.EmptyModlist:
            pass

        conn.disconnect()

    def install_http_cert(self):
        dirname = certs.NSS_DIR

        old_cert = installutils.get_directive(httpinstance.NSS_CONF,
                                              'NSSNickname')

        server_cert = self.import_cert(dirname, self.options.pin,
                                       old_cert, 'HTTP/%s' % api.env.host,
                                       'restart_httpd')

        installutils.set_directive(httpinstance.NSS_CONF,
                                   'NSSNickname', server_cert)

        # Fix the database permissions
        os.chmod(os.path.join(dirname, 'cert8.db'), 0640)
        os.chmod(os.path.join(dirname, 'key3.db'), 0640)
        os.chmod(os.path.join(dirname, 'secmod.db'), 0640)

        pent = pwd.getpwnam("apache")
        os.chown(os.path.join(dirname, 'cert8.db'), 0, pent.pw_gid)
        os.chown(os.path.join(dirname, 'key3.db'), 0, pent.pw_gid)
        os.chown(os.path.join(dirname, 'secmod.db'), 0, pent.pw_gid)

    def import_cert(self, dirname, pkcs12_passwd, old_cert, principal, command):
        pw = write_tmp_file(pkcs12_passwd)
        server_cert = installutils.check_pkcs12(
            pkcs12_info=(self.pkcs12_fname, pw.name),
            ca_file=CACERT,
            hostname=api.env.host)

        cdb = certs.CertDB(api.env.realm, nssdir=dirname)
        try:
            if api.env.enable_ra:
                cdb.untrack_server_cert(old_cert)

            cdb.delete_cert(old_cert)
            cdb.import_pkcs12(self.pkcs12_fname, pw.name)

            if api.env.enable_ra:
                cdb.track_server_cert(server_cert, principal, cdb.passwd_fname,
                                      command)
        except RuntimeError, e:
            raise admintool.ScriptError(str(e))

        return server_cert