def doit(options, lo):
    groups = lo.search('objectClass=univentionGroup',
                       attr=['uniqueMember', 'cn', 'gidNumber'])
    if options.verbose:
        print('Found %d ldap groups' % len(groups))

    if len(groups) < 1:
        print('Abort: Did not found any LDAP group.')
        sys.exit(1)

    # Write to a temporary file
    (fdtemp, fdname) = tempfile.mkstemp()
    fd = os.fdopen(fdtemp, 'w')

    for group in groups:
        rdn = ldap.explode_rdn(group[0])
        groupname = string.join(string.split(rdn[0], '=')[1:], '=')
        members = _get_members(lo, group, [], options.check_member)
        # The list(set(members)) call removes all duplicates from the group members
        fd.write('%s:*:%s:%s\n' % (groupname, group[1].get(
            'gidNumber', [''])[0], string.join(list(set(members)), ',')))
    fd.close()

    os.chmod(fdname, 0o644)

    # Move the file
    shutil.move(fdname, options.file)
    if options.verbose:
        print('The file %s was created.' % options.file)

    _run_hooks(options)

    sys.exit(0)
Exemple #2
0
def test_connection():
	'''Search a query that should never fail: RDN of connector/ad/ldap/base'''
	base = ucr.get('connector/ad/ldap/base')
	rdn = explode_rdn(base)[0]
	p1, stdout, stderr = adsearch(rdn)
	if stderr:
		MODULE.warn(stderr)
	if p1.returncode != 0:
		raise ADNotAvailable()
	return True
Exemple #3
0
	def get_samba_home_path_server(self):
		if configRegistry.get('ucsschool/import/set/sambahome'):
			print 'get_samba_home_path_server: UCR variable ucsschool/import/set/sambahome is set'
			return configRegistry.get('ucsschool/import/set/sambahome')
		if configRegistry.is_true('ucsschool/singlemaster', False):
			print 'get_samba_home_path_server: Singlemaster'
			return configRegistry.get('hostname')
		lo = univention.uldap.getMachineConnection()
		result = lo.search(base=self.school_base, scope=ldap.SCOPE_BASE, attr=['ucsschoolHomeShareFileServer'])
		if result:
			share_file_server_dn = result[0][1].get('ucsschoolHomeShareFileServer')[0]
			return ldap.explode_rdn(share_file_server_dn, notypes=1)[0]
		return None
def _get_members(lo, g, recursion_list, check_member=False):
    result = []
    for m in g[1].get('uniqueMember', []):
        if m.startswith('uid='):
            # Does the member exist?
            if check_member:
                try:
                    res = lo.search(base=m,
                                    scope=ldap.SCOPE_BASE,
                                    filter='uid=*',
                                    attr=['uid'])
                    if len(res) < 1:
                        # Not found
                        continue
                except ldap.NO_SUCH_OBJECT:
                    continue
            mrdn = ldap.explode_rdn(m)
            mname = string.join(string.split(mrdn[0], '=')[1:], '=')
            result.append(mname)
        elif m.startswith('cn='):
            try:
                members = lo.search(
                    base=m,
                    scope=ldap.SCOPE_BASE,
                    filter='objectClass=*',
                    attr=['uniqueMember', 'gidNumber', 'objectClass', 'cn'])
            except ldap.NO_SUCH_OBJECT:
                # Member not found
                continue

            if len(members) == 1:
                member = members[0]
            elif len(members) > 1:
                # Not possible
                continue
            else:
                # Member not found
                continue
            if 'univentionGroup' in member[1].get('objectClass', []):
                if member[0] not in recursion_list:
                    recursion_list.append(g[0])
                    result += _get_members(lo, member, recursion_list,
                                           check_member)
                else:
                    # Recursion !!!
                    pass
            else:
                result.append(member[1].get('cn')[0] + '$')
    return result
Exemple #5
0
def rdn_dict(dn, charset='utf-8'):
    rdn, rest = SplitRDN(dn)
    if not rdn:
        return {}
    if type(rdn) == UnicodeType:
        rdn = rdn.encode(charset)
    result = {}
    for i in ldap.explode_rdn(rdn.strip()):
        attr_type, attr_value = explode_rdn_attr(i)
        #    attr_value = unicode(attr_value,charset)
        if result.has_key(attr_type):
            result[attr_type].append(attr_value)
        else:
            result[attr_type] = [attr_value]
    return result
Exemple #6
0
	def update(self, **kwargs):
		for key in kwargs:
			if key == 'dn':
				self.username = ldap.explode_rdn(kwargs[key], notypes=1)[0]
				self.dn = kwargs[key]
			if key == 'username':
				self.username = kwargs[key]
				self.dn = self.make_dn()
			elif key == 'school':
				self._set_school(kwargs[key])
			elif key == 'schools':
				if not self.school and 'school' not in kwargs:
					self._set_school(sorted(kwargs[key])[0])
				self.schools = kwargs[key]
			elif hasattr(self, key):
				setattr(self, key, kwargs[key])
			else:
				print 'ERROR: cannot update Person(): unknown option %r=%r' % (key, kwargs[key])
Exemple #7
0
def _get_members(lo, g, recursion_list, check_member = False):
	result = []
	for m in g[1].get('uniqueMember', []):
		if m.startswith('uid='):
			# Does the member exist?
			if check_member:
				try:
					res = lo.search(base=m, scope=ldap.SCOPE_BASE, filter='uid=*', attr=['uid'])
					if len(res) < 1:
						# Not found
						continue
				except ldap.NO_SUCH_OBJECT:
					continue
			mrdn = ldap.explode_rdn(m)
			mname = string.join( string.split(mrdn[0],'=')[1:], '=')
			result.append(mname)
		elif m.startswith('cn='):
			try:
				members = lo.search(base=m, scope=ldap.SCOPE_BASE, filter='objectClass=*', attr=['uniqueMember', 'gidNumber', 'objectClass', 'cn'])
			except ldap.NO_SUCH_OBJECT:
				# Member not found
				continue

			if len(members) == 1:
				member = members[0]
			elif len(members) > 1:
				# Not possible
				continue
			else:
				# Member not found
				continue
			if 'univentionGroup' in member[1].get('objectClass', []):
				if member[0] not in recursion_list:
					recursion_list.append(g[0])
					result += _get_members(lo, member, recursion_list, options.check_member)
				else:
					# Recursion !!!
					pass
			else:
				result.append(member[1].get('cn')[0]+'$')
	return result
Exemple #8
0
def activate():
    """
     this function define if the module "base" can be activated.
     @return: return True if this module can be activate
     @rtype: boolean
    """
    config = SambaConfig("samba")

    if config.disabled:
        logger.info("samba plugin disabled by configuration.")
        return False

    if config.defaultSharesPath:
        if config.defaultSharesPath.endswith("/"):
            logger.error("Trailing / is not allowed in defaultSharesPath")
            return False
        if not os.path.exists(config.defaultSharesPath):
            logger.error("The default shares path '%s' does not exist" %
                         config.defaultSharesPath)
            return False

    for cpath in config.authorizedSharePaths:
        if cpath.endswith("/"):
            logger.error("Trailing / is not allowed in authorizedSharePaths")
            return False
        if not os.path.exists(cpath):
            logger.error("The authorized share path '%s' does not exist" %
                         cpath)
            return False

    # Verify if samba conf file exist
    conf = config.samba_conf_file
    if not os.path.exists(conf):
        logger.error(conf + " does not exist")
        return False

    # validate smb.conf
    smbconf = SambaConf()
    if not smbconf.validate(conf):
        logger.error("SAMBA configuration file is not valid")
        return False

    # For each share, test if it sharePath exists
    for share in getDetailedShares():
        shareName = share[0]
        infos = shareInfo(shareName)
        if infos:
            sharePath = infos['sharePath']
            if sharePath and not '%' in sharePath and not os.path.exists(
                    sharePath):
                # only show error
                logger.error("The samba share path '%s' does not exist." %
                             sharePath)
        else:
            return False

    try:
        ldapObj = ldapUserGroupControl()
    except ldap.INVALID_CREDENTIALS:
        logger.error("Can't bind to LDAP: invalid credentials.")
        return False

    # Test if the Samba LDAP schema is available in the directory
    try:
        schema = ldapObj.getSchema("sambaSamAccount")
        if len(schema) <= 0:
            logger.error("Samba schema is not included in LDAP directory")
            return False
    except:
        logger.exception("invalid schema")
        return False

    # Verify if init script exist
    init = config.samba_init_script
    if not os.path.exists(init):
        logger.error(init + " does not exist")
        return False

    # If SAMBA is defined as a PDC, make extra checks
    if smbconf.isPdc():
        samba = SambaLDAP()
        # Create SAMBA computers account OU if it doesn't exist
        head, path = samba.baseComputersDN.split(",", 1)
        ouName = head.split("=")[1]
        samba.addOu(ouName, path)
        # Check that a sambaDomainName entry is in LDAP directory
        domainInfos = samba.getDomain()
        # Set domain policy
        samba.setDomainPolicy()
        if not domainInfos:
            logger.error(
                "Can't find sambaDomainName entry in LDAP for domain %s. Please check your SAMBA LDAP configuration."
                % smbconf.getContent("global", "workgroup"))
            return False
        smbconfbasesuffix = smbconf.getContent("global", "ldap suffix")
        if not smbconfbasesuffix:
            logger.error("SAMBA 'ldap suffix' option is not setted.")
            return False
        if ldap.explode_dn(samba.baseDN) != ldap.explode_dn(smbconfbasesuffix):
            logger.error(
                "SAMBA 'ldap suffix' option is not equal to MMC 'baseDN' option."
            )
            return False
        # Check that SAMBA and MMC given OU are in sync
        for option in [
            ("ldap user suffix", "baseUsersDN", samba.baseUsersDN),
            ("ldap group suffix", "baseGroupsDN", samba.baseGroupsDN),
            ("ldap machine suffix", "baseComputersDN", samba.baseComputersDN)
        ]:
            smbconfsuffix = smbconf.getContent("global", option[0])
            if not smbconfsuffix:
                logger.error("SAMBA '" + option[0] + "' option is not setted")
                return False
            # Do a case insensitive comparison of the corresponding MMC / SAMBA options
            if ldap.explode_rdn(smbconfsuffix)[0].lower() != ldap.explode_rdn(
                    option[2])[0].lower():
                logger.error("SAMBA option '" + option[0] +
                             "' is not equal to MMC '" + option[1] +
                             "' option.")
                return False
        # Check that "ldap delete dn" SAMBA option is set to "No"
        smbconfdeletedn = smbconf.isValueTrue(
            smbconf.getContent("global", "ldap delete dn"))
        if smbconfdeletedn == 1:
            logger.error("SAMBA option 'ldap delete dn' must be disabled.")
            return False
        # Check that Domain Computers group exists
        # We need it to put a machine account in the right group when joigning it to the domain
        if not samba.getDomainComputersGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Computers' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Admins group exists
        if not samba.getDomainAdminsGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Admins' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Guests group exists
        if not samba.getDomainGuestsGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Guests' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Users group exists
        if not samba.getDomainUsersGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Users' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that add machine script option is set, and that the given script exist
        addMachineScript = smbconf.getContent("global", "add machine script")
        if not addMachineScript:
            logger.error("SAMBA 'add machine script' option is not set.")
            return False
        else:
            script = addMachineScript.split(" ")[0]
            if not os.path.exists(script):
                logger.error(
                    "SAMBA 'add machine script' option is set to a non existing file: "
                    + script)
                return False
        # Issue a warning if NSCD is running
        if os.path.exists("/var/run/nscd.pid") or os.path.exists(
                "/var/run/.nscd_socket") or os.path.exists("/var/run/nscd"):
            logger.warning(
                "Looks like NSCD is installed on your system. You should not run NSCD on a SAMBA server."
            )
        # Check that os level is set to 255
        oslevel = smbconf.getContent("global", "os level")
        if int(oslevel) < 255:
            logger.debug("Set SAMBA os level to 255.")
            smbconf.setContent("global", "os level", "255")
            smbconf.save()
            reloadSamba()
    try:
        from mmc.plugins.dashboard.manager import DashboardManager
        from mmc.plugins.samba.panel import SambaPanel
        DM = DashboardManager()
        DM.register_panel(SambaPanel("samba"))
    except ImportError:
        pass

    return True
Exemple #9
0
def activate():
    """
     this function define if the module "base" can be activated.
     @return: return True if this module can be activate
     @rtype: boolean
    """
    config = SambaConfig("samba")

    if config.disabled:
        logger.info("samba plugin disabled by configuration.")
        return False

    if config.defaultSharesPath:
        if config.defaultSharesPath.endswith("/"):
            logger.error("Trailing / is not allowed in defaultSharesPath")
            return False
        if not os.path.exists(config.defaultSharesPath):
            logger.error("The default shares path '%s' does not exist" % config.defaultSharesPath)
            return False

    for cpath in config.authorizedSharePaths:
        if cpath.endswith("/"):
            logger.error("Trailing / is not allowed in authorizedSharePaths")
            return False
        if not os.path.exists(cpath):
            logger.error("The authorized share path '%s' does not exist" % cpath)
            return False

    # Verify if samba conf file exist
    conf = config.samba_conf_file
    if not os.path.exists(conf):
        logger.error(conf + " does not exist")
        return False

    # validate smb.conf
    smbconf = SambaConf()
    if not smbconf.validate(conf):
        logger.error("SAMBA configuration file is not valid")
        return False

    # For each share, test if it sharePath exists
    for share in getDetailedShares():
        shareName = share[0]
        infos = shareInfo(shareName)
        if infos:
            sharePath = infos["sharePath"]
            if sharePath and not "%" in sharePath and not os.path.exists(sharePath):
                # only show error
                logger.error("The samba share path '%s' does not exist." % sharePath)
        else:
            return False

    try:
        ldapObj = ldapUserGroupControl()
    except ldap.INVALID_CREDENTIALS:
        logger.error("Can't bind to LDAP: invalid credentials.")
        return False

    # Test if the Samba LDAP schema is available in the directory
    try:
        schema = ldapObj.getSchema("sambaSamAccount")
        if len(schema) <= 0:
            logger.error("Samba schema is not included in LDAP directory")
            return False
    except:
        logger.exception("invalid schema")
        return False

    # Verify if init script exist
    init = config.samba_init_script
    if not os.path.exists(init):
        logger.error(init + " does not exist")
        return False

    # If SAMBA is defined as a PDC, make extra checks
    if smbconf.isPdc():
        samba = SambaLDAP()
        # Create SAMBA computers account OU if it doesn't exist
        head, path = samba.baseComputersDN.split(",", 1)
        ouName = head.split("=")[1]
        samba.addOu(ouName, path)
        # Check that a sambaDomainName entry is in LDAP directory
        domainInfos = samba.getDomain()
        # Set domain policy
        samba.setDomainPolicy()
        if not domainInfos:
            logger.error(
                "Can't find sambaDomainName entry in LDAP for domain %s. Please check your SAMBA LDAP configuration."
                % smbconf.getContent("global", "workgroup")
            )
            return False
        smbconfbasesuffix = smbconf.getContent("global", "ldap suffix")
        if not smbconfbasesuffix:
            logger.error("SAMBA 'ldap suffix' option is not setted.")
            return False
        if ldap.explode_dn(samba.baseDN) != ldap.explode_dn(smbconfbasesuffix):
            logger.error("SAMBA 'ldap suffix' option is not equal to MMC 'baseDN' option.")
            return False
        # Check that SAMBA and MMC given OU are in sync
        for option in [
            ("ldap user suffix", "baseUsersDN", samba.baseUsersDN),
            ("ldap group suffix", "baseGroupsDN", samba.baseGroupsDN),
            ("ldap machine suffix", "baseComputersDN", samba.baseComputersDN),
        ]:
            smbconfsuffix = smbconf.getContent("global", option[0])
            if not smbconfsuffix:
                logger.error("SAMBA '" + option[0] + "' option is not setted")
                return False
            # Do a case insensitive comparison of the corresponding MMC / SAMBA options
            if ldap.explode_rdn(smbconfsuffix)[0].lower() != ldap.explode_rdn(option[2])[0].lower():
                logger.error("SAMBA option '" + option[0] + "' is not equal to MMC '" + option[1] + "' option.")
                return False
        # Check that "ldap delete dn" SAMBA option is set to "No"
        smbconfdeletedn = smbconf.isValueTrue(smbconf.getContent("global", "ldap delete dn"))
        if smbconfdeletedn == 1:
            logger.error("SAMBA option 'ldap delete dn' must be disabled.")
            return False
        # Check that Domain Computers group exists
        # We need it to put a machine account in the right group when joigning it to the domain
        if not samba.getDomainComputersGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Computers' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Admins group exists
        if not samba.getDomainAdminsGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Admins' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Guests group exists
        if not samba.getDomainGuestsGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Guests' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that Domain Users group exists
        if not samba.getDomainUsersGroup():
            logger.error(
                "Can't find sambaGroupMapping entry in LDAP corresponding to 'Domain Users' group. Please check your SAMBA LDAP configuration."
            )
            return False
        # Check that add machine script option is set, and that the given script exist
        addMachineScript = smbconf.getContent("global", "add machine script")
        if not addMachineScript:
            logger.error("SAMBA 'add machine script' option is not set.")
            return False
        else:
            script = addMachineScript.split(" ")[0]
            if not os.path.exists(script):
                logger.error("SAMBA 'add machine script' option is set to a non existing file: " + script)
                return False
        #  Issue a warning if NSCD is running
        if (
            os.path.exists("/var/run/nscd.pid")
            or os.path.exists("/var/run/.nscd_socket")
            or os.path.exists("/var/run/nscd")
        ):
            logger.warning("Looks like NSCD is installed on your system. You should not run NSCD on a SAMBA server.")
        # Check that os level is set to 255
        oslevel = smbconf.getContent("global", "os level")
        if int(oslevel) < 255:
            logger.debug("Set SAMBA os level to 255.")
            smbconf.setContent("global", "os level", "255")
            smbconf.save()
            reloadSamba()
    try:
        from mmc.plugins.dashboard.manager import DashboardManager
        from mmc.plugins.samba.panel import SambaPanel

        DM = DashboardManager()
        DM.register_panel(SambaPanel("samba"))
    except ImportError:
        pass

    return True
Exemple #10
0
    result = []
    groups = lo.search('objectClass=univentionGroup',
                       attr=['uniqueMember', 'cn', 'gidNumber'])
    if options.verbose:
        print 'Found %d ldap groups' % len(groups)

    if len(groups) < 1:
        print 'Abort: Did not found any LDAP group.'
        sys.exit(1)

    # Write to a temporary file
    (fdtemp, fdname) = tempfile.mkstemp()
    fd = os.fdopen(fdtemp, 'w')

    for group in groups:
        rdn = ldap.explode_rdn(group[0])
        groupname = string.join(string.split(rdn[0], '=')[1:], '=')
        members = _get_members(lo, group, [], options.check_member)
        # The list(set(members)) call removes all duplicates from the group members
        fd.write('%s:*:%s:%s\n' % (groupname, group[1].get(
            'gidNumber', [''])[0], string.join(list(set(members)), ',')))
    fd.close()

    os.chmod(fdname, 0o644)

    # Move the file
    shutil.move(fdname, options.file)
    if options.verbose:
        print 'The file %s was created.' % options.file

    _run_hooks(options)
Exemple #11
0
	result = []
	groups = lo.search('objectClass=univentionGroup', attr=['uniqueMember', 'cn', 'gidNumber'])
	if options.verbose:
		print 'Found %d ldap groups' % len(groups)

	if len(groups) < 1:
		print 'Abort: Did not found any LDAP group.'
		sys.exit(1)
	

	# Write to a temporary file
	(fdtemp, fdname) = tempfile.mkstemp()
	fd = os.fdopen(fdtemp, 'w')

	for group in groups:
		rdn = ldap.explode_rdn(group[0])
		groupname = string.join( string.split(rdn[0],'=')[1:], '=')
		members=_get_members(lo, group, [], options.check_member)
		# The list(set(members)) call removes all duplicates from the group members
		fd.write('%s:*:%s:%s\n' % (groupname, group[1].get('gidNumber', [''])[0], string.join(list(set(members)), ',')))
	fd.close()

	os.chmod(fdname, 0644)

	# Move the file
	shutil.move(fdname, options.file)
	if options.verbose:
		print 'The file %s was created.' % options.file

	sys.exit(0)
Exemple #12
0
                try:
                    timeout = int(optdict.get('-t'))
                except ValueError, e:
                    print "Invalid value for timeout. Should be integer (-1 for unlimited, the default)", e
        else:
            print "Missing arguments"
            return

        try:
            outdict = {}  # Data to be added

            # Get data from input DN
            # TODO: encoding
            dn_comps = ldap.explode_dn(dn)
            # There may be more than one component to the RDN
            rdn_comps = ldap.explode_rdn(dn_comps[0])
            for comp in rdn_comps:
                parts = comp.split('=')
                outdict[parts[0]] = [parts[1]]

            outdict['objectClass'] = ocs

            try:
                # Get attributes for each object class specified
                must, may = self.schema.get_oc_info(ocs)
                # Add a * to the front of mandatory attributes
                # This identifies them and makes them sort at the front
                for attr in must:
                    if outdict.has_key(attr):
                        values = outdict[attr][:]
                        del outdict[attr]