Пример #1
0
def createNewClientSubOUs(ldapuri, newClientsOuDn, gosaconffile):

    try:
        user, pw = getLdapCredentials(gosaconffile)
        l = ldap.initialize(ldapuri)
        l.simple_bind_s(user, pw)

        attrs = {}
        attrs['objectclass'] = ['top', 'organizationalUnit']
        attrs['ou'] = ["systems"]

        ldif = modlist.addModlist(attrs)
        l.add_s("ou=systems," + newClientsOuDn, ldif)

    except ldap.LDAPError, error_message:
        syslog.syslog(syslogprefix + str(error_message))
        pass

        attrs = {}
        attrs['objectclass'] = ['top', 'organizationalUnit']
        attrs['ou'] = ["workstations"]

        ldif = modlist.addModlist(attrs)
        l.add_s("ou=workstations,ou=systems," + newClientsOuDn, ldif)

        l.unbind_s()
def createNewClientSubOUs(ldapuri, newClientsOuDn, gosaconffile):

     try:
	user, pw = getLdapCredentials(gosaconffile)
        l = ldap.initialize(ldapuri)
        l.simple_bind_s(user, pw)


	attrs = {}
	attrs['objectclass'] = ['top','organizationalUnit']
	attrs['ou'] = ["systems"]


	ldif = modlist.addModlist(attrs)
	l.add_s("ou=systems,"+newClientsOuDn,ldif)

     except ldap.LDAPError, error_message:
	syslog.syslog(syslogprefix+str(error_message))
	pass

	attrs = {}
	attrs['objectclass'] = ['top','organizationalUnit']
	attrs['ou'] = ["workstations"]

	ldif = modlist.addModlist(attrs)
	l.add_s("ou=workstations,ou=systems,"+newClientsOuDn,ldif)

	l.unbind_s() 
Пример #3
0
 def add_ou(self):
     modlist = addModlist(
         {'objectClass': [b'organizationalUnit'], 'ou': [b'people']}
     )
     self._ldap_obj.add_s(self.PEOPLE_DN, modlist)
     modlist = addModlist(
         {'objectClass': [b'organizationalUnit'], 'ou': [b'quebec']}
     )
     self._ldap_obj.add_s(self.QUEBEC_DN, modlist)
Пример #4
0
    def psqlusr_ldap_init(self, default_rules):
        """
        Creates a new hbac rule and service during initialisation.
        """
        try:
            self.ldap_obj.add_s("cn=%s,cn=hbacservices,cn=hbac,dc=internal,dc=n0q,dc=eu"
                                % self.postgresql_service,
                                modlist.addModlist(
                                    {'objectClass': [b'ipaobject', b'ipahbacservice'],
                                     'description': [b'psqlusr service for postgresql']}))
        except ALREADY_EXISTS:
            logging.info("HBAC service already exists, skipping creation")
        except LDAPError as err:
            logging.error(err)
            raise SystemError

        try:
            hbacrule_name = "psqlusr_" + self.hostname
            member_user = []
            for line in default_rules:
                line_split = line.split(":")
                if len(line_split) != 4:
                    continue
                if line_split[1] == "group":
                    member_user.append(b"%b" % str("cn={},".format(line_split[0])
                                                   + LDAP_GROUP_BASE).encode())
                elif line_split[1] == "user":
                    member_user.append(b"%b" % str("uid={},".format(line_split[0])
                                                   + LDAP_USER_BASE).encode())
                else:
                    continue
            hbacrule_modlist = modlist.addModlist({
                'objectClass': [b'ipaassociation', b'ipahbacrule'],
                'cn': [b"%b" % str(hbacrule_name).encode()],
                'accessRuleType': [b'allow'],
                'ipaEnabledFlag': [b'TRUE'],
                'memberService': [b'cn=%b,cn=hbacservices,cn=hbac,dc=internal,dc=n0q,dc=eu'
                                  % str(self.postgresql_service).encode()],
                'memberHost': [b'fqdn=%b,%b' % (str(self.hostname).encode(),
                                                LDAP_HOST_BASE.encode())],
                'description': [b'gitlab.n0q.eu/platform/wiki/wikis/psqlusr/deployment-usage\n'
                                b'Place your permissions after this line; each on a new line!\n\n' +
                                b"%b" % "\n".join(default_rules).encode()
                                ],
                'memberUser': member_user
            })

            self.ldap_obj.add_s("ipaUniqueID=%s,cn=hbac,dc=internal,dc=n0q,dc=eu" % hbacrule_name,
                                hbacrule_modlist)

        except ALREADY_EXISTS:
            logging.info("HBAC rule already exists, skipping creation")
        except LDAPError as err:
            logging.error(err)
            raise SystemError
Пример #5
0
def configOU():
    # A dict to help build the "body" of the object
    attrs = {}
    attrs['dn'] = 'dc=10gen,dc=me'
    attrs['objectclass'] = ['organiationalUnit']
    attrs['ou'] = 'Users'
    ldif = modlist.addModlist(attrs)
Пример #6
0
    def create(self, person):
        '''
        Creates a new LDAP user.
        Takes as argument a dictionary with the following key/value pairs:

        objectclass                 ['User','etc']
        givenName                   [first name]
        sn                          [last name]
        carthageDob                 [date of birth]
        settings.LDAP_ID_ATTR       [college ID]
        cn                          [we use email for username]
        mail                        [email]
        userPassword                [password]
        carthageFacultyStatus       [faculty]
        carthageStaffStatus         [staff]
        carthageStudentStatus       [student]
        carthageFormerStudentStatus [alumni]
        carthageOtherStatus         [trustees etc]
        '''

        user = modlist.addModlist(person)

        dn = 'cn={},{}'.format(person['cn'],self.base)
        self.l.add_s(dn, user)
        return self.search(person[settings.LDAP_ID_ATTR])
Пример #7
0
def save(user):
    attrs={}
    attrs['cn']=str(user.username)
    attrs['objectClass']='inetOrgPerson'
    attrs[settings.ACCOUNT_LDAP_USER_ATTR_MAP["first_name"]]=str(user.first_name)
    attrs[settings.ACCOUNT_LDAP_USER_ATTR_MAP["last_name"]]=str(user.last_name)
    attrs[settings.ACCOUNT_LDAP_USER_ATTR_MAP["email"]]=str(user.email)

    ld=init_bind()
    result=search(user.username,ld)

    dn="cn="+str(user.username)+","+settings.ACCOUNT_LDAP_BASE_DN
    if(result==None or result==[]):
        ldif=modlist.addModlist(attrs)
        ld.add_s(dn,ldif)
    else:
        ldn,data=result[0]
        newData=data.copy()
        for key,attrD in attrs.items():
            newData[key]=attrD
        ldif=modlist.modifyModlist(data,newData)
        ld.modify_s(dn,ldif)

    is_deny=searchDenylist(user.username,ld)
    if(user.is_active==False):
       if(is_deny==False):
           appendDenylist(user.username,ld)
    else:
       if(is_deny==True):
           removeDenylist(user.username,ld)

    ld.unbind()
    def _createOrUpdate(self, member_list, ldap_conn):
        new_records = filter(lambda m: not ldap_conn.ldap_search(self._LDAP_TREE['accounts'],
                                                                 _ldap.SCOPE_ONELEVEL,
                                                                 filterstr='employeeNumber=%s' % m['employeeNumber'],
                                                                 attrsonly=1),
                             member_list)

        map(lambda c: ldap_conn.ldap_add('cn=%s,%s' % (self._createCN(c, ldap_conn), self._LDAP_TREE['accounts']),
                                         _modlist.addModlist(self._getLDAPCompatibleAccount(c),
                                                             ignore_attr_types=['cn'])),
            new_records)

        map(lambda u: ldap_conn.ldap_update('%s' % self._ldapCN(u['employeeNumber'], ldap_conn),
                                            _modlist.modifyModlist(ldap_conn.ldap_search(self._LDAP_TREE['accounts'],
                                                                                         _ldap.SCOPE_ONELEVEL,
                                                                                         filterstr='employeeNumber=%s'
                                                                                         % u['employeeNumber'])[0][1],
                                                                   self._getLDAPCompatibleAccount(u),
                                                                   ignore_attr_types=['userPassword', 'cn'])),
            filter(lambda m: cmp(dict(self._getLDAPCompatibleAccount(m)),
                                 ldap_conn.ldap_search(self._LDAP_TREE['accounts'],
                                                       _ldap.SCOPE_ONELEVEL,
                                                       filterstr='employeeNumber=%s' % m['employeeNumber'],
                                                       attrlist=['displayName', 'objectClass', 'employeeType',
                                                                 'mobile', 'employeeNumber', 'sn',
                                                                 'mail', 'givenName'])[0][1]),
                   member_list))

        return new_records
 def as_replog(self, url, basedn, binddn, bindpw):
     ld = ldap.initialize(url)
     ld.simple_bind_s(binddn, bindpw)
     sk = self.ldap_search_key()
     lu = ld.search_s \
         ( basedn
         , ldap.SCOPE_SUBTREE
         , sk
         , self.ldif_map.keys () + self.object_class
         )
     print lu
     if len(lu) > 1:
         raise ValueError, "More than one entry found for %s" % sk
     if not lu:
         return self._ldif \
             (self.dn (), modlist.addModlist (self.as_ldap_entry ()))
     ret = []
     dn = self.dn().split(',')
     if self.dn() != lu[0][0]:
         ret.append('dn: %s' % lu[0][0])
         ret.append('changetype: modrdn')
         ret.append('newrdn: %s' % dn[0])
         ret.append('deleteoldrdn: 1')
         ret.append('newSuperior: %s' % ','.join(dn[1:]))
         ret.append('')
     ret.append \
         ( self._ldif
             ( self.dn ()
             , modlist.modifyModlist (lu [0][1], self.as_ldap_entry ())
             )
         )
     return '\n'.join(ret)
Пример #10
0
    def adduser(self, name, surname, username, usersecret, expireDate, uidNo, badgenum):
        if (self.userexistsbyuid(username) ):
            print("User %s already exist!", username)
            return

        dn = "uid="+username+",ou=People,"+self.dc

        attrs = {}
        attrs['uid']            = username
        attrs['userPassword']   = usersecret
        attrs['givenName']      = name
        attrs['sn']             = surname
        attrs['cn']             = name+' '+surname
        attrs['objectClass']    = ['person',
                                   'organizationalPerson',
                                   'inetOrgPerson',
                                   'posixAccount',
                                   'top',
                                   'shadowAccount']
        attrs['shadowMax']      = '99999'
        attrs['shadowWarning']  = '7'
        attrs['shadowExpire']   = expireDate
        attrs['loginShell']     = '/bin/bash'
        attrs['uidNumber']      = uidNo
        attrs['gidNumber']      = '100'
        attrs['homeDirectory']  = '/home/'+username
        attrs['gecos']          = name+' '+surname+',,,,'+badgenum
        attrs['employeeNumber'] = badgenum
        attrs['mail']           = username+'@lcm.mi.infn.it'

        # Convert our dict to nice syntax for the add-function using modlist-module
        ldif = modlist.addModlist(attrs)

        # Do the actual synchronous add-operation to the ldapuri
        self.conn.add_s(dn,ldif)
Пример #11
0
    def addUserCertificateMetadata(self):
        result = self.conn.search_s(
            'o=gluu', ldap.SCOPE_SUBTREE,
            '(&(objectClass=gluuAttribute)(gluuAttributeName=userCertificate))'
        )
        if not result:
            dn = 'inum={0}!0005!CACA,ou=attributes,o={0},o=gluu'.format(
                self.inumOrg)
            entry = {
                'displayName': ['User certificate'],
                'description': ['User certificate'],
                'gluuStatus': ['active'],
                'objectClass': ['gluuAttribute', 'top'],
                'urn': ['urn:mace:dir:attribute-def:userCertificate'],
                'oxValidation':
                ['{"minLength":null,"maxLength":2048,"regexp":""}'],
                'gluuAttributeEditType': ['admin', 'user'],
                'gluuAttributeOrigin': ['gluuPerson'],
                'gluuAttributeViewType': ['admin', 'user'],
                'inum': ['{0}!0005!CACA'.format(self.inumOrg)],
                'gluuAttributeType': ['certificate'],
                'gluuAttributeName': ['userCertificate']
            }

            result = self.conn.add_s(dn, modlist.addModlist(entry))
        else:
            print "No need to add certificate metadata"
Пример #12
0
def _addUserToLDAP(ldapUrl, adminUser, adminPass, rdfPerson):
    ldapConn = ldap.initialize(ldapUrl)
    ldapConn.simple_bind_s(adminUser, adminPass)

    # construct DN
    dn = "uid="+rdfPerson.uid+",dc=edrn,dc=jpl,dc=nasa,dc=gov"
    attrs = {}
    attrs['objectclass'] = ['top', 'person', 'organizationalPerson', 'edrnPerson', 'inetOrgPerson']
    attrs['cn'] = str(rdfPerson.firstname + " " +rdfPerson.lastname)
    attrs['userPassword'] = str(_defaultPwd)
    attrs['uid'] = str(rdfPerson.uid)
    attrs['mail'] = str(rdfPerson.email)
    attrs['telephoneNumber'] = str(rdfPerson.phone)
    attrs['sn'] = str(rdfPerson.lastname)
    attrs['description'] = str(_defaultDesc+time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()))
    
    ldif = modlist.addModlist(attrs)
    success=False
    
    if(not personExists(ldapConn, rdfPerson.uid)):
        verboseLog("Syncing record: ["+str(ldif)+"]")
        try:
            ldapConn.add_s(dn,ldif)
            success=True
        except ldap.LDAPError, e:
            print e.message['info']
Пример #13
0
 def add(self, new_entry):
     """
     Add new entry to the LDAP directory.
     """
     dn = new_entry.dn
     entry_modlist = modlist.addModlist(new_entry)
     self.ldap_handle.add_s(dn, entry_modlist)
Пример #14
0
    def createUser(self, uid, sammyNick, mail, pwd):
        new_uid = self.get_new_uid()
        con = self.connect(config.LDAP_ADMIN_DN, config.LDAP_ADMIN_PW)

        # Calling .decode() fixed fuckups with strings. Nobody knows how it was introduced :(

        dn = config.LDAP_USER_DN.format(
            ldap.filter.escape_filter_chars(sammyNick.decode()))

        attrs = {}
        self.ensure_object_classes(attrs)
        attrs['uid'] = ldap.filter.escape_filter_chars(uid.decode()).encode()
        attrs['sn'] = ldap.filter.escape_filter_chars(
            sammyNick.decode()).encode()
        attrs['mail'] = ldap.filter.escape_filter_chars(mail.decode()).encode()
        attrs['uidNumber'] = str(new_uid).encode()
        attrs['gidNumber'] = config.LDAP_MEMBER_GID.encode()
        attrs['homeDirectory'] = ldap.filter.escape_filter_chars(
            '/home/{:s}'.format(uid.decode())).encode()

        ldif = modlist.addModlist(attrs)
        print(ldif)
        print(type(ldif))
        print([type(f) for e in ldif for f in e])

        con.add_s(dn, ldif)
        con.passwd_s(dn, None, pwd)
        con.unbind_s()
Пример #15
0
def user_add(admin_password, username, first_name, last_name, email, password):
    # connection and bind
    l = ldap.open(LDAP_SERVER)
    l.simple_bind_s(LDAP_ADMIN, admin_password)

    # dn of the new user
    new_user_dn = 'cn=%s %s,%s' % (first_name, last_name, LDAP_USER_BASE)

    # getting ldap attributes together
    attrs = {}
    attrs['objectclass'] = ['top', 'inetOrgPerson']
    attrs['cn'] = '%s %s' % (str(first_name), str(last_name))
    attrs['mail'] = str(email)
    attrs['givenName'] = str(first_name)
    attrs['sn'] = str(last_name)
    attrs['uid'] = str(username)
    attrs['userPassword'] = str(encode_password(password))

    # create ldif
    ldif = modlist.addModlist(attrs)

    # add ldif to server
    l.add_s(new_user_dn, ldif)

    # disconnect
    l.unbind_s()
Пример #16
0
		def addHacker( self, uid, name, address, alias, econtact, status, level ):

			self.validateUID(uid)
			self.validateName(name)
			self.validateAddress(address)
			self.validateAlias(alias)
			self.validateEContact(econtact)
			self.validateStatus(status)
			self.validateLevel(level)

			if self.hackerExists(uid) == True:
				print "Hacker with uid " + uid + " already exists"
				return
			
			addDN = "uid=" + uid + "," + self.HACKER_BASE

			attrs = {}
			attrs['objectclass'] = [ 'top', 'iLockRocUser']
			attrs['uid'] = uid
			attrs['iLockRocName'] = name
			attrs['iLockRocAddress'] = address
			attrs['iLockRocAlias'] = alias
			attrs['iLockRocEmergencyContact'] = econtact
			attrs['iLockRocMemberStatus'] = status
			attrs['iLockRocMemberLevel'] = level

			# turn it into ldif
			ldif = modlist.addModlist(attrs)

			# add to server
			self.conn.add_s( addDN, ldif )

			# print to screen
			self.dumpHacker( uid )
Пример #17
0
		def	addButton( self, buttonID ):

			#
			# Real men would regexp check the button id right about here and explode
			#
			self.validateButtonID(buttonID)

			if self.buttonExists(buttonID) == True:
				print "Button with ID " + buttonID + " already exists"
				return

			addDN = "uid=" + buttonID + "," + self.BUTTON_BASE

			attrs = {}
			attrs['objectclass'] = ['top','iLockButton']
			attrs['iLockRocButtonID'] = buttonID
			attrs['iLockRocButtonActive'] = 'FALSE'

			# turn it into ldif
			ldif = modlist.addModlist(attrs)

			# stuff it into the server
			self.conn.add_s(addDN,ldif)

			# print to screen
			self.dumpButton( buttonID )
Пример #18
0
    def ldap_add_user(self):
        # this will create the username under the tree for the (self.ldap_base_dn) configured on ad-add-user.yaml
        user_dn = 'cn=' + self.firstname + ' ' + self.lastname + ',' + self.ldap_base_dn
        
        user_attrs = {}
        user_attrs['objectClass']           = ['top', 'person', 'organizationalPerson', 'user']
        user_attrs['cn']                    = [self.firstname + ' ' + self.lastname]
        user_attrs['userPrincipalName']     = [self.user + '@' + self.ldap_domain] # [email protected]
        user_attrs['sAMAccountName']        = [self.user] # john.doe
        user_attrs['givenName']             = [self.firstname] # John
        user_attrs['sn']                    = [self.lastname] # Doe
        user_attrs['displayName']           = [self.displayname] # self.displayname
        user_attrs['userAccountControl']    = ['514'] # account disabled
        user_attrs['mail']                  = [self.mail] # [email protected]
        user_ldif = modlist.addModlist(user_attrs)

        # New group membership
        add_member = [(ldap.MOD_ADD, 'member', user_dn)]

        # Add the new user account
        try:
            if self.debug: print "+ creating user account [%s]" %self.user
            self.ldap_client.add_s(user_dn, user_ldif)
        except ldap.LDAPError, error_message:
          print "Error adding new user: %s" % error_message
          return False
Пример #19
0
def checkParentOu(institutionOu):
    pawseyLdap = initLDAP()
    searchFilter = ("ou=%s" % institutionOu)
    baseDn = ("ou=People,%s" % ldapBaseDN)

    try:
        ldap_result_id = pawseyLdap.search(baseDn, ldapSearchScope, searchFilter, ldapRetrieveAttributes)
        result_data = []
        result_type, result_data = pawseyLdap.result(ldap_result_id, 0)
        pawseyLdap.unbind_s()
        if (result_data == []):
            print ("OU %s does not exist, creating" % institutionOu)
            
            pawseyLdap = initLDAP()
            # This is basDn created above, not ldapBaseDN
            dn = 'ou=%s,%s' % (institutionOu, baseDn)

            attrs = {}
            attrs['ou'] = str(institutionOu) 
            attrs['objectClass'] = 'organizationalunit'
            
            # Make the attributes dictionary into something we can throw at an ldap server
            ldif = modlist.addModlist(attrs)

            # Throw it at the ldap server!
            try: 
                pawseyLdap.add_s(dn,ldif)
            except ldap.LDAPError, e:
                print e
                exit(1)
            return 0

        else:
Пример #20
0
def configOU():
	# A dict to help build the "body" of the object
	attrs = {}
	attrs['dn'] = 'dc=10gen,dc=me'
	attrs['objectclass'] = ['organiationalUnit']
	attrs['ou'] = 'Users'
	ldif = modlist.addModlist(attrs)
Пример #21
0
def create(request):
    if request.POST:
        username = str(request.POST.get('username'))
        password = str(request.POST.get('password'))

        igsb_ldap = ldap.initialize(LDAP_URL)
        igsb_ldap.simple_bind_s(LDAP_BIND_CN, LDAP_PASSWORD)

        dn = 'ou={},dc=igsb,dc=uchicago,dc=edu'.format(username)
        attrs = {
            'objectClass': 'organizationalUnit',
            'ou': username,
            'userPassword': password
        }

        ldif = modlist.addModlist(attrs)

        try:
            igsb_ldap.add_s(dn, ldif)
        except ldap.ALREADY_EXISTS:
            # Username already exists
            messages.add_message(request, messages.INFO, 'Account {} already exists.'.format(username))
            return HttpResponseRedirect(reverse_lazy('create_home'))

        igsb_ldap.unbind_s()

        return HttpResponseRedirect(reverse_lazy('create_success', args=(username,)))

    return HttpResponseRedirect(reverse_lazy('account_error'))
Пример #22
0
def addGroupToLdap(groupname,description,username):
    check = False
    try:
        # Open a connection
        l = ldap.initialize(settings.AUTH_LDAP_SERVER_URI)

        # Bind/authenticate with a user with apropriate rights to add objects
        l.simple_bind_s(settings.AUTH_LDAP_BIND_DN,str(settings.AUTH_LDAP_BIND_PASSWORD))

        # The dn of our new entry/object
        dn="cn="+groupname+","+str(settings.AUTH_LDAP_BASE_GROUP_DN)

        member="uid="+username+","+str(settings.AUTH_LDAP_BASE_USER_DN)

        # A dict to help build the "body" of the object
        attrs = {}
        attrs['objectclass'] = [str('groupOfNames').encode('utf-8')]
        attrs['cn'] = str(groupname).encode('utf-8')
        attrs['description'] = str(description).encode('utf-8')
        attrs['member']=[str(member).encode('utf-8')]
        attrs['owner']=[str(member).encode('utf-8')]
        # Convert our dict to nice syntax for the add-function using modlist-module
        ldif = modlist.addModlist(attrs)

        # Do the actual synchronous add-operation to the ldapserver
        l.add_s(dn,ldif)

        # Its nice to the server to disconnect and free resources when done
        l.unbind_s()
        check = True
    except ldap.LDAPError:
        traceback.print_exc(file=sys.stdout)
    return check
Пример #23
0
def addUser(user, conn, baseDN):
    # # The dn of our new entry/object
    dn = "uid=" + str(user.uid) + ",ou=users," + baseDN
    #
    # # A dict to help build the "body" of the object
    attrs = {}
    attrs['objectclass'] = [b'top', b'inetOrgPerson', b'posixAccount']
    attrs['cn'] = user.fullname.encode('utf-8')
    attrs['sn'] = user.lastname.encode('utf-8')
    attrs['givenname'] = user.firstname.encode('utf-8')
    attrs['displayname'] = attrs['cn']
    attrs['uid'] = user.uid.encode('utf-8')
    attrs['uidNumber'] = str(user.uidNumber).encode('utf-8')
    attrs['gidNumber'] = b'0'
    attrs['description'] = b''
    attrs['homeDirectory'] = b'none'
    attrs['loginShell'] = b'true'
    attrs['userPassword'] = user.passwordHash

    attrs['mail'] = user.mail.encode('utf-8')

    # Convert our dict to nice syntax for the add-function using modlist-module
    ldif = modlist.addModlist(attrs)
    #
    # # Do the actual synchronous add-operation to the ldapserver


    print(userPassword.encode('utf-16-le'))
    print(ldif)

    try:
        conn.add_s(dn,ldif)
        print("Done")
    except ldap.ALREADY_EXISTS:
        print("Already exist")
Пример #24
0
 def ldap_add_user(self, user, password, is_superuser):
     ad_suffix = GVSIGOL_LDAP['AD']
     if self.is_enabled:
         # The dn of our new entry/object
         dn=str("cn=" + user.username + ",ou=users," + self.domain)
         
         # A dict to help build the "body" of the object
         attrs = {}
         attrs['cn'] = str(user.username)
         attrs['gidNumber'] = str('500')
         attrs['givenName'] = str(user.first_name)
         attrs['homeDirectory'] = str('/home/users/' + user.username)
         if is_superuser:
             attrs['objectclass'] = ['top','posixAccount','inetOrgPerson','extensibleObject']
             attrs['olcExtraAttrs'] = 'CAT_ALL_Administrator'
         else:
             attrs['objectclass'] = ['top','posixAccount','inetOrgPerson']
         attrs['userPassword'] = '******' + str(user.username) + ad_suffix
         attrs['uidNumber'] = str(GvSigOnlineServices.ldap_get_last_uid(self) + 1)
         attrs['sn'] = str(user.username)
         attrs['uid'] = str(user.username)
         
         # Convert our dict to nice syntax for the add-function using modlist-module
         ldif = modlist.addModlist(attrs)
         
         # Do the actual synchronous add-operation to the ldapserver
         self.ldap.add_s(dn,ldif)
         
         self.ldap_add_default_group_member(user)
Пример #25
0
 def try_register(username, password, certificate):
     conn = get_ldap_connection()
     conn.simple_bind_s('cn=admin,dc=projet,dc=com', 'Inchalah1.')
     # Search for existing user otherwise raise error
     result = conn.search_s('ou=people,dc=projet,dc=com', ldap.SCOPE_SUBTREE,
                            '(&(objectclass=inetOrgPerson)(sn=' + username + '))',
                            ['sn'])
     if result:
         raise ValueError('User already exist')
     # If user does not exist add it to ldap server
     else:
         attributes = {
             "objectClass": [b"inetOrgPerson"],
             "sn": [username.encode('utf-8')],
             "cn": [username.encode('utf-8')],
             "userPassword": [password.encode('utf-8')],
             "description": [certificate.encode('utf-8')]
         }
         ldif = modlist.addModlist(attributes)
         res = conn.add_s(
             'cn=' + username + ',ou=people,dc=projet,dc=com', ldif
         )
         conn.unbind_s()
         if res:
             return True
         else:
             return False
Пример #26
0
    def create(self, username, full_name, email, shell='/bin/bash'):
        attrs = {}
        attrs['distinguishedName'] = \
            'cn=%s,ou=users,ou=\\+Objects,dc=yourdomain,dc=com' % full_name
        attrs['objectClass'] = [
            'top', 'posixAccount',
            'person', 'organizationalPerson',
            'user', 'account']
        attrs['primaryGroup'] = '513'
        attrs['sAMAccountName'] = username
        attrs['uid'] = username
        attrs['cn'] = full_name
        attrs['givenName'] = full_name.split()[0]
        attrs['sn'] = full_name.split()[1]
        attrs['mail'] = email
        attrs['homeDirectory'] = '/home/%s' % username
        attrs['objectCategory'] = [
            'cn=person,cn=schema,cn=configuration,dc=yourdomain,dc=com']
        attrs['loginShell'] = shell
        attrs['instanceType'] = '4'
        attrs['countryCode'] = '0'
        attrs['userAccountControl'] = '544'
        attrs['gidNumber'] = '1008'
        # Note: 544 = enabled, 546 = disabled

        ldif = modlist.addModlist(attrs)
        userDN = 'cn=%s,ou=users,ou=\\+Objects,dc=yourdomain,dc=com' \
            % full_name
        self.connection.add_s(userDN, ldif)
Пример #27
0
def _addUserToLDAP(ldapUrl, adminUser, adminPass, rdfPerson):
    ldapConn = ldap.initialize(ldapUrl)
    ldapConn.simple_bind_s(adminUser, adminPass)

    # construct DN
    dn = "uid=" + rdfPerson.uid + ",dc=edrn,dc=jpl,dc=nasa,dc=gov"
    attrs = {}
    attrs['objectclass'] = [
        'top', 'person', 'organizationalPerson', 'edrnPerson', 'inetOrgPerson'
    ]
    try:
        attrs['cn'] = str(rdfPerson.firstname + " " + rdfPerson.lastname)
    except UnicodeEncodeError:
        attrs['cn'] = 'UNKNOWN'
    attrs['userPassword'] = generatePassword()
    attrs['uid'] = str(rdfPerson.uid)
    attrs['mail'] = str(rdfPerson.email)
    attrs['telephoneNumber'] = str(rdfPerson.phone)
    attrs['sn'] = str(rdfPerson.lastname)
    attrs['description'] = str(
        _defaultDesc + time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()))

    ldif = modlist.addModlist(attrs)
    success = False

    if (not personExists(ldapConn, rdfPerson.uid)):
        verboseLog("Syncing record: [" + str(ldif) + "]")
        try:
            ldapConn.add_s(dn, ldif)
            success = True
        except ldap.LDAPError, e:
            print e.message['info']
Пример #28
0
    def ldap_add_user(self, username, detailsDict, pwencoding=None, objectclasses=[], usercontainer='', userdn='', basedn=''):
        '''You need to have used an admin enabled username and password to successfully do this'''
        username = username.strip()
        f = "(&(objectclass=person) (uid=%s))" % username
        usrs = self.ldap_query(filter = f, base=self.USER_BASE)
        retval = False
        if len(usrs) != 0:
            #user already existed!
            logger.debug('\tA user called %s already existed. Refusing to add.' % (username))
            #print('\tA user called %s already existed. Refusing to add.' % (username))
        else:
            try:
                logger.debug('\tPreparing to add user %s' % (username))
                dn = 'uid=%s,%s,%s,%s' % (username, usercontainer, userdn, basedn)
                from copy import deepcopy
                data = deepcopy(detailsDict)
                if isinstance(objectclasses, list):
                    data['objectClass'] = objectclasses
                else:
                    data['objectClass'] = [objectclasses]
                    
                #newattrs = []
                #for key in data:
                #    newattrs.append( (str(key), str(data[key])) )
                newattrs = modlist.addModlist(data)

                #so now newattrs contains a list of tuples, which are key value pairs.
                logger.debug('Calling ldap_add: %s and %s' % (dn, str(newattrs)) )
                #print('Calling ldap_add: %s and %s' % (dn, str(newattrs)) )
                res = self.l.add_s(dn, newattrs)
                #TODO interrogate res
                retval = True
            except ldap.LDAPError, e:
                logger.debug('Exception adding LDAP user: ', str(e))
def add_users_to_tenant(tenant, user_list, role=default_role):
	if existed_role_in_tenant(tenant, role):
		return False
	#calling this function must be ensured that role isn't existed in the given tenant
	#need to check outside in the caller method, sync_api.py
	role_dn,attributes = build_role_child_entry(role,tenant)
	# Open a connection
	l = ldap.initialize("ldap://localhost/")
	# Bind/authenticate with a user with apropriate rights to add objects
	l.simple_bind_s("cn=Manager,dc=cse,dc=hcmut","openstack")
	# Convert our dict to nice syntax for the add-function using modlist-module
	ldif = modlist.addModlist(attributes)
	#ldap.modlist.modifyModlist()
	l.add_s(role_dn,ldif)
	
	users = list()
	for user in user_list:
		users.append("cn=%s,%s" %(user,user_base_dn))
		
	current_tenant_dn='cn=%s,cn=%s,%s'%(role,tenant,tenant_base_dn)

	#add bulk of users to roleOccupant
	old = {'roleOccupant':''}
	new = {'roleOccupant':tuple(users)}

	# Convert place-holders for modify-operation using modlist-module
	ldif = modlist.modifyModlist(old,new)
	# Do the actual modification 
	l.modify_s(current_tenant_dn,ldif)
	# Its nice to the server to disconnect and free resources when done
	l.unbind_s()
	return True
Пример #30
0
    def create_user(self, username, base_dn, domain, password='', first_name='', last_name='', email='', group=''):
        """
        Create a new user account in Active Directory.
        """
        username = username.encode('utf-8')
        fname = first_name.encode('utf-8')
        lname = last_name.encode('utf-8')
        domain = domain.encode('utf-8')
        email = email.encode('utf-8')
        group = group.encode('utf-8')

        user_dn = 'cn=%s,%s' % (username, base_dn)

        user_attrs = {
            'objectClass': ['top', 'person', 'organizationalPerson', 'user'],
            'cn': username,
            'userPrincipalName': username + '@' + domain,
            'sAMAccountName': username,
            'givenName': fname,
            'sn': lname,
            # 'member': 'CN=%s,CN=Users,DC=tatar,DC=local' % (group,),
            'displayName': '%s %s' % (fname, lname),
            'unicodePwd': (u'\"%s\"' % password).encode('utf-16-le'),
            'userAccountControl': '66048'
        }
        if email:
            user_attrs['mail'] = email


        user_ldif = modlist.addModlist(user_attrs)

        try:
            self._connection.add_s(user_dn, user_ldif)
        except ldap.LDAPError, error_message:
            raise LdapApiError(error_message)
Пример #31
0
def create_user(new_officers, login):
    print new_officers[login]
    l = init_ldap()
    nextUid = find_next_uid(l)
    # The dn of our new entry/object

    dn = "uid=%s,ou=people,dc=hkn, dc=eecs, dc=berkeley, dc=edu" % login

    # A dict to help build the "body" of the object
    attrs = {}
    attrs['objectClass'] = ['top', 'posixAccount', 'shadowAccount', 'account']
    attrs['cn'] = new_officers[login][5]
    attrs['userPassword'] = '******'
    attrs['uid'] = login
    attrs['uidNumber'] = str(nextUid)
    attrs['gidNumber'] = '200'
    attrs['homeDirectory'] = '/home/%s' % login
    attrs['loginShell'] = '/bin/bash'

    # Convert our dict to nice syntax for the add-function using modlist-module
    ldif = modlist.addModlist(attrs)

    # Do the actual synchronous add-operation to the ldapserver
    l.add_s(dn, ldif)

    # Its nice to the server to disconnect and free resources when done
    l.unbind_s()
Пример #32
0
def ldap_ou(topic, base, ou, name, description):

    log_debug(
        f"[LDAP_OU]\n\tBase: {base}\n\tOU: {ou}\n\tNAME: {name}\n\tDESCRIPTION: {description}"
    )

    result = ldap_session.search_s(
        base, ldap.SCOPE_ONELEVEL,
        f"(&(objectclass=organizationalUnit)(ou={ou}))")
    log_ldap_result(result)

    if len(result) == 0:

        attrs = {}
        attrs['objectclass'] = [
            b'top', b'organizationalUnit', b'extensibleObject'
        ]
        attrs['name'] = name.encode()
        attrs['description'] = description.encode()

        ldif = modlist.addModlist(attrs)

        try:
            ldap_session.add_s(f"ou={ou},{base}", ldif)
            ldap_session.add_s(f"ou=people,ou={ou},{base}", ldif)
            ldap_session.add_s(f"ou=groups,ou={ou},{base}", ldif)
        except Exception as e:
            panic(f"Error during LDAP ADD, Error: {str(e)}")

        push_notification(topic, ou)
Пример #33
0
def create_new_person_on_ldap(user_form):
    l = get_ldap_client()

    attrs = {}
    attrs['objectclass'] = current_app.config["LDAP_PERSON_OBJECT_CLASSES"]
    attrs['uid'] = str(user_form["user"]["username"])
    attrs['userPassword'] = str(user_form["security"]["password"])
    #attrs['cuit'] = str(user_form["user"]["cuit"])
    attrs['mail'] = str(user_form["user"]["email"])
    attrs['cn'] = str(user_form["user"]["cn"])
    attrs['sn'] = str(user_form["user"]["sn"])
    attrs['title'] = str("ACTIVE")
    #attrs['documentType']= str(user_form["user"]["comboBoxdocumentType"]["text"])
    #attrs['documentNumber']= str(user_form["user"]["documentNumber"])
    #attrs['telephoneNumber']= str(user_form["user"]["telephoneNumber"])
    #attrs['inetuserstatus']= str(current_app.config["LDAP_PERSON_STATUS_DEFAULT"])
    #attrs['mobileNumber']= str(user_form["user"]["mobileNumber"])
    try:
        l.add_s(build_user_dn(user_form["user"]["username"]),
                modlist.addModlist(attrs))
        return True, "Ok"
    except Exception, ex:
        current_app.logger.exception(ex)
        if str(ex[0]['desc']) == 'Already exists':
            return False, "El uid:" + str(
                user_form["user"]["username"]) + " ya esta siendo utilizado."
        else:
            return False, "Error al generar el usuario: " + ex[0]['desc']
Пример #34
0
    def create(self):
        """Create object"""
        dn_object = raw_input('Enter the dn that you want to add: '
                              )  #New dn, parent folder should be set
        """
        Example:
        Values in the atmosphere of the Mondial
        Attributes of the new ou = Lio
        dn_object = "ou=Lio,dc=ldap,dc=com"
        """
        attrs = {}
        attrs["objectclass"] = [
            "top", "organizationalRole", "simpleSecurityObject"
        ]
        attrs["cn"] = "Argentina"
        attrs["userPassword"] = password

        ldif = modlist.addModlist(
            attrs)  #This function changing dictionary to  mod list

        try:
            self.ldap_server.add_s(dn_object,
                                   ldif)  #Add_s function adding to the ldap
            print 'Ou/User added'
        except ldap.LDAPError, e:
            print e  #Cannot connect to server or user is not exist
Пример #35
0
def create_user(user_id, uid):
    print 'Adding user', user_id, 'with UID of', uid
    dn="uid=" + user_id + ",cn=users,cn=accounts," + IDM_DC_PATH
    user = {}
    user['displayName'] = user_id
    user['uid'] = user_id
    user['krbCanonicalName'] = user_id + "@" + IDM_REALM
    user['objectClass'] = ['top', 'person', 'organizationalperson', 'inetorgperson', 'inetuser', 'posixaccount', 'krbprincipalaux', 'krbticketpolicyaux', 'ipaobject', 'ipasshuser', 'ipaSshGroupOfPubKeys', 'mepOriginEntry', 'ipauserauthtypeclass', 'ipatokenradiusproxyuser']
    user['loginShell'] = '/bin/bash'
    user['initials'] = 'FromAD'
    user['gecos'] = user_id
    user['sn'] = user_id
    user['homeDirectory'] = '/home/'+ user_id
    user['mail'] = user_id + '@' + IDM_DOMAIN
    user['krbPrincipalName'] = user_id + '@' + IDM_REALM
    user['givenName'] = user_id
    user['cn'] = user_id + user_id
    user['uidNumber'] = str(uid)
    user['gidNumber'] = str(uid)
    user['description'] = 'FromAD'
    user['ipaUserAuthType'] = 'radius'
    user['ipatokenRadiusConfigLink'] = 'cn=RSA-Radius,cn=radiusproxy,dc=mylab,dc=test'
    ldif = modlist.addModlist(user)
    try:
        idm_ldap.add_s(dn, ldif)
    except ldap.LDAPError, e:
        if e.message['desc'] == 'Already exists':
            print "User", user_id, "already exists, nothing to add now"
        else:
            print('LDAPError: %s.' % e)
Пример #36
0
def createLdapProject(projectCode, projectId, priorityArea, service = '', title = 'Title'):

    gidNumber = str(33000 + projectId)

    checkPriorityParentOu(priorityArea)
    
    pawseyLdap = initLDAP()

    # dn for new entry
    dn = ("cn=%s, ou=%s,ou=Projects,ou=Groups,%s" % (projectCode, priorityArea, ldapBaseDN))
    # Attributes for new entry
    attrs = {}
    attrs['objectclass'] = ['top', 'posixGroup', 'hostObject']
    attrs['cn'] = projectCode.encode("utf8")
    attrs['gidnumber'] = gidNumber
    attrs['memberUid'] = 'dummy'
    attrs['host'] = ("%s%s" % ( service.encode("utf8"), str(date.today().year)))
    attrs['description'] = str(title)
    
    # Make the attributes dictionary into something we can throw at an ldap server
    ldif = modlist.addModlist(attrs)

    # Throw it at the ldap server!
    try: 
        pawseyLdap.add_s(dn,ldif)
    except ldap.LDAPError, e:
        print e
        exit(1)
Пример #37
0
    def add_user(self, user, password, unit=None, uid=None):
        """ Add new user into ldap directory """
        # The dn of our new entry/object
        dn = 'cn=%s,c=%s,%s' % (user.login, user.country, self._base)
        log.info('create user %s in ldap' % dn)

        # A dict to help build the "body" of the object
        attrs = {}
        attrs['objectClass'] = ['inetOrgPerson', 'top']
        attrs['employeeType'] = ['Employee']
        attrs['cn'] = [user.login.encode('utf-8')]
        attrs['givenName'] = [user.firstname.encode('utf-8')]
        attrs['sn'] = [user.lastname.encode('utf-8')]
        if uid:
            attrs['uid'] = [uid.encode('utf-8')]
        attrs['mail'] = [user.email.encode('utf-8')]
        if not unit:
            unit = 'development'
        attrs['ou'] = [unit.encode('utf-8')]

        attrs['userPassword'] = [hashPassword(password)]
        attrs['manager'] = [user.manager_dn.encode('utf-8')]

        # Convert our dict for the add-function using modlist-module
        ldif = modlist.addModlist(attrs)
        log.info('sending for dn %r: %r' % (dn, ldif))
        # rebind with system dn
        self._bind(self.system_DN, self.system_password)
        # Do the actual synchronous add-operation to the ldapserver
        self._conn.add_s(dn, ldif)

        # return password to display it to the administrator
        return dn
Пример #38
0
def parent_map(map_name=None, dry_run=True):
    ''' Create a nisMap object in AD. Home to one or more nisObjects.
 https://www.ietf.org/rfc/rfc2307.txt '''
    # log.m.debug('sync.parent_map:' + map_name)

    ad_map_cn = utils.map_cn(map_name)
    if ad_op.get(ad_map_cn) is not None:
        # log.m.debug('Parent map already exists: ' + map_name)
        return

    log_msg = 'Flat file map {0} has no AD equivalent'.format(map_name)
    log.m.debug(log_msg)

    log_msg = 'Creating AD:' + map_name
    log_msg = utils.dry_msg(log_msg, dry_run=dry_run)

    # for master map keys, nisMapName SHOULD have a leading slash
    attrs = {}
    attrs['objectClass'] = ['top', conf.c['t_nismap']]
    attrs['cn'] = [map_name]
    attrs['name'] = [map_name]
    attrs['nisMapName'] = [map_name]

    ml = modlist.addModlist(attrs)
    ad_op.add_obj(dn=utils.map_cn(map_name),
                  debug_attrs=attrs,
                  attrs=ml,
                  dry_run=dry_run)
    return
Пример #39
0
    def add_ou_quebec(self):
        modlist = addModlist({
            'objectClass': [b'organizationalUnit'],
            'ou': [b'quebec'],
        })

        self._ldap_obj.add_s(self.QUEBEC_DN, modlist)
Пример #40
0
def createNewClient(ldapuri, ldapbase, newClientsOuDn, clientMac,
                    gosaconffile):

    user, pw = getLdapCredentials(gosaconffile)
    l = ldap.initialize(ldapuri)
    l.simple_bind_s(user, pw)

    cn = clientMac.replace(":", "")

    # example: cn=test123,ou=workstations,ou=systems,dc=thintenders,dc=local
    dn = "cn=" + cn + ",ou=workstations,ou=systems," + newClientsOuDn
    syslog.syslog(syslogprefix + dn)

    attrs = {}

    attrs['objectclass'] = ['top', 'gotoWorkstation', 'GOhard', 'FAIobject']
    attrs['cn'] = cn
    attrs['macAddress'] = clientMac

    ldif = modlist.addModlist(attrs)

    try:
        l.add_s(dn, ldif)
    except ldap.LDAPError, error_message:
        syslog.syslog(syslogprefix + str(error_message))
        createNewClientSubOUs(ldapuri, newClientsOuDn, gosaconffile)
        l.add_s(dn, ldif)
Пример #41
0
    def add_ou_people(self):
        modlist = addModlist({
            'objectClass': ['organizationalUnit'],
            'ou': ['people'],
        })

        self._ldap_obj.add_s(self.PEOPLE_DN, modlist)
Пример #42
0
    def ldap_add_user(self, dn=None, sn=None, mobile=None, uidnumber=None):
        obj = self.ldapconn
        obj.protocal_version = ldap.VERSION3

        attrs = {}
        cn = dn.split(',')[0].split('=')[-1].encode('utf-8')
        attrs['cn'] = [cn]
        attrs['sn'] = [sn.encode('utf-8')]
        attrs['mobile'] = [mobile.encode('utf-8')]
        attrs['mail'] = [cn + '@aicai.com']
        attrs['givenname'] = [cn.split('.')[-1]]
        attrs['uid'] = [cn]
        attrs['uidNumber'] = [str(uidnumber)]
        attrs['loginShell'] = ['/sbin/false']
        attrs['homeDirectory'] = ['/home/null']
        attrs['objectClass'] = [
            'top', 'posixAccount', 'ipHost', 'inetOrgPerson'
        ]
        attrs['gidNumber'] = ['2000']
        attrs['ipHostNumber'] = ['1.1.1.1']
        attrs['userPassword'] = ['{SSHA}b14XtgW07oqEPJ+MgekrFGk9ztG8qqZa']
        print attrs
        print dn

        ldif = modlist.addModlist(attrs)

        try:
            obj.add_s(dn, ldif)
            return True
        except ldap.ALREADY_EXISTS:
            print '用户已经存在'
            return False
        except ldap.LDAPError, e:
            print e
            return False
def createNewClient(ldapuri, ldapbase, newClientsOuDn, clientMac, gosaconffile):

	user, pw = getLdapCredentials(gosaconffile)
	l = ldap.initialize(ldapuri)
	l.simple_bind_s(user, pw)

	cn=clientMac.replace(":","")

	
	# example: cn=test123,ou=workstations,ou=systems,dc=thintenders,dc=local
	dn = "cn="+cn+",ou=workstations,ou=systems,"+newClientsOuDn
	syslog.syslog(syslogprefix+dn)

	attrs = {}

	attrs['objectclass'] = ['top','gotoWorkstation','GOhard', 'FAIobject']	
	attrs['cn'] = cn
	attrs['macAddress'] = clientMac

	ldif = modlist.addModlist(attrs)

	try:
		l.add_s(dn,ldif)	
	except ldap.LDAPError, error_message:
        	syslog.syslog(syslogprefix+str(error_message))
		createNewClientSubOUs(ldapuri, newClientsOuDn, gosaconffile)
		l.add_s(dn,ldif)	
def create_ldap_group(group_name, gid, attributes_list):
    dn = 'cn=' + group_name + dn_groups
    ldif = modlist.addModlist(create_ldap_attributes(attributes_list))
    l.add_s(dn, ldif)
    print('Created ' + group_name + ' group')
    print('-------------------------------------')
    print(' ')
Пример #45
0
	def add_building(self, building):
		'''
			Add a new building. Transform a subset of building fields to the field names of the LDAP/AD schema.
		'''
		
		status = False
		try:
			self.log.info('add_building(): adding building: ' + building['building_code'] + " to LDAP")
			self.connect_ldap()
			dn = 'buildingIdentifier=' + building['building_identifier'] + ',' + config.ldap_base
			self.log.info('add_building(): adding building, dn: ' + dn)
			attrs = self.mapm(building)
			self.log.info('add_building(): attrs to add: ' + str(attrs))
			ldif = modlist.addModlist(attrs)
			self.log.info('add_building(): ldif to add: ' + str(ldif))
			self.ldap_con.add_s(dn, ldif)
			status = True
			self.log.debug('add_building(): ldif: ' + str(ldif))
			
			self.log.info('add_building(): successfully added building: ' + building['building_code'] + " to LDAP")
			self.ldap_con.unbind_s()
		except Exception as ex:
			self.log.error('add_buildings(): failed to add ' + building['building_code'] + ' to LDAP: error: ' + str(ex))
		
		return status
Пример #46
0
    def add_user(self, attrs):
        """add a user"""
        ldap_client = self._bind()
        # encoding crap
        attrs_srt = self.attrs_pretreatment(attrs)

        attrs_srt[self._byte_p2('objectClass')] = self.objectclasses
        # construct is DN
        dn = \
            self._byte_p2(self.dn_user_attr) + \
            self._byte_p2('=') + \
            self._byte_p2(ldap.dn.escape_dn_chars(
                        attrs[self.dn_user_attr]
                    )
                ) + \
            self._byte_p2(',') + \
            self._byte_p2(self.userdn)
        # gen the ldif first add_s and add the user
        ldif = modlist.addModlist(attrs_srt)
        try:
            ldap_client.add_s(dn, ldif)
        except ldap.ALREADY_EXISTS as e:
            raise UserAlreadyExists(attrs[self.key], self.backend_name)
        except Exception as e:
            ldap_client.unbind_s()
            self._exception_handler(e)
        ldap_client.unbind_s()
Пример #47
0
def addUser2LDAP(entry):
    if 'sAMAccountName' in entry and 'sn' in entry:
        try:
            localLDAP = ldap.initialize(LDAP_URI)
            localLDAP.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
            localLDAP.protocol_version = ldap.VERSION3
            dn = "cn=" + entry['name'][0].upper() + "," + LDAP_SEARCH_BASE
            attrs = {}

            attrs['objectclass'] = [
                'top', 'person', 'organizationalPerson', 'inetOrgPerson'
            ]
            attrs['cn'] = entry['name'][0].upper()
            attrs['userPassword'] = '******'
            attrs['displayName'] = entry['givenName'][0] + " " + entry['sn'][0]
            attrs['mail'] = entry['mail'][0]
            attrs['uid'] = entry['name'][0].upper()
            attrs['sn'] = entry['name'][0].upper()
            attrs['employeeType'] = 'developer'

            ldif = modlist.addModlist(attrs)
            localLDAP.add_s(dn, ldif)
            print("User " + entry['name'][0].upper() + " added successfully")

        except ldap.LDAPError as e:
            print("Adding user " + entry['name'][0].upper() + " failed: ")
            print('LDAPError: %s.' % e)
        finally:
            localLDAP.unbind_s()
Пример #48
0
 def handle(self,dn,entry):
     ldif = modlist.addModlist(entry)
     l = ldap.open('localhost', 389)
     try:
         l.bind("cn=admin,cn=config", "config")
     except ldap.SERVER_DOWN, e:
         print "ldap server is down"
    def add_user(self, modlist):
        """
        example param modlist dict should look like below containing only strings:

        modlist = {
            "objectClass": ["inetOrgPerson", "posixAccount", "shadowAccount"],
            "uid": ["jdoe"],
            "sn": ["Doe"],
            "givenName": ["John"],
            "cn": ["John Doe"],
            "displayName": ["John Doe"],
            "mail": ["*****@*****.**"],
            "homePhone": ["07234232434"],
            "uidNumber": ["1003"], # generate a unique ID
            "gidNumber": [502], # get from settings.LDAP_GID
            "loginShell": ["/bin/bash"],
            "homeDirectory": ["/home/users/jdoe"]
        }

        :param modlist:
        :return: tuple

        """
        dn = 'uid=' + modlist['uid'][0] + ',' + settings.LDAP_BASE_DN

        # convert modlist to bytes form ie b'abc'
        modlist_bytes = {}
        for key in modlist.keys():
            modlist_bytes[key] = [
                i.encode('utf-8') for i in modlist[key] if i is not None
            ]

        result = self.con.add_s(dn, addModlist(modlist_bytes))
        return result
Пример #50
0
    def add(self, username, full_name, password, user_id, group_id, homedir, login_shell):
        """
        Add a new user to the ldap server.
        """

        fulldn = "cn=%s, ou=people, " % full_name + self.dn

        # A dict to help build the "body" of the object
        attrs = {}
        attrs['objectclass'] = ['top','person','posixAccount','shadowAccount','organizationalPerson','inetOrgPerson']
        attrs['cn'] = full_name
        attrs['uid'] = username
        attrs['uidNumber'] = str(user_id)
        attrs['userPassword'] = password
        attrs['gidNumber'] = str(group_id)
        attrs['gecos'] = full_name
        attrs['homeDirectory'] = homedir
        attrs['loginShell'] = login_shell
        attrs['surname'] = full_name.split()[-1]

        # Convert our dict to nice syntax for the add-function using modlist-module
        ldif = modlist.addModlist(attrs)

        # Do the actual synchronous add-operation to the ldapserver
        self.l.add_s(fulldn, ldif)
        return self.get(username)
Пример #51
0
    def add_user(self, user, password, unit=None, uid=None):
        """ Add new user into ldap directory """
        # The dn of our new entry/object
        dn = 'cn=%s,c=%s,%s' % (user.login, user.country, self._base)
        log.info('create user %s in ldap' % dn)

        # A dict to help build the "body" of the object
        attrs = {}
        attrs['objectClass'] = ['inetOrgPerson', 'top']
        attrs['employeeType'] = ['Employee']
        attrs['cn'] = [user.login.encode('utf-8')]
        attrs['givenName'] = [user.firstname.encode('utf-8')]
        attrs['sn'] = [user.lastname.encode('utf-8')]
        if uid:
            attrs['uid'] = [uid.encode('utf-8')]
        attrs['mail'] = [user.email.encode('utf-8')]
        if not unit:
            unit = 'development'
        attrs['ou'] = [unit.encode('utf-8')]

        attrs['userPassword'] = [hashPassword(password)]
        attrs['manager'] = [user.manager_dn.encode('utf-8')]

        # Convert our dict for the add-function using modlist-module
        ldif = modlist.addModlist(attrs)
        log.info('sending for dn %r: %r' % (dn, ldif))
        # rebind with system dn
        self._bind(self.system_DN, self.system_password)
        # Do the actual synchronous add-operation to the ldapserver
        self._conn.add_s(dn, ldif)

        # return password to display it to the administrator
        return dn
Пример #52
0
def api_createGroup():
    if not request.json or \
       'cn' not in request.json:
        abort(400)
    attrs = {}
    attrs['cn'] = str(request.json['cn'])
    #    attrs['displayName'] = attrs['cn']
    if 'description' in request.json:
        attrs['description'] = str(request.json['description'])
    attrs['objectClass'] = ['top', 'posixGroup']
    if 'gidNumber' in request.json:
        attrs['gidNumber'] = str(request.json['gidNumber'])
    else:
        attrs['gidNumber'] = str(getNextgidNumber())
    dn = 'cn={},{}'.format(attrs['cn'], getConfig.group_ou)
    ldif = modlist.addModlist(attrs)
    try:
        connect = ldap.initialize('ldap://{0}:{1}'.format(
            getConfig.ldap_server, getConfig.ldap_port))
        connect.bind_s(getConfig.ldapcred, getConfig.ldappass)
        connect.add_s(dn, ldif)
    except ldap.LDAPError as e:
        connect.unbind_s()
        return make_response(jsonify({"Erreur LDAP": e.message['desc']}), 400)
    connect.unbind_s()
    return api_getGroup(attrs['cn'])
Пример #53
0
def user_add(admin_password, username, first_name, last_name, email, password):
    # connection and bind
    l = ldap.open(LDAP_SERVER)
    l.simple_bind_s(LDAP_ADMIN, admin_password)

    # dn of the new user
    new_user_dn = 'cn=%s %s,%s' % (first_name,
                                   last_name, LDAP_USER_BASE)

    # getting ldap attributes together
    attrs = {}
    attrs['objectclass'] = ['top', 'inetOrgPerson']
    attrs['cn'] = '%s %s' % (str(first_name), str(last_name))
    attrs['mail'] = str(email)
    attrs['givenName'] = str(first_name)
    attrs['sn'] = str(last_name)
    attrs['uid'] = str(username)
    attrs['userPassword'] = str(encode_password(password))

    # create ldif
    ldif = modlist.addModlist(attrs)

    # add ldif to server
    l.add_s(new_user_dn, ldif)

    # disconnect
    l.unbind_s()
Пример #54
0
 def ldap_user_add(self,uid=None,dt=None):
     try:
         addDN = "cn=%s,ou=People,dc=sohutest,dc=com" % uid
         u = int(self.mod_mysql.s_uid())+1
         g = int(self.mod_mysql.s_gid(dept=dt))
         p = self.mod_mysql.r_pas()
         m = uid + '@sohu-inc.com'
         attrs = {}
         attrs['cn'] = [uid]
         attrs['ou'] = ['People']
         #attrs['homeDirectory'] = ['/home/user/%s' % uid]
         attrs['homeDirectory'] = ['/home/user/ldapuser']
         attrs['loginShell'] = ['/bin/bash']
         attrs['uid'] = [uid]
         attrs['uidNumber'] = ['%s' %u]
         attrs['gidNumber'] = ['%s' %g]
         attrs['userPassword'] = p
         attrs['objectClass'] =  ['account', 'posixAccount', 'top', 'shadowAccount']
         self.conn.add_s(addDN, modlist.addModlist(attrs))
         #self.conn.unbind_s()
         #os.system("mkdir /home/user/%s" %uid)
         self.mod_mysql.add_user(uid,p,u,g,dt,m)
         return 'ok',p
     except ldap.LDAPError,e:
         return e
Пример #55
0
 def new(cls, name, primary_group):
     group = Group.get(
         'cn=%s,ou=Group,%s' %
         (primary_group, cls.config('/passport/ldap/root_dn')))
     if not group:
         return False, "primary group not found"
     dn = 'uid=%s,ou=People,%s' % (name,
                                   cls.config('/passport/ldap/root_dn'))
     entry = dict()
     entry['objectClass'] = [
         'account', 'posixAccount', 'top', 'shadowAccount'
     ]
     entry['gidNumber'] = group.gid
     entry['cn'] = [
         name,
     ]
     entry['homeDirectory'] = [
         '/home/%s' % name,
     ]
     entry['loginShell'] = ['/bin/bash']
     entry['uid'] = [
         name,
     ]
     entry['uidNumber'] = [cls._get_max_uid() + 1]
     ldif = modlist.addModlist(entry)
     cls.db.add_s(dn, ldif)
     return cls.get(dn)
Пример #56
0
    def add_user(self, attrs):
        """add a user"""
        ldap_client = self._bind()
        # encoding crap
        attrs_str = self.attrs_pretreatment(attrs)

        attrs_str['objectClass'] = self.objectclasses
        # construct is DN
        dn = \
            self._str(self.dn_user_attr) + \
            '=' + \
            ldap.dn.escape_dn_chars(
                self._str(attrs[self.dn_user_attr])
                ) + \
            ',' + \
            self._str(self.userdn)
        # gen the ldif fir add_s and add the user
        ldif = modlist.addModlist(attrs_str)
        try:
            ldap_client.add_s(dn, ldif)
        except ldap.ALREADY_EXISTS as e:
            raise UserAlreadyExists(attrs[self.key], self.backend_name)
        except Exception as e:
            ldap_client.unbind_s()
            self._exception_handler(e)
        ldap_client.unbind_s()
Пример #57
0
 def create_user(self, user_name, uid, password, home_dir, gid):
     logger.info(
         "create user, home: [%s], name: [%s], uid: [%s], "
         "gid: [%s], pwd: [%s]", home_dir, user_name, uid, gid, password)
     import time
     create_time = time.strftime('%Y-%m-%d %H:%M:%S',
                                 time.localtime(time.time()))
     attrs = dict(
         sn=user_name,
         cn=user_name,  # common name
         uid=user_name,
         uidNumber=uid,
         gidNumber=gid,
         userPassword=password,
         ou=self.user_ou,  # People
         homeDirectory=home_dir,
         loginShell="/bin/bash",
         description=create_time,
         objectClass=self.
         user_object_class  # ['posixAccount','inetOrgPerson'] #cn、sn必填
     )
     dn = "cn={cn},ou={ou},{parent_dn}".format(cn=user_name,
                                               ou=self.user_ou,
                                               parent_dn=self.parent_dn)
     ldif = modlist.addModlist(attrs)
     res = self.ldap_object.add_s(dn, ldif)
     logger.info("create user response: [%s]", res)
     logger.info("create user successfully.")
Пример #58
0
    def create_machine(self, template):
        machines = self.list_machines()
        index = template.find("#")
        if index < 0:
            return False

        # Extract a maximum substring.
        size = 1
        while template[index:index+size] == ("#" * size):
            size += 1
        size -= 1

        # Compute an integer in the range we want.
        fmt = "%%0%sd" % size
        maximum = pow(10, size)
        n = 1
        while n < maximum:
            # Find the next unused machine name that fits template
            name = template.replace("#" * size, fmt % n)
            if not(name.lower() in machines):
                break
            n = n + 1

            # Fail out if we've run out of machine names.
            if n == maximum:
                return False

        # Generate a password.
        password = generate_password()
        quoted_password = '******' + password + '"'
        utf_password = password.encode('utf-16-le')
        utf_quoted_password = quoted_password.encode('utf-16-le')
        base64_password = base64.b64encode(utf_password)

        # Generate the queries for creating the account.
        new_record = {}
        new_record.update(COMPUTER_RECORD.items())
        new_record['cn']             = name.upper()
        new_record['description']    = ''
        new_record['dNSHostName']    = '%s.%s' % (name, self.domain)
        new_record['sAMAccountName'] = '%s$' % name
        new_record['servicePrincipalName'] = [
            'HOST/%s' % name.upper(),
            'HOST/%s.%s' % (name, self.domain),
            'TERMSRV/%s' % name.upper(),
            'TERMSRV/%s.%s' % (name, self.domain),
            'RestrictedKrbHost/%s' % name.upper(),
            'RestrictedKrbHost/%s.%s' % (name, self.domain)
        ]
        new_record['unicodePwd'] = utf_quoted_password
        new_record['userAccountControl'] = '4096' # Enable account.

        descr = self._machine_description(name)
        connection = self._open()

        # Create the new account.
        connection.add_s(descr, modlist.addModlist(new_record))

        return (name, base64_password)