2 from passlib.hash import ldap_salted_sha1 as lssha
3 from sfa.util.xrn import get_authority
5 from sfa.util.config import Config
6 from sfa.trust.hierarchy import Hierarchy
8 import ldap.modlist as modlist
9 from sfa.util.sfalogging import logger
16 def __init__(self, config_file = '/etc/sfa/ldap_config.py'):
19 execfile(config_file, self.__dict__)
21 self.config_file = config_file
22 # path to configuration data
23 self.config_path = os.path.dirname(config_file)
25 raise IOError, "Could not find or load the configuration file: %s" \
30 """ Set admin login and server configuration variables."""
33 #Senslab PROD LDAP parameters
35 ldap_config = LdapConfig()
36 self.config = ldap_config
37 self.ldapHost = ldap_config.LDAP_IP_ADDRESS
38 self.ldapPeopleDN = ldap_config.LDAP_PEOPLE_DN
39 self.ldapGroupDN = ldap_config.LDAP_GROUP_DN
40 self.ldapAdminDN = ldap_config.LDAP_WEB_DN
41 self.ldapAdminPassword = ldap_config.LDAP_WEB_PASSWORD
44 self.ldapPort = ldap.PORT
45 self.ldapVersion = ldap.VERSION3
46 self.ldapSearchScope = ldap.SCOPE_SUBTREE
49 def connect(self, bind = True):
50 """Enables connection to the LDAP server.
51 Set the bind parameter to True if a bind is needed
52 (for add/modify/delete operations).
53 Set to False otherwise.
57 self.ldapserv = ldap.open(self.ldapHost)
58 except ldap.LDAPError, error:
59 return {'bool' : False, 'message' : error }
61 # Bind with authentification
69 """ Binding method. """
71 # Opens a connection after a call to ldap.open in connect:
72 self.ldapserv = ldap.initialize("ldap://" + self.ldapHost)
74 # Bind/authenticate with a user with apropriate
75 #rights to add objects
76 self.ldapserv.simple_bind_s(self.ldapAdminDN, \
77 self.ldapAdminPassword)
79 except ldap.LDAPError, error:
80 return {'bool' : False, 'message' : error }
85 """ Close the LDAP connection """
87 self.ldapserv.unbind_s()
88 except ldap.LDAPError, error:
89 return {'bool' : False, 'message' : error }
94 logger.setLevelDebug()
96 self.senslabauth = Hierarchy()
99 self.authname = config.SFA_REGISTRY_ROOT_AUTH
101 self.conn = ldap_co()
102 self.ldapUserQuotaNFS = self.conn.config.LDAP_USER_QUOTA_NFS
103 self.ldapUserUidNumberMin = self.conn.config.LDAP_USER_UID_NUMBER_MIN
104 self.ldapUserGidNumber = self.conn.config.LDAP_USER_GID_NUMBER
105 self.ldapUserHomePath = self.conn.config.LDAP_USER_HOME_PATH
107 self.lengthPassword = 8
108 self.baseDN = self.conn.ldapPeopleDN
109 #authinfo=self.senslabauth.get_auth_info(self.authname)
112 self.charsPassword = [ '!','$','(',')','*','+',',','-','.', \
113 '0','1','2','3','4','5','6','7','8','9', \
114 'A','B','C','D','E','F','G','H','I','J', \
115 'K','L','M','N','O','P','Q','R','S','T', \
116 'U','V','W','X','Y','Z','_','a','b','c', \
117 'd','e','f','g','h','i','j','k','l','m', \
118 'n','o','p','q','r','s','t','u','v','w', \
121 self.ldapShell = '/bin/bash'
124 def generate_login(self, record):
125 """Generate login for adding a new user in LDAP Directory
126 (four characters minimum length)
127 Record contains first name and last name.
130 if 'first_name' in record and 'last_name' in record:
131 #Remove all special characters from first_name/last name
132 lower_first_name = record['first_name'].replace('-','')\
133 .replace('_','').replace('[','')\
134 .replace(']','').replace(' ','')\
136 lower_last_name = record['last_name'].replace('-','')\
137 .replace('_','').replace('[','')\
138 .replace(']','').replace(' ','')\
142 #No first name and last name
145 email = record['mail']
146 email = email.split('@')[0].lower()
147 lower_first_name = None
148 lower_last_name = None
149 #Assume there is first name and last name in email
150 #if there is a separator
151 separator_list = ['.','_','-']
152 for sep in separator_list:
154 mail = email.split(sep)
155 lower_first_name = mail[0]
156 lower_last_name = mail[1]
158 #Otherwise just take the part before the @ as the
159 #lower_first_name and lower_last_name
160 if lower_first_name is None:
161 lower_first_name = email
162 lower_last_name = email
164 length_last_name = len(lower_last_name)
167 #Try generating a unique login based on first name and last name
169 if length_last_name >= login_max_length :
170 login = lower_last_name[0:login_max_length]
172 logger.debug("login : %s index : %s" %(login, index))
173 elif length_last_name >= 4 :
174 login = lower_last_name
176 logger.debug("login : %s index : %s" %(login, index))
177 elif length_last_name == 3 :
178 login = lower_first_name[0:1] + lower_last_name
180 logger.debug("login : %s index : %s" %(login, index))
181 elif length_last_name == 2:
182 if len ( lower_first_name) >=2:
183 login = lower_first_name[0:2] + lower_last_name
185 logger.debug("login : %s index : %s" %(login, index))
187 logger.error("LoginException : \
188 Generation login error with \
189 minimum four characters")
193 logger.error("LDAP generate_login failed : \
194 impossible to generate unique login for %s %s" \
195 %(lower_first_name,lower_last_name))
197 login_filter = '(uid=' + login + ')'
200 #Check if login already in use
201 while (len(self.LdapSearch(login_filter, getAttrs)) is not 0 ):
205 logger.error("LoginException : Generation login error \
206 with minimum four characters")
209 login = lower_first_name[0:index] + \
210 lower_last_name[0:login_max_length-index]
211 login_filter = '(uid='+ login+ ')'
213 print "lower_first_name - lower_last_name too short"
215 logger.debug("LDAP.API \t generate_login login %s" %(login))
218 except ldap.LDAPError, error :
219 logger.log_exc("LDAP generate_login Error %s" %error)
224 def generate_password(self):
226 """Generate password for adding a new user in LDAP Directory
227 (8 characters length) return password
231 length = len(self.charsPassword)
232 for index in range(self.lengthPassword):
233 char_index = random.randint(0, length-1)
234 password += self.charsPassword[char_index]
238 def encrypt_password(self, password):
239 """ Use passlib library to make a RFC2307 LDAP encrypted password
240 salt size = 8, use sha-1 algorithm. Returns encrypted password.
243 #Keep consistency with Java Senslab's LDAP API
244 #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
245 return lssha.encrypt(password, salt_size = 8)
249 def find_max_uidNumber(self):
251 """Find the LDAP max uidNumber (POSIX uid attribute) .
252 Used when adding a new user in LDAP Directory
253 returns string max uidNumber + 1
256 #First, get all the users in the LDAP
257 getAttrs = "(uidNumber=*)"
258 login_filter = ['uidNumber']
260 result_data = self.LdapSearch(getAttrs, login_filter)
261 #It there is no user in LDAP yet, First LDAP user
262 if result_data == []:
263 max_uidnumber = self.ldapUserUidNumberMin
264 #Otherwise, get the highest uidNumber
267 uidNumberList = [int(r[1]['uidNumber'][0])for r in result_data ]
268 logger.debug("LDAPapi.py \tfind_max_uidNumber \
269 uidNumberList %s " %(uidNumberList))
270 max_uidnumber = max(uidNumberList) + 1
272 return str(max_uidnumber)
275 def get_ssh_pkey(self, record):
276 """TODO ; Get ssh public key from sfa record
277 To be filled by N. Turro ? or using GID pl way?
282 def make_ldap_filters_from_record(self, record=None):
283 """TODO Handle OR filtering in the ldap query when
284 dealing with a list of records instead of doing a for loop in GetPersons
285 Helper function to make LDAP filter requests out of SFA records.
290 if 'first_name' in record and 'last_name' in record:
291 req_ldapdict['cn'] = str(record['first_name'])+" "\
292 + str(record['last_name'])
293 if 'email' in record :
294 req_ldapdict['mail'] = record['email']
296 req_ldapdict['mail'] = record['mail']
297 if 'enabled' in record:
298 if record['enabled'] == True :
299 req_ldapdict['shadowExpire'] = '-1'
301 req_ldapdict['shadowExpire'] = '0'
303 #Hrn should not be part of the filter because the hrn
304 #presented by a certificate of a SFA user not imported in
305 #Senslab does not include the senslab login in it
306 #Plus, the SFA user may already have an account with senslab
307 #using another login.
311 logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
312 record %s req_ldapdict %s" \
313 %(record, req_ldapdict))
315 for k in req_ldapdict:
316 req_ldap += '('+ str(k)+ '=' + str(req_ldapdict[k]) + ')'
317 if len(req_ldapdict.keys()) >1 :
318 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
320 req_ldap = req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
326 def make_ldap_attributes_from_record(self, record):
327 """When addind a new user to Senslab's LDAP, creates an attributes
328 dictionnary from the SFA record.
333 attrs['objectClass'] = ["top", "person", "inetOrgPerson", \
334 "organizationalPerson", "posixAccount", \
335 "shadowAccount", "systemQuotas", \
339 attrs['uid'] = self.generate_login(record)
341 attrs['givenName'] = str(record['first_name']).lower().capitalize()
342 attrs['sn'] = str(record['last_name']).lower().capitalize()
343 attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
344 attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
347 attrs['givenName'] = attrs['uid']
348 attrs['sn'] = attrs['uid']
349 attrs['cn'] = attrs['uid']
350 attrs['gecos'] = attrs['uid']
353 attrs['quota'] = self.ldapUserQuotaNFS
354 attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
355 attrs['loginShell'] = self.ldapShell
356 attrs['gidNumber'] = self.ldapUserGidNumber
357 attrs['uidNumber'] = self.find_max_uidNumber()
358 attrs['mail'] = record['mail'].lower()
360 attrs['sshPublicKey'] = record['pkey']
362 attrs['sshPublicKey'] = self.get_ssh_pkey(record)
365 #Password is automatically generated because SFA user don't go
366 #through the Senslab website used to register new users,
367 #There is no place in SFA where users can enter such information
369 #If the user wants to set his own password , he must go to the Senslab
371 password = self.generate_password()
372 attrs['userPassword'] = self.encrypt_password(password)
374 #Account automatically validated (no mail request to admins)
375 #Set to 0 to disable the account, -1 to enable it,
376 attrs['shadowExpire'] = '-1'
378 #Motivation field in Senslab
379 attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
381 attrs['ou'] = 'SFA' #Optional: organizational unit
382 #No info about those here:
383 attrs['l'] = 'To be defined'#Optional: Locality.
384 attrs['st'] = 'To be defined' #Optional: state or province (country).
390 def LdapAddUser(self, record) :
391 """Add SFA user to LDAP if it is not in LDAP yet. """
393 user_ldap_attrs = self.make_ldap_attributes_from_record(record)
396 #Check if user already in LDAP wih email, first name and last name
397 filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
398 user_exist = self.LdapSearch(filter_by)
400 logger.warning(" \r\n \t LDAP LdapAddUser user %s %s \
401 already exists" %(user_ldap_attrs['sn'], \
402 user_ldap_attrs['mail']))
403 return {'bool': False}
406 result = self.conn.connect()
410 # A dict to help build the "body" of the object
412 logger.debug(" \r\n \t LDAP LdapAddUser attrs %s " %user_ldap_attrs)
414 # The dn of our new entry/object
415 dn = 'uid=' + user_ldap_attrs['uid'] + "," + self.baseDN
418 ldif = modlist.addModlist(user_ldap_attrs)
419 logger.debug("LDAPapi.py add attrs %s \r\n ldif %s"\
420 %(user_ldap_attrs,ldif) )
421 self.conn.ldapserv.add_s(dn,ldif)
423 logger.info("Adding user %s login %s in LDAP" \
424 %(user_ldap_attrs['cn'] ,user_ldap_attrs['uid']))
427 except ldap.LDAPError, error:
428 logger.log_exc("LDAP Add Error %s" %error)
429 return {'bool' : False, 'message' : error }
432 return {'bool': True}
437 def LdapDelete(self, person_dn):
439 Deletes a person in LDAP. Uses the dn of the user.
442 result = self.conn.connect()
445 self.conn.ldapserv.delete_s(person_dn)
447 return {'bool': True}
449 except ldap.LDAPError, error:
450 logger.log_exc("LDAP Delete Error %s" %error)
451 return {'bool': False}
454 def LdapDeleteUser(self, record_filter):
456 Deletes a SFA person in LDAP, based on the user's hrn.
458 #Find uid of the person
459 person = self.LdapFindUser(record_filter,[])
460 logger.debug("LDAPapi.py \t LdapDeleteUser record %s person %s" \
461 %(record_filter, person))
464 dn = 'uid=' + person['uid'] + "," +self.baseDN
466 return {'bool': False}
468 result = self.LdapDelete(dn)
472 def LdapModify(self, dn, old_attributes_dict, new_attributes_dict):
473 """ Modifies a LDAP entry """
475 ldif = modlist.modifyModlist(old_attributes_dict,new_attributes_dict)
476 # Connect and bind/authenticate
477 result = self.conn.connect()
480 self.conn.ldapserv.modify_s(dn,ldif)
482 return {'bool' : True }
483 except ldap.LDAPError, error:
484 logger.log_exc("LDAP LdapModify Error %s" %error)
485 return {'bool' : False }
488 def LdapModifyUser(self, user_record, new_attributes_dict):
490 Gets the record from one user_uid_login based on record_filter
491 and changes the attributes according to the specified new_attributes.
492 Does not use this if we need to modify the uid. Use a ModRDN
493 #operation instead ( modify relative DN )
495 if user_record is None:
496 logger.error("LDAP \t LdapModifyUser Need user record ")
497 return {'bool': False}
499 #Get all the attributes of the user_uid_login
500 #person = self.LdapFindUser(record_filter,[])
501 req_ldap = self.make_ldap_filters_from_record(user_record)
502 person_list = self.LdapSearch(req_ldap,[])
503 logger.debug("LDAPapi.py \t LdapModifyUser person_list : %s" \
505 if person_list and len(person_list) > 1 :
506 logger.error("LDAP \t LdapModifyUser Too many users returned")
507 return {'bool': False}
508 if person_list is None :
509 logger.error("LDAP \t LdapModifyUser User %s doesn't exist "\
511 return {'bool': False}
513 # The dn of our existing entry/object
514 #One result only from ldapSearch
515 person = person_list[0][1]
516 dn = 'uid=' + person['uid'][0] + "," +self.baseDN
518 if new_attributes_dict:
520 for k in new_attributes_dict:
525 logger.debug(" LDAPapi.py \t LdapModifyUser new_attributes %s"\
526 %( new_attributes_dict))
527 result = self.LdapModify(dn, old,new_attributes_dict)
530 logger.error("LDAP \t LdapModifyUser No new attributes given. ")
531 return {'bool': False}
536 def LdapMarkUserAsDeleted(self, record):
541 new_attrs['shadowExpire'] = '0'
542 logger.debug(" LDAPapi.py \t LdapMarkUserAsDeleted ")
543 ret = self.LdapModifyUser(record, new_attrs)
547 def LdapResetPassword(self,record):
549 Resets password for the user whose record is the parameter and changes
550 the corresponding entry in the LDAP.
553 password = self.generate_password()
555 attrs['userPassword'] = self.encrypt_password(password)
556 logger.debug("LDAP LdapResetPassword encrypt_password %s"\
557 %(attrs['userPassword']))
558 result = self.LdapModifyUser(record, attrs)
562 def LdapSearch (self, req_ldap = None, expected_fields = None ):
564 Used to search directly in LDAP, by using ldap filters and
566 When req_ldap is None, returns all the entries in the LDAP.
569 result = self.conn.connect(bind = False)
570 if (result['bool']) :
572 return_fields_list = []
573 if expected_fields == None :
574 return_fields_list = ['mail','givenName', 'sn', 'uid', \
575 'sshPublicKey', 'shadowExpire']
577 return_fields_list = expected_fields
578 #No specifc request specified, get the whole LDAP
582 logger.debug("LDAP.PY \t LdapSearch req_ldap %s \
583 return_fields_list %s" \
584 %(req_ldap, return_fields_list))
587 msg_id = self.conn.ldapserv.search(
588 self.baseDN,ldap.SCOPE_SUBTREE,\
589 req_ldap, return_fields_list)
590 #Get all the results matching the search from ldap in one
592 result_type, result_data = \
593 self.conn.ldapserv.result(msg_id,1)
597 logger.debug("LDAP.PY \t LdapSearch result_data %s"\
602 except ldap.LDAPError,error :
603 logger.log_exc("LDAP LdapSearch Error %s" %error)
607 logger.error("LDAP.PY \t Connection Failed" )
610 def LdapFindUser(self, record = None, is_user_enabled=None, \
611 expected_fields = None):
613 Search a SFA user with a hrn. User should be already registered
615 Returns one matching entry
620 custom_record['enabled'] = is_user_enabled
622 custom_record.update(record)
625 req_ldap = self.make_ldap_filters_from_record(custom_record)
626 return_fields_list = []
627 if expected_fields == None :
628 return_fields_list = ['mail','givenName', 'sn', 'uid', \
631 return_fields_list = expected_fields
633 result_data = self.LdapSearch(req_ldap, return_fields_list )
634 logger.debug("LDAP.PY \t LdapFindUser result_data %s" %(result_data))
636 if len(result_data) is 0:
638 #Asked for a specific user
641 ldapentry = result_data[0][1]
642 logger.debug("LDAP.PY \t LdapFindUser ldapentry %s" %(ldapentry))
643 tmpname = ldapentry['uid'][0]
645 tmpemail = ldapentry['mail'][0]
646 if ldapentry['mail'][0] == "unknown":
650 #logger.error("LDAP ldapFindHRn : no entry for record %s found"\
656 parent_hrn = get_authority(hrn)
657 peer_authority = None
658 if parent_hrn is not self.authname:
659 peer_authority = parent_hrn
663 'pkey': ldapentry['sshPublicKey'][0],
664 #'uid': ldapentry[1]['uid'][0],
667 #'email': ldapentry[1]['mail'][0],
668 'first_name': ldapentry['givenName'][0],
669 'last_name': ldapentry['sn'][0],
672 'authority': parent_hrn,
673 'peer_authority': peer_authority,
677 except KeyError,error:
678 logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
682 #Asked for all users in ldap
684 for ldapentry in result_data:
685 logger.debug(" LDAP.py LdapFindUser ldapentry name : %s " \
686 %(ldapentry[1]['uid'][0]))
687 tmpname = ldapentry[1]['uid'][0]
688 hrn=self.authname+"."+ tmpname
690 tmpemail = ldapentry[1]['mail'][0]
691 if ldapentry[1]['mail'][0] == "unknown":
695 parent_hrn = get_authority(hrn)
696 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
700 'pkey': ldapentry[1]['sshPublicKey'][0],
701 #'uid': ldapentry[1]['uid'][0],
704 #'email': ldapentry[1]['mail'][0],
705 'first_name': ldapentry[1]['givenName'][0],
706 'last_name': ldapentry[1]['sn'][0],
709 'authority': self.authname,
710 'peer_authority': '',
714 except KeyError,error:
715 logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" \