summaryrefslogtreecommitdiffstats
path: root/base/server/python/pki/server/cli/db.py
blob: 3df911cd91783ef8149b933406b113d87728995a (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
# Authors:
#     Fraser Tweedale <ftweedal@redhat.com>
#
# 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; version 2 of the License.
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright (C) 2016 Red Hat, Inc.
# All rights reserved.
#

from __future__ import absolute_import
from __future__ import print_function
import getopt
import ldap
import nss.nss as nss
import subprocess
import sys
import getpass

import pki.cli


class DBCLI(pki.cli.CLI):

    def __init__(self):
        super(DBCLI, self).__init__(
            'db', 'DB management commands')

        self.add_module(DBUpgrade())
        self.add_module(DBSchemaUpgrade())


class DBSchemaUpgrade(pki.cli.CLI):

    SCHEMA_PATH = '/usr/share/pki/server/conf/schema.ldif'

    def __init__(self):
        super(DBSchemaUpgrade, self).__init__(
            'schema-upgrade', 'Upgrade PKI database schema')

    def usage(self):
        print('Usage: pki-server db-schema-upgrade [OPTIONS]')
        print()
        print('  -i, --instance <instance ID>       Instance ID (default: pki-tomcat).')
        print('  -D, --bind-dn <Bind DN>            Connect DN (default: cn=Directory Manager).')
        print('  -w, --bind-password <password>     Password to connect to DB.')
        print('  -v, --verbose                      Run in verbose mode.')
        print('      --help                         Show help message.')
        print()

    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(
                argv, 'i:D:w:v', ['instance=', 'bind-dn=', 'bind-password=',
                                  'verbose', 'help'])

        except getopt.GetoptError as e:
            print('ERROR: ' + str(e))
            self.usage()
            sys.exit(1)

        instance_name = 'pki-tomcat'
        bind_dn = 'cn=Directory Manager'
        bind_password = None

        for o, a in opts:
            if o in ('-i', '--instance'):
                instance_name = a

            elif o in ('-D', '--bind-dn'):
                bind_dn = a

            elif o in ('-w', '--bind-password'):
                bind_password = a

            elif o in ('-v', '--verbose'):
                self.set_verbose(True)

            elif o == '--help':
                self.usage()
                sys.exit()

            else:
                print('ERROR: unknown option ' + o)
                self.usage()
                sys.exit(1)

        instance = pki.server.PKIInstance(instance_name)
        if not instance.is_valid():
            print("ERROR: Invalid instance %s." % instance_name)
            sys.exit(1)
        instance.load()

        if not instance.subsystems:
            print("ERROR: No subsystem in instance %s." % instance_name)
            sys.exit(1)

        if not bind_password:
            bind_password = getpass.getpass(prompt='Enter password: ')

        try:
            self.update_schema(instance.subsystems[0], bind_dn, bind_password)

        except subprocess.CalledProcessError as e:
            print("ERROR: " + e.output)
            sys.exit(e.returncode)

        self.print_message('Upgrade complete')

    def update_schema(self, subsystem, bind_dn, bind_password):
        # TODO(alee) re-implement this using open_database
        host = subsystem.config['internaldb.ldapconn.host']
        port = subsystem.config['internaldb.ldapconn.port']
        secure = subsystem.config['internaldb.ldapconn.secureConn']
        cmd = ['ldapmodify',
               '-c',
               '-D', bind_dn,
               '-w', bind_password,
               '-h', host,
               '-p', port,
               '-f', self.SCHEMA_PATH
               ]

        if secure.lower() == "true":
            cmd.append('-Z')

        subprocess.check_output(cmd, stderr=subprocess.STDOUT)


class DBUpgrade(pki.cli.CLI):
    def __init__(self):
        super(DBUpgrade, self).__init__(
            'upgrade', 'Upgrade PKI server database')

    def usage(self):
        print('Usage: pki-server db-upgrade [OPTIONS]')
        print()
        print('  -i, --instance <instance ID>       Instance ID (default: pki-tomcat).')
        print('  -v, --verbose                      Run in verbose mode.')
        print('      --help                         Show help message.')
        print()

    def execute(self, argv):
        try:
            opts, _ = getopt.gnu_getopt(
                argv, 'i:v', ['instance=', 'verbose', 'help'])

        except getopt.GetoptError as e:
            print('ERROR: ' + str(e))
            self.usage()
            sys.exit(1)

        instance_name = 'pki-tomcat'

        for o, a in opts:
            if o in ('-i', '--instance'):
                instance_name = a

            elif o in ('-v', '--verbose'):
                self.set_verbose(True)

            elif o == '--help':
                self.usage()
                sys.exit()

            else:
                print('ERROR: unknown option ' + o)
                self.usage()
                sys.exit(1)

        nss.nss_init_nodb()

        instance = pki.server.PKIInstance(instance_name)
        if not instance.is_valid():
            print("ERROR: Invalid instance %s." % instance_name)
            sys.exit(1)
        instance.load()

        subsystem = instance.get_subsystem('ca')
        if not subsystem:
            print('ERROR: No CA subsystem in instance %s.' + instance_name)
            sys.exit(1)

        base_dn = subsystem.config['internaldb.basedn']
        conn = subsystem.open_database()

        try:
            repo_dn = 'ou=certificateRepository,ou=ca,%s' % base_dn
            if self.verbose:
                print('Searching certificates records with missing issuerName in %s' % repo_dn)

            entries = conn.ldap.search_s(
                repo_dn,
                ldap.SCOPE_ONELEVEL,
                '(&(objectclass=certificaterecord)(|(!(issuername=*))(issuername=)))',
                None)

            for entry in entries:
                self.add_issuer_name(conn, entry)

        finally:
            conn.close()

        self.print_message('Upgrade complete')

    def add_issuer_name(self, conn, entry):
        dn, attrs = entry

        if self.verbose:
            print('Fixing certificate record %s' % dn)

        attr_cert = attrs.get('userCertificate;binary')
        if not attr_cert:
            return  # shouldn't happen, but nothing we can do if it does

        cert = nss.Certificate(bytearray(attr_cert[0]))
        issuer_name = str(cert.issuer)

        try:
            conn.ldap.modify_s(dn, [(ldap.MOD_REPLACE, 'issuerName', issuer_name)])
        except ldap.LDAPError as e:
            print(
                'Failed to add issuerName to certificate {}: {}'
                .format(attrs.get('cn', ['<unknown>'])[0], e))