Example #1
0
def removePrivileges(sambaSID, privileges):

	listener.setuid(0)

	try:
		tdbKey = 'PRIV_%s\x00' % (sambaSID)
		tdbFile = tdb.Tdb(SAMBA_POLICY_TDB)
		tdbFile.lock_all()
		privs = tdbFile.get(tdbKey)

		if privs:
			for privilege in privileges:
				if SAMBA_PRIVILEGES.get(privilege, ""):
					index = SAMBA_PRIVILEGES[privilege].get("index", "")
					number = SAMBA_PRIVILEGES[privilege].get("number", "")
					if ord(privs[index]) & number:
						new = chr(ord(privs[index]) - number)
						privs = privs[0:index] + new + privs[(index + 1):len(privs)]
						tdbFile[tdbKey] = privs

			# delete key if no privileges are assigned
			if privs == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00':
				tdbFile.delete(tdbKey)

		tdbFile.unlock_all()
		tdbFile.close()
	finally:
		listener.unsetuid()
Example #2
0
def addPrivileges( sambaSID, privileges ):

	listener.setuid(0)

	try:
		tdbKey='PRIV_%s\x00' % ( sambaSID )
		tdbFile=tdb.Tdb(SAMBA_POLICY_TDB)
		tdbFile.lock_all()
		privs = tdbFile.get(tdbKey)
		if not privs:
			privs='\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
	
		for privilege in privileges:
			if SAMBA_PRIVILEGES.get(privilege, ""):
				index = SAMBA_PRIVILEGES[privilege].get("index", 0)
				number = SAMBA_PRIVILEGES[privilege].get("number", 0)
				if (ord(privs[index]) & number) == 0:
					new = chr(ord(privs[index]) + number)
					privs = privs[0:index] + new + privs[(index+1):len(privs)]
	
		tdbFile[tdbKey]=privs
		tdbFile.unlock_all()
		tdbFile.close()
	finally:
		listener.unsetuid()
Example #3
0
def readPluginConfig():
	global __pluginconfig
	global __pluginconfdirstat

	if __pluginconfdirstat != os.stat( __pluginconfdir )[8]:
		# save modification time
		__pluginconfdirstat = os.stat( __pluginconfdir )[8]

		univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO, 'NAGIOS-CLIENT: updating plugin config')

		listener.setuid(0)
		try:
			for fn in os.listdir( __pluginconfdir ):
				fp = open( os.path.join( __pluginconfdir, fn),'r')
				content = fp.read()
				fp.close()
				for cmddef in re.split('\s*define\s+command\s*\{', content):
					mcmdname = re.search('^\s+command_name\s+(.*?)\s*$', cmddef, re.MULTILINE)
					mcmdline = re.search('^\s+command_line\s+(.*?)\s*$', cmddef, re.MULTILINE)
					if mcmdname and mcmdline:
						__pluginconfig[mcmdname.group(1)] = mcmdline.group(1)
						univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO,
											   'NAGIOS-CLIENT: read configline for plugin %s ==> %s' % (mcmdname.group(1), mcmdline.group(1)))
		finally:
			listener.unsetuid()
def handler(dn, new, old):
    # type: (str, dict, dict) -> None
    configRegistry = univention.config_registry.ConfigRegistry()
    configRegistry.load()

    old_hosteddomains = set(
        re.split('[ ]+', configRegistry.get('mail/hosteddomains', '')))
    hosteddomains = old_hosteddomains.copy()

    # remove old add new
    if old.get('cn'):
        hosteddomains.discard(old['cn'][0].decode('UTF-8'))
        univention.debug.debug(univention.debug.LISTENER,
                               univention.debug.INFO,
                               "hosteddomains: removed %r" % old['cn'][0])
    if new.get('cn'):
        hosteddomains.add(new['cn'][0].decode('UTF-8'))
        univention.debug.debug(univention.debug.LISTENER,
                               univention.debug.INFO,
                               "hosteddomains: added %r" % new['cn'][0])

    # if something changed then set UCR variable
    if old_hosteddomains != hosteddomains:
        try:
            listener.setuid(0)
            univention.debug.debug(
                univention.debug.LISTENER, univention.debug.INFO,
                "hosteddomains: %s" % u'mail/hosteddomains=%s' %
                ' '.join(hosteddomains))
            univention.config_registry.handler_set(
                [u'mail/hosteddomains=%s' % ' '.join(hosteddomains)])
        finally:
            listener.unsetuid()
Example #5
0
def license_stats():
    listener.setuid(0)
    lo = ul.getMachineConnection()
    users = lo.search('univentionOpenvpnAccount=1')
    myname = listener.baseConfig['hostname']
    me = lo.search('cn=%s' % myname)
    try:
        key = me[0][1]['univentionOpenvpnLicense'][0]
    except:
        key = ""
    listener.unsetuid()
    connected_users = userlist()

    c_connected_users = len(connected_users)
    c_users = len(users)
    c_licenced = univention_openvpn_common.maxvpnusers(0, key)
    try:
        l = univention_openvpn_common.license(0, key)
        valid = str(date.fromordinal(l['vdate']))
    except:
        valid = "No valid license on this host"

    info = {"expiration": valid, "connected": c_connected_users, "total": c_users, "licenced": c_licenced}

    count = str(len(connected_users))

    query = web.ctx.query
    if query:
        # jsonp
        queries = query.split('&')
        callback = queries[0].split('=')[1]
        return '%s({"draw": 1, "recordsTotal": %s, "recordsFiltered": %s, "info": %s});' % (callback, count, count, json.dumps(info))
    else:
        return '{"info": %s}' % json.dumps(info)
Example #6
0
def postrun():
	listener.setuid(0)
	try:
		os.spawnv(os.P_WAIT, '/bin/sh', ['sh', '/etc/init.d/samba4wins', 'stop'])
		os.spawnv(os.P_WAIT, '/bin/sh', ['sh', '/etc/init.d/samba4wins', 'start'])
	finally:
		listener.unsetuid()
Example #7
0
def run_cmd(command, *expected_retvals):
    cmd = ' '.join(quote(arg) for arg in command)
    ud.debug(ud.LISTENER, ud.INFO, "manageusercertificate: run %s" % cmd)
    listener.setuid(0)
    proc = subprocess.Popen(command,
                            bufsize=0,
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    stdout = None
    stderr = None
    retval = 0
    try:
        (stdout, stderr) = proc.communicate()
    finally:
        listener.unsetuid()

    if proc.returncode not in expected_retvals:
        retval = 1
        ud.debug(ud.LISTENER, ud.ERROR, "manageusercertificate: run %s" % cmd)
        ud.debug(
            ud.LISTENER, ud.ERROR,
            "manageusercertificate: command failed with exit code: %s" %
            proc.returncode)
        ud.debug(ud.LISTENER, ud.ERROR,
                 "manageusercertificate: stderr: %s" % stderr)
        ud.debug(ud.LISTENER, ud.ERROR,
                 "manageusercertificate: stdout: %s" % stderr)

    return retval
Example #8
0
def check_sitetosite(no):
    listener.setuid(0)
    lo = ul.getMachineConnection()

    servers = lo.search('(univentionOpenvpnLicense=*)')

    sitetosite = False
    for server in servers:
        key = server[1].get('univentionOpenvpnLicense', [None])[0]
        try:
            l = license(no, key)
            ud.debug(ud.LISTENER, ud.INFO, '%d Processing license with ID %s:' % (no, l['id']))
            ud.debug(ud.LISTENER, ud.INFO, '%d Valid until: %s' % (no, date.fromordinal(l['vdate'])))
            ud.debug(ud.LISTENER, ud.INFO, '%d Users: %s' % (no, l['u']))
            ud.debug(ud.LISTENER, ud.INFO, '%d Site-2-Site: %s' % (no, l['s2s']))
            if l.get('s2s'): sitetosite = True
            break
        except:
            pass
    listener.unsetuid()
    if not sitetosite:
        ud.debug(ud.LISTENER, ud.INFO, '%d Skipping actions' % no)
        return False
    else:
        return True
def update_schema(attr):
    listener.setuid(0)
    try:
        fp = open('/var/lib/univention-ldap/schema.conf.new', 'w')
    finally:
        listener.unsetuid()

    print >> fp, '# This schema was automatically replicated from the master server'
    print >> fp, '# Please do not edit this file\n'
    subschema = ldap.schema.SubSchema(attr)

    for oid in subschema_sort(subschema, ldap.schema.AttributeType):
        if oid in BUILTIN_OIDS:
            continue
        obj = subschema.get_obj(ldap.schema.AttributeType, oid)
        print >> fp, 'attributetype %s' % (obj, )

    for oid in subschema_sort(subschema, ldap.schema.ObjectClass):
        if oid in BUILTIN_OIDS:
            continue
        obj = subschema.get_obj(ldap.schema.ObjectClass, oid)
        print >> fp, 'objectclass %s' % (obj, )

    fp.close()

    # move temporary file
    listener.setuid(0)
    try:
        os.rename('/var/lib/univention-ldap/schema.conf.new',
                  '/var/lib/univention-ldap/schema.conf')
    finally:
        listener.unsetuid()

    init_slapd('restart')
Example #10
0
def handler(dn, new, old):
    """Handle change in LDAP."""
    ucr = univention.config_registry.ConfigRegistry()
    ucr.load()

    if ucr['server/role'] == 'domaincontroller_master':
        return

    listener.setuid(0)
    try:
        if 'univentionServerRole' in new:
            try:
                domain = new['associatedDomain'][0]
            except LookupError:
                domain = ucr['domainname']
            add_ldap_server(ucr, new['cn'][0], domain,
                            new['univentionServerRole'][0])
        elif 'univentionServerRole' in old and not new:
            try:
                domain = old['associatedDomain'][0]
            except LookupError:
                domain = ucr['domainname']
            remove_ldap_server(ucr, old['cn'][0], domain,
                               old['univentionServerRole'][0])
    finally:
        listener.unsetuid()
Example #11
0
def initialize():
    if not os.path.exists('/etc/samba/printers.conf.d'):
        listener.setuid(0)
        try:
            os.mkdir('/etc/samba/printers.conf.d')
        finally:
            listener.unsetuid()
def postrun():
	global s4_init_mode
	global group_objects
	global connector_needs_restart

	if s4_init_mode:
		listener.setuid(0)
		try:
			s4_init_mode = False
			for ob in group_objects:
				for directory in dirs:
					filename = os.path.join(directory, "%f" % time.time())
					f = open(filename, 'w+')
					os.chmod(filename, 0600)
					p = cPickle.Pickler(f)
					p.dump(ob)
					p.clear_memo()
					f.close()
			del group_objects
			group_objects = []
		finally:
			listener.unsetuid()

	if connector_needs_restart is True:
		_restart_connector()
		connector_needs_restart = False
Example #13
0
def removePrivileges( sambaSID, privileges ):
	
	listener.setuid(0)

	try:
		tdbKey = 'PRIV_%s\x00' % ( sambaSID )
		tdbFile = tdb.Tdb(SAMBA_POLICY_TDB)
		tdbFile.lock_all()
		privs = tdbFile.get(tdbKey)
	
		if privs:
			for privilege in privileges:
				if SAMBA_PRIVILEGES.get(privilege, ""):
					index = SAMBA_PRIVILEGES[privilege].get("index", "")
					number = SAMBA_PRIVILEGES[privilege].get("number", "")
					if ord(privs[index]) & number:
						new = chr(ord(privs[index]) - number)
						privs = privs[0:index] + new + privs[(index+1):len(privs)]
						tdbFile[tdbKey] = privs

			# delete key if no privileges are assigned
			if privs == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00':
				tdbFile.delete(tdbKey)

		tdbFile.unlock_all()
		tdbFile.close()
	finally:
		listener.unsetuid()
Example #14
0
def initialize():
	if not os.path.exists('/etc/samba/printers.conf.d'):
		listener.setuid(0)
		try:
			os.mkdir('/etc/samba/printers.conf.d')
		finally:
			listener.unsetuid()
Example #15
0
def handler(dn, new, old, command):
    ud.debug(ud.LISTENER, ud.INFO, 'manageusercertificate: handler')

    # load config registry
    cr = univention.config_registry.ConfigRegistry()
    cr.load()

    # only on master and backup
    if cr['server/role'] != 'domaincontroller_master':
        ud.debug(ud.LISTENER, ud.PROCESS,
                 'manageusercertificate: this is not a master')
        return

    # copy object "old" - otherwise it gets modified for other listener modules
    old = copy.deepcopy(old)

    # do nothing if command is 'r' ==> modrdn
    if command == 'r':
        listener.setuid(0)
        try:
            with open(FN_CACHE, 'w+') as f:
                os.chmod(FN_CACHE, 0600)
                cPickle.dump(old, f)
        except Exception, e:
            ud.debug(
                ud.LISTENER, ud.ERROR,
                'manageusercertificate: failed to open/write pickle file: %s' %
                str(e))
        listener.unsetuid()
        return
def change_net(network, netmask, ccd, fn_ips, ipv6):
    if ipv6:
        option = "ifconfig-ipv6-push"
        appendix = "/" + network.split('/')[1] + "\n"
    else:
        option = "ifconfig-push"
        appendix = " " + netmask + "\n"

    ip_map_new = []
    listener.setuid(0)
    lo = ul.getMachineConnection()
    users = lo.search('univentionOpenvpnAccount=1')
    listener.unsetuid()

    users = map(lambda user: user[1].get('uid', [None])[0], users)

    for name in users:
        ip_new = generate_ip(network, ip_map_new)
        ip_map_new.append((name, ip_new))

        # write entry in ccd
        cc = univention_openvpn_common.load_rc(3, ccd + name + ".openvpn")
        if cc is None:
            cc = []
        else:
            cc = [x for x in cc if not re.search(option, x)]
        cc.append(option + " " + ip_new + appendix)
        univention_openvpn_common.write_rc(3, cc, ccd + name + ".openvpn")

    univention_openvpn_common.write_ip_map(3, ip_map_new, fn_ips)
def handler(dn, new, old, cmd):
    ud.debug(ud.LISTENER, ud.INFO, '2 master2 handler')

    if cmd == 'n':
        return

    name = new.get('cn', [None])[0]
    port = new.get('univentionOpenvpnPort', [None])[0]
    addr = new.get('univentionOpenvpnAddress', [None])[0]

    if not name or not port or not addr:
        return

    listener.setuid(0)
    lo = ul.getMachineConnection()
    vpnusers = lo.search('(univentionOpenvpnAccount=1)')

    if not univention_openvpn_common.check_user_count(2):                                                                                                                                                                                 
        return          # do nothing

    for user in vpnusers:
        uid = user[1].get('uid', [None])[0]
        home = user[1].get('homeDirectory', ['/dev/null'])[0]
        ud.debug(ud.LISTENER, ud.INFO, '2 Create new certificate for %s in %s' % (uid, home))

        proto = 'udp6' if addr and addr.count(':') else 'udp'

        if uid and home:
        # update bundle for this openvpn server with new config
            try:
                listener.run('/usr/lib/openvpn-int/create-bundle', ['create-bundle', 'no', uid, home, name, addr, port, proto], uid=0)
            finally:
                listener.unsetuid()

    listener.unsetuid()
Example #18
0
def handler(dn, new, old):
	"""Handle changes to 'dn'."""
	setuid(0)
	try:
		# if configRegistry['server/role'] != 'domaincontroller_master':
		#	return

	        # ud.debug(ud.LISTENER, ud.INFO, 'BAREOS: handler '+dn+' '+str(bareos_gid))

		if new and not old:
			# changeType: add
		        name=getFqdn(new)
			processClient(name,new)

		elif old and not new:
			# changeType: delete
			try:
				name = getFqdn(old)
				processClient(name,old,delete=True)
			except:
				pass
		else:
			# changeType: modify
		        name=getFqdn(new)
			processClient(name,new)
	finally:
		unsetuid()
Example #19
0
def createHostExtInfo(fqdn, new):
	global __exthostinfo_mapping
	global __hostextinfodir

	fn = os.path.join( __hostextinfodir, '%s.cfg' % fqdn )

	if new:
		hosttype = getUniventionComputerType(new)
		if not __exthostinfo_mapping.has_key(hosttype):
			univention.debug.debug(univention.debug.LISTENER, univention.debug.ERROR, 'NAGIOS-SERVER: createHostExtInfo: unknown host type "%s" of %s' % (hosttype, fqdn))
			return

		listener.setuid(0)
		try:
			fp = open(fn, 'w')
			fp.write('# Warning: This file is auto-generated and might be overwritten.\n')
			fp.write('#          Please use univention-admin instead.\n')
			fp.write('# Warnung: Diese Datei wurde automatisch generiert und wird\n')
			fp.write('#          automatisch ueberschrieben. Bitte benutzen Sie\n')
			fp.write('#          stattdessen den Univention Admin.\n')
			fp.write('\n')
			fp.write('define hostextinfo {\n')
			fp.write('    host_name               %s\n' % fqdn)
			fp.write('    icon_image              %s\n' % __exthostinfo_mapping[hosttype]['icon_image'])
			fp.write('    vrml_image              %s\n' % __exthostinfo_mapping[hosttype]['vrml_image'])
			fp.write('    statusmap_image         %s\n' % __exthostinfo_mapping[hosttype]['statusmap_image'])
			fp.write('}\n')
			fp.close()

		finally:
			listener.unsetuid()

		univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO, 'NAGIOS-SERVER: extended info for host %s written' % fqdn)
def handler(dn, new, old):
    listener.setuid(0)
    try:
        portal = _load().get('portal')
        if portal is None:
            ud.debug(ud.LISTENER, ud.PROCESS,
                     'No file found. Saving default initially')
            _save_external_portal()
            portal = _load()['portal']
        if new:
            is_computer = 'univentionPortalComputer' in new['objectClass']
        else:
            is_computer = 'univentionPortalComputer' in old['objectClass']
        if is_computer:
            if new:
                portal_dn = new.get('univentionComputerPortal', [''])[0]
                if portal_dn != portal['dn']:
                    _save_external_portal(portal_dn)
        else:
            if dn == portal['dn']:
                if old and not new:
                    # Remove
                    ud.debug(ud.LISTENER, ud.WARN,
                             'Removed Portal object! Falling back to default')
                    _save_external_portal()
                else:
                    # Add or Change
                    ud.debug(ud.LISTENER, ud.PROCESS, 'Add / change obj')
                    obj = _make_obj(new)
                    _save(dn, obj)
                    _write_css(new)
    finally:
        listener.unsetuid()
Example #21
0
def postrun():
    global _s4_connector_restart
    global _relativeDomainName_trigger_set

    if not listener.configRegistry.is_true('connector/s4/autostart', True):
        univention.debug.debug(
            univention.debug.LISTENER, univention.debug.PROCESS,
            '%s: S4 Connector restart skipped, disabled via connector/s4/autostart.'
            % (name, ))
        return

    if os.path.isfile('/etc/init.d/univention-s4-connector'):
        if _s4_connector_restart:
            univention.debug.debug(univention.debug.LISTENER,
                                   univention.debug.PROCESS,
                                   '%s: Restarting S4 Connector' % (name, ))
            listener.setuid(0)
            try:
                p = subprocess.Popen(
                    ["/etc/init.d/univention-s4-connector", "restart"],
                    close_fds=True)
                p.wait()
                if p.returncode != 0:
                    ud.debug(
                        ud.LISTENER, ud.ERROR,
                        '%s: S4 Connector restart returned %s.' %
                        (name, p.returncode))
                _s4_connector_restart = False
            finally:
                listener.unsetuid()

        if _relativeDomainName_trigger_set:
            trigger_sync_ucs_to_s4()

    run_hooks("postrun")
Example #22
0
def createContact( contact ):
	global __contactsdir
	global __predefinedTimeperiod

	listener.setuid(0)
	try:
		filename = '%s%s.cfg' % (__contactsdir, contact)
		fp = open(filename, 'w')
		fp.write('# Warning: This file is auto-generated and might be overwritten.\n')
		fp.write('#          Please use univention-admin instead.\n')
		fp.write('# Warnung: Diese Datei wurde automatisch generiert und wird\n')
		fp.write('#          automatisch ueberschrieben. Bitte benutzen Sie\n')
		fp.write('#          stattdessen den Univention Admin.\n')
		fp.write('\n')
		fp.write('define contact {\n')
		fp.write('    contact_name                   %s\n' % contact)
		fp.write('    alias                          Kontakt %s\n' % contact)
		fp.write('    host_notification_period       %s\n' % __predefinedTimeperiod)
		fp.write('    service_notification_period    %s\n' % __predefinedTimeperiod)
		fp.write('    host_notification_options      d,u,r,f\n')
		fp.write('    service_notification_options   w,u,c,r,f\n')
		fp.write('    host_notification_commands     notify-host-by-email\n')
		fp.write('    service_notification_commands  notify-service-by-email\n')
		fp.write('    email                          %s\n' % contact)
		fp.write('}\n')
		fp.close()

		univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO, 'NAGIOS-SERVER: contact %s written' % contact)
	finally:
		listener.unsetuid()
Example #23
0
def handler(dn, new, old):
    ucr = ConfigRegistry()
    ucr.load()
    listener.setuid(0)
    try:
        try:
            fqdn = '%s.%s' % (new['cn'][0], new['associatedDomain'][0])
        except (KeyError, IndexError):
            return

        change = False
        if 'univention-saml' in new.get('univentionService', []):
            handler_set(['ucs/server/saml-idp-server/%s=%s' % (fqdn, fqdn)])
            change = True
        elif 'univention-saml' in old.get('univentionService', []):
            handler_unset(['ucs/server/saml-idp-server/%s' % (fqdn, )])
            change = True

        if change:
            path_to_cert = ucr.get('saml/idp/certificate/certificate')
            path_to_key = ucr.get('saml/idp/certificate/privatekey')
            if path_to_cert and os.path.exists(
                    path_to_cert) and path_to_key and os.path.exists(
                        path_to_key):
                subprocess.call(['invoke-rc.d', 'univention-saml', 'restart'])
    finally:
        listener.unsetuid()
def get_logger(name, path=None):
    """
	Get a logging instance. Caching wrapper for
	:py:func:`get_listener_logger()`.

	:param str name: name of the logger instance will be <root loggers name>.name
	:param str path: path to log file to create. If unset will be
	`/var/log/univention/listener_modules/<name>.log`.
	:return: a python logging object
	:rtype: logging.Logger
	"""
    if name not in _logger_cache:
        file_name = name.replace('/', '_')
        logger_name = name.replace('.', '_')
        log_dir = '/var/log/univention/listener_modules'
        file_path = path or os.path.join(log_dir, '{}.log'.format(file_name))
        listener_uid = pwd.getpwnam('listener').pw_uid
        adm_grp = grp.getgrnam('adm').gr_gid
        if not os.path.isdir(log_dir):
            old_uid = os.geteuid()
            try:
                if old_uid != 0:
                    listener.setuid(0)
                os.mkdir(log_dir)
                os.chown(log_dir, listener_uid, adm_grp)
                os.chmod(
                    log_dir, stat.S_ISGID | stat.S_IRUSR | stat.S_IWUSR
                    | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP)
            finally:
                if old_uid != 0:
                    listener.unsetuid()
        _logger_cache[name] = get_listener_logger(logger_name, file_path)
    return _logger_cache[name]
Example #25
0
def handler(dn, new, old):
    """Handle changes to 'dn'."""
    setuid(0)
    try:
        # if configRegistry['server/role'] != 'domaincontroller_master':
        #       return

        # ud.debug(ud.LISTENER, ud.INFO, 'BAREOS: handler '+dn+' '+str(bareos_gid))

        if new and not old:
            # changeType: add
            name = getFqdn(new)
            processClient(name, new)

        elif old and not new:
            # changeType: delete
            try:
                name = getFqdn(old)
                processClient(name, old, delete=True)
            except:
                pass
        else:
            # changeType: modify
            name = getFqdn(new)
            processClient(name, new)
    finally:
        unsetuid()
Example #26
0
def addPrivileges(sambaSID, privileges):

	listener.setuid(0)

	try:
		tdbKey = 'PRIV_%s\x00' % (sambaSID)
		tdbFile = tdb.Tdb(SAMBA_POLICY_TDB)
		tdbFile.lock_all()
		privs = tdbFile.get(tdbKey)
		if not privs:
			privs = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

		for privilege in privileges:
			if SAMBA_PRIVILEGES.get(privilege, ""):
				index = SAMBA_PRIVILEGES[privilege].get("index", 0)
				number = SAMBA_PRIVILEGES[privilege].get("number", 0)
				if (ord(privs[index]) & number) == 0:
					new = chr(ord(privs[index]) + number)
					privs = privs[0:index] + new + privs[(index + 1):len(privs)]

		tdbFile[tdbKey] = privs
		tdbFile.unlock_all()
		tdbFile.close()
	finally:
		listener.unsetuid()
def handler(dn, new, old):
	listener.setuid(0)
	try:
		if old:
			if old.get('SAMLServiceProviderIdentifier'):
				# delete old service provider config file
				old_filename = os.path.join(sp_config_dir, '%s.php' % old.get('SAMLServiceProviderIdentifier')[0].replace('/', '_'))
				if os.path.exists(old_filename):
					ud.debug(ud.LISTENER, ud.INFO, 'Deleting old SAML SP Configuration file %s' % old_filename)
					try:
						os.unlink(old_filename)
					except IOError as exc:
						ud.debug(ud.LISTENER, ud.ERROR, 'Deleting failed: %s' % (exc,))

		if new and new.get('SAMLServiceProviderIdentifier') and new.get('isServiceProviderActivated')[0] == "TRUE":
			# write new service provider config file
			filename = os.path.join(sp_config_dir, '%s.php' % new.get('SAMLServiceProviderIdentifier')[0].replace('/', '_'))
			ud.debug(ud.LISTENER, ud.INFO, 'Writing to SAML SP Configuration file %s' % filename)
			write_configuration_file(dn, new, filename)

		with open(include_file, 'w') as fd:
			fd.write('<?php\n')
			for filename in glob.glob(os.path.join(sp_config_dir, '*.php')):
				fd.write("require_once(%s);\n" % (php_string(filename),))
	finally:
		listener.unsetuid()
Example #28
0
def writeTimeperiod( filename, name, alias, periods ):
	listener.setuid(0)
	try:
		fp = open(filename, 'w')
		fp.write('# Warning: This file is auto-generated and might be overwritten.\n')
		fp.write('#          Please use univention-directory-manager instead.\n')
		fp.write('# Warnung: Diese Datei wurde automatisch generiert und wird\n')
		fp.write('#          automatisch ueberschrieben. Bitte benutzen Sie\n')
		fp.write('#          stattdessen den Univention Directory Manager.\n')
		fp.write('\n')
		fp.write('define timeperiod {\n')
		fp.write('    timeperiod_name   %s\n' % name)
		fp.write('    alias             %s\n' % alias)

		if periods[0]:
			fp.write('    monday            %s\n' % periods[0])
		if periods[1]:
			fp.write('    tuesday           %s\n' % periods[1])
		if periods[2]:
			fp.write('    wednesday         %s\n' % periods[2])
		if periods[3]:
			fp.write('    thursday          %s\n' % periods[3])
		if periods[4]:
			fp.write('    friday            %s\n' % periods[4])
		if periods[5]:
			fp.write('    saturday          %s\n' % periods[5])
		if periods[6]:
			fp.write('    sunday            %s\n' % periods[6])
		fp.write('}\n')
		fp.close()

		univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO, 'NAGIOS-SERVER: timeperiod %s written' % name)
	finally:
		listener.unsetuid()
Example #29
0
def handleService(dn, new, old):
	global __servicesdir
	global __contactgrpsdir
	if old:
		listener.setuid(0)
		try:
			for fn in os.listdir( __servicesdir ):
				if fn.find( "%s," % old['cn'][0] ) == 0:
					os.unlink( os.path.join( __servicesdir, fn) )
		finally:
			listener.unsetuid()


	if new:
		listener.setuid(0)
		try:
			if new.has_key('univentionNagiosHostname') and new['univentionNagiosHostname']:
				for host in new['univentionNagiosHostname']:
					filename = os.path.join( __servicesdir, '%s,%s.cfg' % (new['cn'][0], host))
					fp = open(filename, 'w')
					fp.write('# Warning: This file is auto-generated and might be overwritten.\n')
					fp.write('#          Please use univention-admin instead.\n')
					fp.write('# Warnung: Diese Datei wurde automatisch generiert und wird\n')
					fp.write('#          automatisch ueberschrieben. Bitte benutzen Sie\n')
					fp.write('#          stattdessen den Univention Admin.\n')
					fp.write('\n')
					fp.write('define service {\n')
					fp.write('    host_name               %s\n' % host)
					fp.write('    service_description     %s\n' % new['cn'][0])

					if new.has_key('univentionNagiosUseNRPE') and new['univentionNagiosUseNRPE'] and new['univentionNagiosUseNRPE'][0] == '1':
						fp.write('    check_command           check_nrpe_1arg!%s\n' % new['cn'][0])
					else:
						if new.has_key('univentionNagiosCheckArgs') and new['univentionNagiosCheckArgs'] and new['univentionNagiosCheckArgs'][0]:
							fp.write('    check_command           %s!%s\n' % (new['univentionNagiosCheckCommand'][0],
																			  new['univentionNagiosCheckArgs'][0]))
						else:
							fp.write('    check_command           %s\n' % new['univentionNagiosCheckCommand'][0])

					fp.write('    normal_check_interval   %s\n' % new['univentionNagiosNormalCheckInterval'][0])
					fp.write('    retry_check_interval    %s\n' % new['univentionNagiosRetryCheckInterval'][0])
					fp.write('    max_check_attempts      %s\n' % new['univentionNagiosMaxCheckAttempts'][0])
					fp.write('    check_period            %s\n' % new['univentionNagiosCheckPeriod'][0])
					fp.write('    notification_interval   %s\n' % new['univentionNagiosNotificationInterval'][0])
					fp.write('    notification_period     %s\n' % new['univentionNagiosNotificationPeriod'][0])
					fp.write('    notification_options    %s\n' % new['univentionNagiosNotificationOptions'][0])
					fp.write('    contact_groups          cg-%s\n' % host)
					fp.write('}\n')
					fp.close()

					cg_filename = os.path.join( __contactgrpsdir, 'cg-%s.cfg' % host)
					if not os.path.exists( cg_filename ):
						univention.debug.debug(univention.debug.LISTENER, univention.debug.ERROR,
											   'NAGIOS-SERVER: handleService: contactgrp for host %s does not exist - using fallback' % host)

						createContactGroup( 'cg-%s' % host, [ __fallbackContact ] )
						listener.setuid(0)

		finally:
			listener.unsetuid()
Example #30
0
def handler(dn, new, old):
	global keytab

	configRegistry = univention.config_registry.ConfigRegistry()
	configRegistry.load()

	server_role = configRegistry['server/role']
	if server_role == 'domaincontroller_master':
			
		if not new.get('krb5Key'):
			return

		listener.setuid(0)
		try:
			if old:
				try:
					os.unlink('/var/lib/univention-heimdal/%s' %old['cn'][0])
				except:
					pass
			if new:
				#FIXME: otherwise the keytab entry is duplicated
				os.spawnv(os.P_WAIT, '/usr/sbin/kadmin', ['kadmin', '-l', 'ext', '--keytab=/var/lib/univention-heimdal/%s' % new['cn'][0], new['krb5PrincipalName'][0]])
				try:
					userID=pwd.getpwnam('%s$'%new['cn'][0])[2]
					os.chown('/var/lib/univention-heimdal/%s' %new['cn'][0], userID, 0)
					os.chmod('/var/lib/univention-heimdal/%s' %new['cn'][0],0660)
				except:
					pass


		finally:
			listener.unsetuid()
def clean():
    global slave
    if not slave:
        return 1
    ud.debug(ud.LISTENER, ud.INFO, 'replication: removing cache')
    # init_slapd('stop')

    # FIXME
    listener.run('/usr/bin/killall', ['killall', '-9', 'slapd'], uid=0)
    time.sleep(1)  # FIXME

    dirname = '/var/lib/univention-ldap/ldap'
    listener.setuid(0)
    try:
        for f in os.listdir(dirname):
            filename = os.path.join(dirname, f)
            try:
                os.unlink(filename)
            except OSError:
                pass
        if os.path.exists(LDIF_FILE):
            os.unlink(LDIF_FILE)
    finally:
        listener.unsetuid()
    listener.run('/usr/sbin/univention-config-registry', [
        'univention-config-registry', 'commit',
        '/var/lib/univention-ldap/ldap/DB_CONFIG'
    ],
                 uid=0)
Example #32
0
def update_schema(attr):
	listener.setuid(0)
	try:
		fp = open('/var/lib/univention-ldap/schema.conf.new', 'w')
	finally:
		listener.unsetuid()

	queue = []

	print >>fp, '# This schema was automatically replicated from the master server'
	print >>fp, '# Please do not edit this file\n'
	subschema = ldap.schema.SubSchema(attr)

	for oid in subschema_sort(subschema, ldap.schema.AttributeType):
		if oid in BUILTIN_OIDS:
			continue
		obj = subschema.get_obj(ldap.schema.AttributeType, oid)
		print >>fp, 'attributetype', str(obj)

	for oid in subschema_sort(subschema, ldap.schema.ObjectClass):
		if oid in BUILTIN_OIDS:
			continue
		obj = subschema.get_obj(ldap.schema.ObjectClass, oid)
		print >>fp, 'objectclass', str(obj)

	fp.close()

	# move temporary file
	listener.setuid(0)
	try:
		os.rename('/var/lib/univention-ldap/schema.conf.new', '/var/lib/univention-ldap/schema.conf')
	finally:
		listener.unsetuid()

	init_slapd('restart')
def handler(dn, new, old):
    if not new.get('krb5Key'):
        return

    if server_role == 'domaincontroller_master':
        listener.setuid(0)
        try:
            if old:
                cn = old['cn'][0]
                ud.debug(ud.LISTENER, ud.PROCESS,
                         'Purging krb5.keytab of %s' % (cn, ))
                ktab = '/var/lib/univention-heimdal/%s' % (cn, )
                try:
                    os.unlink(ktab)
                except EnvironmentError:
                    pass
            if new:
                cn = new['cn'][0]
                ud.debug(ud.LISTENER, ud.PROCESS,
                         'Generating krb5.keytab for %s' % (cn, ))
                ktab = '/var/lib/univention-heimdal/%s' % (cn, )
                # FIXME: otherwise the keytab entry is duplicated
                call([
                    'kadmin', '-l', 'ext',
                    '--keytab=%s' % (ktab, ), new['krb5PrincipalName'][0]
                ])
                try:
                    userID = pwd.getpwnam('%s$' % cn)[2]
                    os.chown(ktab, userID, 0)
                    os.chmod(ktab, 0o660)
                except (KeyError, EnvironmentError):
                    pass
        finally:
            listener.unsetuid()
Example #34
0
def check_user_count(no):
    listener.setuid(0)
    lo = ul.getMachineConnection()

    servers = lo.search('(univentionOpenvpnLicense=*)')

    vpnusers = lo.search('(univentionOpenvpnAccount=1)')
    vpnuc = len(vpnusers)
    maxu = 5
    for server in servers:
        key = server[1].get('univentionOpenvpnLicense', [None])[0]
        try:
            l = license(no, key)
            ud.debug(ud.LISTENER, ud.INFO, '%d Processing license with ID %s:' % (no, l['id']))
            ud.debug(ud.LISTENER, ud.INFO, '%d Valid until: %s' % (no, date.fromordinal(l['vdate'])))
            ud.debug(ud.LISTENER, ud.INFO, '%d Users: %s' % (no, l['u']))
            ud.debug(ud.LISTENER, ud.INFO, '%d Site-2-Site: %s' % (no, l['s2s']))
        except:
            pass
        mu = maxvpnusers(no, key)
        if mu > maxu: maxu = mu
    ud.debug(ud.LISTENER, ud.INFO, '%d Found %u active openvpn users (%u allowed)' % (no, vpnuc, maxu))
    listener.unsetuid()
    if vpnuc > maxu:
        ud.debug(ud.LISTENER, ud.INFO, '%d Skipping actions' % no)
        return False
    else:
        return True
Example #35
0
def prerun():
	if not os.path.exists('/etc/samba/shares.conf.d'):
		listener.setuid(0)
		try:
			os.mkdir('/etc/samba/shares.conf.d')
		finally:
			listener.unsetuid()
Example #36
0
def clean():
	global slave
	if not slave:
		return 1
	univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO, 'removing replica\'s cache')
	#init_slapd('stop')

	#FIXME
	listener.run('/usr/bin/killall', ['killall', '-9', 'slapd'], uid=0)
	time.sleep(1) #FIXME

	dir='/var/lib/univention-ldap/ldap'
	listener.setuid(0)
	try:
		for f in os.listdir(dir):
			file=os.path.join(dir, f)
			try:
				os.unlink(file)
			except OSError:
				pass
		if os.path.exists(LDIF_FILE):
			os.unlink(LDIF_FILE)
	finally:
		listener.unsetuid()
	listener.run('/usr/sbin/univention-config-registry', ['univention-config-registry','commit', '/var/lib/univention-ldap/ldap/DB_CONFIG'], uid=0)
Example #37
0
def postrun():
	listener.setuid(0)
	try:
		initscript = '/etc/init.d/samba'
		os.spawnv(os.P_WAIT, initscript, ['samba', 'reload'])
	finally:
		listener.unsetuid()
Example #38
0
def connected_users():
    listener.setuid(0)
    lo = ul.getMachineConnection()
    users = lo.search('univentionOpenvpnAccount=1')
    users = map(lambda user: "******" % user[1].get('uid', [None])[0], users)
    myname = listener.baseConfig['hostname']
    me = lo.search('cn=%s' % myname)
    listener.unsetuid()
    connected_users = userlist()

    # append not connected users
    for user in users:
        if not any(u['name'] == user for u in connected_users):
            connected_users.append({'name': user, 'connected': 0, 'type': 0, 'realip': '', 'virtips': '', 'cons': '', 'conr': '', 'recv': 0, 'sent': 0})

    for user in connected_users:
        user['cert'] = os.popen("/usr/sbin/univention-certificate dump -name %s|grep 'Not After'|cut -d ':' -f2-" % user['name']).read()

    data = {"users": connected_users}

    count = str(len(connected_users))

    query = web.ctx.query
    if query:
        # jsonp
        queries = query.split('&')
        callback = queries[0].split('=')[1]
        return '%s({"draw": 1, "recordsTotal": %s, "recordsFiltered": %s, "data": %s});' % (callback, count, count, json.dumps(data))
    else:
        return '{"data": %s}' % json.dumps(data)
Example #39
0
def createContactGroup( grpname, contactlist ):
	global __contactgrpsdir
	global __contactsdir

	listener.setuid(0)
	try:
		filename = '%s%s.cfg' % (__contactgrpsdir, grpname)
		fp = open(filename, 'w')
		fp.write('# Warning: This file is auto-generated and might be overwritten.\n')
		fp.write('#          Please use univention-admin instead.\n')
		fp.write('# Warnung: Diese Datei wurde automatisch generiert und wird\n')
		fp.write('#          automatisch ueberschrieben. Bitte benutzen Sie\n')
		fp.write('#          stattdessen den Univention Admin.\n')
		fp.write('\n')
		fp.write('define contactgroup {\n')
		fp.write('    contactgroup_name    %s\n' % grpname)
		fp.write('    alias                Gruppe %s\n' % grpname)
		fp.write('    members              %s\n' % ', '.join(contactlist))
		fp.write('}\n')
		fp.close()

		univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO, 'NAGIOS-SERVER: contactgroup %s written: members=%s' % (grpname, contactlist))
		# create missing contacts
		for contact in contactlist:
			if not os.path.exists( os.path.join( __contactsdir, '%s.cfg' % contact) ):
				createContact(contact)

		# create default timeperiod if missing
		createDefaultTimeperiod()

	finally:
		listener.unsetuid()
Example #40
0
def handler(dn, new, old):
	global reload
	configRegistry = univention.config_registry.ConfigRegistry()
	configRegistry.load()

	old_hosteddomains = set(re.split('[ ]+', configRegistry.get('mail/hosteddomains','')))
	hosteddomains = old_hosteddomains.copy()

	# remove old add new
	if old.get('cn'):
		hosteddomains.discard(old.get('cn')[0])
		univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO, "hosteddomains: removed %s" % old.get('cn')[0])
	if new.get('cn'):
		hosteddomains.add(new.get('cn')[0])
		univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO, "hosteddomains: added %s" % new.get('cn')[0])

	# if something changed then set UCR variable
	if old_hosteddomains != hosteddomains:
		try:
			listener.setuid(0)
			univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO, "hosteddomains: %s" % u'mail/hosteddomains=%s' % ' '.join(hosteddomains) )
			univention.config_registry.handler_set( [ u'mail/hosteddomains=%s' % ' '.join(hosteddomains) ] )
			reload = True
		finally:
			listener.unsetuid()
Example #41
0
def prerun():
	if not os.path.exists('/etc/samba/shares.conf.d'):
		listener.setuid(0)
		try:
			os.mkdir('/etc/samba/shares.conf.d')
		finally:
			listener.unsetuid()
def reload_printer_restrictions():
    # type: () -> None
    listener.setuid(0)
    try:
        subprocess.call(['python3', '-m', 'univention.lib.share_restrictions'])
    finally:
        listener.unsetuid()
Example #43
0
def postrun():
    global __reload

    if __reload:
        global __initscript
        initscript = __initscript
        # restart nagios if not running and nagios/server/autostart is set to yes/true/1
        # otherwise if nagios is running, ask nagios to reload config
        p = subprocess.Popen(('pidof', '/usr/sbin/nagios3'),
                             stdout=subprocess.PIPE)
        pidlist, stderr = p.communicate()
        listener.setuid(0)
        null = open(os.path.devnull, 'w')
        try:
            retcode = subprocess.call(
                ('nagios3', '-v', '/etc/nagios3/nagios.cfg'),
                stdout=null,
                stderr=null)
        finally:
            null.close()
        listener.unsetuid()
        if not pidlist.strip():
            if retcode == 0:
                if listener.baseConfig.is_true("nagios/server/autostart",
                                               False):
                    univention.debug.debug(
                        univention.debug.LISTENER, univention.debug.INFO,
                        'NAGIOS-SERVER: nagios3 not running - restarting server'
                    )

                    listener.setuid(0)
                    try:
                        listener.run(initscript, ['nagios3', 'restart'], uid=0)
                    finally:
                        listener.unsetuid()
            else:
                univention.debug.debug(
                    univention.debug.LISTENER, univention.debug.ERROR,
                    'NAGIOS-SERVER: nagios3 reported an error in configfile /etc/nagios3/nagios.cfg. Please restart nagios3 manually: "%s restart".'
                    % initscript)
                listener.unsetuid()

        else:
            if retcode == 0:
                univention.debug.debug(univention.debug.LISTENER,
                                       univention.debug.INFO,
                                       'NAGIOS-SERVER: reloading server')
                listener.setuid(0)
                try:
                    listener.run(initscript, ['nagios3', 'reload'], uid=0)
                finally:
                    listener.unsetuid()
            else:
                univention.debug.debug(
                    univention.debug.LISTENER, univention.debug.ERROR,
                    'NAGIOS-SERVER: nagios3 reported an error in configfile /etc/nagios3/nagios.cfg. Please restart nagios3 manually: "%s restart".'
                    % initscript)
                listener.unsetuid()
        __reload = False
def postrun():
    global __reload

    if __reload:
        global __initscript
        initscript = __initscript
        # restart nagios if not running and nagios/server/autostart is set to yes/true/1
        # otherwise if nagios is running, ask nagios to reload config
        p = subprocess.Popen(
            ('pidof', '/usr/lib/x86_64-linux-gnu/icinga2/sbin/icinga2'),
            stdout=subprocess.PIPE)
        pidlist, stderr = p.communicate()
        listener.setuid(0)
        null = open(os.path.devnull, 'w')
        try:
            retcode = subprocess.call(('icinga2', 'daemon', '-C'),
                                      stdout=null,
                                      stderr=null)
        finally:
            null.close()
        listener.unsetuid()
        if not pidlist.strip():
            if retcode == 0:
                if listener.baseConfig.is_true("icinga2/server/autostart",
                                               False):
                    univention.debug.debug(
                        univention.debug.LISTENER, univention.debug.INFO,
                        'ICINGA2-SERVER: icinga2 not running - restarting server'
                    )

                    listener.setuid(0)
                    try:
                        listener.run(initscript, ['icinga2', 'restart'], uid=0)
                    finally:
                        listener.unsetuid()
            else:
                univention.debug.debug(
                    univention.debug.LISTENER, univention.debug.ERROR,
                    'ICINGA2-SERVER: icinga2 reported an error. Please restart icinga2 manually: "systemctl restart icinga2.service".'
                )
                listener.unsetuid()

        else:
            if retcode == 0:
                univention.debug.debug(univention.debug.LISTENER,
                                       univention.debug.INFO,
                                       'ICINGA2-SERVER: reloading server')
                listener.setuid(0)
                try:
                    listener.run(initscript, ['icinga2', 'reload'], uid=0)
                finally:
                    listener.unsetuid()
            else:
                univention.debug.debug(
                    univention.debug.LISTENER, univention.debug.ERROR,
                    'ICINGA2-SERVER: icinga2 reported an error. Please restart icinga2 manually: "systemctl restart icinga2.service".'
                )
                listener.unsetuid()
        __reload = False
Example #45
0
def clean():
	dirname='/etc/nagios3/conf.univention.d'
	if os.path.exists(dirname):
		listener.setuid(0)
		try:
			deleteTree(dirname)
		finally:
			listener.unsetuid()
Example #46
0
def delete(old_dn, old, command):
    # this is also called on modrdn (command == 'r').
    listener.setuid(0)
    try:
        # in modrdn phase 'r' the DN is still present in local LDAP, so we explicitly exclude it
        update_ucr_overrides(excludeDN=old_dn)
    finally:
        listener.unsetuid()
Example #47
0
def removeConfig( name ):
	filename = os.path.join( __confdir, "%s.cfg" % name )
	listener.setuid(0)
	try:
		if os.path.exists( filename ):
			os.unlink( filename )
	finally:
		listener.unsetuid()
Example #48
0
	def setquota(mailbox, quota):
		try:
			listener.setuid(0)
			p = os.popen('/usr/sbin/univention-cyrus-set-quota-shared %s %s' % ( mailbox, quota ) )
			p.close()
			listener.unsetuid()
		except:
			pass
def clean():
    dirname = '/etc/icinga2/conf.d/conf.univention.d/'
    if os.path.exists(dirname):
        listener.setuid(0)
        try:
            deleteTree(dirname)
        finally:
            listener.unsetuid()
 def flush_auth_cache():
     try:
         listener.setuid(0)
         listener.run('/usr/bin/doveadm',
                      ["/usr/bin/doveadm", "auth", "cache", "flush"],
                      uid=0)
     finally:
         listener.unsetuid()
def clean():
    dirname = '/etc/nagios/nrpe.univention.d'
    if os.path.exists(dirname):
        listener.setuid(0)
        try:
            deleteTree(dirname)
        finally:
            listener.unsetuid()
def removeConfig(name):
    filename = os.path.join(__confdir, "%s.cfg" % name)
    listener.setuid(0)
    try:
        if os.path.exists(filename):
            os.unlink(filename)
    finally:
        listener.unsetuid()
def _write(lines):
	listener.setuid(0)
	try:
		univention.debug.debug(univention.debug.LISTENER, univention.debug.PROCESS, 'Writing /etc/exports with %d lines' % (len(lines),))
		with open(__exports, 'w') as fp:
			fp.write('\n'.join(lines) + '\n')
	finally:
		listener.unsetuid()
Example #54
0
def removeHost(fqdn):
	global __hostextinfodir
	fn = os.path.join( __hostsdir, '%s.cfg' % fqdn )
	if os.path.exists( fn ):
		listener.setuid(0)
		try:
			os.unlink(fn)
		finally:
			listener.unsetuid()
Example #55
0
def initialize():
	dirname = '/etc/nagios/nrpe.univention.d'

	if not os.path.exists( dirname ):
		listener.setuid(0)
		try:
			os.mkdir( dirname )
		finally:
			listener.unsetuid()
Example #56
0
def clean():
	global keytab

	listener.setuid(0)
	try:
		if os.path.exists('/etc/krb5.keytab'):
			os.unlink('/etc/krb5.keytab')
	finally:
		listener.unsetuid()
Example #57
0
def postrun():
	global __initscript
	initscript = __initscript
	univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO, 'Restarting fetchmail-daemon')
	listener.setuid(0)
	try:
		listener.run(initscript, ['fetchmail', 'restart'], uid=0)
	finally:
		listener.unsetuid()
Example #58
0
def create_cyrus_mailbox(new):
	if new.has_key('mailPrimaryAddress') and new['mailPrimaryAddress'][0]:
		mailAddress = string.lower(new['mailPrimaryAddress'][0])
		try:
			listener.setuid(0)
			subprocess.call(("/usr/sbin/univention-cyrus-mkdir", mailAddress))
			create_cyrus_userlogfile(mailAddress)
		finally:
			listener.unsetuid()