Exemple #1
0
def execute(*args, **kw):
    if conf.has_section('example.org'):
        primary_domain = conf.get('kolab', 'primary_domain')

        if not primary_domain == 'example.org':
            utils.multiline_message(
                _("""
                            Copying the configuration section for 'example.org' over to
                            a section applicable to your domain '%s'.
                        """) % (primary_domain))

            conf.cfg_parser._sections[primary_domain] = \
                    conf.cfg_parser._sections['example.org']
            conf.cfg_parser._sections.pop('example.org')

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

    if os.path.isfile('/etc/default/kolab-server'):
        myaugeas = Augeas()
        setting = os.path.join('/files/etc/default/kolab-server', 'START')
        if not myaugeas.get(setting) == 'yes':
            myaugeas.set(setting, 'yes')
            myaugeas.save()
        myaugeas.close()

    if os.path.isfile('/bin/systemctl'):
        if os.path.isfile('/etc/debian_version'):
            subprocess.call(
                ['/bin/systemctl', 'restart', 'kolab-server.service'])
        else:
            subprocess.call(['/bin/systemctl', 'restart', 'kolabd.service'])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['/sbin/service', 'kolabd', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service', 'kolab-server', 'restart'])
    else:
        log.error(_("Could not start the kolab server service."))

    if os.path.isfile('/bin/systemctl'):
        if os.path.isfile('/etc/debian_version'):
            subprocess.call(
                ['/bin/systemctl', 'enable', 'kolab-server.service'])
        else:
            subprocess.call(['/bin/systemctl', 'enable', 'kolabd.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'kolabd', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'kolab-server', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "kolab server service."))
Exemple #2
0
def execute(*args, **kw):
    if conf.has_section('example.org'):
        primary_domain = conf.get('kolab', 'primary_domain')

        if not primary_domain == 'example.org':
            utils.multiline_message(
                    _("""
                            Copying the configuration section for 'example.org' over to
                            a section applicable to your domain '%s'.
                        """) % (primary_domain)
                )

            conf.cfg_parser._sections[primary_domain] = \
                    conf.cfg_parser._sections['example.org']
            conf.cfg_parser._sections.pop('example.org')

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

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'restart', 'kolabd.service'])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['/sbin/service', 'kolabd', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service','kolab-server','restart'])
    else:
        log.error(_("Could not start the kolab server service."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'enable', 'kolabd.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'kolabd', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'kolab-server', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "kolab server service."))
Exemple #3
0
def execute(*args, **kw):
    if conf.timezone == None:
        print >> sys.stderr, utils.multiline_message(
                _("""
                        Please supply the timezone PHP should be using.
                        You have to use a Continent or Country / City locality name
                        like 'Europe/Berlin', but not just 'CEST'.
                    """)
            )

        conf.timezone = utils.ask_question(
                _("Timezone ID"),
                default="UTC"
            )

    if not conf.php_ini_path == None:
        if not os.path.isfile(conf.php_ini_path):
            log.error(_("Cannot configure PHP through %r (No such file or directory)") % (conf.php_ini_path))
            return
        php_ini = conf.php_ini_path

    else:
        # Search and destroy
        php_ini = "/etc/php.ini"
        if not os.path.isfile(php_ini):
            php_ini = "/etc/php5/apache2/php.ini"

        if not os.path.isfile(php_ini):
            log.error(_("Could not find PHP configuration file php.ini"))
            return

    myaugeas = Augeas()

    setting_base = '/files%s/' % (php_ini)

    setting = os.path.join(setting_base, 'Date', 'date.timezone')
    current_value = myaugeas.get(setting)

    if current_value == None:
        insert_paths = myaugeas.match('/files%s/Date/*' % (php_ini))
        insert_path = insert_paths[(len(insert_paths)-1)]
        myaugeas.insert(insert_path, 'date.timezone', False)

    log.debug(_("Setting key %r to %r") % ('Date/date.timezone', conf.timezone), level=8)
    myaugeas.set(setting, conf.timezone)

    myaugeas.save()
Exemple #4
0
def execute(*args, **kw):
    if conf.timezone == None:
        print >> sys.stderr, utils.multiline_message(
            _("""
                        Please supply the timezone PHP should be using.
                        You have to use a Continent or Country / City locality name
                        like 'Europe/Berlin', but not just 'CEST'.
                    """))

        conf.timezone = utils.ask_question(_("Timezone ID"), default="UTC")

    if not conf.php_ini_path == None:
        if not os.path.isfile(conf.php_ini_path):
            log.error(
                _("Cannot configure PHP through %r (No such file or directory)"
                  ) % (conf.php_ini_path))
            return
        php_ini = conf.php_ini_path

    else:
        # Search and destroy
        php_ini = "/etc/php.ini"
        if not os.path.isfile(php_ini):
            php_ini = "/etc/php5/apache2/php.ini"

        if not os.path.isfile(php_ini):
            log.error(_("Could not find PHP configuration file php.ini"))
            return

    myaugeas = Augeas()

    setting_base = '/files%s/' % (php_ini)

    setting = os.path.join(setting_base, 'Date', 'date.timezone')
    current_value = myaugeas.get(setting)

    if current_value == None:
        insert_paths = myaugeas.match('/files%s/Date/*' % (php_ini))
        insert_path = insert_paths[(len(insert_paths) - 1)]
        myaugeas.insert(insert_path, 'date.timezone', False)

    log.debug(_("Setting key %r to %r") %
              ('Date/date.timezone', conf.timezone),
              level=8)
    myaugeas.set(setting, conf.timezone)

    myaugeas.save()
Exemple #5
0
    def to_message(self):
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEBase import MIMEBase
        from email.MIMEText import MIMEText
        from email.Utils import COMMASPACE, formatdate
        from email import Encoders

        msg = MIMEMultipart()
        organizer = self.get_organizer()
        email = organizer.email()
        name = organizer.name()

        if not name:
            msg['From'] = email
        else:
            msg['From'] = '"%s" <%s>' % (name, email)

        msg['To'] = ', '.join([x.__str__() for x in self.get_attendees()])
        msg['Date'] = formatdate(localtime=True)

        msg.add_header('X-Kolab-Type', 'application/x-vnd.kolab.event')

        text = utils.multiline_message("""
                    This is a Kolab Groupware object. To view this object you
                    will need an email client that understands the Kolab
                    Groupware format. For a list of such email clients please
                    visit http://www.kolab.org/
            """)

        msg.attach( MIMEText(text) )

        part = MIMEBase('application', "calendar+xml")
        part.set_charset('UTF-8')

        msg["Subject"] = self.get_uid()

        part.set_payload(str(self))

        part.add_header('Content-Disposition', 'attachment; filename="kolab.xml"')
        part.replace_header('Content-Transfer-Encoding', '8bit')

        msg.attach(part)

        return msg
Exemple #6
0
    def to_message_itip(self, from_address, method="REQUEST", participant_status="ACCEPTED"):
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEBase import MIMEBase
        from email.MIMEText import MIMEText
        from email.Utils import COMMASPACE, formatdate
        from email import Encoders

        msg = MIMEMultipart()

        msg_from = None

        if method == "REPLY":
            # TODO: Make user friendly name <email>
            msg['To'] = self.get_organizer().email()

            attendees = self.get_attendees()

            # TODO: There's an exception here for delegation (partstat DELEGATED)
            for attendee in attendees:
                if attendee.get_email() == from_address:
                    # Only the attendee is supposed to be listed in a reply
                    attendee.set_participant_status(participant_status)

                    self._attendees = [attendee]
                    self.event.setAttendees(self._attendees)

                    name = attendee.get_name()
                    email = attendee.get_email()

                    if not name:
                        msg_from = email
                    else:
                        msg_from = '"%s" <%s>' % (name, email)

            if msg_from == None:
                organizer = self.get_organizer()
                email = organizer.email()
                name = organizer.name()
                if email == from_address:
                    if not name:
                        msg_from = email
                    else:
                        msg_from = '"%s" <%s>' % (name, email)

        elif method == "REQUEST":
            organizer = self.get_organizer()
            email = organizer.get_email()
            name = organizer.get_name()
            if not name:
                msg_from = email
            else:
                msg_from = '"%s" <%s>' % (name, email)

        if msg_from == None:
            if from_address == None:
                log.error(_("No sender specified"))
            else:
                msg_from = from_address

        msg['From'] = msg_from

        msg['Date'] = formatdate(localtime=True)

        # TODO: Should allow for localization
        text = utils.multiline_message("""
                    This is a response to one of your event requests.
            """)

        msg.attach( MIMEText(text) )

        part = MIMEBase('text', "calendar")
        part.set_charset('UTF-8')

        # TODO: Should allow for localization
        msg["Subject"] = "Meeting Request %s" % (participant_status)

        part.set_payload(self.as_string_itip(method=method))

        part.add_header('Content-Disposition', 'attachment; filename="event.ics"')
        part.replace_header('Content-Transfer-Encoding', '8bit')

        msg.attach(part)

        return msg
Exemple #7
0
def execute(*args, **kw):
    ask_questions = True

    if not conf.config_file == conf.defaults.config_file:
        ask_questions = False

    _input = {}

    if ask_questions:
        print >> sys.stderr, utils.multiline_message(
                _("""
                        Please supply a password for the LDAP administrator user
                        'admin', used to login to the graphical console of 389
                        Directory server.
                    """)
            )

        _input['admin_pass'] = utils.ask_question(
                _("Administrator password"),
                default=utils.generate_password(),
                password=True,
                confirm=True
            )

        print >> sys.stderr, utils.multiline_message(
                _("""
                        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.
                    """)
            )

        _input['dirmgr_pass'] = utils.ask_question(
                _("Directory Manager password"),
                default=utils.generate_password(),
                password=True,
                confirm=True
            )

        print >> sys.stderr, utils.multiline_message(
                _("""
                        Please choose the system user and group the service
                        should use to run under. These should be existing,
                        unprivileged, local system POSIX accounts with no shell.
                    """)
            )

        try:
            pw = pwd.getpwnam("dirsrv")
        except:
            _input['userid'] = utils.ask_question(_("User"), default="nobody")
            _input['group'] = utils.ask_question(_("Group"), default="nobody")
        else:
            _input['userid'] = utils.ask_question(_("User"), default="dirsrv")
            _input['group'] = utils.ask_question(_("Group"), default="dirsrv")

    else:
        _input['admin_pass'] = conf.get('ldap', 'bind_pw')
        _input['dirmgr_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.

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

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

    _input['rootdn'] = utils.standard_root_dn(_input['domain'])

    if ask_questions:
        print >> sys.stderr, utils.multiline_message(
                _("""
                        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.
                    """)
            )

        answer = utils.ask_confirmation("%s" % (_input['domain']))

        if not answer:
            positive_answer = False
            while not positive_answer:
                _input['domain'] = utils.ask_question(_("Domain name to use"))
                if not _input['domain'] == None and not _input['domain'] == "":
                    positive_answer = True
                else:
                    print >> sys.stderr, utils.multiline_message(
                            _("""
                                    Invalid input. Please try again.
                                """)
                        )

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

        print >> sys.stderr, utils.multiline_message(
                _("""
                        The standard root dn we composed for you follows. Please
                        confirm this is the root dn you wish to use.
                    """)
            )

        answer = utils.ask_confirmation("%s" % (_input['rootdn']))

        if not answer:
            positive_answer = False
            while not positive_answer:
                _input['rootdn'] = utils.ask_question(_("Root DN to use"))
                if not _input['rootdn'] == None and not _input['rootdn'] == "":
                    positive_answer = True
                else:
                    print >> sys.stderr, utils.multiline_message(
                            _("""
                                    Invalid input. Please try again.
                                """)
                        )

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

    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
""" % (_input)

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

    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"):
        setup_ds_admin = "/usr/sbin/setup-ds"
    else:
        log.error(_("No directory server setup tool available."))

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

    print >> sys.stderr, utils.multiline_message(
            _("""
                    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"))

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

    (stdoutdata, stderrdata) = setup_389.communicate()

    # TODO: Get the return code and display output if not successful.

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

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

    # TODO: Fails when ran a second time.

    # TODO: When fail, fail gracefully.

    # Find the kolab schema. It's installed as %doc in the kolab-schema package.
    # TODO: Chown nobody, nobody, chmod 440
    schema_file = None
    for root, directories, filenames in os.walk('/usr/share/doc/'):
        for filename in filenames:
            if filename.startswith('kolab') and filename.endswith('.ldif') and schema_file == None:
                schema_file = os.path.join(root,filename)

    if not schema_file == 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 os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'restart', 'dirsrv.target'])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['/sbin/service', 'dirsrv', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service','dirsrv','stop'])
        time.sleep(20)
        subprocess.call(['/usr/sbin/service','dirsrv','start'])
    else:
        log.error(_("Could not start the directory server service."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'enable', 'dirsrv.target'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'dirsrv', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'dirsrv', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "directory server service."))

    if ask_questions:
        print >> sys.stderr, utils.multiline_message(
                _("""
                        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.
                    """)
            )

        _input['cyrus_admin_pass'] = utils.ask_question(
                _("Cyrus Administrator password"),
                default=utils.generate_password(),
                password=True,
                confirm=True
            )

        print >> sys.stderr, utils.multiline_message(
                _("""
                        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.
                    """)
            )

        _input['kolab_service_pass'] = utils.ask_question(
                _("Kolab Service password"),
                default=utils.generate_password(),
                password=True,
                confirm=True
            )

    else:
        _input['cyrus_admin_pass'] = conf.get('cyrus-imap', 'admin_password')
        _input['kolab_service_pass'] = conf.get('ldap', 'service_bind_pw')

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

    # Write out kolab configuration
    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', 'bind_pw', _input['dirmgr_pass'])
    conf.command_set('ldap', 'service_bind_dn', 'uid=kolab-service,ou=Special Users,%s' % (_input['rootdn']))
    conf.command_set('ldap', 'service_bind_pw', _input['kolab_service_pass'])

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

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

    # Insert service users
    auth = Auth(_input['domain'])
    auth.connect()
    auth._auth.connect()
    auth._auth._bind()

    dn = 'uid=%s,ou=Special Users,%s' % (conf.get('cyrus-imap', 'admin_login'), _input['rootdn'])

    # 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'] = _input['cyrus_admin_pass']

    # 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)

    conf.command_set('cyrus-imap', 'admin_password', _input['cyrus_admin_pass'])

    dn = 'uid=kolab-service,ou=Special Users,%s' % (_input['rootdn'])

    # 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'] = _input['kolab_service_pass']
    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' % (_input['rootdn'])

    # 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' % (_input['rootdn'])

    # 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");)' % ('uid=kolab-service,ou=Special Users,%s' % (_input['rootdn']))
        )

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

    log.info(_("Adding domain %s to list of domains for this deployment") % (_input['domain']))
    dn = "associateddomain=%s,cn=kolab,cn=config" % (_input['domain'])
    attrs = {}
    attrs['objectclass'] = ['top','domainrelatedobject']
    attrs['associateddomain'] = '%s' % (_input['domain'])
    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 not _input['rootdn'] == utils.standard_root_dn(_input['domain']):
        attrs['objectclass'].append('inetdomain')
        attrs['inetdomainbasedn'] = _input['rootdn']

    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" % (_input['rootdn'])
    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") % (_input['rootdn']))
    dn = _input['rootdn']
    aci = []

    if not schema_error:
        aci.append('(targetattr = "homePhone || preferredDeliveryMethod || jpegPhoto || postalAddress || carLicense || userPassword || mobile || displayName || description || labeledURI || homePostalAddress || postOfficeBox || registeredAddress || postalCode || photo || title || street || pager || o || l || initials || telephoneNumber || preferredLanguage || facsimileTelephoneNumber") (version 3.0;acl "Enable self write for common attributes";allow (read,compare,search,write)(userdn = "ldap:///self");)')
    else:
        aci.append('(targetattr = "homePhone || preferredDeliveryMethod || jpegPhoto || postalAddress || carLicense || userPassword || mobile || kolabAllowSMTPRecipient || displayName || kolabDelegate || description || labeledURI || homePostalAddress || postOfficeBox || registeredAddress || postalCode || photo || title || street || kolabInvitationPolicy || pager || o || l || initials || kolabAllowSMTPSender || telephoneNumber || preferredLanguage || facsimileTelephoneNumber") (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 = "*") (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)

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'enable', 'dirsrv-admin.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'dirsrv-admin', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'dirsrv-admin', 'defaults'])
    else:
        log.error(_("Could not start and configure to start on boot, the " + \
                "directory server admin service."))
Exemple #8
0
def execute(*args, **kw):
    schema_files = []
    for root, directories, filenames in os.walk('/usr/share/doc/'):
        for directory in directories:
            if directory.startswith("kolab-syncroton"):
                for root, directories, filenames in os.walk(os.path.join(root, directory)):
                    for filename in filenames:
                        if filename.startswith('mysql.initial') and filename.endswith('.sql'):
                            schema_filepath = os.path.join(root,filename)
                            if not schema_filepath in schema_files:
                                schema_files.append(schema_filepath)
                                break

                if len(schema_files) > 0:
                    break
        if len(schema_files) > 0:
            break

    if not os.path.isfile('/tmp/kolab-setup-my.cnf'):
        utils.multiline_message(
                """Please supply the MySQL root password"""
            )

        mysql_root_password = utils.ask_question(
                _("MySQL root password"),
                password=True
            )

        data = """
[mysql]
user=root
password='******'
""" % (mysql_root_password)

        fp = open('/tmp/kolab-setup-my.cnf', 'w')
        os.chmod('/tmp/kolab-setup-my.cnf', 0600)
        fp.write(data)
        fp.close()

    for schema_file in schema_files:
        p1 = subprocess.Popen(['cat', schema_file], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf', 'roundcube'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

    time.sleep(2)

    httpservice = 'httpd.service'

    if os.path.isfile('/usr/lib/systemd/system/apache2.service'):
        httpservice = 'apache2.service'

    if os.path.isdir('/lib/systemd/system/apache2.service.d'):
        httpservice = 'apache2.service'

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'restart', httpservice])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['/sbin/service', 'httpd', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service','apache2','restart'])
    else:
        log.error(_("Could not start the webserver server service."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'enable', httpservice])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'httpd', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'apache2', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "webserver server service."))
Exemple #9
0
def execute(*args, **kw):
    print >> sys.stderr, utils.multiline_message(
        _("""
                    Please supply a password for the MySQL user 'roundcube'.
                    This password will be used by the Roundcube webmail
                    interface.
                """))

    mysql_roundcube_password = utils.ask_question(
        _("MySQL roundcube password"),
        default=utils.generate_password(),
        password=True,
        confirm=True)

    conf.mysql_roundcube_password = mysql_roundcube_password

    rc_settings = {
        'des_key':
        re.sub(
            r'[^a-zA-Z0-9]', "", "%s%s" %
            (hashlib.md5("%s" % random.random()).digest().encode("base64"),
             hashlib.md5(
                 "%s" % random.random()).digest().encode("base64")))[:24],
        'imap_admin_login':
        conf.get('cyrus-imap', 'admin_login'),
        'imap_admin_password':
        conf.get('cyrus-imap', 'admin_password'),
        'ldap_base_dn':
        conf.get('ldap', 'base_dn'),
        'ldap_group_base_dn':
        conf.get('ldap', 'group_base_dn'),
        'ldap_group_filter':
        conf.get('ldap', 'group_filter'),
        'ldap_ldap_uri':
        conf.get('ldap', 'ldap_uri'),
        'ldap_resource_base_dn':
        conf.get('ldap', 'resource_base_dn'),
        'ldap_resource_filter':
        conf.get('ldap', 'resource_filter'),
        'ldap_service_bind_dn':
        conf.get('ldap', 'service_bind_dn'),
        'ldap_service_bind_pw':
        conf.get('ldap', 'service_bind_pw'),
        'ldap_user_base_dn':
        conf.get('ldap', 'user_base_dn'),
        'ldap_user_filter':
        conf.get('ldap', 'user_filter'),
        'primary_domain':
        conf.get('kolab', 'primary_domain'),
        'mysql_uri':
        'mysqli://*****:*****@localhost/roundcube' %
        (mysql_roundcube_password),
        'conf':
        conf
    }

    rc_paths = [
        "/usr/share/roundcubemail/", "/usr/share/roundcube/",
        "/srv/www/roundcubemail/", "/var/www/roundcubemail/"
    ]

    rcpath = ''
    for rc_path in rc_paths:
        if os.path.isdir(rc_path):
            rcpath = rc_path
            break

    if not os.path.isdir(rcpath):
        log.error(_("Roundcube installation path not found."))
        return

    if os.access(rcpath + 'skins/enterprise/', os.R_OK):
        rc_settings['skin'] = 'enterprise'
    elif os.access(rcpath + 'skins/chameleon/', os.R_OK):
        rc_settings['skin'] = 'chameleon'
    else:
        rc_settings['skin'] = 'larry'

    want_files = [
        'acl.inc.php', 'calendar.inc.php', 'config.inc.php',
        'kolab_addressbook.inc.php', 'kolab_auth.inc.php',
        'kolab_delegation.inc.php', 'kolab_files.inc.php',
        'kolab_folders.inc.php', 'libkolab.inc.php', 'managesieve.inc.php',
        'owncloud.inc.php', 'password.inc.php', 'recipient_to_contact.inc.php',
        'terms.html', 'terms.inc.php'
    ]

    for want_file in want_files:
        template_file = None
        if os.path.isfile('/etc/kolab/templates/roundcubemail/%s.tpl' %
                          (want_file)):
            template_file = '/etc/kolab/templates/roundcubemail/%s.tpl' % (
                want_file)
        elif os.path.isfile('/usr/share/kolab/templates/roundcubemail/%s.tpl' %
                            (want_file)):
            template_file = '/usr/share/kolab/templates/roundcubemail/%s.tpl' % (
                want_file)
        elif os.path.isfile(
                os.path.abspath(
                    os.path.join(__file__, '..', '..', '..', 'share',
                                 'templates', 'roundcubemail',
                                 '%s.tpl' % (want_file)))):
            template_file = os.path.abspath(
                os.path.join(__file__, '..', '..', '..', 'share', 'templates',
                             'roundcubemail', '%s.tpl' % (want_file)))

        if not template_file == None:
            log.debug(_("Using template file %r") % (template_file), level=8)
            fp = open(template_file, 'r')
            template_definition = fp.read()
            fp.close()

            t = Template(template_definition, searchList=[rc_settings])
            log.debug(
                _("Successfully compiled template %r, writing out to %r") %
                (template_file, want_file),
                level=8)

            fp = None
            if os.path.isdir('/etc/roundcubemail'):
                fp = open('/etc/roundcubemail/%s' % (want_file), 'w')
            elif os.path.isdir('/etc/roundcube'):
                fp = open('/etc/roundcube/%s' % (want_file), 'w')

            if not fp == None:
                fp.write(t.__str__())
                fp.close()

    schema_files = []
    for root, directories, filenames in os.walk('/usr/share/doc/'):
        directories.sort()
        for directory in directories:
            if directory.startswith("roundcubemail"):
                for nested_root, nested_directories, nested_filenames in os.walk(
                        os.path.join(root, directory)):
                    for filename in nested_filenames:
                        if filename.startswith(
                                'mysql.initial') and filename.endswith('.sql'):
                            schema_filepath = os.path.join(
                                nested_root, filename)
                            if not schema_filepath in schema_files:
                                schema_files.append(schema_filepath)

                if len(schema_files) > 0:
                    break
        if len(schema_files) > 0:
            break

    for root, directories, filenames in os.walk(
            rcpath + 'plugins/calendar/drivers/kolab/'):
        for filename in filenames:
            if filename.startswith('mysql') and filename.endswith('.sql'):
                schema_filepath = os.path.join(root, filename)
                if not schema_filepath in schema_files:
                    schema_files.append(schema_filepath)

    for root, directories, filenames in os.walk(rcpath + 'plugins/libkolab/'):
        for filename in filenames:
            if filename.startswith('mysql') and filename.endswith('.sql'):
                schema_filepath = os.path.join(root, filename)
                if not schema_filepath in schema_files:
                    schema_files.append(schema_filepath)

    for root, directories, filenames in os.walk('/usr/share/doc/'):
        directories.sort()
        for directory in directories:
            if directory.startswith("chwala"):
                for nested_root, nested_directories, nested_filenames in os.walk(
                        os.path.join(root, directory)):
                    for filename in nested_filenames:
                        if filename.startswith(
                                'mysql.initial') and filename.endswith('.sql'):
                            schema_filepath = os.path.join(
                                nested_root, filename)
                            if not schema_filepath in schema_files:
                                schema_files.append(schema_filepath)

                if len(schema_files) > 0:
                    break
        if len(schema_files) > 0:
            break

    if not os.path.isfile('/tmp/kolab-setup-my.cnf'):
        utils.multiline_message("""Please supply the MySQL root password""")

        mysql_root_password = utils.ask_question(_("MySQL root password"),
                                                 password=True)

        data = """
[mysql]
user=root
password='******'
""" % (mysql_root_password)

        fp = open('/tmp/kolab-setup-my.cnf', 'w')
        os.chmod('/tmp/kolab-setup-my.cnf', 0600)
        fp.write(data)
        fp.close()

    p1 = subprocess.Popen(['echo', 'create database roundcube;'],
                          stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf'],
                          stdin=p1.stdout)
    p1.stdout.close()
    p2.communicate()

    p1 = subprocess.Popen([
        'echo',
        'GRANT ALL PRIVILEGES ON roundcube.* TO \'roundcube\'@\'localhost\' IDENTIFIED BY \'%s\';'
        % (mysql_roundcube_password)
    ],
                          stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf'],
                          stdin=p1.stdout)
    p1.stdout.close()
    p2.communicate()

    for schema_file in schema_files:
        p1 = subprocess.Popen(['cat', schema_file], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(
            ['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf', 'roundcube'],
            stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

    p1 = subprocess.Popen(['echo', 'FLUSH PRIVILEGES;'],
                          stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf'],
                          stdin=p1.stdout)
    p1.stdout.close()
    p2.communicate()

    time.sleep(2)

    # Find Roundcube configuration that is not readable by the
    # webserver user/group.
    if os.path.isdir('/etc/roundcubemail/'):
        rccpath = "/etc/roundcubemail/"
    elif os.path.isdir('/etc/roundcube/'):
        rccpath = "/etc/roundcube"
    else:
        log.warning(
            _("Cannot find the configuration directory for roundcube."))
        rccpath = None

    root_uid = 0

    webserver_gid = None

    for webserver_group in ['apache', 'www-data', 'www']:
        try:
            (a, b, webserver_gid, c) = grp.getgrnam(webserver_group)
            break
        except Exception, errmsg:
            pass
Exemple #10
0
def execute(*args, **kw):
    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'restart', 'mysqld.service'])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['/sbin/service', 'mysqld', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service','mysql','restart'])
    else:
        log.error(_("Could not start the MySQL database service."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'enable', 'mysqld.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'mysqld', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'mysql', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "MySQL database service."))

    options = {
            1: "Existing MySQL server (with root password already set).",
            2: "New MySQL server (needs to be initialized)."
        }

    answer = 0
    if os.path.exists('/var/run/mysqld/mysqld.sock'):
        answer = utils.ask_menu(_("What MySQL server are we setting up?"), options)

    if answer == "1" or answer == 1:
        print >> sys.stderr, utils.multiline_message(
                _("""
                        Please supply the root password for MySQL, so we can set
                        up user accounts for other components that use MySQL.
                    """)
            )

        mysql_root_password = utils.ask_question(
                _("MySQL root password"),
                password=True
            )

    else:
        print >> sys.stderr, utils.multiline_message(
                _("""
                        Please supply a root password for MySQL. This password
                        will be the administrative user for this MySQL server,
                        and it should be kept a secret. After this setup process
                        has completed, Kolab is going to discard and forget
                        about this password, but you will need it for
                        administrative tasks in MySQL.
                    """)
            )

        mysql_root_password = utils.ask_question(
                _("MySQL root password"),
                default=utils.generate_password(),
                password=True,
                confirm=True
            )

        p1 = subprocess.Popen(['echo', 'UPDATE mysql.user SET Password=PASSWORD(\'%s\') WHERE User=\'root\';' % (mysql_root_password)], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

        p1 = subprocess.Popen(['echo', 'FLUSH PRIVILEGES;'], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

    data = """
[mysql]
user=root
password='******'
""" % (mysql_root_password)

    fp = open('/tmp/kolab-setup-my.cnf', 'w')
    os.chmod('/tmp/kolab-setup-my.cnf', 0600)
    fp.write(data)
    fp.close()

    schema_file = None
    for root, directories, filenames in os.walk('/usr/share/doc/'):
        for filename in filenames:
            if filename.startswith('kolab_wap') and filename.endswith('.sql'):
                schema_file = os.path.join(root,filename)

    if not schema_file == None:
        p1 = subprocess.Popen(['echo', 'create database kolab;'], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

        print >> sys.stderr, utils.multiline_message(
                _("""
                        Please supply a password for the MySQL user 'kolab'.
                        This password will be used by Kolab services, such as
                        the Web Administration Panel.
                    """)
            )

        mysql_kolab_password = utils.ask_question(
                _("MySQL kolab password"),
                default=utils.generate_password(),
                password=True,
                confirm=True
            )

        p1 = subprocess.Popen(['echo', 'GRANT ALL PRIVILEGES ON kolab.* TO \'kolab\'@\'localhost\' IDENTIFIED BY \'%s\';' % (mysql_kolab_password)], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

        p1 = subprocess.Popen(['cat', schema_file], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf', 'kolab'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

        conf.command_set('kolab_wap', 'sql_uri', 'mysql://*****:*****@localhost/kolab' % (mysql_kolab_password))
    else:
        log.warning(_("Could not find the MySQL Kolab schema file"))
Exemple #11
0
    def to_message(self, creator=None):
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEBase import MIMEBase
        from email.MIMEText import MIMEText
        from email.Utils import COMMASPACE, formatdate

        msg = MIMEMultipart()
        organizer = self.get_organizer()
        email = organizer.email()
        name = organizer.name()

        if creator:
            msg['From'] = creator
        elif not name:
            msg['From'] = email
        else:
            msg['From'] = '"%s" <%s>' % (name, email)

        msg['To'] = ', '.join([x.__str__() for x in self.get_attendees()])
        msg['Date'] = formatdate(localtime=True)

        msg.add_header('X-Kolab-MIME-Version', '3.0')
        msg.add_header('X-Kolab-Type', 'application/x-vnd.kolab.' + self.type)

        text = utils.multiline_message("""
                    This is a Kolab Groupware object. To view this object you
                    will need an email client that understands the Kolab
                    Groupware format. For a list of such email clients please
                    visit http://www.kolab.org/
            """)

        msg.attach( MIMEText(text) )

        part = MIMEBase('application', "calendar+xml")
        part.set_charset('UTF-8')

        msg["Subject"] = self.get_uid()

        # extract attachment data into separate MIME parts
        vattach = self.event.attachments()
        i = 0
        for attach in vattach:
            if attach.uri():
                continue

            mimetype = attach.mimetype()
            (primary, seconday) = mimetype.split('/')
            name = attach.label()
            if not name:
                name = 'unknown.x'

            (basename, suffix) = path.splitext(name)
            t = datetime.datetime.now()
            cid = "%s.%s.%s%s" % (basename, time.mktime(t.timetuple()), t.microsecond + len(self._attachment_parts), suffix)

            p = MIMEBase(primary, seconday)
            p.add_header('Content-Disposition', 'attachment', filename=name)
            p.add_header('Content-Transfer-Encoding', 'base64')
            p.add_header('Content-ID', '<' + cid + '>')
            p.set_payload(base64.b64encode(attach.data()))

            self._attachment_parts.append(p)

            # modify attachment object
            attach.setData('', mimetype)
            attach.setUri('cid:' + cid, mimetype)
            vattach[i] = attach
            i += 1

        self.event.setAttachments(vattach)

        part.set_payload(str(self))

        part.add_header('Content-Disposition', 'attachment; filename="kolab.xml"')
        part.replace_header('Content-Transfer-Encoding', '8bit')

        msg.attach(part)

        # append attachment parts
        for p in self._attachment_parts:
            msg.attach(p)

        return msg
Exemple #12
0
def execute(*args, **kw):
    print >> sys.stderr, utils.multiline_message(
            _("""
                    Please supply a password for the MySQL user 'roundcube'.
                    This password will be used by the Roundcube webmail
                    interface.
                """)
        )

    mysql_roundcube_password = utils.ask_question(
            _("MySQL roundcube password"),
            default=utils.generate_password(),
            password=True,
            confirm=True
        )

    conf.mysql_roundcube_password = mysql_roundcube_password

    rc_settings = {
            'des_key': re.sub(
                    r'[^a-zA-Z0-9]',
                    "",
                    "%s%s" % (
                            hashlib.md5("%s" % random.random()).digest().encode("base64"),
                            hashlib.md5("%s" % random.random()).digest().encode("base64")
                        )
                )[:24],

            'imap_admin_login': conf.get('cyrus-imap', 'admin_login'),
            'imap_admin_password': conf.get('cyrus-imap', 'admin_password'),
            'ldap_base_dn': conf.get('ldap', 'base_dn'),
            'ldap_group_base_dn': conf.get('ldap', 'group_base_dn'),
            'ldap_group_filter': conf.get('ldap', 'group_filter'),
            'ldap_ldap_uri': conf.get('ldap', 'ldap_uri'),
            'ldap_service_bind_dn': conf.get('ldap', 'service_bind_dn'),
            'ldap_service_bind_pw': conf.get('ldap', 'service_bind_pw'),
            'ldap_user_base_dn': conf.get('ldap', 'user_base_dn'),
            'ldap_user_filter': conf.get('ldap', 'user_filter'),
            'mysql_uri': 'mysqli://*****:*****@localhost/roundcube' % (mysql_roundcube_password),
            'conf': conf
        }


    want_files = [
            'acl.inc.php',
            'calendar.inc.php',
            'db.inc.php',
            'kolab_auth.inc.php',
            'kolab_folders.inc.php',
            'kolab.inc.php',
            'main.inc.php',
            'managesieve.inc.php',
            'owncloud.inc.php',
            'password.inc.php',
            'recipient_to_contact.inc.php',
            'terms.html',
            'terms.inc.php'
        ]

    for want_file in want_files:
        template_file = None
        if os.path.isfile('/etc/kolab/templates/roundcubemail/%s.tpl' % (want_file)):
            template_file = '/etc/kolab/templates/roundcubemail/%s.tpl' % (want_file)
        elif os.path.isfile('/usr/share/kolab/templates/roundcubemail/%s.tpl' % (want_file)):
            template_file = '/usr/share/kolab/templates/roundcubemail/%s.tpl' % (want_file)
        elif os.path.isfile(os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'roundcubemail', '%s.tpl' % (want_file)))):
            template_file = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'share', 'templates', 'roundcubemail', '%s.tpl' % (want_file)))

        if not template_file == None:
            log.debug(_("Using template file %r") % (template_file), level=8)
            fp = open(template_file, 'r')
            template_definition = fp.read()
            fp.close()

            t = Template(template_definition, searchList=[rc_settings])
            log.debug(
                    _("Successfully compiled template %r, writing out to %r") % (template_file, want_file),
                    level=8
                )
            if os.path.isdir('/etc/roundcubemail'):
                fp = open('/etc/roundcubemail/%s' % (want_file), 'w')
            elif os.path.isdir('/etc/roundcube'):
                fp = open('/etc/roundcube/%s' % (want_file), 'w')
            fp.write(t.__str__())
            fp.close()

    schema_files = []
    for root, directories, filenames in os.walk('/usr/share/doc/'):
        for filename in filenames:
            if filename.startswith('mysql.initial') and filename.endswith('.sql'):
                schema_filepath = os.path.join(root,filename)
                if not schema_filepath in schema_files:
                    schema_files.append(schema_filepath)

            if filename.startswith('horde_cache') and filename.endswith('.sql'):
                schema_filepath = os.path.join(root,filename)
                if not schema_filepath in schema_files:
                    schema_files.append(schema_filepath)

    if os.path.isdir('/usr/share/roundcubemail'):
        rcpath = '/usr/share/roundcubemail/'
    elif os.path.isdir('/usr/share/roundcube'):
        rcpath = '/usr/share/roundcube/'
    for root, directories, filenames in os.walk(rcpath + 'plugins/calendar/drivers/kolab/'):
        for filename in filenames:
            if filename.startswith('mysql') and filename.endswith('.sql'):
                schema_filepath = os.path.join(root,filename)
                if not schema_filepath in schema_files:
                    schema_files.append(schema_filepath)

    for root, directories, filenames in os.walk(rcpath + 'plugins/libkolab/'):
        for filename in filenames:
            if filename.startswith('mysql') and filename.endswith('.sql'):
                schema_filepath = os.path.join(root,filename)
                if not schema_filepath in schema_files:
                    schema_files.append(schema_filepath)

    p1 = subprocess.Popen(['echo', 'create database roundcube;'], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf'], stdin=p1.stdout)
    p1.stdout.close()
    p2.communicate()

    p1 = subprocess.Popen(['echo', 'GRANT ALL PRIVILEGES ON roundcube.* TO \'roundcube\'@\'localhost\' IDENTIFIED BY \'%s\';' % (mysql_roundcube_password)], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf'], stdin=p1.stdout)
    p1.stdout.close()
    p2.communicate()

    for schema_file in schema_files:
        p1 = subprocess.Popen(['cat', schema_file], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf', 'roundcube'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

    p1 = subprocess.Popen(['echo', 'FLUSH PRIVILEGES;'], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf'], stdin=p1.stdout)
    p1.stdout.close()
    p2.communicate()

    time.sleep(2)

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'restart', 'httpd.service'])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['/sbin/service', 'httpd', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service','apache2','restart'])
    else:
        log.error(_("Could not start the webserver server service."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'enable', 'httpd.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'httpd', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'apache2', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "webserver server service."))
Exemple #13
0
def execute(*args, **kw):
    ask_questions = True

    if not conf.config_file == conf.defaults.config_file:
        ask_questions = False

    if conf.without_ldap:
        print >> sys.stderr, _("Skipping setup of LDAP, as specified")
        return

    _input = {}

    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:
        print >> sys.stderr, utils.multiline_message(
            _("""
                        You can not configure Kolab to run against OpenLDAP
                        and Active Directory simultaneously.
                    """))

        sys.exit(1)

    # Pre-execution checks
    for path, directories, files in os.walk('/etc/dirsrv/'):
        for direct in directories:
            if direct.startswith('slapd-'):
                print >> sys.stderr, utils.multiline_message(
                    _("""
                                It seems 389 Directory Server has an existing
                                instance configured. This setup script does not
                                intend to destroy or overwrite your data. Please
                                make sure /etc/dirsrv/ and /var/lib/dirsrv/ are
                                clean so that this setup does not have to worry.
                            """))

                sys.exit(1)

    _input = {}

    if ask_questions:
        print >> sys.stderr, utils.multiline_message(
            _("""
                        Please supply a password for the LDAP administrator user
                        'admin', used to login to the graphical console of 389
                        Directory server.
                    """))

        _input['admin_pass'] = utils.ask_question(
            _("Administrator password"),
            default=utils.generate_password(),
            password=True,
            confirm=True)

        if conf.directory_manager_pwd is not None:
            _input['dirmgr_pass'] = conf.directory_manager_pwd
        else:
            print >> sys.stderr, utils.multiline_message(
                _("""
                        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.
                    """))

            _input['dirmgr_pass'] = utils.ask_question(
                _("Directory Manager password"),
                default=utils.generate_password(),
                password=True,
                confirm=True)

        print >> sys.stderr, utils.multiline_message(
            _("""
                        Please choose the system user and group the service
                        should use to run under. These should be existing,
                        unprivileged, local system POSIX accounts with no shell.
                    """))

        try:
            pw = pwd.getpwnam("dirsrv")
        except:
            _input['userid'] = utils.ask_question(_("User"), default="nobody")
            _input['group'] = utils.ask_question(_("Group"), default="nobody")
        else:
            _input['userid'] = utils.ask_question(_("User"), default="dirsrv")
            _input['group'] = utils.ask_question(_("Group"), default="dirsrv")

    else:
        _input['admin_pass'] = conf.get('ldap', 'bind_pw')
        _input['dirmgr_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.

    if conf.fqdn:
        _input['fqdn'] = conf.fqdn
        _input['hostname'] = conf.fqdn.split('.')[0]
        _input['domain'] = '.'.join(conf.fqdn.split('.')[1:])
    else:
        _input['fqdn'] = fqdn
        _input['hostname'] = hostname.split('.')[0]
        _input['domain'] = domainname
    _input['nodotdomain'] = _input['domain'].replace('.', '_')

    _input['rootdn'] = utils.standard_root_dn(_input['domain'])

    if ask_questions:
        print >> sys.stderr, utils.multiline_message(
            _("""
                        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.
                    """))

        answer = utils.ask_confirmation("%s" % (_input['domain']))

        if not answer:
            positive_answer = False
            while not positive_answer:
                _input['domain'] = utils.ask_question(_("Domain name to use"))
                if not _input['domain'] == None and not _input['domain'] == "":
                    positive_answer = True
                else:
                    print >> sys.stderr, utils.multiline_message(
                        _("""
                                    Invalid input. Please try again.
                                """))

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

        print >> sys.stderr, utils.multiline_message(
            _("""
                        The standard root dn we composed for you follows. Please
                        confirm this is the root dn you wish to use.
                    """))

        answer = utils.ask_confirmation("%s" % (_input['rootdn']))

        if not answer:
            positive_answer = False
            while not positive_answer:
                _input['rootdn'] = utils.ask_question(_("Root DN to use"))
                if not _input['rootdn'] == None and not _input['rootdn'] == "":
                    positive_answer = True
                else:
                    print >> sys.stderr, utils.multiline_message(
                        _("""
                                    Invalid input. Please try again.
                                """))

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

    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
""" % (_input)

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

    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.pl"):
        setup_ds_admin = "/usr/sbin/setup-ds.pl"
    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)

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

    print >> sys.stderr, utils.multiline_message(
        _("""
                    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"))

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

    (stdoutdata, stderrdata) = setup_389.communicate()

    if not setup_389.returncode == 0:
        print >> sys.stderr, utils.multiline_message(
            _("""
                        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 not 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 = None
    for root, directories, filenames in os.walk('/usr/share/doc/'):
        for filename in filenames:
            if filename.startswith('kolab') and filename.endswith(
                    '.ldif') and schema_file == None:
                schema_file = os.path.join(root, filename)

    if not schema_file == 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 os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'restart', 'dirsrv.target'])
        time.sleep(20)
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['/sbin/service', 'dirsrv', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service', 'dirsrv', 'stop'])
        time.sleep(20)
        subprocess.call(['/usr/sbin/service', 'dirsrv', 'start'])
    else:
        log.error(_("Could not start the directory server service."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'enable', 'dirsrv.target'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'dirsrv', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'dirsrv', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "directory server service."))

    if ask_questions:
        print >> sys.stderr, utils.multiline_message(
            _("""
                        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.
                    """))

        _input['cyrus_admin_pass'] = utils.ask_question(
            _("Cyrus Administrator password"),
            default=utils.generate_password(),
            password=True,
            confirm=True)

        print >> sys.stderr, utils.multiline_message(
            _("""
                        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.
                    """))

        _input['kolab_service_pass'] = utils.ask_question(
            _("Kolab Service password"),
            default=utils.generate_password(),
            password=True,
            confirm=True)

    else:
        _input['cyrus_admin_pass'] = conf.get('cyrus-imap', 'admin_password')
        _input['kolab_service_pass'] = conf.get('ldap', 'service_bind_pw')

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

    # Write out kolab configuration
    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', 'bind_pw', _input['dirmgr_pass'])
    conf.command_set(
        'ldap', 'service_bind_dn',
        'uid=kolab-service,ou=Special Users,%s' % (_input['rootdn']))
    conf.command_set('ldap', 'service_bind_pw', _input['kolab_service_pass'])

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

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

    # Insert service users
    auth = Auth(_input['domain'])
    auth.connect()
    auth._auth.connect()
    auth._auth._bind(bind_dn='cn=Directory Manager',
                     bind_pw=_input['dirmgr_pass'])

    dn = 'uid=%s,ou=Special Users,%s' % (conf.get(
        'cyrus-imap', 'admin_login'), _input['rootdn'])

    # 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'] = _input['cyrus_admin_pass']

    # 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)

    conf.command_set('cyrus-imap', 'admin_password',
                     _input['cyrus_admin_pass'])

    dn = 'uid=kolab-service,ou=Special Users,%s' % (_input['rootdn'])

    # 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'] = _input['kolab_service_pass']
    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' % (_input['rootdn'])

    # 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' % (_input['rootdn'])

    # 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"
    attrs[
        'aci'] = '(targetattr = "*") (version 3.0;acl "Kolab Services";allow (read,compare,search)(userdn = "ldap:///uid=kolab-service,ou=Special Users,%s");)' % (
            _input['rootdn'])

    # 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(
        _("Adding domain %s to list of domains for this deployment") %
        (_input['domain']))
    dn = "associateddomain=%s,cn=kolab,cn=config" % (_input['domain'])
    attrs = {}
    attrs['objectclass'] = ['top', 'domainrelatedobject']
    attrs['associateddomain'] = [
        '%s' % (_input['domain']),
        '%s' % (_input['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(
        _input['domain']))
    attrs['associateddomain'] = [_input['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 not _input['rootdn'] == utils.standard_root_dn(_input['domain']):
        attrs['objectclass'].append('inetdomain')
        attrs['inetdomainbasedn'] = _input['rootdn']

    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)

    # Add kolab-admin role
    log.info(_("Adding the kolab-admin role"))
    dn = "cn=kolab-admin,%s" % (_input['rootdn'])
    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)

    # User writeable attributes on root_dn
    log.info(_("Setting access control to %s") % (_input['rootdn']))
    dn = _input['rootdn']
    aci = []

    if schema_error:
        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)

    if os.path.isfile('/bin/systemctl'):
        if not os.path.isfile('/usr/lib/systemd/system/dirsrv-admin.service'):
            log.info(_("directory server admin service not available"))
        else:
            subprocess.call(
                ['/bin/systemctl', 'enable', 'dirsrv-admin.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'dirsrv-admin', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'dirsrv-admin', 'defaults'])
    else:
        log.error(_("Could not start and configure to start on boot, the " + \
                "directory server admin service."))
Exemple #14
0
def execute(*args, **kw):

    socket_paths = [
            "/var/lib/mysql/mysql.sock",
            "/var/run/mysqld/mysqld.sock",
            "/var/run/mysql/mysql.sock",
            "/var/run/mysqld/mysqld.pid"
        ]

    # on CentOS7, there is MariaDB instead of MySQL
    mysqlservice = 'mysqld.service'
    if os.path.isfile('/usr/lib/systemd/system/mariadb.service'):
        mysqlservice = 'mariadb.service'
    elif os.path.isfile('/usr/lib/systemd/system/mysql.service'):
        mysqlservice = 'mysql.service'
    if not os.path.isfile('/usr/lib/systemd/system/' + mysqlservice):
        # on Debian Jessie, systemctl restart mysql
        mysqlservice = 'mysql'

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'restart', mysqlservice])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['/sbin/service', 'mysqld', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service','mysql','restart'])
    else:
        log.error(_("Could not start the MySQL database service."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'enable', mysqlservice])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'mysqld', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'mysql', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "MySQL database service."))

    log.info(_("Waiting for at most 30 seconds for MySQL/MariaDB to settle..."))
    max_wait = 30
    while max_wait > 0:
        for socket_path in socket_paths:
            if os.path.exists(socket_path):
                max_wait = 0

        if max_wait > 0:
            max_wait = max_wait - 1
            time.sleep(1)

    options = {
            1: "Existing MySQL server (with root password already set).",
            2: "New MySQL server (needs to be initialized)."
        }

    answer = 0
    if len([x for x in socket_paths if os.path.exists(x)]) > 0:
        if conf.mysqlserver:
            if conf.mysqlserver == 'existing':
                answer = 1
            elif conf.mysqlserver == 'new':
                answer = 2
        if answer == 0:
            answer = utils.ask_menu(_("What MySQL server are we setting up?"), options)

    if answer == "1" or answer == 1:
        print >> sys.stderr, utils.multiline_message(
                _("""
                        Please supply the root password for MySQL, so we can set
                        up user accounts for other components that use MySQL.
                    """)
            )

        mysql_root_password = utils.ask_question(
                _("MySQL root password"),
                password=True
            )

    else:
        print >> sys.stderr, utils.multiline_message(
                _("""
                        Please supply a root password for MySQL. This password
                        will be the administrative user for this MySQL server,
                        and it should be kept a secret. After this setup process
                        has completed, Kolab is going to discard and forget
                        about this password, but you will need it for
                        administrative tasks in MySQL.
                    """)
            )

        mysql_root_password = utils.ask_question(
                _("MySQL root password"),
                default=utils.generate_password(),
                password=True,
                confirm=True
            )

        p1 = subprocess.Popen(['echo', 'UPDATE mysql.user SET Password=PASSWORD(\'%s\') WHERE User=\'root\';' % (mysql_root_password)], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

        p1 = subprocess.Popen(['echo', 'FLUSH PRIVILEGES;'], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

    data = """
[mysql]
user=root
password='******'
""" % (mysql_root_password)

    fp = open('/tmp/kolab-setup-my.cnf', 'w')
    os.chmod('/tmp/kolab-setup-my.cnf', 0600)
    fp.write(data)
    fp.close()

    schema_file = None
    for root, directories, filenames in os.walk('/usr/share/doc/'):
        for filename in filenames:
            if filename.startswith('kolab_wap') and filename.endswith('.sql'):
                # Skip the Oracle file
                if filename.endswith('oracle.sql'):
                    continue

                schema_file = os.path.join(root,filename)

    if not schema_file == None:
        p1 = subprocess.Popen(['echo', 'create database kolab;'], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

        print >> sys.stderr, utils.multiline_message(
                _("""
                        Please supply a password for the MySQL user 'kolab'.
                        This password will be used by Kolab services, such as
                        the Web Administration Panel.
                    """)
            )

        mysql_kolab_password = utils.ask_question(
                _("MySQL kolab password"),
                default=utils.generate_password(),
                password=True,
                confirm=True
            )

        p1 = subprocess.Popen(['echo', 'GRANT ALL PRIVILEGES ON kolab.* TO \'kolab\'@\'localhost\' IDENTIFIED BY \'%s\';' % (mysql_kolab_password)], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

        p1 = subprocess.Popen(['cat', schema_file], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf', 'kolab'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

        conf.command_set('kolab_wap', 'sql_uri', 'mysql://*****:*****@localhost/kolab' % (mysql_kolab_password))
        conf.command_set('kolab_smtp_access_policy', 'cache_uri', 'mysql://*****:*****@localhost/kolab' % (mysql_kolab_password))
    else:
        log.warning(_("Could not find the MySQL Kolab schema file"))
Exemple #15
0
def execute(*args, **kw):
    schema_files = []
    for root, directories, filenames in os.walk('/usr/share/doc/'):
        for directory in directories:
            if directory.startswith("kolab-syncroton"):
                for root, directories, filenames in os.walk(os.path.join(root, directory)):
                    for filename in filenames:
                        if filename.startswith('mysql.initial') and filename.endswith('.sql'):
                            schema_filepath = os.path.join(root,filename)
                            if not schema_filepath in schema_files:
                                schema_files.append(schema_filepath)
                                break

                if len(schema_files) > 0:
                    break
        if len(schema_files) > 0:
            break

    if not os.path.isfile('/tmp/kolab-setup-my.cnf'):
        utils.multiline_message(
                """Please supply the MySQL root password"""
            )

        mysql_root_password = utils.ask_question(
                _("MySQL root password"),
                password=True
            )

        data = """
[mysql]
user=root
password='******'
""" % (mysql_root_password)

        fp = open('/tmp/kolab-setup-my.cnf', 'w')
        os.chmod('/tmp/kolab-setup-my.cnf', 0600)
        fp.write(data)
        fp.close()

    for schema_file in schema_files:
        p1 = subprocess.Popen(['cat', schema_file], stdout=subprocess.PIPE)
        p2 = subprocess.Popen(['mysql', '--defaults-file=/tmp/kolab-setup-my.cnf', 'roundcube'], stdin=p1.stdout)
        p1.stdout.close()
        p2.communicate()

    time.sleep(2)

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'restart', 'httpd.service'])
    elif os.path.isfile('/sbin/service'):
        subprocess.call(['/sbin/service', 'httpd', 'restart'])
    elif os.path.isfile('/usr/sbin/service'):
        subprocess.call(['/usr/sbin/service','apache2','restart'])
    else:
        log.error(_("Could not start the webserver server service."))

    if os.path.isfile('/bin/systemctl'):
        subprocess.call(['/bin/systemctl', 'enable', 'httpd.service'])
    elif os.path.isfile('/sbin/chkconfig'):
        subprocess.call(['/sbin/chkconfig', 'httpd', 'on'])
    elif os.path.isfile('/usr/sbin/update-rc.d'):
        subprocess.call(['/usr/sbin/update-rc.d', 'apache2', 'defaults'])
    else:
        log.error(_("Could not configure to start on boot, the " + \
                "webserver server service."))