示例#1
0
    def nagiosModifyServiceList(self):
        fqdn = ''

        if 'nagios' in self.old_options:
            if self.hasChanged('name') and self.hasChanged('domain'):
                oldfqdn = u'%s.%s' % (self.oldinfo['name'],
                                      self.oldinfo['domain'])
                newfqdn = u'%s.%s' % (self['name'], self['domain'])
                self.__change_fqdn(oldfqdn, newfqdn)
            elif self.hasChanged('name'):
                oldfqdn = u'%s.%s' % (self.oldinfo['name'], self['domain'])
                newfqdn = u'%s.%s' % (self['name'], self['domain'])
                self.__change_fqdn(oldfqdn, newfqdn)
            elif self.hasChanged('domain'):
                oldfqdn = u'%s.%s' % (self.oldinfo['name'],
                                      self.oldinfo['domain'])
                newfqdn = u'%s.%s' % (self['name'], self['domain'])
                self.__change_fqdn(oldfqdn, newfqdn)

        fqdn = '%s.%s' % (self['name'], configRegistry.get("domainname"))
        if self.has_property('domain') and self['domain']:
            fqdn = '%s.%s' % (self['name'], self['domain'])

        # remove host from services
        if 'nagios' in self.old_options:
            for servicedn in self.oldinfo.get('nagiosServices', []):
                if servicedn not in self.info.get('nagiosServices', []):
                    oldmembers = self.lo.getAttr(servicedn,
                                                 'univentionNagiosHostname')
                    newmembers = [
                        x for x in oldmembers
                        if x.decode('UTF-8').lower() != fqdn.lower()
                    ]
                    self.lo.modify(
                        servicedn,
                        [('univentionNagiosHostname', oldmembers, newmembers)])

        if 'nagios' in self.options:
            # add host to new services
            ud.debug(ud.ADMIN, ud.INFO, 'nagios.py: NMSL: nagios in options')
            for servicedn in self.info.get('nagiosServices', []):
                if not servicedn:
                    continue
                ud.debug(ud.ADMIN, ud.INFO,
                         'nagios.py: NMSL: servicedn %s' % servicedn)
                if 'nagios' not in self.old_options or servicedn not in self.oldinfo[
                        'nagiosServices']:
                    ud.debug(ud.ADMIN, ud.INFO, 'nagios.py: NMSL: add')
                    # option nagios was freshly enabled or service has been enabled just now
                    oldmembers = self.lo.getAttr(servicedn,
                                                 'univentionNagiosHostname')
                    newmembers = copy.deepcopy(oldmembers)
                    newmembers.append(fqdn.encode('UTF-8'))
                    ud.debug(ud.ADMIN, ud.WARN,
                             'nagios.py: NMSL: oldmembers: %s' % oldmembers)
                    ud.debug(ud.ADMIN, ud.WARN,
                             'nagios.py: NMSL: newmembers: %s' % newmembers)
                    self.lo.modify(
                        servicedn,
                        [('univentionNagiosHostname', oldmembers, newmembers)])
示例#2
0
	def _ldap_pre_create(self):
		super(object, self)._ldap_pre_create()
		if configRegistry.is_false('directory/manager/child/cn/ou', True):
			if not self.lo.compare_dn(self.position.getDn(), configRegistry.get('ldap/base')):
				# it is possible to have a basedn with cn=foo
				# in this case it is allowed to create a ou
				# under a cn.
				if any(m and m.module == 'container/cn' for m in univention.admin.modules.identify(self.position.getDn(), self.lo.get(self.position.getDn()))):
					raise univention.admin.uexceptions.invalidChild(_('It is not allowed to create a container/ou as child object of a container/cn.'))
示例#3
0
    def __getFQDN(self):
        hostname = self.oldattr.get("cn", [b''])[0].decode('UTF-8')
        domain = self.oldattr.get("associatedDomain", [b''])[0].decode('UTF-8')
        if not domain:
            domain = configRegistry.get("domainname", None)
        if domain and hostname:
            return hostname + "." + domain

        return None
	def open(self):
		univention.admin.handlers.simpleLdap.open(self)

		try:
			caching_timeout = int(configRegistry.get('directory/manager/web/modules/groups/group/caching/uniqueMember/timeout', '300'))
			self.cache_uniqueMember.set_timeout(caching_timeout)
		except:
			pass

		if 'samba' in self.options:
			sid = self.oldattr.get('sambaSID', [''])[0]
			pos = sid.rfind('-')
			self.info['sambaRID'] = sid[pos + 1:]

		if self.exists():
			self['memberOf'] = self.lo.searchDn(filter=filter_format('(&(objectClass=posixGroup)(uniqueMember=%s))', [self.dn]))

			time_start = time.time()

			self['users'] = []
			self['hosts'] = []
			self['nestedGroup'] = []
			for i in self.oldattr.get('uniqueMember', []):
				if cache_uniqueMember.is_valid(i):
					membertype = cache_uniqueMember.get(i).get('type')
					if membertype == 'user':
						self['users'].append(i)
					elif membertype == 'group':
						self['nestedGroup'].append(i)
					elif membertype == 'host':
						self['hosts'].append(i)
				elif i.startswith('uid='):
					self['users'].append(i)
					cache_uniqueMember.set(i, {'type': 'user'})
				else:
					result = self.lo.getAttr(i, 'objectClass')
					if result:
						if 'univentionGroup' in result:
							self['nestedGroup'].append(i)
							cache_uniqueMember.set(i, {'type': 'group'})
						elif 'univentionHost' in result:
							self['hosts'].append(i)
							cache_uniqueMember.set(i, {'type': 'host'})
						else:
							self['users'].append(i)
					else:
						# removing following line breaks deletion of computers from groups
						self['users'].append(i)

			time_end = time.time()
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'groups/group: open(): member check duration: %1.2fs' % (time_end - time_start))

			self['allowedEmailUsers'] = self.oldattr.get('univentionAllowedEmailUsers', [])
			self['allowedEmailGroups'] = self.oldattr.get('univentionAllowedEmailGroups', [])

			self.save()
示例#5
0
	def _ldap_pre_create(self):
		self.dn='%s=%s,%s' % (mapping.mapName('name'), mapping.mapValue('name', self.info['name']), self.position.getDn())
		if configRegistry.is_false('directory/manager/child/cn/ou', True):
			if self.position.getDn() != configRegistry.get('ldap/base'):
				# it is possible to have a basedn with cn=foo
				# in this case it is allowed to create a ou 
				# under a cn.
				m = univention.admin.modules.identifyOne(self.position.getDn(), self.lo.get(self.position.getDn()))
				if m.module == 'container/cn':
					raise univention.admin.uexceptions.invalidChild(_('It is not allowed to create a container/ou as child object of a container/cn.'))
示例#6
0
	def nagiosSaveParentHostList(self, ml):
		if self.hasChanged('nagiosParents'):
			parentlist = []
			for parentdn in self.info.get('nagiosParents', []):
				domain = self.lo.getAttr(parentdn, 'associatedDomain')
				cn = self.lo.getAttr(parentdn, 'cn')
				if not domain:
					domain = [configRegistry.get("domainname")]
				if cn and domain:
					parentlist.append('%s.%s' % (cn[0], domain[0]))
			ml.insert(0, ('univentionNagiosParent', self.oldattr.get('univentionNagiosParent', []), parentlist))
示例#7
0
	def open(self):
		univention.admin.handlers.simpleLdap.open(self)

		try:
			caching_timeout = int(configRegistry.get('directory/manager/web/modules/groups/group/caching/uniqueMember/timeout', '300'))
			self.cache_uniqueMember.set_timeout(caching_timeout)
		except Exception:
			pass

		if 'samba' in self.options:
			sid = self.oldattr.get('sambaSID', [b''])[0].decode('ASCII')
			sid, has_rid, rid = sid.rpartition(u'-')
			if has_rid and rid.isdigit():
				self.info['sambaRID'] = rid

		if self.exists():
			self['memberOf'] = self.lo.searchDn(filter=filter_format('(&(objectClass=posixGroup)(uniqueMember=%s))', [self.dn]))

			time_start = time.time()

			self['users'] = []
			self['hosts'] = []
			self['nestedGroup'] = []
			for i in [x.decode('utf-8') for x in self.oldattr.get('uniqueMember', [])]:
				if cache_uniqueMember.is_valid(i):
					membertype = cache_uniqueMember.get(i).get('type')
					if membertype == 'user':
						self['users'].append(i)
					elif membertype == 'group':
						self['nestedGroup'].append(i)
					elif membertype == 'host':
						self['hosts'].append(i)
				elif i.startswith('uid='):
					self['users'].append(i)
					cache_uniqueMember.set(i, {'type': 'user'})
				else:
					result = self.lo.getAttr(i, 'objectClass')
					if result:
						if b'univentionGroup' in result:
							self['nestedGroup'].append(i)
							cache_uniqueMember.set(i, {'type': 'group'})
						elif b'univentionHost' in result:
							self['hosts'].append(i)
							cache_uniqueMember.set(i, {'type': 'host'})
						elif set(result) & {b'person', b'inetOrgPerson', b'organizationalPerson'}:
							self['users'].append(i)
						else:
							raise RuntimeError('%s not detected: %r' % (i, result))

			time_end = time.time()
			ud.debug(ud.ADMIN, ud.INFO, 'groups/group: open(): member check duration: %1.2fs' % (time_end - time_start))

			self.save()
示例#8
0
    def _ldap_modlist(self):
        ml = univention.admin.handlers.simpleLdap._ldap_modlist(self)

        options = []
        for key, value in self.OPTION_BITS.items():
            if self[key] == '1':
                options.append(value)  # type: List[bytes]

        # univentionNagiosNotificationOptions is required in LDAP schema
        if not options:
            options.append(b'n')

        newoptions = b','.join(options)
        ml.append(('univentionNagiosNotificationOptions',
                   self.oldattr.get('univentionNagiosNotificationOptions',
                                    []), newoptions))

        # save assigned hosts
        if self.hasChanged('assignedHosts'):
            hostlist = []
            for hostdn in self.info.get('assignedHosts', []):
                try:
                    host = self.lo.get(hostdn, ['associatedDomain', 'cn'],
                                       required=True)
                    cn = host['cn'][0]  # type: bytes
                except (univention.admin.uexceptions.noObject,
                        ldap.NO_SUCH_OBJECT):
                    raise univention.admin.uexceptions.valueError(
                        _('The host "%s" does not exists.') % (hostdn, ),
                        property='assignedHosts')
                except KeyError:
                    raise univention.admin.uexceptions.valueError(
                        _('The host "%s" is invalid, it has no "cn" attribute.'
                          ) % (hostdn, ),
                        property='assignedHosts')

                domain = host.get(
                    'associatedDomain',
                    [configRegistry.get("domainname").encode('ASCII')
                     ])[0]  # type: bytes
                hostlist.append(b"%s.%s" % (cn, domain))

            ml.insert(
                0,
                ('univentionNagiosHostname',
                 self.oldattr.get('univentionNagiosHostname', []), hostlist))

        return ml
示例#9
0
	def check_for_group_recursion(self):
		# perform check only if membership of groups has changed
		if not self.hasChanged('memberOf') and not self.hasChanged('nestedGroup'):
			return

		# perform check only if enabled via UCR
		if configRegistry.get('directory/manager/web/modules/groups/group/checks/circular_dependency', 'yes').lower() in ('no', 'false', '0'):
			return

		grpdn2childgrpdns = {}
		grp_module = univention.admin.modules.get('groups/group')

		cn = self.info.get('name', 'UNKNOWN')

		# test self dependency
		# ==> nestedGroup or memberOf contains self.dn
		for field in ('nestedGroup', 'memberOf'):
			if self.dn.lower() in (x.lower() for x in self.info.get(field, [])):
				raise univention.admin.uexceptions.circularGroupDependency('%s ==> %s' % (cn, cn))

		# test short dependencies: A -> B -> A
		# ==> intersection of nestedGroup and memberOf is not empty
		set_nestedGroup = set([x.lower() for x in self.info.get('nestedGroup', [])])
		set_memberOf = set([x.lower() for x in self.info.get('memberOf', [])])
		set_intersection = set_nestedGroup & set_memberOf
		if set_intersection:
			childdn = list(set_intersection)[0]
			# get cn for first detected object
			childobj = univention.admin.objects.get(grp_module, self.co, self.lo, position='', dn=childdn)
			childcn = childobj.info.get('name', 'UNKNOWN')
			raise univention.admin.uexceptions.circularGroupDependency('%s ==> %s ==> %s' % (childcn, cn, childcn))

		# test long dependencies: A -> B -> C -> A
		if self.info.get('memberOf'):   # TODO: FIXME:  perform extended check only if self.hasChanged('memberOf') is True
			# if user added some groups to memberOf, the group objects specified in memberOf do not contain self as
			# uniqueMember (aka nestedGroup) when this test is performed. So this test has to perform the recursion check
			# with each member of memberOf as parent
			for upgrp in self.info.get('memberOf', []):
				for subgrp in self.info.get('nestedGroup', []):
					self._check_group_childs_for_recursion(grp_module, grpdn2childgrpdns, subgrp.lower(), [upgrp.lower(), self.dn.lower()])
		else:
			for subgrp in self.info.get('nestedGroup', []):
				self._check_group_childs_for_recursion(grp_module, grpdn2childgrpdns, subgrp.lower(), [self.dn.lower()])
示例#10
0
文件: group.py 项目: B-Rich/smart
	def check_for_group_recursion(self):
		# perform check only if membership of groups has changed
		if not self.hasChanged('memberOf') and not self.hasChanged('nestedGroup'):
			return

		# perform check only if enabled via UCR
		if configRegistry.get('directory/manager/web/modules/groups/group/checks/circular_dependency','yes').lower() in ('no','false','0'):
			return

		grpdn2childgrpdns = {}
		grp_module=univention.admin.modules.get('groups/group')

		cn = self.info.get('name', 'UNKNOWN')

		# test self dependency
		# ==> nestedGroup or memberOf contains self.dn
		for field in ('nestedGroup', 'memberOf'):
			if self.dn.lower() in [ x.lower() for x in self.info.get(field,[]) ]:
				raise univention.admin.uexceptions.circularGroupDependency('%s ==> %s' % (cn, cn))

		# test short dependencies: A -> B -> A
		# ==> intersection of nestedGroup and memberOf is not empty
		set_nestedGroup = set( [ x.lower() for x in self.info.get('nestedGroup',[]) ] )
		set_memberOf = set( [ x.lower() for x in self.info.get('memberOf',[]) ] )
		set_intersection = set_nestedGroup & set_memberOf
		if set_intersection:
			childdn = list(set_intersection)[0]
			# get cn for first detected object
			childobj = univention.admin.objects.get(grp_module, self.co, self.lo, position='', dn=childdn)
			childcn = childobj.info.get('name','UNKNOWN')
			raise univention.admin.uexceptions.circularGroupDependency('%s ==> %s ==> %s' % (childcn, cn, childcn))

		# test long dependencies: A -> B -> C -> A
		if self.info.get('memberOf'):   # TODO: FIXME:  perform extended check only if self.hasChanged('memberOf') is True
			# if user added some groups to memberOf, the group objects specified in memberOf do not contain self als
			# uniqueMember (aka nestedGroup) when this test is performed. So this test has to perform the recursion check
			# with each member of memberOf as parent
			for upgrp in self.info.get('memberOf',[]):
				for subgrp in self.info.get('nestedGroup',[]):
					self._check_group_childs_for_recursion(grp_module, grpdn2childgrpdns, subgrp.lower(), [ upgrp.lower(), self.dn.lower() ])
		else:
			for subgrp in self.info.get('nestedGroup',[]):
				self._check_group_childs_for_recursion(grp_module, grpdn2childgrpdns, subgrp.lower(), [ self.dn.lower() ])
示例#11
0
    def _ldap_modlist(self):
        ml = univention.admin.handlers.simpleLdap._ldap_modlist(self)

        options = []
        if self['notificationOptionWarning'] in ['1']:
            options.append('w')
        if self['notificationOptionCritical'] in ['1']:
            options.append('c')
        if self['notificationOptionUnreachable'] in ['1']:
            options.append('u')
        if self['notificationOptionRecovered'] in ['1']:
            options.append('r')

        # univentionNagiosNotificationOptions is required in LDAP schema
        if len(options) == 0:
            options.append('n')

        newoptions = ','.join(options)
        ml.append(('univentionNagiosNotificationOptions',
                   self.oldattr.get('univentionNagiosNotificationOptions',
                                    []), newoptions))

        # save assigned hosts
        if self.hasChanged('assignedHosts'):
            hostlist = []
            for hostdn in self.info.get('assignedHosts', []):
                domain = self.lo.getAttr(hostdn, 'associatedDomain')
                cn = self.lo.getAttr(hostdn, 'cn')
                if not domain:
                    domain = [configRegistry.get("domainname")]
                fqdn = "%s.%s" % (cn[0], domain[0])
                hostlist.append(fqdn)

            ml.insert(
                0,
                ('univentionNagiosHostname',
                 self.oldattr.get('univentionNagiosHostname', []), hostlist))

        return ml
示例#12
0
 univention.admin.property(
     short_description=_('Zone time to live'),
     long_description=_('The time this entry may be cached.'),
     syntax=univention.admin.syntax.UNIX_TimeInterval,
     required=True,
     default=(('3', 'hours'), []),
     dontsearch=True,
 ),
 'contact':
 univention.admin.property(
     short_description=_('Contact person'),
     long_description=_(
         'The email address of the person responsible for this zone.'),
     syntax=univention.admin.syntax.string,
     required=True,
     default=('root@%s.' % configRegistry.get('domainname', ''), []),
 ),
 'serial':
 univention.admin.property(
     short_description=_('Serial number'),
     long_description=_(
         'The sequence number for this zone. Updates automatically.'),
     syntax=univention.admin.syntax.integer,
     required=True,
     default=('1', [])),
 'refresh':
 univention.admin.property(
     short_description=_('Refresh interval'),
     long_description=
     _('The time interval secondary DNS servers use to check the zone for updates.'
       ),
示例#13
0
			options=[],
			required=1,
			may_change=1,
			identifies=0,
			default=( ( '3', 'hours' ), [])
		),
	'contact': univention.admin.property(
			short_description=_('Contact person'),
			long_description='',
			syntax=univention.admin.syntax.emailAddress,
			multivalue=0,
			options=[],
			required=1,
			may_change=1,
			identifies=0,
			default = ( 'root@%s' % configRegistry.get( 'domainname' ), [] ),
		),
	'serial': univention.admin.property(
			short_description=_('Serial number'),
			long_description='',
			syntax=univention.admin.syntax.integer,
			multivalue=0,
			options=[],
			required=1,
			may_change=1,
			identifies=0,
			default=('1', [])
		),
	'refresh': univention.admin.property(
			short_description=_('Refresh interval'),
			long_description='',
示例#14
0
		syntax=univention.admin.syntax.DNS_ReverseZone,
		multivalue=True,
		options=[],
		required=False,
		may_change=False,
		identifies=False
	),
	'sambaDomainName': univention.admin.property(
		short_description=_('Samba domain name'),
		long_description='',
		syntax=univention.admin.syntax.string,
		multivalue=True,
		options=['samba'],
		required=True,
		may_change=True,
		default=(configRegistry.get('domainname', '').upper(), []),
		identifies=False
	),
	'sambaSID': univention.admin.property(
		short_description=_('Samba SID'),
		long_description='',
		syntax=univention.admin.syntax.string,
		multivalue=False,
		options=['samba'],
		required=True,
		may_change=False,
		identifies=False
	),
	'sambaNextUserRid': univention.admin.property(
		short_description=_('Samba Next User RID'),
		long_description='',
示例#15
0
文件: group.py 项目: B-Rich/smart
	def open(self):
		global options
		univention.admin.handlers.simpleLdap.open(self)

		try:
			caching_timeout = int(configRegistry.get('directory/manager/web/modules/groups/group/caching/uniqueMember/timeout','300'))
			self.cache_uniqueMember.set_timeout( caching_timeout )
		except:
			pass

		self.options=[]
		if self.oldattr.has_key('objectClass'):
			ocs=self.oldattr['objectClass']
			if 'posixGroup' in ocs:
				self.options.append( 'posix' )
			if 'sambaGroupMapping' in ocs:
				self.options.append( 'samba' )
		else:
			self._define_options( options )

		self.info['gidNumber'] = self.oldattr.get('gidNumber', [''])[0]

		if 'samba' in self.options:
			sid = self.oldattr.get('sambaSID', [''])[0]
			pos = sid.rfind('-')
			self.info['sambaRID'] = sid[pos+1:]

		if self.dn:
			self['memberOf']=self.lo.searchDn(filter='(&(objectClass=posixGroup)(uniqueMember=%s))' % univention.admin.filter.escapeForLdapFilter(self.dn))

			time_start = time.time()

			self['users']=self['hosts']=self['nestedGroup']=[]
			if self.oldattr.has_key('uniqueMember'):
				groupMembers=self.oldattr['uniqueMember']

				for i in groupMembers:
					if cache_uniqueMember.is_valid(i):
						membertype = cache_uniqueMember.get(i).get('type')
						if membertype == 'user':
							self['users'].append(i)
						elif membertype == 'group':
							self['nestedGroup'].append(i)
						elif membertype == 'host':
							self['hosts'].append(i)
					elif i.startswith('uid='):
						self['users'].append(i)
						cache_uniqueMember.set(i, { 'type': 'user' })
					else:
						result = self.lo.getAttr(i, 'objectClass' )
						if result:
							if 'univentionGroup' in result:
								self['nestedGroup'].append(i)
								cache_uniqueMember.set(i, { 'type': 'group' })
							elif 'univentionHost' in result:
								self['hosts'].append(i)
								cache_uniqueMember.set(i, { 'type': 'host' })
							else:
								self['users'].append(i)
						else:
							# removing following line breaks deletion of computers from groups
							self['users'].append(i)

			time_end = time.time()
			univention.debug.debug(univention.debug.ADMIN, univention.debug.INFO, 'groups/group: open(): member check duration: %1.2fs' % (time_end - time_start))


			self['allowedEmailUsers'] = []
			if self.oldattr.has_key('univentionAllowedEmailUsers'):
				self['allowedEmailUsers'] = self.oldattr['univentionAllowedEmailUsers']

			self['allowedEmailGroups'] = []
			if self.oldattr.has_key('univentionAllowedEmailGroups'):
				self['allowedEmailGroups'] = self.oldattr['univentionAllowedEmailGroups']

			self.save()
示例#16
0
文件: dc.py 项目: B-Rich/smart
			syntax=univention.admin.syntax.string,
			multivalue=0,
			include_in_default_search=1,
			options=[],
			required=1,
			may_change=0,
			identifies=1
		),
	'dnsForwardZone': univention.admin.property(
			short_description=_('DNS forward lookup zone'),
			long_description='',
			syntax=univention.admin.syntax.dnsName,
			multivalue=1,
			options=[],
			required=0,
			default = ( '<name>.%s' % configRegistry.get( 'domainname', '' ), [] ),
			may_change=0,
			identifies=0
		),
	'dnsReverseZone': univention.admin.property(
			short_description=_('DNS reverse lookup zone'),
			long_description='',
			syntax=univention.admin.syntax.reverseLookupSubnet,
			multivalue=1,
			options=[],
			required=0,
			may_change=0,
			identifies=0
		),
	'sambaDomainName': univention.admin.property(
			short_description=_('Samba domain name'),