summaryrefslogtreecommitdiffstats
path: root/pykolab/setup/setup_ldap.py
blob: d2bbbf288113e9504f1d547f75d1cfba7a1f244b (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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
# -*- coding: utf-8 -*-
# Copyright 2010-2013 Kolab Systems AG (http://www.kolabsys.com)
# Copyright 2013, 2014 Paul Boddie <paul@boddie.org.uk>
#
# Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.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, 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/>.
#

from glob import glob
from subprocess import Popen, PIPE
import ldap
import ldap.modlist
import os
import pwd
import shutil
import tempfile
import time

import components

import pykolab

from pykolab import utils
from pykolab.auth import Auth
from pykolab.constants import *
from pykolab.setup.services import *
from pykolab.translate import _

log = pykolab.getLogger('pykolab.setup')
conf = pykolab.getConf()

def __init__():
    components.register('ldap', execute, description=description())

def cli_options():
    ldap_group = conf.add_cli_parser_option_group(_("LDAP Options"))

    ldap_group.add_option(
            "--fqdn",
            dest    = "fqdn",
            action  = "store",
            default = fqdn,
            help    = _("Specify FQDN (overriding defaults).")
        )

    ldap_group.add_option(
            "--allow-anonymous",
            dest    = "anonymous",
            action  = "store_true",
            default = False,
            help    = _("Allow anonymous binds (default: no).")
        )

    ldap_group.add_option(
            "--choose-ldap-server",
            dest    = "choose_ldap_server",
            action  = "store_true",
            default = False,
            help    = _("Provide a choice of LDAP server.")
        )

    ldap_group.add_option(
            "--without-ldap",
            dest    = "without_ldap",
            action  = "store_true",
            default = False,
            help    = _("Skip setting up the LDAP server.")
        )

    ldap_group.add_option(
            "--reset-ldap-config",
            dest    = "reset_ldap_config",
            action  = "store_true",
            default = False,
            help    = _("Skip setting up the LDAP server, but reset Kolab's configuration for LDAP.")
        )

    ldap_group.add_option(
            "--with-openldap",
            dest    = "with_openldap",
            action  = "store_true",
            default = False,
            help    = _("Setup configuration for OpenLDAP compatibility.")
        )

    ldap_group.add_option(
            "--with-ad",
            dest    = "with_ad",
            action  = "store_true",
            default = False,
            help    = _("Setup configuration for Active Directory compatibility.")
        )

def description():
    return _("Setup LDAP.")

def execute(*args, **kw):

    # Signal that interaction may occur. This will involve debconf and similar
    # system-specific mechanisms if available.

    start_interaction("kolab-conf/title-ldap")
    try:
        _execute(*args, **kw)
    finally:
        stop_interaction()

def _execute(*args, **kw):

    # Interactive mode is enabled when dealing with an unconfigured system.
    # Reconfiguring a configured system should not cause repetition of the
    # questions.

    unconfigured = conf.get('ldap', 'bind_pw') == "Welcome123"

    ask_for_server = unconfigured or conf.choose_ldap_server
    ask_for_credentials = unconfigured or conf.reset_ldap_config

    if conf.without_ldap:
        ask_question("kolab-conf/ldap-setup-skipped",
                _("Skipping setup of LDAP, as specified.")
            )
        return

    if conf.with_openldap and not conf.with_ad:

        conf.command_set('ldap', 'unique_attribute', 'entryuuid')

        fp = open(conf.defaults.config_file, "w+")
        conf.cfg_parser.write(fp)
        fp.close()

        return

    elif conf.with_ad and not conf.with_openldap:
        conf.command_set('ldap', 'auth_attributes', 'samaccountname')
        conf.command_set('ldap', 'modifytimestamp_format', '%%Y%%m%%d%%H%%M%%S.0Z')
        conf.command_set('ldap', 'unique_attribute', 'userprincipalname')
        
        # TODO: These attributes need to be checked
        conf.command_set('ldap', 'mail_attributes', 'mail')
        conf.command_set('ldap', 'mailserver_attributes', 'mailhost')
        conf.command_set('ldap', 'quota_attribute', 'mailquota')

        return

    elif conf.with_ad and conf.with_openldap:
        ask_question("kolab-conf/ldap-system-conflict",
                _("""
                        You cannot configure Kolab to run against OpenLDAP
                        and Active Directory simultaneously.
                    """)
            )
        sys.exit(1)

    # Where the LDAP server is to be chosen explicitly, interact with the user.

    have_ldap_server = have_slapd()

    ldap_uri = conf.get('ldap', 'ldap_uri')
    ldap_uri_default = "ldap://localhost:389/"

    if not conf.check_only:
        if ask_for_server:
            ldap_uri = ask_question("kolab-conf/ldap-server-selection",
                    _("""
                        Please indicate the LDAP server to be used by the Kolab
                        components. (If this is a remote server, no attempt will be
                        made to set up server instances or to configure services, but
                        the indicated server instance will be populated with Kolab
                        settings.)
                        """),
                    _("LDAP URI"),
                    default=(ldap_uri or ldap_uri_default)
                ).strip()

            # Remember the chosen server, used to connect and perform work.

            conf.command_set('ldap', 'ldap_uri', ldap_uri)

        elif not ldap_uri:
            conf.command_set('ldap', 'ldap_uri', ldap_default)

    ldap_server = ldap_uri and get_host_from_url(ldap_uri) or "localhost"
    local_server = ldap_server == "localhost" and have_ldap_server

    # Pre-execution checks.

    update_directory = False

    # A directory update is required if a local directory is required but
    # missing.

    if local_server:
        update_directory = not get_slapd_configuration()

    # Non-local directories may need populating.

    elif not conf.check_only:
        if ask_for_server:
            update_directory = ask_confirmation("kolab-conf/ldap-server-population",
                    _("""
                        A different host is being used for LDAP services. Do you
                        want to populate the directory on this remote host?
                        """),
                    _("Populate remote directory"),
                    default=False
                )

    need_to_connect = local_server or ask_for_server and update_directory
    can_connect = need_to_connect and can_connect_to_slapd(local_server)

    # When only checking, use the existence of a directory to reflect the need
    # to do any work.

    if conf.check_only:
        utils.setup_status("ldap",
            (update_directory or need_to_connect and not can_connect) and _("needs setup") or
            _("setup done"))
        return

    # When performing work, advise the user about the directory status.
    # Unless the configuration is being reset or needs to be set up for the
    # first time, no further work will be done.

    if not update_directory:
        if not conf.reset_ldap_config and not unconfigured:
            if can_connect:
                ask_question("kolab-conf/ldap-instances-found-available",
                        _("""
                                It seems the directory server has an existing
                                instance configured and that this instance is
                                available using the stored credentials.

                                This setup script will not modify your directory.
                                If the intention is to start with a fresh
                                directory, please make sure /etc/dirsrv/ and
                                /var/lib/dirsrv/ are clean so that this setup
                                does not have to worry.

                                To change the Kolab configuration information,
                                should you wish to do so, run the following
                                command:

                                setup-kolab ldap --reset-ldap-config
                            """)
                    )
                return

            elif local_server:
                ask_question("kolab-conf/ldap-instances-found-unavailable",
                        _("""
                                It seems the directory server has an existing
                                instance configured but that this instance is
                                not available using the stored credentials.

                                This setup script will not modify your directory.
                                If the intention is to start with a fresh
                                directory, please make sure /etc/dirsrv/ and
                                /var/lib/dirsrv/ are clean so that this setup
                                does not have to worry.

                                To update the Kolab configuration with
                                appropriate information, run the following
                                command:

                                setup-kolab ldap --reset-ldap-config
                            """)
                    )
                sys.exit(1)

            else:
                return

    _input = {}

    # Get user credentials and details for LDAP access and administration.

    if ask_for_credentials:
        _input['dirmgr_pass'] = ask_question("kolab-conf/ldap-manager",
                _("""
                        Please supply a password for the LDAP Directory Manager
                        user, which is the administrator user you will be using
                        to at least initially log in to the Web Admin, and that
                        Kolab uses to perform administrative tasks.
                    """),
                _("Directory Manager password"),
                default=utils.generate_password(),
                password=True,
                confirm=True
            )

        # Local directory server operation.

        if local_server:
            _input['admin_pass'] = ask_question("kolab-conf/ldap-admin",
                    _("""
                            Please supply a password for the LDAP administrator user
                            'admin', used to login to the graphical console of 389
                            Directory server.
                        """),
                    _("Administrator password"),
                    default=utils.generate_password(),
                    password=True,
                    confirm=True
                )

            try:
                pw = pwd.getpwnam("dirsrv")
            except KeyError:
                user_default = group_default = "nobody"
            else:
                user_default = group_default = "dirsrv"

            _input['userid'] = ask_question("kolab-conf/dirsrv-user",
                    _("""
                            Please choose the system user the directory service should
                            use to run under. It should be an existing, unprivileged,
                            local system POSIX account with no shell.
                        """),
                    _("User"), user_default)

            _input['group'] = ask_question("kolab-conf/dirsrv-group",
                    _("""
                            Please choose the system group the directory service should
                            use to run under.
                        """),
                    _("Group"), group_default)

    else:
        _input['dirmgr_pass'] = conf.get('ldap', 'bind_pw')

        # Local directory server operation.

        if local_server:
            _input['admin_pass'] = conf.get('ldap', 'bind_pw')
            try:
                pw = pwd.getpwnam("dirsrv")
            except:
                _input['userid'] = "nobody"
                _input['group'] = "nobody"
            else:
                _input['userid'] = "dirsrv"
                _input['group'] = "dirsrv"

    # TODO: Verify the user and group exist.

    # TODO: This takes the system fqdn, domainname and hostname, rather then
    # the desired fqdn, domainname and hostname.
    #
    # TODO^2: This should be confirmed.

    domain = conf.get('kolab', 'primary_domain')

    if conf.fqdn:
        _input['fqdn'] = conf.fqdn
        _input['hostname'] = conf.fqdn.split('.')[0]
        _input['domain'] = domain or '.'.join(conf.fqdn.split('.')[1:])

    # The following values are supplied by the constants module.

    else:
        _input['fqdn'] = fqdn
        _input['hostname'] = hostname.split('.')[0]
        _input['domain'] = domain or domainname

    _input['nodotdomain'] = _input['domain'].replace('.','_')

    _input['rootdn'] = conf.get('ldap', 'base_dn') or utils.standard_root_dn(_input['domain'])

    # TODO: Loudly complain if the fqdn does not resolve back to this system.

    if ask_for_credentials:
        _input['domain'] = ask_question("kolab-conf/kolab-domain-namespace",
                _("""
                        This setup procedure plans to set up Kolab Groupware for
                        the following domain name space. This domain name is
                        obtained from the reverse DNS entry on your network
                        interface. Please confirm this is the appropriate domain
                        name space.
                    """),
                _("Domain name to use"),
                "%s" % _input['domain'])

        _input['nodotdomain'] = _input['domain'].replace('.','_')

        _input['rootdn'] = ask_question("kolab-conf/kolab-root-dn",
                _("""
                        The standard root dn we composed for you as follows.
                        Please confirm this is the root dn you wish to use.
                    """),
                _("Root DN to use"),
                utils.standard_root_dn(_input['domain'])
            )

        _input['cyrus_admin_pass'] = ask_question("kolab-conf/cyrus-admin",
                _("""
                        Please supply a Cyrus administrator password. This
                        password is used by Kolab to execute administrative
                        tasks in Cyrus IMAP. You may also need the password
                        yourself to troubleshoot Cyrus IMAP and/or perform
                        other administrative tasks against Cyrus IMAP directly.
                    """),
                _("Cyrus Administrator password"),
                default=utils.generate_password(),
                password=True,
                confirm=True
            )

        _input['kolab_service_pass'] = ask_question("kolab-conf/ldap-kolab-service",
                _("""
                        Please supply a Kolab service account password. This
                        account is used by various services such as Postfix,
                        and Roundcube, as anonymous binds to the LDAP server
                        will not be allowed.
                    """),
                _("Kolab Service password"),
                default=utils.generate_password(),
                password=True,
                confirm=True
            )

        log.info(_("Writing out configuration to kolab.conf"))

        # Write out kolab configuration.

        conf.command_set('ldap', 'bind_pw', _input['dirmgr_pass'])
        conf.command_set('ldap', 'service_bind_pw', _input['kolab_service_pass'])
        conf.command_set('cyrus-imap', 'admin_password', _input['cyrus_admin_pass'])

    conf.fqdn = fqdn
    conf.command_set('kolab', 'primary_domain', _input['domain'])
    conf.command_set('ldap', 'base_dn', _input['rootdn'])
    conf.command_set('ldap', 'bind_dn', 'cn=Directory Manager')
    conf.command_set('ldap', 'service_bind_dn', 'uid=kolab-service,ou=Special Users,%s' % (_input['rootdn']))

    # Update the configuration file.

    fp = open(conf.defaults.config_file, "w+")
    conf.cfg_parser.write(fp)
    fp.close()

    # Administer the LDAP server.

    if not update_directory:
        ask_question("kolab-conf/ldap-directory-not-changed",
                _("""
                        No further LDAP configuration will be performed due to
                        the presence of existing directory information. Only the
                        Kolab configuration file has been updated.
                    """)
            )
        return

    # Only where the server is local will any attempt be made to create new
    # instances and to configure the services.

    if local_server:
        if os.path.isfile("/usr/sbin/setup-ds-admin.pl"):
            setup_ds_admin = "/usr/sbin/setup-ds-admin.pl"
        #elif os.path.isfile("/usr/sbin/setup-ds-admin"):
            #setup_ds_admin = "/usr/sbin/setup-ds-admin"
        elif os.path.isfile("/usr/sbin/setup-ds"):
            setup_ds_admin = "/usr/sbin/setup-ds"
        else:
            log.error(_("No directory server setup tool available."))
            sys.exit(1)

        (fp, filename) = tempfile.mkstemp(dir="/tmp/")
        os.write(fp, ldap_setup_data % _input)
        os.close(fp)

        command = [
                setup_ds_admin,
                '--debug',
                '--silent',
                '--force',
                '--file=%s' % (filename)
            ]

        ask_question("kolab-conf/ldap-setup-in-progress",
                _("""
                        Setup is now going to set up the 389 Directory Server. This
                        may take a little while (during which period there is no
                        output and no progress indication).
                    """)
            )

        log.info(_("Setting up 389 Directory Server"))

        if not control_service('dirsrv', 'stop', '.target'):
            log.error(_("Could not stop the directory server service."))

        setup_389 = Popen(
                command,
                stdout=PIPE,
                stderr=PIPE
            )

        (stdoutdata, stderrdata) = setup_389.communicate()

        if setup_389.returncode != 0:
            ask_question("kolab-conf/ldap-setup-error",
                    _("""
                            An error was detected in the setup procedure for 389
                            Directory Server. This setup will write out stderr and
                            stdout to /var/log/kolab/setup.error.log and
                            /var/log/kolab/setup.out.log respectively, before it
                            exits.
                        """)
                )

            fp = open('/var/log/kolab/setup.error.log', 'w')
            fp.write(stderrdata)
            fp.close()

            fp = open('/var/log/kolab/setup.out.log', 'w')
            fp.write(stdoutdata)
            fp.close()

        log.debug(_("Setup DS stdout:"), level=8)
        log.debug(stdoutdata, level=8)

        log.debug(_("Setup DS stderr:"), level=8)
        log.debug(stderrdata, level=8)

        if setup_389.returncode != 0:
            sys.exit(1)

        # Find the kolab schema. It's installed as %doc in the kolab-schema package.
        # TODO: Chown nobody, nobody, chmod 440

        schema_file = find_schema_file()

        if schema_file is not None:
            try:
                shutil.copy(
                        schema_file,
                        '/etc/dirsrv/slapd-%s/schema/99%s' % (
                                _input['hostname'],
                                os.path.basename(schema_file)
                            )
                    )

                schema_error = False
            except:
                log.error(_("Could not copy the LDAP extensions for Kolab"))
                schema_error = True
        else:
            log.error(_("Could not find the ldap Kolab schema file"))
            schema_error = True

        if not control_service('dirsrv', 'restart', '.target'):
            log.error(_("Could not restart the directory server service."))

        # Handle any failure to restart the service.

        if not ensure_slapd_service(_input['hostname']):
            log.error(_("Directory server service not available."))
            sys.exit(1)

        if not configure_service('dirsrv', True, '.target'):
            log.error(_("Could not configure to start on boot, the " + \
                    "directory server service."))

        if not configure_service('dirsrv-admin', True):
            log.error(_("Could not start and configure to start on boot, the " + \
                    "directory server admin service."))

    # Schema population can occur on both a local server and a remote server.

    if update_directory:
        try:
            populate_schema(_input, not schema_error)
        except ldap.ALREADY_EXISTS:
            log.info(_("Information already seems to exist in the directory."))

def find_schema_file():
    for kolab_dir in glob('/usr/share/doc/kolab*'):
        for root, directories, filenames in os.walk(kolab_dir):
            for filename in filenames:
                if filename.startswith('kolab') and filename.endswith('.ldif'):
                    return join(root, filename)
    return None

def get_ldap_auth(domain):
    auth = Auth(domain)
    auth.connect()
    auth._auth.connect()
    auth._auth._bind()
    return auth

def can_connect_to_slapd(local_server=True):
    hostname = conf.fqdn and conf.fqdn.split('.')[0] or hostname
    if not local_server or have_slapd_process(hostname):
        auth = get_ldap_auth(conf.get('kolab', 'primary_domain'))
        return auth._auth.bind
    else:
        return False

def ensure_slapd_service(hostname):
    for retries in range(0, 3):
        if have_slapd_process(hostname):
            return True
        else:
            log.info(_("Directory service not started. Starting..."))
            if not control_service('dirsrv', 'start', '.target'):
                log.error(_("Could not start the directory server service."))
            time.sleep(10)
    else:
        return False

def populate_schema(_input, have_schema=True):

    """
        Populate the schema using the values from '_input', although the
        configuration will be used in preference (having been set using the
        input) to make the population process somewhat more transparent.
    """

    auth = get_ldap_auth(conf.get('kolab', 'primary_domain'))

    # Insert service users.

    log.info(_("Inserting service users into LDAP."))

    dn = 'uid=%s,ou=Special Users,%s' % (
        conf.get('cyrus-imap', 'admin_login'),
        conf.get('ldap', 'base_dn'))

    # A dict to help build the "body" of the object
    attrs = {}
    attrs['objectclass'] = ['top','person','inetorgperson','organizationalperson']
    attrs['uid'] = conf.get('cyrus-imap', 'admin_login')
    attrs['givenname'] = "Cyrus"
    attrs['surname'] = "Administrator"
    attrs['cn'] = "Cyrus Administrator"
    attrs['userPassword'] = conf.get('cyrus-imap', 'admin_password')

    # Convert our dict to nice syntax for the add-function using modlist-module
    ldif = ldap.modlist.addModlist(attrs)

    # Do the actual synchronous add-operation to the ldapserver
    auth._auth.ldap.add_s(dn, ldif)

    dn = conf.get('ldap', 'service_bind_dn')

    # A dict to help build the "body" of the object
    attrs = {}
    attrs['objectclass'] = ['top','person','inetorgperson','organizationalperson']
    attrs['uid'] = "kolab-service"
    attrs['givenname'] = "Kolab"
    attrs['surname'] = "Service"
    attrs['cn'] = "Kolab Service"
    attrs['userPassword'] = conf.get('ldap', 'service_bind_pw')
    attrs['nslookthroughlimit'] = '-1'
    attrs['nssizelimit'] = '-1'
    attrs['nstimelimit'] = '-1'
    attrs['nsidletimeout'] = '-1'

    # Convert our dict to nice syntax for the add-function using modlist-module
    ldif = ldap.modlist.addModlist(attrs)

    # Do the actual synchronous add-operation to the ldapserver
    auth._auth.ldap.add_s(dn, ldif)

    dn = 'ou=Resources,%s' % conf.get('ldap', 'base_dn')

    # A dict to help build the "body" of the object
    attrs = {}
    attrs['objectclass'] = ['top','organizationalunit']
    attrs['ou'] = "Resources"

    # Convert our dict to nice syntax for the add-function using modlist-module
    ldif = ldap.modlist.addModlist(attrs)

    # Do the actual synchronous add-operation to the ldapserver
    auth._auth.ldap.add_s(dn, ldif)

    dn = 'ou=Shared Folders,%s' % conf.get('ldap', 'base_dn')

    # A dict to help build the "body" of the object
    attrs = {}
    attrs['objectclass'] = ['top','organizationalunit']
    attrs['ou'] = "Shared Folders"

    # Convert our dict to nice syntax for the add-function using modlist-module
    ldif = ldap.modlist.addModlist(attrs)

    # Do the actual synchronous add-operation to the ldapserver
    auth._auth.ldap.add_s(dn, ldif)

    log.info(_("Writing out cn=kolab,cn=config"))

    dn = 'cn=kolab,cn=config'

    # A dict to help build the "body" of the object
    attrs = {}
    attrs['objectclass'] = ['top','extensibleobject']
    attrs['cn'] = "kolab"

    # Convert our dict to nice syntax for the add-function using modlist-module
    ldif = ldap.modlist.addModlist(attrs)

    # Do the actual synchronous add-operation to the ldapserver
    auth._auth.ldap.add_s(dn, ldif)

    auth._auth.set_entry_attribute(
            dn,
            'aci',
            '(targetattr = "*") (version 3.0;acl "Kolab Services";allow (read,compare,search)(userdn = "ldap:///%s");)' %
                conf.get('ldap', 'service_bind_dn')
        )

    # TODO: Add kolab-admin role
    # TODO: Assign kolab-admin admin ACLs

    log.info(_("Adding domain %s to list of domains for this deployment") % conf.get('kolab', 'primary_domain'))
    dn = "associateddomain=%s,cn=kolab,cn=config" % conf.get('kolab', 'primary_domain')
    attrs = {}
    attrs['objectclass'] = ['top','domainrelatedobject']
    attrs['associateddomain'] = [
            conf.get('kolab', 'primary_domain'),
            conf.fqdn,
            'localhost.localdomain',
            'localhost'
        ]

    # De-duplicate attribute values before attempting to insert the object (#2205)
    attrs['associateddomain'] = list(set(attrs['associateddomain']))
    attrs['associateddomain'].pop(attrs['associateddomain'].index(conf.get('kolab', 'primary_domain')))
    attrs['associateddomain'] = [ conf.get('kolab', 'primary_domain') ] + attrs['associateddomain']

    attrs['aci'] = '(targetattr = "*") (version 3.0;acl "Read Access for %(domain)s Users";allow (read,compare,search)(userdn = "ldap:///%(rootdn)s??sub?(objectclass=*)");)' % (_input)

    # Add inetdomainbasedn in case the configured root dn is not the same as the
    # standard root dn for the domain name configured
    if conf.get('ldap', 'base_dn') != utils.standard_root_dn(conf.get('kolab', 'primary_domain')):
        attrs['objectclass'].append('inetdomain')
        attrs['inetdomainbasedn'] = conf.get('ldap', 'base_dn')

    ldif = ldap.modlist.addModlist(attrs)
    auth._auth.ldap.add_s(dn, ldif)

    if not conf.anonymous:
        log.info(_("Disabling anonymous binds"))
        dn = "cn=config"
        modlist = []
        modlist.append((ldap.MOD_REPLACE, "nsslapd-allow-anonymous-access", "off"))
        auth._auth.ldap.modify_s(dn, modlist)

    # TODO: Ensure the uid attribute is unique
    # TODO^2: Consider renaming the general "attribute uniqueness to "uid attribute uniqueness"
    log.info(_("Enabling attribute uniqueness plugin"))
    dn = "cn=attribute uniqueness,cn=plugins,cn=config"
    modlist = []
    modlist.append((ldap.MOD_REPLACE, "nsslapd-pluginEnabled", "on"))
    auth._auth.ldap.modify_s(dn, modlist)

    log.info(_("Enabling referential integrity plugin"))
    dn = "cn=referential integrity postoperation,cn=plugins,cn=config"
    modlist = []
    modlist.append((ldap.MOD_REPLACE, "nsslapd-pluginEnabled", "on"))
    auth._auth.ldap.modify_s(dn, modlist)

    log.info(_("Enabling and configuring account policy plugin"))
    dn = "cn=Account Policy Plugin,cn=plugins,cn=config"
    modlist = []
    modlist.append((ldap.MOD_REPLACE, "nsslapd-pluginEnabled", "on"))
    modlist.append((ldap.MOD_ADD, "nsslapd-pluginarg0", "cn=config,cn=Account Policy Plugin,cn=plugins,cn=config"))
    auth._auth.ldap.modify_s(dn, modlist)

    dn = "cn=config,cn=Account Policy Plugin,cn=plugins,cn=config"
    modlist = []
    modlist.append((ldap.MOD_REPLACE, "alwaysrecordlogin", "yes"))
    modlist.append((ldap.MOD_ADD, "stateattrname", "lastLoginTime"))
    modlist.append((ldap.MOD_ADD, "altstateattrname", "createTimestamp"))
    auth._auth.ldap.modify_s(dn, modlist)

    # TODO: Add kolab-admin role
    log.info(_("Adding the kolab-admin role"))
    dn = "cn=kolab-admin,%s" % conf.get('ldap', 'base_dn')
    attrs = {}
    attrs['description'] = "Kolab Administrator"
    attrs['objectClass'] = ['top','ldapsubentry','nsroledefinition','nssimpleroledefinition','nsmanagedroledefinition']
    attrs['cn'] = "kolab-admin"
    ldif = ldap.modlist.addModlist(attrs)

    auth._auth.ldap.add_s(dn, ldif)

    # TODO: User writeable attributes on root_dn
    log.info(_("Setting access control to %s") % conf.get('ldap', 'base_dn'))
    dn = conf.get('ldap', 'base_dn')
    aci = []

    if not have_schema:
        aci.append('(targetattr = "carLicense || description || displayName || facsimileTelephoneNumber || homePhone || homePostalAddress || initials || jpegPhoto || l || labeledURI || mobile || o || pager || photo || postOfficeBox || postalAddress || postalCode || preferredDeliveryMethod || preferredLanguage || registeredAddress || roomNumber || secretary || seeAlso || st || street || telephoneNumber || telexNumber || title || userCertificate || userPassword || userSMIMECertificate || x500UniqueIdentifier") (version 3.0; acl "Enable self write for common attributes"; allow (read,compare,search,write)(userdn = "ldap:///self");)')
    else:
        aci.append('(targetattr = "carLicense || description || displayName || facsimileTelephoneNumber || homePhone || homePostalAddress || initials || jpegPhoto || l || labeledURI || mobile || o || pager || photo || postOfficeBox || postalAddress || postalCode || preferredDeliveryMethod || preferredLanguage || registeredAddress || roomNumber || secretary || seeAlso || st || street || telephoneNumber || telexNumber || title || userCertificate || userPassword || userSMIMECertificate || x500UniqueIdentifier || kolabDelegate || kolabInvitationPolicy || kolabAllowSMTPSender") (version 3.0; acl "Enable self write for common attributes"; allow (read,compare,search,write)(userdn = "ldap:///self");)')


    aci.append('(targetattr = "*") (version 3.0;acl "Directory Administrators Group";allow (all)(groupdn = "ldap:///cn=Directory Administrators,%(rootdn)s" or roledn = "ldap:///cn=kolab-admin,%(rootdn)s");)' % (_input))
    aci.append('(targetattr="*")(version 3.0; acl "Configuration Administrators Group"; allow (all) groupdn="ldap:///cn=Configuration Administrators,ou=Groups,ou=TopologyManagement,o=NetscapeRoot";)')
    aci.append('(targetattr="*")(version 3.0; acl "Configuration Administrator"; allow (all) userdn="ldap:///uid=admin,ou=Administrators,ou=TopologyManagement,o=NetscapeRoot";)')
    aci.append('(targetattr = "*")(version 3.0; acl "SIE Group"; allow (all) groupdn = "ldap:///cn=slapd-%(hostname)s,cn=389 Directory Server,cn=Server Group,cn=%(fqdn)s,ou=%(domain)s,o=NetscapeRoot";)' %(_input))
    aci.append('(targetattr != "userPassword") (version 3.0;acl "Search Access";allow (read,compare,search)(userdn = "ldap:///all");)')
    modlist = []
    modlist.append((ldap.MOD_REPLACE, "aci", aci))
    auth._auth.ldap.modify_s(dn, modlist)

# Data used by the above code.

ldap_setup_data = """\
[General]
FullMachineName = %(fqdn)s
SuiteSpotUserID = %(userid)s
SuiteSpotGroup = %(group)s
AdminDomain = %(domain)s
ConfigDirectoryLdapURL = ldap://%(fqdn)s:389/o=NetscapeRoot
ConfigDirectoryAdminID = admin
ConfigDirectoryAdminPwd = %(admin_pass)s

[slapd]
SlapdConfigForMC = Yes
UseExistingMC = 0
ServerPort = 389
ServerIdentifier = %(hostname)s
Suffix = %(rootdn)s
RootDN = cn=Directory Manager
RootDNPwd = %(dirmgr_pass)s
ds_bename = %(nodotdomain)s
AddSampleEntries = No

[admin]
Port = 9830
ServerAdminID = admin
ServerAdminPwd = %(admin_pass)s
"""