Example #1
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 #2
0
def _safe_write(fname,content):
	"""Safe write to a file.

	(1)	create a temp file, write content.
	(2)	rename to real destination name.

	Sets identity to root.
	
	Error behaviour:
		-	catches all exceptions
		-	writes log here
		
	To return true/false on success/failure doesn't make sense since our callers
	don't bother looking at our results.
	"""
	
	bakfile = fname + '.tmp'
	
	listener.setuid(0)
	try:
		f = io.open(bakfile,'w',encoding='utf-8')
		f.write(content)
		f.close()
		ud.debug(ud.LISTENER,ud.INFO,"plucs-groups: File '%s' written (%d chars)" % (bakfile,len(content)))
		os.rename(bakfile,fname)
		ud.debug(ud.LISTENER,ud.INFO,"plucs-groups: File '%s' renamed to '%s'" % (bakfile,fname))

	except Exception,e:
		ud.debug(ud.LISTENER,ud.WARN,"plucs-groups: Could not write '%s': %s" % (bakfile,str(e)))
Example #3
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 #4
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 #5
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 #6
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 #7
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 #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
Example #9
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 #10
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)
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)
Example #12
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 #13
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 #14
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 #15
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()
Example #16
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 #17
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 #18
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 #19
0
def handler(dn, new, old, command):

	configRegistry = ConfigRegistry()
	configRegistry.load()
	interfaces = Interfaces(configRegistry)

	# dymanic module object filter
	current_fqdn = "%s.%s" % (configRegistry['hostname'], domainname)
	current_ip = str(interfaces.get_default_ip_address().ip)

	new_univentionShareHost = new.get('univentionShareHost', [None])[0]
	if new and not new_univentionShareHost in (current_fqdn, current_ip):
		new = {}	## new object is not for this host

	old_univentionShareHost = old.get('univentionShareHost', [None])[0]
	if old and not old_univentionShareHost in (current_fqdn, current_ip):
		old = {}	## old object is not for this host

	if not (new or old):
		return

	# create tmp dir
	tmpDir = os.path.dirname(tmpFile)
	listener.setuid(0)
	try:
		if not os.path.exists(tmpDir):
			os.makedirs(tmpDir)
	except Exception, e:
		univention.debug.debug(
			univention.debug.LISTENER, univention.debug.ERROR,
			"%s: could not create tmp dir %s (%s)" % (name, tmpDir, str(e)))
		return
Example #20
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()
Example #21
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, 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 #23
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)
Example #24
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 #25
0
def write_rc(no, flist, wfile):
    listener.setuid(0)
    try:
        f = open(wfile,"w")
        f.writelines(flist)
        f.close()
    except Exception, e:
        ud.debug(ud.LISTENER, ud.ERROR, '%d Failed to write file "%s": %s' % (no, wfile, str(e)))
Example #26
0
def write_rc(flist, wfile):
	listener.setuid(0)
	try:
		f = open(wfile,"w")
		f.writelines(flist)
		f.close()
	except Exception, e:
		univention.debug.debug(univention.debug.LISTENER, univention.debug.ERROR, 'Failed to write to file "%s": %s' % (wfile, str(e)))
Example #27
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
Example #28
0
def clean():
	dirname='/etc/nagios3/conf.univention.d'
	if os.path.exists(dirname):
		listener.setuid(0)
		try:
			deleteTree(dirname)
		finally:
			listener.unsetuid()
Example #29
0
def handler(dn, new, old):
    """Handle changes to 'dn'."""
    setuid(0)
    try:
        if configRegistry['server/role'] != 'domaincontroller_master':
            return

        global uidNumber
        try:
            uidNumber = int(new.get('uidNumber', ['0'])[0])
        except (LookupError, TypeError, ValueError):
            uidNumber = 0

        global gidNumber
        try:
            gidNumber = int(grp.getgrnam('DC Backup Hosts')[2])
        except (LookupError, TypeError, ValueError):
            ud.debug(ud.LISTENER, ud.WARN,
                     'CERTIFICATE: Failed to get groupID for "%s"' % dn)
            gidNumber = 0

        if new and not old:
            # changeType: add
            try:
                domain = new['associatedDomain'][0]
            except LookupError:
                domain = configRegistry['domainname']
            create_certificate(new['cn'][0], domainname=domain)
        elif old and not new:
            # changeType: delete
            try:
                domain = old['associatedDomain'][0]
            except LookupError:
                domain = configRegistry['domainname']
            remove_certificate(old['cn'][0], domainname=domain)
        else:
            # changeType: modify
            try:
                old_domain = old['associatedDomain'][0]
            except LookupError:
                old_domain = configRegistry['domainname']

            try:
                new_domain = new['associatedDomain'][0]
            except LookupError:
                new_domain = configRegistry['domainname']

            if new_domain != old_domain:
                remove_certificate(old['cn'][0], domainname=old_domain)
                create_certificate(new['cn'][0], domainname=new_domain)
            else:
                # Reset permissions
                fqdn = "%s.%s" % (new['cn'][0], new_domain)
                certpath = os.path.join(SSLDIR, fqdn)
                os.path.walk(certpath, set_permissions, None)
    finally:
        unsetuid()
Example #30
0
def handler(dn, new, old):

    if not listener.configRegistry.is_true("nfs/create/homesharepath"):
        return

    # new and modify
    if new and new.get("uid"):

        uid = new.get("uid")
        uidNumber = new.get("uidNumber")
        gidNumber = new.get("gidNumber")
        automountInformation = new.get("automountInformation")

        if not uidNumber or not len(uidNumber) == 1:
            return
        if not gidNumber or not len(gidNumber) == 1:
            return
        if not uid or not len(uid) == 1:
            return
        if not automountInformation or not len(automountInformation) == 1:
            return

        uid = uid[0]
        automountInformation = automountInformation[0]
        gidNumber = gidNumber[0]
        uidNumber = uidNumber[0]

        try:
            gidNumber = int(gidNumber)
            uidNumber = int(uidNumber)
        except:
            return

        unc = automountInformation
        if " " in automountInformation:
            flags, unc = automountInformation.split(" ", 1)
        if ":" in unc:
            host, path = unc.split(':', 1)
            if host and host == fqdn:
                if not os.path.exists(path):
                    univention.debug.debug(
                        univention.debug.LISTENER, univention.debug.INFO,
                        "%s: creating share path %s for user %s" %
                        (name, path, uid))
                    listener.setuid(0)
                    try:
                        os.makedirs(path)
                        os.chmod(path,
                                 stat.S_IRWXU | stat.S_IXGRP | stat.S_IXOTH)
                        os.chown(path, uidNumber, gidNumber)
                    except Exception as e:
                        univention.debug.debug(
                            univention.debug.LISTENER, univention.debug.ERROR,
                            "%s: failed to create home path %s for user %s (%s)"
                            % (name, path, uid, e))
                    finally:
                        listener.unsetuid()
Example #31
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 #32
0
def _restart_connector():
	listener.setuid(0)
	try:
		if not subprocess.call(['pgrep', '-f', 'connector/ad/main.py']):
			univention.debug.debug(univention.debug.LISTENER, univention.debug.PROCESS, "ad-connector: restarting connector ...")
			subprocess.call(('service', 'univention-ad-connector', 'restart'))
			univention.debug.debug(univention.debug.LISTENER, univention.debug.PROCESS, "ad-connector: ... done")
	finally:
		listener.unsetuid()
def removeConfig(name):
    # type: (str) -> None
    filename = os.path.join(__confdir, "%s.cfg" % name)
    listener.setuid(0)
    try:
        if os.path.exists(filename):
            os.unlink(filename)
    finally:
        listener.unsetuid()
Example #34
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()
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()
def clean():
    # type: () -> None
    dirname = '/etc/nagios/nrpe.univention.d'
    if os.path.exists(dirname):
        listener.setuid(0)
        try:
            deleteTree(dirname)
        finally:
            listener.unsetuid()
def handler(dn, new, old):
    listener.setuid(0)
    ud.debug(ud.LISTENER, ud.INFO, 'portal server handler has fired!')
    try:
        with open('/var/cache/univention-portal/refresh_portal', 'w'):
            pass
        ud.debug(ud.LISTENER, ud.INFO, 'refresh_portal file was created.')
    finally:
        listener.unsetuid()
Example #38
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 #39
0
def write_rc(flist, wfile):
	listener.setuid(0)
	try:
		f = open(wfile, "w")
		f.writelines(flist)
		f.close()
	except Exception as e:
		univention.debug.debug(univention.debug.LISTENER, univention.debug.ERROR, 'Failed to write to file "%s": %s' % (wfile, str(e)))
	listener.unsetuid()
Example #40
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 #41
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()
def initialize():
    # type: () -> None
    if not os.path.exists('/etc/samba/printers.conf.d'):
        listener.setuid(0)
        try:
            os.mkdir('/etc/samba/printers.conf.d')
            os.chmod('/etc/samba/printers.conf.d', 0o755)
        finally:
            listener.unsetuid()
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 #44
0
def reload_printer_restrictions():
    listener.setuid(0)
    try:
        subprocess.call([
            'python',
            '/usr/share/pyshared/univention/lib/share_restrictions.py'
        ])
    finally:
        listener.unsetuid()
def _write(lines):
	# type: (list) -> None
	listener.setuid(0)
	try:
		ud.debug(ud.LISTENER, ud.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 #46
0
 def flush_auth_cache():
     # type: () -> None
     try:
         listener.setuid(0)
         listener.run('/usr/bin/doveadm',
                      ["/usr/bin/doveadm", "auth", "cache", "flush"],
                      uid=0)
     finally:
         listener.unsetuid()
def handler(dn, new, old, command):
    # type: (str, Optional[Dict[str, List[bytes]]], Optional[Dict[str, List[bytes]]], str) -> None
    global group_objects
    global init_mode
    global connector_needs_restart

    # restart connector on extended attribute changes
    if b'univentionUDMProperty' in new.get(
            'objectClass', []) or b'univentionUDMProperty' in old.get(
                'objectClass', []):
        connector_needs_restart = True
    else:
        if connector_needs_restart is True:
            _restart_connector()
            connector_needs_restart = False

    listener.setuid(0)
    try:
        for directory in dirs:
            if not os.path.exists(os.path.join(directory, 'tmp')):
                os.makedirs(os.path.join(directory, 'tmp'))

            old_dn = None
            old_object = {}  # type: Dict[str, List[bytes]]

            if os.path.exists(os.path.join(directory, 'tmp', 'old_dn')):
                (old_dn, old_object) = _load_old_object(directory)
            if command == 'r':
                _save_old_object(directory, dn, old)
            else:
                # Normally we see two steps for the modrdn operation. But in case of the selective replication we
                # might only see the first step.
                #  https://forge.univention.org/bugzilla/show_bug.cgi?id=32542
                if old_dn and new.get('entryUUID') != old_object.get(
                        'entryUUID'):
                    ud.debug(
                        ud.LISTENER, ud.PROCESS,
                        "The entryUUID attribute of the saved object (%s) does not match the entryUUID attribute of the current object (%s). This can be normal in a selective replication scenario."
                        % (old_dn, dn))
                    _dump_changes_to_file_and_check_file(
                        directory, old_dn, {}, old_object, None)
                    old_dn = None

                if init_mode:
                    if new and b'univentionGroup' in new.get(
                            'objectClass', []):
                        group_objects.append((dn, new, old, old_dn))

                _dump_changes_to_file_and_check_file(directory, dn, new, old,
                                                     old_dn)

                if os.path.exists(os.path.join(directory, 'tmp', 'old_dn')):
                    os.unlink(os.path.join(directory, 'tmp', 'old_dn'))

    finally:
        listener.unsetuid()
Example #48
0
def postrun():
    # type: () -> None
    global __initscript
    initscript = __initscript
    ud.debug(ud.LISTENER, ud.INFO, 'Restarting fetchmail-daemon')
    listener.setuid(0)
    try:
        listener.run(initscript, ['fetchmail', 'restart'], uid=0)
    finally:
        listener.unsetuid()
Example #49
0
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 #50
0
def postrun():
	global __initscript
	initscript = __initscript
	if listener.baseConfig.has_key("nagios/client/autostart") and ( listener.baseConfig["nagios/client/autostart"] in ["yes", "true", '1']):
		univention.debug.debug(univention.debug.LISTENER, univention.debug.INFO, 'NRPED: Restarting server')
		listener.setuid(0)
		try:
			listener.run(initscript, ['nagios-nrpe-server', 'restart'], uid=0)
		finally:
			listener.unsetuid()
Example #51
0
def _restart_connector():
	# type: () -> None
	listener.setuid(0)
	try:
		if not subprocess.call(['pgrep', '-f', 'python.*s4connector.s4.main']):
			ud.debug(ud.LISTENER, ud.PROCESS, "s4-connector: restarting connector ...")
			subprocess.call(('systemctl', 'restart', 'univention-s4-connector'))
			ud.debug(ud.LISTENER, ud.PROCESS, "s4-connector: ... done")
	finally:
		listener.unsetuid()
def handler(dn, new, old):
	if new and old:
		if __login_is_locked(old) and not __login_is_locked(new):
			# reset local bad password count
			listener.setuid(0)
			try:
				ud.debug(ud.LISTENER, ud.PROCESS, 'Reset faillog for user %s' % new['uid'][0])
				listener.run('/sbin/pam_tally', ['pam_tally', '--user', new['uid'][0], '--reset'])
			finally:
				listener.unsetuid()
Example #53
0
def setVar(content):

    listener.setuid(0)
    try:
        univention.config_registry.handler_set(
            [u'%s=%s' % (var, " ".join(content))])
    finally:
        listener.unsetuid

    return
Example #54
0
def _remove_user(uid):
    listener.setuid(0)
    try:
        _remove_user_from_file('passwd', uid)
        modified = _remove_user_from_file('shadow', uid)
        if modified:
            _set_shadow_permissions()
            _cleanup_groups()
    finally:
        listener.unsetuid()
Example #55
0
def deleteHostGroup(grpname):
	global __hostgrpsdir
	grp_filename = os.path.join(__hostgrpsdir, '%s.cfg' % grpname)

	listener.setuid(0)
	try:
		if os.path.exists(grp_filename):
			os.unlink(os.path.join(__servicesdir, grp_filename))
	finally:
		listener.unsetuid()
def handler(dn, new, old):
    # type: (str, dict, dict) -> None
    # don't do anything here if this system is joined as a Samba/AD DC
    if samba4_role.upper() in ('DC', 'RODC'):
        return

    if not new.get('krb5Key'):
        return

    if server_role == 'memberserver':
        ud.debug(ud.LISTENER, ud.PROCESS,
                 'Fetching %s from %s' % (K5TAB, ldap_master))
        listener.setuid(0)
        try:
            if os.path.exists(K5TAB):
                os.remove(K5TAB)
            count = 0
            while not os.path.exists(K5TAB):
                call([
                    'univention-scp', '/etc/machine.secret',
                    '%s$@%s:/var/lib/univention-heimdal/%s' %
                    (hostname, ldap_master, hostname), K5TAB
                ])
                if not os.path.exists(K5TAB):
                    if count > 30:
                        ud.debug(
                            ud.LISTENER, ud.ERROR,
                            'E: failed to download keytab for Managed Node')
                        return -1
                    ud.debug(
                        ud.LISTENER, ud.WARN,
                        'W: failed to download keytab for Managed Node, retry')
                    count += 1
                    time.sleep(2)
            os.chown(K5TAB, 0, 0)
            os.chmod(K5TAB, 0o600)
        finally:
            listener.unsetuid()
    else:
        ud.debug(ud.LISTENER, ud.PROCESS,
                 'Exporting %s on %s' % (K5TAB, server_role))
        listener.setuid(0)
        try:
            if old:
                call([
                    'ktutil', 'remove', '-p',
                    old['krb5PrincipalName'][0].decode('UTF-8')
                ])
            if new:
                call([
                    'kadmin', '-l', 'ext',
                    new['krb5PrincipalName'][0].decode('UTF-8')
                ])
        finally:
            listener.unsetuid()
Example #57
0
def postrun():
	ucr = univention.config_registry.ConfigRegistry()
	ucr.load()

	if ucr.is_true('nss/group/cachefile', False) and ucr.is_true('nss/group/cachefile/invalidate_on_changes', True):
		listener.setuid(0)
		param = ['ldap-group-to-file.py']
		if ucr.is_true('nss/group/cachefile/check_member', True):
			param.append('--check_member')
		listener.run('/usr/lib/univention-pam/ldap-group-to-file.py', param, uid=0)
		listener.unsetuid()
Example #58
0
def load_rc(ofile):
	l = None
	listener.setuid(0)
	try:
		f = open(ofile, "r")
		l = f.readlines()
		f.close()
	except Exception as e:
		univention.debug.debug(univention.debug.LISTENER, univention.debug.ERROR, 'Failed to open "%s": %s' % (ofile, str(e)))
	listener.unsetuid()
	return l
def remove_user_quota(username, quota):
    mountpoint = quota.split(delimiter)[1]
    exec_array = [
        '/usr/sbin/setquota', '-u',
        '%s' % username, '0', '0', '0', '0',
        '%s' % mountpoint
    ]
    ud.debug(ud.LISTENER, ud.INFO, "remove_user_quota running %s" % exec_array)
    listener.setuid(0)
    subprocess.call(exec_array)
    listener.unsetuid()
Example #60
0
def clean():
    # don't do anything here if this system is joined as a Samba 4 DC
    if samba4_role.upper() in ('DC', 'RODC'):
        return

    listener.setuid(0)
    try:
        if os.path.exists(K5TAB):
            os.unlink(K5TAB)
    finally:
        listener.unsetuid()