summaryrefslogtreecommitdiffstats
path: root/base/server/python/pki/server/cli/nuxwdog.py
blob: 8d93d82dca87bb05c9daf1d64265497b82f92d5b (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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
#!/usr/bin/python
# Authors:
#     Ade Lee <alee@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) 2015 Red Hat, Inc.
# All rights reserved.
#

from __future__ import absolute_import
import getopt
import fileinput
import os
import re
import struct
import subprocess
import sys

from lxml import etree

import pki.cli
import pki.server


class NuxwdogCLI(pki.cli.CLI):

    def __init__(self):
        super(NuxwdogCLI, self).__init__(
            'nuxwdog',
            'Nuxwdog related commands')
        self.add_module(NuxwdogEnableCLI())
        self.add_module(NuxwdogDisableCLI())


class NuxwdogEnableCLI(pki.cli.CLI):

    def __init__(self):
        self.parser = etree.XMLParser(remove_blank_text=True)
        self.nuxwdog_listener_class = (
            'com.netscape.cms.tomcat.PKIListener'
        )
        self.nuxwdog_pwstore_class = (
            'com.netscape.cms.tomcat.NuxwdogPasswordStore'
        )
        super(NuxwdogEnableCLI, self).__init__(
            'enable',
            'Enable nuxwdog')

    def print_help(self):
        print 'Usage: pki-server nuxwdog-enable [OPTIONS]'
        print
        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', [
                'verbose', 'help'])

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

        for o, _ in opts:
            if o in ('-v', '--verbose'):
                self.set_verbose(True)

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

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

        instances = pki.server.PKIServer.instances()

        for instance in instances:
            self.enable_nuxwdog(instance)

        self.print_message('Nuxwdog enabled for system.')

    def enable_nuxwdog(self, instance):
        # add nuxwdog link
        self.add_nuxwdog_link(instance)

        # modify sysconfig file
        self.enable_nuxwdog_sysconfig_file(instance)

        # create nuxwdog conf file
        subprocess.call(['pki-server-nuxwdog', instance.name])

        # modify server.xml
        server_xml = os.path.join(instance.conf_dir, 'server.xml')
        self.enable_nuxwdog_server_xml(server_xml, instance)

        # change systemd links
        self.change_systemd_links(instance)

        # modify CS.cfg
        self.modify_password_class_in_cs_cfg(instance)

    def add_nuxwdog_link(self, instance):
        nuxwdog_jar_path = '/usr/lib/java/nuxwdog.jar'
        if not os.path.exists(nuxwdog_jar_path):
            print (
                "Error: nuxwdog jar file does not exist.  "
                "Is nuxwdog installed?"
            )
            sys.exit(1)
        instance_jar_path = os.path.join(
            instance.base_dir,
            'common',
            'lib',
            'nuxwdog.jar')

        if os.path.exists(instance_jar_path):
            os.remove(instance_jar_path)

        os.symlink(nuxwdog_jar_path, instance_jar_path)

    def enable_nuxwdog_sysconfig_file(self, instance):
        sysconfig_file = os.path.join('/etc/sysconfig', instance.name)

        arch = struct.calcsize("P") * 8
        if arch == 64:
            jni_str = "-Djava.library.path=/usr/lib64/nuxwdog-jni"
        else:
            jni_str = "-Djava.library.path=/usr/lib/nuxwdog-jni"

        got_use_nuxwdog = False

        for line in fileinput.input(sysconfig_file, inplace=1):
            match = re.search("^JAVA_OPTS=\"(.*)\"", line)
            if match:
                opts = match.group(1)
                if jni_str not in opts:
                    line = "JAVA_OPTS=\"" + opts + " " + jni_str + "\"\n"

            match = re.search("^USE_NUXWDOG=.*", line)
            if match:
                line = "USE_NUXWDOG=\"true\"\n"
                got_use_nuxwdog = True

            sys.stdout.write(line)

        if not got_use_nuxwdog:
            with open(sysconfig_file, 'a') as f:
                f.write("USE_NUXWDOG=\"true\"\n")

        os.chown(sysconfig_file, instance.uid, instance.gid)

    def get_conf_file(self, instance):
        # return the path to the first instance
        subsystem = instance.subsystems[0]
        return os.path.join(subsystem.conf_dir, 'CS.cfg')

    def enable_nuxwdog_server_xml(self, filename, instance):
        if self.verbose:
            print 'Enabling nuxwdog in %s' % filename

        conf_file = self.get_conf_file(instance)

        document = etree.parse(filename, self.parser)

        server = document.getroot()

        global_naming_resources = None

        nuxwdog_listener = etree.Element('Listener')
        nuxwdog_listener.set('className', self.nuxwdog_listener_class)

        children = list(server)
        for child in children:

            if child.tag == 'Listener':
                class_name = child.get('className')
                if class_name == self.nuxwdog_listener_class:
                    nuxwdog_listener = None
            elif child.tag == 'GlobalNamingResources':
                global_naming_resources = child

        # add before GlobalResourcesLifecycleListener if exists
        if global_naming_resources is not None:
            index = list(server).index(global_naming_resources) - 1
        else:
            index = 0

        if nuxwdog_listener is not None:
            server.insert(index, nuxwdog_listener)

        connectors = server.findall('Service/Connector')
        for connector in connectors:
            if connector.get('secure') == 'true':
                connector.set('passwordClass', self.nuxwdog_pwstore_class)
                connector.set('passwordFile', conf_file)

        with open(filename, 'w') as f:
            f.write(etree.tostring(document, pretty_print=True))

        os.chown(filename, instance.uid, instance.gid)

    def change_systemd_links(self, instance):
        old_systemd_unit_file = 'pki-tomcatd@' + instance.name + '.service'
        old_systemd_link = os.path.join(
            '/etc/systemd/system/pki-tomcatd.target.wants',
            old_systemd_unit_file)

        new_systemd_unit_file = ('pki-tomcatd-nuxwdog@' + instance.name
                                 + '.service')
        new_systemd_link = os.path.join(
            '/etc/systemd/system/pki-tomcatd-nuxwdog.target.wants',
            new_systemd_unit_file)
        new_systemd_source = '/lib/systemd/system/pki-tomcatd-nuxwdog@.service'

        if os.path.exists(old_systemd_link):
            os.unlink(old_systemd_link)

        if os.path.exists(new_systemd_link):
            os.unlink(new_systemd_link)
        os.symlink(new_systemd_source, new_systemd_link)

        subprocess.check_call(['systemctl', 'daemon-reload'])

    def modify_password_class_in_cs_cfg(self, instance):
        pclass = "com.netscape.cmsutil.password.NuxwdogPasswordStore"

        for subsystem in instance.subsystems:
            cs_cfg = os.path.join(subsystem.conf_dir, 'CS.cfg')
            for line in fileinput.input(cs_cfg, inplace=1):
                match = re.search("^passwordClass=(.*)", line)
                if match:
                    line = "passwordClass=" + pclass + "\n"
                sys.stdout.write(line)
            os.chown(cs_cfg, instance.uid, instance.gid)


class NuxwdogDisableCLI(pki.cli.CLI):

    def __init__(self):
        self.parser = etree.XMLParser(remove_blank_text=True)
        self.nuxwdog_listener_class = (
            'com.netscape.cms.tomcat.PKIListener'
        )
        self.plain_pwstore_class = (
            'org.apache.tomcat.util.net.jss.PlainPasswordFile'
        )
        super(NuxwdogDisableCLI, self).__init__(
            'disable',
            'Disable nuxwdog')

    def print_help(self):
        print 'Usage: pki-server nuxwdog-disable [OPTIONS]'
        print
        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', [
                'verbose', 'help'])

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

        for o, _ in opts:
            if o in ('-v', '--verbose'):
                self.set_verbose(True)

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

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

        instances = pki.server.PKIServer.instances()

        for instance in instances:
            self.disable_nuxwdog(instance)

        self.print_message('Nuxwdog disabled for system.')

    def disable_nuxwdog(self, instance):
        self.disable_nuxwdog_sysconfig_file(instance)
        self.remove_nuxwdog_link(instance)

        nuxwdog_conf = os.path.join(instance.conf_dir, 'nuxwdog.conf')
        if os.path.exists(nuxwdog_conf):
            os.remove(nuxwdog_conf)

        server_xml = os.path.join(instance.conf_dir, 'server.xml')
        self.disable_nuxwdog_server_xml(server_xml, instance)

        self.change_systemd_links(instance)

        self.modify_password_class_in_cs_cfg(instance)

    def disable_nuxwdog_sysconfig_file(self, instance):
        sysconfig_file = os.path.join('/etc/sysconfig', instance.name)

        arch = struct.calcsize("P") * 8
        if arch == 64:
            jni_str = "-Djava.library.path=/usr/lib64/nuxwdog-jni"
        else:
            jni_str = "-Djava.library.path=/usr/lib/nuxwdog-jni"

        for line in fileinput.input(sysconfig_file, inplace=1):
            match = re.search("^JAVA_OPTS=\"(.*)\"", line)
            if match:
                opts = match.group(1)
                line = "JAVA_OPTS=\"" + opts.replace(jni_str, '') + "\"\n"

            match = re.search("^USE_NUXWDOG=.*", line)
            if match:
                line = "USE_NUXWDOG=\"false\"\n"

            sys.stdout.write(line)

        os.chown(sysconfig_file, instance.uid, instance.gid)

    def remove_nuxwdog_link(self, instance):
        instance_jar_path = os.path.join(
            instance.base_dir,
            'common',
            'lib',
            'nuxwdog.jar')

        if os.path.exists(instance_jar_path):
            os.remove(instance_jar_path)

    def disable_nuxwdog_server_xml(self, filename, instance):
        if self.verbose:
            print 'Disabling nuxwdog in %s' % filename

        pw_conf = os.path.join(instance.conf_dir, 'password.conf')

        document = etree.parse(filename, self.parser)

        server = document.getroot()

        connectors = server.findall('Service/Connector')
        for connector in connectors:
            if connector.get('secure') == 'true':
                connector.set('passwordClass', self.plain_pwstore_class)
                connector.set('passwordFile', pw_conf)

        with open(filename, 'w') as f:
            f.write(etree.tostring(document, pretty_print=True))

        os.chown(filename, instance.uid, instance.gid)

    def change_systemd_links(self, instance):
        old_systemd_unit_file = ('pki-tomcatd-nuxwdog@' + instance.name
                                 + '.service')
        old_systemd_link = os.path.join(
            '/etc/systemd/system/pki-tomcatd-nuxwdog.target.wants',
            old_systemd_unit_file)

        new_systemd_unit_file = 'pki-tomcatd@' + instance.name + '.service'
        new_systemd_link = os.path.join(
            '/etc/systemd/system/pki-tomcatd.target.wants',
            new_systemd_unit_file)
        new_systemd_source = '/lib/systemd/system/pki-tomcatd@.service'

        if os.path.exists(old_systemd_link):
            os.unlink(old_systemd_link)

        if os.path.exists(new_systemd_link):
            os.unlink(new_systemd_link)
        os.symlink(new_systemd_source, new_systemd_link)

        subprocess.check_call(['systemctl', 'daemon-reload'])

    def modify_password_class_in_cs_cfg(self, instance):
        pclass = "com.netscape.cmsutil.password.PlainPasswordFile"

        for subsystem in instance.subsystems:
            cs_cfg = os.path.join(subsystem.conf_dir, 'CS.cfg')
            for line in fileinput.input(cs_cfg, inplace=1):
                match = re.search("^passwordClass=(.*)", line)
                if match:
                    line = "passwordClass=" + pclass + "\n"
                sys.stdout.write(line)
                os.chown(cs_cfg, instance.uid, instance.gid)