summaryrefslogtreecommitdiffstats
path: root/install/tools/ipa-replica-install
blob: af7128cf4346e30be695fc8161a2c2b170a6b9de (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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
#! /usr/bin/python -E
# Authors: Karl MacMillan <kmacmillan@mentalrootkit.com>
#
# Copyright (C) 2007  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; version 2 only
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#

import sys
import socket

import tempfile, os, pwd, traceback, logging, shutil
from ConfigParser import SafeConfigParser
import ldap

from ipapython import ipautil

from ipaserver.install import dsinstance, replication, installutils, krbinstance, service
from ipaserver.install import bindinstance, httpinstance, ntpinstance, certs
from ipaserver import ipaldap
from ipapython import version
from ipalib import api, util

CACERT="/usr/share/ipa/html/ca.crt"

class HostnameLocalhost(Exception):
    pass

class ReplicaConfig:
    def __init__(self):
        self.realm_name = ""
        self.domain_name = ""
        self.master_host_name = ""
        self.dirman_password = ""
        self.ds_user = ""
        self.host_name = ""
        self.repl_password = ""
        self.dir = ""
        self.subject_base = "O=IPA"

def parse_options():
    from optparse import OptionParser
    parser = OptionParser(version=version.VERSION)
    parser.add_option("-N", "--no-ntp", dest="conf_ntp", action="store_false",
                      help="do not configure ntp", default=True)
    parser.add_option("-d", "--debug", dest="debug", action="store_true",
                      default=False, help="gather extra debugging information")
    parser.add_option("-p", "--password", dest="password", 
                      help="Directory Manager (existing master) password")
    parser.add_option("--setup-dns", dest="setup_dns", action="store_true",
                      default=False, help="configure bind with our zone")
    parser.add_option("--forwarder", dest="forwarders", action="append",
                      help="Add a DNS forwarder")
    parser.add_option("--no-forwarders", dest="no_forwarders", action="store_true",
                      default=False, help="Do not add any DNS forwarders, use root servers instead")

    options, args = parser.parse_args()

    if len(args) != 1:
        parser.error("you must provide a file generated by ipa-replica-prepare")

    if not options.setup_dns:
        if options.forwarders:
            parser.error("You cannot specify a --forwarder option without the --setup-dns option")
        if options.no_forwarders:
            parser.error("You cannot specify a --no-forwarders option without the --setup-dns option")
    elif options.forwarders and options.no_forwarders:
        parser.error("You cannot specify a --forwarder option together with --no-forwarders")
    elif not options.forwarders and not options.no_forwarders:
        parser.error("You must specify at least one --forwarder option or --no-forwarders option")

    return options, args[0]

def get_dirman_password():
    return installutils.read_password("Directory Manager (existing master)", confirm=False, validate=False)

def expand_info(filename, password):
    top_dir = tempfile.mkdtemp("ipa")
    tarfile = top_dir+"/files.tar"
    dir = top_dir + "/realm_info"
    ipautil.decrypt_file(filename, tarfile, password, top_dir)
    ipautil.run(["tar", "xf", tarfile, "-C", top_dir])
    os.remove(tarfile)

    return top_dir, dir

def read_info(dir, rconfig):
    filename = dir + "/realm_info"
    fd = open(filename)
    config = SafeConfigParser()
    config.readfp(fd)

    rconfig.realm_name = config.get("realm", "realm_name")
    rconfig.master_host_name = config.get("realm", "master_host_name")
    rconfig.ds_user = config.get("realm", "ds_user")
    rconfig.domain_name = config.get("realm", "domain_name")
    rconfig.host_name = config.get("realm", "destination_host")
    rconfig.subject_base = config.get("realm", "subject_base")

def get_host_name():
    hostname = installutils.get_fqdn()
    try:
        installutils.verify_fqdn(hostname)
    except RuntimeError, e:
        logging.error(str(e))
        sys.exit(1)

    return hostname

def resolve_host(host_name):
    ip = socket.gethostbyname(host_name)

    if ip == "127.0.0.1" or ip == "::1":
        raise HostnameLocalhost

    return ip

def set_owner(config, dir):
    pw = pwd.getpwnam(config.ds_user)
    os.chown(dir, pw.pw_uid, pw.pw_gid)

def install_ca(config):
    # FIXME, need to pass along the CA plugin to use
    cafile = config.dir + "/ca.p12"

    if not ipautil.file_exists(cafile):
        return None

    try:
        from ipaserver.install import cainstance
    except ImportError:
        print >> sys.stderr, "Import failed: %s" % sys.exc_value
        sys.exit(1)

    if not cainstance.check_inst():
        print "A CA was specified but the dogtag certificate server"
        print "is not installed on the system"
        print "Please install dogtag and restart the setup program"
        sys.exit(1)

    cs = cainstance.CADSInstance()
    cs.create_instance(config.ds_user, config.realm_name, config.host_name, config.domain_name, config.dirman_password)
    ca = cainstance.CAInstance()
    ca.configure_instance("pkiuser", config.host_name, config.dirman_password, config.dirman_password, pkcs12_info=(cafile,), master_host=config.master_host_name, subject_base=config.subject_base)

    return ca

def install_ds(config):
    dsinstance.check_existing_installation()
    dsinstance.check_ports()

    # if we have a pkcs12 file, create the cert db from
    # that. Otherwise the ds setup will create the CA
    # cert
    pkcs12_info = None
    if ipautil.file_exists(config.dir + "/dscert.p12"):
        pkcs12_info = (config.dir + "/dscert.p12",
                       config.dir + "/dirsrv_pin.txt")

    ds = dsinstance.DsInstance()
    ds.create_instance(config.ds_user, config.realm_name, config.host_name, config.domain_name, config.dirman_password, pkcs12_info)

    return ds

def install_krb(config):
    krb = krbinstance.KrbInstance()
    ldappwd_filename = config.dir + "/ldappwd"
    kpasswd_filename = config.dir + "/kpasswd.keytab"
    krb.create_replica(config.ds_user, config.realm_name, config.host_name,
                       config.domain_name, config.dirman_password,
                       ldappwd_filename, kpasswd_filename)

def install_ca_cert(config):
    if ipautil.file_exists(config.dir + "/ca.crt"):
        try:
            shutil.copy(config.dir + "/ca.crt", CACERT)
            os.chmod(CACERT, 0444)
        except Exception, e:
            print "error copying files: " + str(e)
            sys.exit(1)

def install_http(config):
    # if we have a pkcs12 file, create the cert db from
    # that. Otherwise the ds setup will create the CA
    # cert
    pkcs12_info = None
    if ipautil.file_exists(config.dir + "/httpcert.p12"):
        pkcs12_info = (config.dir + "/httpcert.p12",
                       config.dir + "/http_pin.txt")

    http = httpinstance.HTTPInstance()
    http.create_instance(config.realm_name, config.host_name, config.domain_name, config.dirman_password, False, pkcs12_info, self_signed_ca=True)

    # Now copy the autoconfiguration files
    if ipautil.file_exists(config.dir + "/preferences.html"):
        try:
            shutil.copy(config.dir + "/preferences.html", "/usr/share/ipa/html/preferences.html")
            shutil.copy(config.dir + "/configure.jar", "/usr/share/ipa/html/configure.jar")
        except Exception, e:
            print "error copying files: " + str(e)
            sys.exit(1)

def install_bind(config, options):
    if options.forwarders:
        forwarders = options.forwarders
    else:
        forwarders = ()
    bind = bindinstance.BindInstance(dm_password=config.dirman_password)
    ip_address = resolve_host(config.host_name)
    bind.setup(config.host_name, ip_address, config.realm_name,
               config.domain_name, forwarders, options.conf_ntp)
    bind.create_instance()

def check_dirsrv():
    serverids = dsinstance.check_existing_installation()
    if serverids:
        print ""
        print "An existing Directory Server has been detected."
        if not ipautil.user_input("Do you wish to remove it and create a new one?", False):
            print ""
            print "Only a single Directory Server instance is allowed on an IPA"
            print "server, the one used by IPA itself."
            sys.exit(1)

        try:
            service.stop("dirsrv")
        except:
            pass

        for serverid in serverids:
            dsinstance.erase_ds_instance_data(serverid)

    (ds_unsecure, ds_secure) = dsinstance.check_ports()
    if not ds_unsecure or not ds_secure:
        print "IPA requires ports 389 and 636 for the Directory Server."
        print "These are currently in use:"
        if not ds_unsecure:
            print "\t389"
        if not ds_secure:
            print "\t636"
        sys.exit(1)

def check_bind():
    if not bindinstance.check_inst(unattended=True):
        print "Aborting installation"
        sys.exit(1)

def main():
    options, filename = parse_options()
    installutils.standard_logging_setup("/var/log/ipareplica-install.log", options.debug)

    if not ipautil.file_exists(filename):
        sys.exit("Replica file %s does not exist" % filename)

    if options.setup_dns:
        check_bind()
    check_dirsrv()

    # get the directory manager password
    dirman_password = options.password
    if not dirman_password:
        try:
            dirman_password = get_dirman_password()
        except KeyboardInterrupt:
            sys.exit(0)

    try:
        top_dir, dir = expand_info(filename, dirman_password)
    except Exception, e:
        print "ERROR: Failed to decrypt or open the replica file."
        print "Verify you entered the correct Directory Manager password."
        sys.exit(1)

    config = ReplicaConfig()
    read_info(dir, config)
    config.dirman_password = dirman_password
    host = get_host_name()
    if config.host_name != host:
        try:
            print "This replica was created for '%s' but this machine is named '%s'" % (config.host_name, host)
            if not ipautil.user_input("This may cause problems. Continue?", True):
                sys.exit(0)
            config.host_name = host
            print ""
        except KeyboardInterrupt:
            sys.exit(0)
    config.repl_password = ipautil.ipa_generate_password()
    config.dir = dir

    # Try out the password
    try:
        conn = ipaldap.IPAdmin(config.master_host_name)
        conn.do_simple_bind(bindpw=config.dirman_password)
        conn.unbind()
    except ldap.CONNECT_ERROR, e:
        sys.exit("\nUnable to connect to LDAP server %s" % config.master_host_name)
    except ldap.SERVER_DOWN, e:
        sys.exit("\nUnable to connect to LDAP server %s" % config.master_host_name)
    except ldap.INVALID_CREDENTIALS, e :
        sys.exit("\nThe password provided is incorrect for LDAP server %s" % config.master_host_name)

    if ipautil.file_exists(config.dir + "/ca.p12"):
        ca_type = 'dogtag'
    else:
        ca_type = 'selfsign'

    api.bootstrap(in_server=True, ra_plugin=ca_type)
    api.finalize()

    # Install CA cert so that we can do SSL connections with ldap
    install_ca_cert(config)

    # Configure ntpd
    if options.conf_ntp:
        ntp = ntpinstance.NTPInstance()
        ntp.create_instance()

    # Configure the CA if necessary
    CA = install_ca(config)

    # Configure dirsrv
    ds = install_ds(config)

    try:
        repl = replication.ReplicationManager(config.host_name, config.dirman_password)
        ret = repl.setup_replication(config.master_host_name, config.realm_name)
    except Exception, e:
        logging.debug("Connection error: %s" % e)
        raise RuntimeError("Unable to connect to LDAP server %s." % config.host_name)
    if ret != 0:
        raise RuntimeError("Failed to start replication")

    install_krb(config)
    install_http(config)
    if CA:
        CA.import_ra_cert(dir + "/ra.p12")
        CA.fix_ra_perms()
        service.restart("httpd")
        service.print_msg("Setting the certificate subject base")
        CA.set_subject_in_config(util.realm_to_suffix(config.realm_name))

    # The DS instance is created before the keytab, add the SSL cert we
    # generated
    ds.add_cert_to_service()

    # Create the management framework config file
    fd = open("/etc/ipa/default.conf", "w")
    fd.write("[global]\n")
    fd.write("basedn=" + util.realm_to_suffix(config.realm_name) + "\n")
    fd.write("realm=" + config.realm_name + "\n")
    fd.write("domain=" + config.domain_name + "\n")
    fd.write("xmlrpc_uri=https://%s/ipa/xml\n" % config.host_name)
    fd.write("ldap_uri=ldapi://%%2fvar%%2frun%%2fslapd-%s.socket\n" % dsinstance.realm_to_serverid(config.realm_name))
    if ipautil.file_exists(config.dir + "/ca.p12"):
        fd.write("enable_ra=True\n")
        fd.write("ra_plugin=dogtag\n")
    fd.close()

    # Apply any LDAP updates. Needs to be done after the replica is synced-up
    service.print_msg("Applying LDAP updates")
    ds.apply_updates()

    service.restart("dirsrv")
    service.restart("krb5kdc")
    service.restart("httpd")

    if options.setup_dns:
        api.Backend.ldap2.connect(bind_dn="cn=Directory Manager",
                                  bind_pw=config.dirman_password)

        install_bind(config, options)

    # Call client install script
    try:
        ipautil.run(["/usr/sbin/ipa-client-install", "--on-master", "--unattended", "--domain", config.domain_name, "--server", config.host_name, "--realm", config.realm_name])
    except Exception, e:
        print "Configuration of client side components failed!"
        print "ipa-client-install returned: " + str(e)
        raise RuntimeError("Failed to configure the client")

    ds.init_memberof()

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

    main()
    sys.exit(0)
except SystemExit, e:
    sys.exit(e)
except socket.error, (errno, errstr):
    print errstr
except HostnameLocalhost:
    print "The hostname resolves to the localhost address (127.0.0.1/::1)"
    print "Please change your /etc/hosts file so that the hostname"
    print "resolves to the ip address of your network interface."
    print ""
    print "Please fix your /etc/hosts file and restart the setup program"
except Exception, e:
    print "creation of replica failed: %s" % str(e)
    message = str(e)
    for str in traceback.format_tb(sys.exc_info()[2]):
        message = message + "\n" + str
    logging.debug(message)
except KeyboardInterrupt:
    print "Installation cancelled." 

print ""
print "Your system may be partly configured." 
print "Run /usr/sbin/ipa-server-install --uninstall to clean up."

# the only way to get here is on error or ^C
sys.exit(1)