summaryrefslogtreecommitdiffstats
path: root/install/tools/ipa-httpd-kdcproxy
blob: c71f9cccfe0c05e1484aac7cfcd6801050ed51ab (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
#!/usr/bin/python2
# Authors:
#   Christian Heimes <cheimes@redhat.com>
#
# Copyright (C) 2015  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/>.
#
"""ipa-httpd-kdproxy

This script creates or removes the symlink from /etc/ipa/ipa-kdc-proxy.conf
to /etc/httpd/conf.d/. It's called from ExecStartPre hook in httpd.service.
"""
import os
import sys

from ipalib import api, errors
from ipapython.ipa_log_manager import standard_logging_setup
from ipapython.ipaldap import IPAdmin
from ipapython.dn import DN
from ipaplatform.paths import paths


DEBUG = False
TIME_LIMIT = 2


class CheckError(Exception):
    """An unrecoverable error has occured"""


class KDCProxyConfig(object):
    ipaconfig_flag = 'ipaKDCProxyEnabled'

    def __init__(self, time_limit=TIME_LIMIT):
        self.time_limit = time_limit
        self.con = None
        self.log = api.log
        self.ldap_uri = api.env.ldap_uri
        self.kdc_dn = DN(('cn', 'KDC'), ('cn', api.env.host),
                         ('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'),
                         api.env.basedn)
        self.conf = paths.HTTPD_IPA_KDCPROXY_CONF
        self.conflink = paths.HTTPD_IPA_KDCPROXY_CONF_SYMLINK

    def _ldap_con(self):
        """Establish LDAP connection"""
        self.log.debug('ldap_uri: %s', self.ldap_uri)
        try:
            self.con = IPAdmin(ldap_uri=self.ldap_uri)
            # EXTERNAL bind as root user
            self.con.ldapi = True
            self.con.do_bind(timeout=self.time_limit)
        except errors.NetworkError as e:
            msg = 'Failed to get setting from dirsrv: %s' % e
            self.log.exception(msg)
            raise CheckError(msg)
        except Exception as e:
            msg = ('Unknown error while retrieving setting from %s: %s' %
                   (self.ldap_uri, e))
            self.log.exception(msg)
            raise CheckError(msg)

    def _find_entry(self, dn, attrs, filter, scope=IPAdmin.SCOPE_BASE):
        """Find an LDAP entry, handles NotFound and Limit"""
        try:
            entries, truncated = self.con.find_entries(
                filter, attrs, dn, scope, time_limit=self.time_limit)
            if truncated:
                raise errors.LimitsExceeded()
        except errors.NotFound:
            self.log.debug('Entry not found: %s', dn)
            return None
        except Exception as e:
            msg = ('Unknown error while retrieving setting from %s: %s' %
                   (self.ldap_uri, e))
            self.log.exception(msg)
            raise CheckError(msg)
        return entries[0]

    def is_host_enabled(self):
        """Check replica specific flag"""
        self.log.debug('Read settings from dn: %s', self.kdc_dn)
        srcfilter = self.con.make_filter(
            {'ipaConfigString': u'kdcProxyEnabled'}
        )
        entry = self._find_entry(self.kdc_dn, ['cn'], srcfilter)
        self.log.debug('%s ipaConfigString: %s', self.kdc_dn, entry)
        return entry is not None

    def validate_symlink(self):
        """Validate symlink in Apache conf.d"""
        if not os.path.exists(self.conflink):
            return False
        if not os.path.islink(self.conflink):
            raise CheckError("'%s' already exists, but it is not a symlink" %
                             self.conflink)
        dest = os.readlink(self.conflink)
        if dest != self.conf:
            raise CheckError("'%s' points to '%s', expected '%s'"
                             % (self.conflink, dest, self.conf))
        return True

    def create_symlink(self):
        """Create symlink to enable KDC proxy support"""
        try:
            valid = self.validate_symlink()
        except CheckError as e:
            self.log.warn("Cannot enable KDC proxy: %s " % e)
            return False

        if valid:
            self.log.debug("Symlink exists and is valid")
            return True

        if not os.path.isfile(self.conf):
            self.log.warn("'%s' does not exist", self.conf)
            return False

        # create the symbolic link
        self.log.debug("Creating symlink from '%s' to '%s'",
                       self.conf, self.conflink)
        os.symlink(self.conf, self.conflink)
        return True

    def remove_symlink(self):
        """Delete symlink to disable KDC proxy support"""
        try:
            valid = self.validate_symlink()
        except CheckError as e:
            self.log.warn("Cannot disable KDC proxy: %s " % e)
            return False

        if valid:
            self.log.debug("Removing symlink '%s'", self.conflink)
            os.unlink(self.conflink)
        else:
            self.log.debug("Symlink '%s' has already been removed.",
                           self.conflink)

        return True

    def __enter__(self):
        self._ldap_con()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        if self.con is not None:
            self.con.unbind()
            self.con = None


def main(debug=DEBUG, time_limit=TIME_LIMIT):
    # initialize API without file logging
    if not api.isdone('bootstrap'):
        api.bootstrap(context='kdcproxyshim', log=None, debug=debug)
        standard_logging_setup(verbose=True, debug=debug)

    with KDCProxyConfig(time_limit) as cfg:
        if cfg.is_host_enabled():
            if cfg.create_symlink():
                api.log.info('KDC proxy enabled')
        else:
            if cfg.remove_symlink():
                api.log.info('KDC proxy disabled')

if __name__ == '__main__':
    main()