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", \
338 attrs['givenName'] = str(record['first_name']).lower().capitalize()
339 attrs['sn'] = str(record['last_name']).lower().capitalize()
340 attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
341 attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
342 attrs['uid'] = self.generate_login(record)
344 attrs['quota'] = self.ldapUserQuotaNFS
345 attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
346 attrs['loginShell'] = self.ldapShell
347 attrs['gidNumber'] = self.ldapUserGidNumber
348 attrs['uidNumber'] = self.find_max_uidNumber()
349 attrs['mail'] = record['mail'].lower()
351 attrs['sshPublicKey'] = record['pkey']
353 attrs['sshPublicKey'] = self.get_ssh_pkey(record)
356 #Password is automatically generated because SFA user don't go
357 #through the Senslab website used to register new users,
358 #There is no place in SFA where users can enter such information
360 #If the user wants to set his own password , he must go to the Senslab
362 password = self.generate_password()
363 attrs['userPassword'] = self.encrypt_password(password)
365 #Account automatically validated (no mail request to admins)
366 #Set to 0 to disable the account, -1 to enable it,
367 attrs['shadowExpire'] = '-1'
369 #Motivation field in Senslab
370 attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
372 attrs['ou'] = 'SFA' #Optional: organizational unit
373 #No info about those here:
374 attrs['l'] = 'To be defined'#Optional: Locality.
375 attrs['st'] = 'To be defined' #Optional: state or province (country).
381 def LdapAddUser(self, record) :
382 """Add SFA user to LDAP if it is not in LDAP yet. """
384 user_ldap_attrs = self.make_ldap_attributes_from_record(record)
387 #Check if user already in LDAP wih email, first name and last name
388 filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
389 user_exist = self.LdapSearch(filter_by)
391 logger.warning(" \r\n \t LDAP LdapAddUser user %s %s \
392 already exists" %(user_ldap_attrs['sn'], \
393 user_ldap_attrs['mail']))
394 return {'bool': False}
397 result = self.conn.connect()
401 # A dict to help build the "body" of the object
403 logger.debug(" \r\n \t LDAP LdapAddUser attrs %s " %user_ldap_attrs)
405 # The dn of our new entry/object
406 dn = 'uid=' + user_ldap_attrs['uid'] + "," + self.baseDN
409 ldif = modlist.addModlist(user_ldap_attrs)
410 logger.debug("LDAPapi.py add attrs %s \r\n ldif %s"\
411 %(user_ldap_attrs,ldif) )
412 self.conn.ldapserv.add_s(dn,ldif)
414 logger.info("Adding user %s login %s in LDAP" \
415 %(user_ldap_attrs['cn'] ,user_ldap_attrs['uid']))
418 except ldap.LDAPError, error:
419 logger.log_exc("LDAP Add Error %s" %error)
420 return {'bool' : False, 'message' : error }
423 return {'bool': True}
428 def LdapDelete(self, person_dn):
430 Deletes a person in LDAP. Uses the dn of the user.
433 result = self.conn.connect()
436 self.conn.ldapserv.delete_s(person_dn)
438 return {'bool': True}
440 except ldap.LDAPError, error:
441 logger.log_exc("LDAP Delete Error %s" %error)
442 return {'bool': False}
445 def LdapDeleteUser(self, record_filter):
447 Deletes a SFA person in LDAP, based on the user's hrn.
449 #Find uid of the person
450 person = self.LdapFindUser(record_filter,[])
451 logger.debug("LDAPapi.py \t LdapDeleteUser record %s person %s" \
452 %(record_filter, person))
455 dn = 'uid=' + person['uid'] + "," +self.baseDN
457 return {'bool': False}
459 result = self.LdapDelete(dn)
463 def LdapModify(self, dn, old_attributes_dict, new_attributes_dict):
464 """ Modifies a LDAP entry """
466 ldif = modlist.modifyModlist(old_attributes_dict,new_attributes_dict)
467 # Connect and bind/authenticate
468 result = self.conn.connect()
471 self.conn.ldapserv.modify_s(dn,ldif)
473 return {'bool' : True }
474 except ldap.LDAPError, error:
475 logger.log_exc("LDAP LdapModify Error %s" %error)
476 return {'bool' : False }
479 def LdapModifyUser(self, user_record, new_attributes_dict):
481 Gets the record from one user_uid_login based on record_filter
482 and changes the attributes according to the specified new_attributes.
483 Does not use this if we need to modify the uid. Use a ModRDN
484 #operation instead ( modify relative DN )
486 if user_record is None:
487 logger.error("LDAP \t LdapModifyUser Need user record ")
488 return {'bool': False}
490 #Get all the attributes of the user_uid_login
491 #person = self.LdapFindUser(record_filter,[])
492 req_ldap = self.make_ldap_filters_from_record(user_record)
493 person_list = self.LdapSearch(req_ldap,[])
494 logger.debug("LDAPapi.py \t LdapModifyUser person_list : %s" \
496 if person_list and len(person_list) > 1 :
497 logger.error("LDAP \t LdapModifyUser Too many users returned")
498 return {'bool': False}
499 if person_list is None :
500 logger.error("LDAP \t LdapModifyUser User %s doesn't exist "\
502 return {'bool': False}
504 # The dn of our existing entry/object
505 #One result only from ldapSearch
506 person = person_list[0][1]
507 dn = 'uid=' + person['uid'][0] + "," +self.baseDN
509 if new_attributes_dict:
511 for k in new_attributes_dict:
516 logger.debug(" LDAPapi.py \t LdapModifyUser new_attributes %s"\
517 %( new_attributes_dict))
518 result = self.LdapModify(dn, old,new_attributes_dict)
521 logger.error("LDAP \t LdapModifyUser No new attributes given. ")
522 return {'bool': False}
527 def LdapMarkUserAsDeleted(self, record):
532 new_attrs['shadowExpire'] = '0'
533 logger.debug(" LDAPapi.py \t LdapMarkUserAsDeleted ")
534 ret = self.LdapModifyUser(record, new_attrs)
538 def LdapResetPassword(self,record):
540 Resets password for the user whose record is the parameter and changes
541 the corresponding entry in the LDAP.
544 password = self.generate_password()
546 attrs['userPassword'] = self.encrypt_password(password)
547 logger.debug("LDAP LdapResetPassword encrypt_password %s"\
548 %(attrs['userPassword']))
549 result = self.LdapModifyUser(record, attrs)
553 def LdapSearch (self, req_ldap = None, expected_fields = None ):
555 Used to search directly in LDAP, by using ldap filters and
557 When req_ldap is None, returns all the entries in the LDAP.
560 result = self.conn.connect(bind = False)
561 if (result['bool']) :
563 return_fields_list = []
564 if expected_fields == None :
565 return_fields_list = ['mail','givenName', 'sn', 'uid', \
566 'sshPublicKey', 'shadowExpire']
568 return_fields_list = expected_fields
569 #No specifc request specified, get the whole LDAP
573 logger.debug("LDAP.PY \t LdapSearch req_ldap %s \
574 return_fields_list %s" \
575 %(req_ldap, return_fields_list))
578 msg_id = self.conn.ldapserv.search(
579 self.baseDN,ldap.SCOPE_SUBTREE,\
580 req_ldap, return_fields_list)
581 #Get all the results matching the search from ldap in one
583 result_type, result_data = \
584 self.conn.ldapserv.result(msg_id,1)
588 logger.debug("LDAP.PY \t LdapSearch result_data %s"\
593 except ldap.LDAPError,error :
594 logger.log_exc("LDAP LdapSearch Error %s" %error)
598 logger.error("LDAP.PY \t Connection Failed" )
601 def LdapFindUser(self, record = None, is_user_enabled=None, \
602 expected_fields = None):
604 Search a SFA user with a hrn. User should be already registered
606 Returns one matching entry
611 custom_record['enabled'] = is_user_enabled
613 custom_record.update(record)
616 req_ldap = self.make_ldap_filters_from_record(custom_record)
617 return_fields_list = []
618 if expected_fields == None :
619 return_fields_list = ['mail','givenName', 'sn', 'uid', \
622 return_fields_list = expected_fields
624 result_data = self.LdapSearch(req_ldap, return_fields_list )
625 logger.debug("LDAP.PY \t LdapFindUser result_data %s" %(result_data))
627 if len(result_data) is 0:
629 #Asked for a specific user
632 ldapentry = result_data[0][1]
633 logger.debug("LDAP.PY \t LdapFindUser ldapentry %s" %(ldapentry))
634 tmpname = ldapentry['uid'][0]
636 tmpemail = ldapentry['mail'][0]
637 if ldapentry['mail'][0] == "unknown":
641 #logger.error("LDAP ldapFindHRn : no entry for record %s found"\
647 parent_hrn = get_authority(hrn)
648 peer_authority = None
649 if parent_hrn is not self.authname:
650 peer_authority = parent_hrn
654 'pkey': ldapentry['sshPublicKey'][0],
655 #'uid': ldapentry[1]['uid'][0],
658 #'email': ldapentry[1]['mail'][0],
659 'first_name': ldapentry['givenName'][0],
660 'last_name': ldapentry['sn'][0],
663 'authority': parent_hrn,
664 'peer_authority': peer_authority,
668 except KeyError,error:
669 logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
673 #Asked for all users in ldap
675 for ldapentry in result_data:
676 logger.debug(" LDAP.py LdapFindUser ldapentry name : %s " \
677 %(ldapentry[1]['uid'][0]))
678 tmpname = ldapentry[1]['uid'][0]
679 hrn=self.authname+"."+ tmpname
681 tmpemail = ldapentry[1]['mail'][0]
682 if ldapentry[1]['mail'][0] == "unknown":
686 parent_hrn = get_authority(hrn)
687 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
691 'pkey': ldapentry[1]['sshPublicKey'][0],
692 #'uid': ldapentry[1]['uid'][0],
695 #'email': ldapentry[1]['mail'][0],
696 'first_name': ldapentry[1]['givenName'][0],
697 'last_name': ldapentry[1]['sn'][0],
700 'authority': self.authname,
701 'peer_authority': '',
705 except KeyError,error:
706 logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" \