summaryrefslogtreecommitdiffstats
path: root/install/tools/ipa-upgradeconfig
blob: 725a9d106833b8892fedf9897061e80ebf4500e6 (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
#!/usr/bin/python
#
# Authors:
#   Rob Crittenden <rcritten@redhat.com>
#
# Copyright (C) 2009  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/>.

"""
Upgrade configuration files to a newer template.
"""

import sys
try:
    from ipapython import ipautil, sysrestore
    from ipaserver.install import installutils
    from ipaserver.install import dsinstance
    from ipaserver.install import httpinstance
    from ipaserver.install import memcacheinstance
    from ipaserver.install import service
    import ldap
    import krbV
    import re
    import os
    import shutil
    import fileinput
    import ipalib.errors
except ImportError:
    print >> sys.stderr, """\
There was a problem importing one of the required Python modules. The
error was:

    %s
""" % sys.exc_value
    sys.exit(1)

class KpasswdInstance(service.SimpleServiceInstance):
    def __init__(self):
        service.SimpleServiceInstance.__init__(self, "ipa_kpasswd")

def uninstall_ipa_kpasswd():
    """
    We can't use the full service uninstaller because that will attempt
    to stop and disable the service which by now doesn't exist. We just
    want to clean up sysrestore.state to remove all references to
    ipa_kpasswd.
    """
    ipa_kpasswd = KpasswdInstance()

    running = ipa_kpasswd.restore_state("running")
    enabled = not ipa_kpasswd.restore_state("enabled")

    if enabled is not None and not enabled:
        ipa_kpasswd.remove()

def backup_file(filename, ext):
    """Make a backup of filename using ext as the extension. Do not overwrite
       previous backups."""
    if not os.path.isabs(filename):
        raise ValueError("Absolute path required")

    backupfile = filename + ".bak"
    (reldir, file) = os.path.split(filename)

    while os.path.exists(backupfile):
        backupfile = backupfile + "." + str(ext)

    try:
        shutil.copy2(filename, backupfile)
    except IOError, e:
        if e.errno == 2: # No such file or directory
            pass
        else:
            raise e

def update_conf(sub_dict, filename, template_filename):
    template = ipautil.template_file(template_filename, sub_dict)
    fd = open(filename, "w")
    fd.write(template)
    fd.close()

def find_hostname():
    """Find the hostname currently configured in ipa-rewrite.conf"""
    filename="/etc/httpd/conf.d/ipa-rewrite.conf"

    if not ipautil.file_exists(filename):
        return None

    pattern = "^[\s#]*.*https:\/\/([A-Za-z0-9\.\-]*)\/.*"
    p = re.compile(pattern)
    for line in fileinput.input(filename):
        if p.search(line):
            fileinput.close()
            return p.search(line).group(1)
    fileinput.close()

    raise RuntimeError("Unable to determine the fully qualified hostname from %s" % filename)

def find_version(filename):
    """Find the version of a configuration file"""
    if os.path.exists(filename):
        pattern = "^[\s#]*VERSION\s+([0-9]+)\s+.*"
        p = re.compile(pattern)
        for line in fileinput.input(filename):
            if p.search(line):
                fileinput.close()
                return p.search(line).group(1)
        fileinput.close()

        # no VERSION found
        return 0
    else:
        return -1

def upgrade(sub_dict, filename, template, add=False):
    """
    Get the version from the current and template files and update the
    installed configuration file if there is a new template.

    If add is True then create a new configuration file.
    """
    old = int(find_version(filename))
    new = int(find_version(template))

    if old < 0 and not add:
        print "%s not found." % filename
        sys.exit(1)

    if new < 0:
        print "%s not found." % template

    if old < new or (add and old == 0):
        backup_file(filename, new)
        update_conf(sub_dict, filename, template)
        print "Upgraded %s to version %d" % (filename, new)

def check_certs():
    """Check ca.crt is in the right place, and try to fix if not"""
    if not os.path.exists("/usr/share/ipa/html/ca.crt"):
        ca_file = "/etc/httpd/alias/cacert.asc"
        if os.path.exists(ca_file):
            old_umask = os.umask(022)   # make sure its readable by httpd
            try:
                shutil.copyfile(ca_file, "/usr/share/ipa/html/ca.crt")
            finally:
                os.umask(old_umask)
        else:
            print "Missing Certification Authority file."
            print "You should place a copy of the CA certificate in /usr/share/ipa/html/ca.crt"

def upgrade_pki():
    """
    Update/add the dogtag proxy configuration. The IPA side of this is
    handled in ipa-pki-proxy.conf.

    This requires enabling SSL renegotiation.
    """
    if not os.path.exists('/etc/pki-ca/CS.cfg'):
        return

    fstore = sysrestore.FileStore('/var/lib/ipa/sysrestore')
    http = httpinstance.HTTPInstance(fstore)
    http.enable_mod_nss_renegotiate()
    if not installutils.get_directive('/etc/pki-ca/CS.cfg',
                                      'proxy.securePort', '=') and \
            os.path.exists('/usr/bin/pki-setup-proxy'):
        ipautil.run(['/usr/bin/pki-setup-proxy', '-pki_instance_root=/var/lib'
                     ,'-pki_instance_name=pki-ca','-subsystem_type=ca'])

def update_dbmodules(realm, filename="/etc/krb5.conf"):
    newfile = []
    found_dbrealm = False
    found_realm = False
    prefix = ''

    st = os.stat(filename)
    fd = open(filename)

    lines = fd.readlines()
    fd.close()

    if '    db_library = ipadb.so\n' in lines:
        # Already updated
        return

    for line in lines:
        if line.startswith('[dbmodules]'):
            found_dbrealm = True
        if found_dbrealm and line.find(realm) > -1:
            found_realm = True
            prefix = '#'
        if found_dbrealm and line.find('}') > -1 and found_realm:
            found_realm = False
            newfile.append('#%s' % line)
            prefix = ''
            continue
      
        newfile.append('%s%s' % (prefix, line))

    # Append updated dbmodules information
    newfile.append('  %s = {\n' % realm)
    newfile.append('    db_library = ipadb.so\n')
    newfile.append('  }\n')

    # Write out new file
    fd = open(filename, 'w')
    fd.write("".join(newfile))
    fd.close()

def main():
    """
    Get some basics about the system. If getting those basics fail then
    this is likely because the machine isn't currently an IPA server so
    exit gracefully.
    """

    if not os.geteuid()==0:
        sys.exit("\nYou must be root to run this script.\n")

    try:
        krbctx = krbV.default_context()
    except krbV.Krb5Error, e:
        # Unable to get default kerberos realm
        sys.exit(0)

    fqdn = find_hostname()
    if fqdn is None:
        # ipa-rewrite.conf doesn't exist, nothing to do
        sys.exit(0)

    # Ok, we are an IPA server, do the additional tests

    check_certs()

    sub_dict = { "REALM" : krbctx.default_realm, "FQDN": fqdn }

    upgrade(sub_dict, "/etc/httpd/conf.d/ipa.conf", ipautil.SHARE_DIR + "ipa.conf")
    upgrade(sub_dict, "/etc/httpd/conf.d/ipa-rewrite.conf", ipautil.SHARE_DIR + "ipa-rewrite.conf")
    upgrade(sub_dict, "/etc/httpd/conf.d/ipa-pki-proxy.conf", ipautil.SHARE_DIR + "ipa-pki-proxy.conf", add=True)
    upgrade_pki()
    update_dbmodules(krbctx.default_realm)
    uninstall_ipa_kpasswd()

    http = httpinstance.HTTPInstance()
    http.remove_httpd_ccache()

    memcache = memcacheinstance.MemcacheInstance()
    memcache.ldapi = True
    memcache.realm = krbctx.default_realm
    try:
        if not memcache.is_configured():
            memcache.create_instance('MEMCACHE', fqdn, None, ipautil.realm_to_suffix(krbctx.default_realm))
    except (ldap.ALREADY_EXISTS, ipalib.errors.DuplicateEntry):
        pass

try:
    if __name__ == "__main__":
        sys.exit(main())
except SystemExit, e:
    sys.exit(e)
except KeyboardInterrupt, e:
    sys.exit(1)