4 from passlib.hash import ldap_salted_sha1 as lssha
5 from sfa.util.xrn import Xrn,get_authority
7 from sfa.util.config import Config
8 from sfa.trust.hierarchy import Hierarchy
9 from sfa.trust.certificate import *
10 import ldap.modlist as modlist
11 from sfa.util.sfalogging import logger
18 def __init__(self, config_file = '/etc/sfa/ldap_config.py'):
19 self.load(config_file)
21 def load(self, config_file):
23 execfile(config_file, self.__dict__)
24 self.config_file = config_file
25 # path to configuration data
26 self.config_path = os.path.dirname(config_file)
28 raise IOError, "Could not find or load the configuration file: %s" % config_file
31 """ Set admin login and server configuration variables."""
34 #Senslab PROD LDAP parameters
35 LdapConfig = ldap_config()
36 self.config = LdapConfig
37 self.ldapHost = LdapConfig.LDAP_IP_ADDRESS
38 self.ldapPeopleDN = LdapConfig.LDAP_PEOPLE_DN
39 self.ldapGroupDN = LdapConfig.LDAP_GROUP_DN
40 self.ldapAdminDN = LdapConfig.LDAP_WEB_DN
41 self.ldapAdminPassword = LdapConfig.LDAP_WEB_PASSWORD
45 self.ldapPort = ldap.PORT
46 self.ldapVersion = ldap.VERSION3
47 self.ldapSearchScope = ldap.SCOPE_SUBTREE
50 def connect(self, bind = True):
51 """Enables connection to the LDAP server.
52 Set the bind parameter to True if a bind is needed
53 (for add/modify/delete operations).
54 Set to False otherwise.
58 self.ldapserv = ldap.open(self.ldapHost)
59 except ldap.LDAPError, e:
60 return {'bool' : False, 'message' : e }
62 # Bind with authentification
70 """ Binding method. """
72 # Opens a connection after a call to ldap.open in connect:
73 self.ldapserv = ldap.initialize("ldap://" + self.ldapHost)
75 # Bind/authenticate with a user with apropriate rights to add objects
76 self.ldapserv.simple_bind_s(self.ldapAdminDN, self.ldapAdminPassword)
78 except ldap.LDAPError, e:
79 return {'bool' : False, 'message' : e }
84 """ Close the LDAP connection """
86 self.ldapserv.unbind_s()
87 except ldap.LDAPError, e:
88 return {'bool' : False, 'message' : e }
93 #logger.setLevelDebug()
95 self.senslabauth=Hierarchy()
98 self.authname=config.SFA_REGISTRY_ROOT_AUTH
100 self.conn = ldap_co()
101 self.ldapUserQuotaNFS = self.conn.config.LDAP_USER_QUOTA_NFS
102 self.ldapUserUidNumberMin = self.conn.config.LDAP_USER_UID_NUMBER_MIN
103 self.ldapUserGidNumber = self.conn.config.LDAP_USER_GID_NUMBER
104 self.ldapUserHomePath = self.conn.config.LDAP_USER_HOME_PATH
106 self.lengthPassword = 8;
107 self.baseDN = self.conn.ldapPeopleDN
108 #authinfo=self.senslabauth.get_auth_info(self.authname)
111 self.charsPassword = [ '!','$','(',')','*','+',',','-','.',\
112 '0','1','2','3','4','5','6','7','8','9',\
113 'A','B','C','D','E','F','G','H','I','J',\
114 'K','L','M','N','O','P','Q','R','S','T',\
115 'U','V','W','X','Y','Z','_','a','b','c',\
116 'd','e','f','g','h','i','j','k','l','m',\
117 'n','o','p','q','r','s','t','u','v','w',\
120 self.ldapShell = '/bin/bash'
123 def generate_login(self, record):
124 """Generate login for adding a new user in LDAP Directory
125 (four characters minimum length)
126 Record contains first name and last name.
129 #Remove all special characters from first_name/last name
130 lower_first_name = record['first_name'].replace('-','')\
131 .replace('_','').replace('[','')\
132 .replace(']','').replace(' ','')\
134 lower_last_name = record['last_name'].replace('-','')\
135 .replace('_','').replace('[','')\
136 .replace(']','').replace(' ','')\
138 length_last_name = len(lower_last_name)
141 #Try generating a unique login based on first name and last name
143 if length_last_name >= login_max_length :
144 login = lower_last_name[0:login_max_length]
146 logger.debug("login : %s index : %s" %(login,index))
147 elif length_last_name >= 4 :
148 login = lower_last_name
150 logger.debug("login : %s index : %s" %(login,index))
151 elif length_last_name == 3 :
152 login = lower_first_name[0:1] + lower_last_name
154 logger.debug("login : %s index : %s" %(login,index))
155 elif length_last_name == 2:
156 if len ( lower_first_name) >=2:
157 login = lower_first_name[0:2] + lower_last_name
159 logger.debug("login : %s index : %s" %(login,index))
161 logger.error("LoginException : \
162 Generation login error with \
163 minimum four characters")
167 logger.error("LDAP generate_login failed : \
168 impossible to generate unique login for %s %s" \
169 %(lower_first_name,lower_last_name))
171 filter = '(uid=' + login + ')'
174 #Check if login already in use
175 while (len(self.LdapSearch(filter, getAttrs)) is not 0 ):
179 logger.error("LoginException : Generation login error \
180 with minimum four characters")
183 login = lower_first_name[0:index] + \
184 lower_last_name[0:login_max_length-index]
185 filter = '(uid='+ login+ ')'
187 print "lower_first_name - lower_last_name too short"
189 logger.debug("LDAP.API \t generate_login login %s" %(login))
192 except ldap.LDAPError,e :
193 logger.log_exc("LDAP generate_login Error %s" %e)
198 def generate_password(self):
200 """Generate password for adding a new user in LDAP Directory
201 (8 characters length) return password
205 length = len(self.charsPassword)
206 for index in range(self.lengthPassword):
207 char_index = random.randint(0,length-1)
208 password += self.charsPassword[char_index]
212 def encrypt_password(self, password):
213 """ Use passlib library to make a RFC2307 LDAP encrypted password
214 salt size = 8, use sha-1 algorithm. Returns encrypted password.
217 #Keep consistency with Java Senslab's LDAP API
218 #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
219 return lssha.encrypt(password,salt_size = 8)
223 def find_max_uidNumber(self):
225 """Find the LDAP max uidNumber (POSIX uid attribute) .
226 Used when adding a new user in LDAP Directory
227 returns string max uidNumber + 1
230 #First, get all the users in the LDAP
231 getAttrs = "(uidNumber=*)"
232 filter = ['uidNumber']
234 result_data = self.LdapSearch(getAttrs, filter)
235 #It there is no user in LDAP yet, First LDAP user
236 if result_data == []:
237 max_uidnumber = self.ldapUserUidNumberMin
238 #Otherwise, get the highest uidNumber
241 uidNumberList = [int(r[1]['uidNumber'][0])for r in result_data ]
242 logger.debug("LDAPapi.py \tfind_max_uidNumber \
243 uidNumberList %s " %(uidNumberList))
244 max_uidnumber = max(uidNumberList) + 1
246 return str(max_uidnumber)
248 #TODO ; Get ssh public key from sfa record
249 #To be filled by N. Turro
250 def get_ssh_pkey(self, record):
254 #TODO Handle OR filtering in the ldap query when
255 #dealing with a list of records instead of doing a for loop in GetPersons
256 def make_ldap_filters_from_record(self, record=None):
258 Helper function to make LDAP filter requests out of SFA records.
262 if 'first_name' in record and 'last_name' in record:
263 req_ldapdict['cn'] = str(record['first_name'])+" "\
264 + str(record['last_name'])
265 if 'email' in record :
266 req_ldapdict['mail'] = record['email']
268 req_ldapdict['mail'] = record['mail']
270 #Hrn should not be part of the filter because the hrn
271 #presented by a certificate of a SFA user not imported in
272 #Senslab does not include the senslab login in it
273 #Plus, the SFA user may already have an account with senslab
274 #using another login.
276 #if 'hrn' in record :
277 #splited_hrn = record['hrn'].split(".")
278 #if splited_hrn[0] != self.authname :
279 #logger.warning(" \r\n LDAP.PY \
280 #make_ldap_filters_from_record I know nothing \
281 #about %s my authname is %s not %s" \
282 #%(record['hrn'], self.authname, splited_hrn[0]) )
284 #login=splited_hrn[1]
285 #req_ldapdict['uid'] = login
288 logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
289 record %s req_ldapdict %s" \
290 %(record, req_ldapdict))
292 for k in req_ldapdict:
293 req_ldap += '('+str(k)+'='+str(req_ldapdict[k])+')'
294 if len(req_ldapdict.keys()) >1 :
295 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
297 req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
303 def make_ldap_attributes_from_record(self, record):
304 """When addind a new user to Senslab's LDAP, creates an attributes
305 dictionnary from the SFA record.
310 attrs['objectClass'] = ["top", "person", "inetOrgPerson",\
311 "organizationalPerson", "posixAccount",\
312 "shadowAccount", "systemQuotas",\
315 attrs['givenName'] = str(record['first_name']).lower().capitalize()
316 attrs['sn'] = str(record['last_name']).lower().capitalize()
317 attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
318 attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
319 attrs['uid'] = self.generate_login(record)
321 attrs['quota'] = self.ldapUserQuotaNFS
322 attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
323 attrs['loginShell'] = self.ldapShell
324 attrs['gidNumber'] = self.ldapUserGidNumber
325 attrs['uidNumber'] = self.find_max_uidNumber()
326 attrs['mail'] = record['mail'].lower()
328 attrs['sshPublicKey'] = self.get_ssh_pkey(record)
331 #Password is automatically generated because SFA user don't go
332 #through the Senslab website used to register new users,
333 #There is no place in SFA where users can enter such information
335 #If the user wants to set his own password , he must go to the Senslab
337 password = self.generate_password()
338 attrs['userPassword']= self.encrypt_password(password)
340 #Account automatically validated (no mail request to admins)
341 #Set to 0 to disable the account, -1 to enable it,
342 attrs['shadowExpire'] = '-1'
344 #Motivation field in Senslab
345 attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
347 attrs['ou'] = 'SFA' #Optional: organizational unit
348 #No info about those here:
349 attrs['l'] = 'To be defined'#Optional: Locality.
350 attrs['st'] = 'To be defined' #Optional: state or province (country).
356 def LdapAddUser(self, record = None) :
357 """Add SFA user to LDAP if it is not in LDAP yet. """
359 user_ldap_attrs = self.make_ldap_attributes_from_record(record)
362 #Check if user already in LDAP wih email, first name and last name
363 filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
364 user_exist = self.LdapSearch(filter_by)
366 logger.warning(" \r\n \t LDAP LdapAddUser user %s %s already exists" \
367 %(user_ldap_attrs['sn'],user_ldap_attrs['mail']))
368 return {'bool': False}
371 result = self.conn.connect()
375 # A dict to help build the "body" of the object
377 logger.debug(" \r\n \t LDAP LdapAddUser attrs %s " %user_ldap_attrs)
379 # The dn of our new entry/object
380 dn = 'uid=' + user_ldap_attrs['uid'] + "," + self.baseDN
383 ldif = modlist.addModlist(user_ldap_attrs)
384 logger.debug("LDAPapi.py add attrs %s \r\n ldif %s"\
385 %(user_ldap_attrs,ldif) )
386 self.conn.ldapserv.add_s(dn,ldif)
388 logger.info("Adding user %s login %s in LDAP" \
389 %(user_ldap_attrs['cn'] ,user_ldap_attrs['uid']))
392 except ldap.LDAPError, e:
393 logger.log_exc("LDAP Add Error %s" %e)
394 return {'bool' : False, 'message' : e }
397 return {'bool': True}
402 def LdapDelete(self, person_dn):
404 Deletes a person in LDAP. Uses the dn of the user.
407 result = self.conn.connect()
410 self.conn.ldapserv.delete_s(person_dn)
412 return {'bool': True}
414 except ldap.LDAPError, e:
415 logger.log_exc("LDAP Delete Error %s" %e)
416 return {'bool': False}
419 def LdapDeleteUser(self, record_filter):
421 Deletes a SFA person in LDAP, based on the user's hrn.
423 #Find uid of the person
424 person = self.LdapFindUser(record_filter,[])
425 logger.debug("LDAPapi.py \t LdapDeleteUser record %s person %s" \
426 %(record_filter,person))
429 dn = 'uid=' + person['uid'] + "," +self.baseDN
431 return {'bool': False}
433 result = self.LdapDelete(dn)
437 def LdapModify(self, dn, old_attributes_dict, new_attributes_dict):
438 """ Modifies a LDAP entry """
440 ldif = modlist.modifyModlist(old_attributes_dict,new_attributes_dict)
441 # Connect and bind/authenticate
442 result = self.conn.connect()
445 self.conn.ldapserv.modify_s(dn,ldif)
447 return {'bool' : True }
448 except ldap.LDAPError, e:
449 logger.log_exc("LDAP LdapModify Error %s" %e)
450 return {'bool' : False }
453 def LdapModifyUser(self, user_record, new_attributes_dict):
455 Gets the record from one user_uid_login based on record_filter
456 and changes the attributes according to the specified new_attributes.
457 Does not use this if we need to modify the uid. Use a ModRDN
458 #operation instead ( modify relative DN )
460 if user_record is None:
461 logger.error("LDAP \t LdapModifyUser Need user record ")
462 return {'bool': False}
464 #Get all the attributes of the user_uid_login
465 #person = self.LdapFindUser(record_filter,[])
466 req_ldap = self.make_ldap_filters_from_record(user_record)
467 person_list = self.LdapSearch(req_ldap,[])
468 logger.debug("LDAPapi.py \t LdapModifyUser person_list : %s" %(person_list))
469 if person_list and len(person_list) > 1 :
470 logger.error("LDAP \t LdapModifyUser Too many users returned")
471 return {'bool': False}
472 if person_list is None :
473 logger.error("LDAP \t LdapModifyUser User %s doesn't exist "\
475 return {'bool': False}
477 # The dn of our existing entry/object
478 #One result only from ldapSearch
479 person = person_list[0][1]
480 dn = 'uid=' + person['uid'][0] + "," +self.baseDN
482 if new_attributes_dict:
484 for k in new_attributes_dict:
489 logger.debug(" LDAPapi.py \t LdapModifyUser new_attributes %s"\
490 %( new_attributes_dict))
491 result = self.LdapModify(dn, old,new_attributes_dict)
494 logger.error("LDAP \t LdapModifyUser No new attributes given. ")
495 return {'bool': False}
498 def LdapResetPassword(self,record):
500 Resets password for the user whose record is the parameter and changes
501 the corresponding entry in the LDAP.
504 password = self.generate_password()
506 attrs['userPassword'] = self.encrypt_password(password)
507 logger.debug("LDAP LdapResetPassword encrypt_password %s"\
508 %(attrs['userPassword']))
509 result = self.LdapModifyUser(record, attrs)
513 def LdapSearch (self, req_ldap = None, expected_fields = None ):
515 Used to search directly in LDAP, by using ldap filters and
517 When req_ldap is None, returns all the entries in the LDAP.
520 result = self.conn.connect(bind = False)
521 if (result['bool']) :
523 return_fields_list = []
524 if expected_fields == None :
525 return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
527 return_fields_list = expected_fields
528 #No specifc request specified, gert the whole LDAP
532 logger.debug("LDAP.PY \t LdapSearch req_ldap %s \
533 return_fields_list %s" %(req_ldap,return_fields_list))
536 msg_id = self.conn.ldapserv.search(
537 self.baseDN,ldap.SCOPE_SUBTREE,\
538 req_ldap,return_fields_list)
539 #Get all the results matching the search from ldap in one
541 result_type, result_data = \
542 self.conn.ldapserv.result(msg_id,1)
546 logger.debug("LDAP.PY \t LdapSearch result_data %s"\
551 except ldap.LDAPError,e :
552 logger.log_exc("LDAP LdapSearch Error %s" %e)
556 logger.error("LDAP.PY \t Connection Failed" )
560 def LdapFindUser(self,record = None, expected_fields = None):
562 Search a SFA user with a hrn. User should be already registered
564 Returns one matching entry
567 req_ldap = self.make_ldap_filters_from_record(record)
568 return_fields_list = []
569 if expected_fields == None :
570 return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
572 return_fields_list = expected_fields
574 result_data = self.LdapSearch(req_ldap, return_fields_list )
575 logger.debug("LDAP.PY \t LdapFindUser result_data %s" %(result_data))
577 if len(result_data) is 0:
579 #Asked for a specific user
582 ldapentry = result_data[0][1]
583 logger.debug("LDAP.PY \t LdapFindUser ldapentry %s" %(ldapentry))
584 tmpname = ldapentry['uid'][0]
586 tmpemail = ldapentry['mail'][0]
587 if ldapentry['mail'][0] == "unknown":
591 #logger.error("LDAP ldapFindHRn : no entry for record %s found"\
597 parent_hrn = get_authority(hrn)
598 peer_authority = None
599 if parent_hrn is not self.authname:
600 peer_authority = parent_hrn
604 'pkey': ldapentry['sshPublicKey'][0],
605 #'uid': ldapentry[1]['uid'][0],
608 #'email': ldapentry[1]['mail'][0],
609 'first_name': ldapentry['givenName'][0],
610 'last_name': ldapentry['sn'][0],
613 'authority': parent_hrn,
614 'peer_authority': peer_authority,
619 logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
623 #Asked for all users in ldap
625 for ldapentry in result_data:
626 logger.debug(" LDAP.py LdapFindUser ldapentry name : %s " \
627 %(ldapentry[1]['uid'][0]))
628 tmpname = ldapentry[1]['uid'][0]
629 hrn=self.authname+"."+ tmpname
631 tmpemail = ldapentry[1]['mail'][0]
632 if ldapentry[1]['mail'][0] == "unknown":
636 parent_hrn = get_authority(hrn)
637 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
641 'pkey': ldapentry[1]['sshPublicKey'][0],
642 #'uid': ldapentry[1]['uid'][0],
645 #'email': ldapentry[1]['mail'][0],
646 'first_name': ldapentry[1]['givenName'][0],
647 'last_name': ldapentry[1]['sn'][0],
650 'authority': self.authname,
651 'peer_authority': '',
656 logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" %(e))