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
7 #from sfa.trust.certificate import *
8 import ldap.modlist as modlist
9 from sfa.util.sfalogging import logger
16 def __init__(self, config_file = '/etc/sfa/ldap_config.py'):
18 execfile(config_file, self.__dict__)
20 self.config_file = config_file
21 # path to configuration data
22 self.config_path = os.path.dirname(config_file)
24 raise IOError, "Could not find or load the configuration file: %s" \
29 """ Set admin login and server configuration variables."""
32 #Senslab PROD LDAP parameters
34 ldap_config = LdapConfig()
35 self.config = ldap_config
36 self.ldapHost = ldap_config.LDAP_IP_ADDRESS
37 self.ldapPeopleDN = ldap_config.LDAP_PEOPLE_DN
38 self.ldapGroupDN = ldap_config.LDAP_GROUP_DN
39 self.ldapAdminDN = ldap_config.LDAP_WEB_DN
40 self.ldapAdminPassword = ldap_config.LDAP_WEB_PASSWORD
43 self.ldapPort = ldap.PORT
44 self.ldapVersion = ldap.VERSION3
45 self.ldapSearchScope = ldap.SCOPE_SUBTREE
48 def connect(self, bind = True):
49 """Enables connection to the LDAP server.
50 Set the bind parameter to True if a bind is needed
51 (for add/modify/delete operations).
52 Set to False otherwise.
56 self.ldapserv = ldap.open(self.ldapHost)
57 except ldap.LDAPError, error:
58 return {'bool' : False, 'message' : error }
60 # Bind with authentification
68 """ Binding method. """
70 # Opens a connection after a call to ldap.open in connect:
71 self.ldapserv = ldap.initialize("ldap://" + self.ldapHost)
73 # Bind/authenticate with a user with apropriate
74 #rights to add objects
75 self.ldapserv.simple_bind_s(self.ldapAdminDN, \
76 self.ldapAdminPassword)
78 except ldap.LDAPError, error:
79 return {'bool' : False, 'message' : error }
84 """ Close the LDAP connection """
86 self.ldapserv.unbind_s()
87 except ldap.LDAPError, error:
88 return {'bool' : False, 'message' : error }
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 login_filter = '(uid=' + login + ')'
174 #Check if login already in use
175 while (len(self.LdapSearch(login_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 login_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, error :
193 logger.log_exc("LDAP generate_login Error %s" %error)
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 login_filter = ['uidNumber']
234 result_data = self.LdapSearch(getAttrs, login_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)
249 def get_ssh_pkey(self, record):
250 """TODO ; Get ssh public key from sfa record
251 To be filled by N. Turro ? or using GID pl way?
256 def make_ldap_filters_from_record(self, record=None):
257 """TODO Handle OR filtering in the ldap query when
258 dealing with a list of records instead of doing a for loop in GetPersons
259 Helper function to make LDAP filter requests out of SFA records.
264 if 'first_name' in record and 'last_name' in record:
265 req_ldapdict['cn'] = str(record['first_name'])+" "\
266 + str(record['last_name'])
267 if 'email' in record :
268 req_ldapdict['mail'] = record['email']
270 req_ldapdict['mail'] = record['mail']
271 if 'enabled' in record:
272 if record['enabled'] == True :
273 req_ldapdict['shadowExpire'] = '-1'
275 req_ldapdict['shadowExpire'] = '0'
277 #Hrn should not be part of the filter because the hrn
278 #presented by a certificate of a SFA user not imported in
279 #Senslab does not include the senslab login in it
280 #Plus, the SFA user may already have an account with senslab
281 #using another login.
283 #if 'hrn' in record :
284 #splited_hrn = record['hrn'].split(".")
285 #if splited_hrn[0] != self.authname :
286 #logger.warning(" \r\n LDAP.PY \
287 #make_ldap_filters_from_record I know nothing \
288 #about %s my authname is %s not %s" \
289 #%(record['hrn'], self.authname, splited_hrn[0]) )
291 #login=splited_hrn[1]
292 #req_ldapdict['uid'] = login
295 logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
296 record %s req_ldapdict %s" \
297 %(record, req_ldapdict))
299 for k in req_ldapdict:
300 req_ldap += '('+ str(k)+ '=' + str(req_ldapdict[k]) + ')'
301 if len(req_ldapdict.keys()) >1 :
302 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
304 req_ldap = req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
310 def make_ldap_attributes_from_record(self, record):
311 """When addind a new user to Senslab's LDAP, creates an attributes
312 dictionnary from the SFA record.
317 attrs['objectClass'] = ["top", "person", "inetOrgPerson", \
318 "organizationalPerson", "posixAccount", \
319 "shadowAccount", "systemQuotas", \
322 attrs['givenName'] = str(record['first_name']).lower().capitalize()
323 attrs['sn'] = str(record['last_name']).lower().capitalize()
324 attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
325 attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
326 attrs['uid'] = self.generate_login(record)
328 attrs['quota'] = self.ldapUserQuotaNFS
329 attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
330 attrs['loginShell'] = self.ldapShell
331 attrs['gidNumber'] = self.ldapUserGidNumber
332 attrs['uidNumber'] = self.find_max_uidNumber()
333 attrs['mail'] = record['mail'].lower()
335 attrs['sshPublicKey'] = record['pkey']
337 attrs['sshPublicKey'] = self.get_ssh_pkey(record)
340 #Password is automatically generated because SFA user don't go
341 #through the Senslab website used to register new users,
342 #There is no place in SFA where users can enter such information
344 #If the user wants to set his own password , he must go to the Senslab
346 password = self.generate_password()
347 attrs['userPassword']= self.encrypt_password(password)
349 #Account automatically validated (no mail request to admins)
350 #Set to 0 to disable the account, -1 to enable it,
351 attrs['shadowExpire'] = '-1'
353 #Motivation field in Senslab
354 attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
356 attrs['ou'] = 'SFA' #Optional: organizational unit
357 #No info about those here:
358 attrs['l'] = 'To be defined'#Optional: Locality.
359 attrs['st'] = 'To be defined' #Optional: state or province (country).
365 def LdapAddUser(self, record) :
366 """Add SFA user to LDAP if it is not in LDAP yet. """
368 user_ldap_attrs = self.make_ldap_attributes_from_record(record)
371 #Check if user already in LDAP wih email, first name and last name
372 filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
373 user_exist = self.LdapSearch(filter_by)
375 logger.warning(" \r\n \t LDAP LdapAddUser user %s %s \
376 already exists" %(user_ldap_attrs['sn'], \
377 user_ldap_attrs['mail']))
378 return {'bool': False}
381 result = self.conn.connect()
385 # A dict to help build the "body" of the object
387 logger.debug(" \r\n \t LDAP LdapAddUser attrs %s " %user_ldap_attrs)
389 # The dn of our new entry/object
390 dn = 'uid=' + user_ldap_attrs['uid'] + "," + self.baseDN
393 ldif = modlist.addModlist(user_ldap_attrs)
394 logger.debug("LDAPapi.py add attrs %s \r\n ldif %s"\
395 %(user_ldap_attrs,ldif) )
396 self.conn.ldapserv.add_s(dn,ldif)
398 logger.info("Adding user %s login %s in LDAP" \
399 %(user_ldap_attrs['cn'] ,user_ldap_attrs['uid']))
402 except ldap.LDAPError, error:
403 logger.log_exc("LDAP Add Error %s" %error)
404 return {'bool' : False, 'message' : error }
407 return {'bool': True}
412 def LdapDelete(self, person_dn):
414 Deletes a person in LDAP. Uses the dn of the user.
417 result = self.conn.connect()
420 self.conn.ldapserv.delete_s(person_dn)
422 return {'bool': True}
424 except ldap.LDAPError, error:
425 logger.log_exc("LDAP Delete Error %s" %error)
426 return {'bool': False}
429 def LdapDeleteUser(self, record_filter):
431 Deletes a SFA person in LDAP, based on the user's hrn.
433 #Find uid of the person
434 person = self.LdapFindUser(record_filter,[])
435 logger.debug("LDAPapi.py \t LdapDeleteUser record %s person %s" \
436 %(record_filter, person))
439 dn = 'uid=' + person['uid'] + "," +self.baseDN
441 return {'bool': False}
443 result = self.LdapDelete(dn)
447 def LdapModify(self, dn, old_attributes_dict, new_attributes_dict):
448 """ Modifies a LDAP entry """
450 ldif = modlist.modifyModlist(old_attributes_dict,new_attributes_dict)
451 # Connect and bind/authenticate
452 result = self.conn.connect()
455 self.conn.ldapserv.modify_s(dn,ldif)
457 return {'bool' : True }
458 except ldap.LDAPError, error:
459 logger.log_exc("LDAP LdapModify Error %s" %error)
460 return {'bool' : False }
463 def LdapModifyUser(self, user_record, new_attributes_dict):
465 Gets the record from one user_uid_login based on record_filter
466 and changes the attributes according to the specified new_attributes.
467 Does not use this if we need to modify the uid. Use a ModRDN
468 #operation instead ( modify relative DN )
470 if user_record is None:
471 logger.error("LDAP \t LdapModifyUser Need user record ")
472 return {'bool': False}
474 #Get all the attributes of the user_uid_login
475 #person = self.LdapFindUser(record_filter,[])
476 req_ldap = self.make_ldap_filters_from_record(user_record)
477 person_list = self.LdapSearch(req_ldap,[])
478 logger.debug("LDAPapi.py \t LdapModifyUser person_list : %s" \
480 if person_list and len(person_list) > 1 :
481 logger.error("LDAP \t LdapModifyUser Too many users returned")
482 return {'bool': False}
483 if person_list is None :
484 logger.error("LDAP \t LdapModifyUser User %s doesn't exist "\
486 return {'bool': False}
488 # The dn of our existing entry/object
489 #One result only from ldapSearch
490 person = person_list[0][1]
491 dn = 'uid=' + person['uid'][0] + "," +self.baseDN
493 if new_attributes_dict:
495 for k in new_attributes_dict:
500 logger.debug(" LDAPapi.py \t LdapModifyUser new_attributes %s"\
501 %( new_attributes_dict))
502 result = self.LdapModify(dn, old,new_attributes_dict)
505 logger.error("LDAP \t LdapModifyUser No new attributes given. ")
506 return {'bool': False}
511 def LdapMarkUserAsDeleted(self, record):
516 new_attrs['shadowExpire'] = '0'
517 logger.debug(" LDAPapi.py \t LdapMarkUserAsDeleted ")
518 ret = self.LdapModifyUser(record, new_attrs)
522 def LdapResetPassword(self,record):
524 Resets password for the user whose record is the parameter and changes
525 the corresponding entry in the LDAP.
528 password = self.generate_password()
530 attrs['userPassword'] = self.encrypt_password(password)
531 logger.debug("LDAP LdapResetPassword encrypt_password %s"\
532 %(attrs['userPassword']))
533 result = self.LdapModifyUser(record, attrs)
537 def LdapSearch (self, req_ldap = None, expected_fields = None ):
539 Used to search directly in LDAP, by using ldap filters and
541 When req_ldap is None, returns all the entries in the LDAP.
544 result = self.conn.connect(bind = False)
545 if (result['bool']) :
547 return_fields_list = []
548 if expected_fields == None :
549 return_fields_list = ['mail','givenName', 'sn', 'uid', \
550 'sshPublicKey', 'shadowExpire']
552 return_fields_list = expected_fields
553 #No specifc request specified, get the whole LDAP
557 logger.debug("LDAP.PY \t LdapSearch req_ldap %s \
558 return_fields_list %s" \
559 %(req_ldap, return_fields_list))
562 msg_id = self.conn.ldapserv.search(
563 self.baseDN,ldap.SCOPE_SUBTREE,\
564 req_ldap, return_fields_list)
565 #Get all the results matching the search from ldap in one
567 result_type, result_data = \
568 self.conn.ldapserv.result(msg_id,1)
572 logger.debug("LDAP.PY \t LdapSearch result_data %s"\
577 except ldap.LDAPError,error :
578 logger.log_exc("LDAP LdapSearch Error %s" %error)
582 logger.error("LDAP.PY \t Connection Failed" )
585 def LdapFindUser(self, record = None, is_user_enabled=None, \
586 expected_fields = None):
588 Search a SFA user with a hrn. User should be already registered
590 Returns one matching entry
595 custom_record['enabled'] = is_user_enabled
597 custom_record.update(record)
600 req_ldap = self.make_ldap_filters_from_record(custom_record)
601 return_fields_list = []
602 if expected_fields == None :
603 return_fields_list = ['mail','givenName', 'sn', 'uid', \
606 return_fields_list = expected_fields
608 result_data = self.LdapSearch(req_ldap, return_fields_list )
609 logger.debug("LDAP.PY \t LdapFindUser result_data %s" %(result_data))
611 if len(result_data) is 0:
613 #Asked for a specific user
616 ldapentry = result_data[0][1]
617 logger.debug("LDAP.PY \t LdapFindUser ldapentry %s" %(ldapentry))
618 tmpname = ldapentry['uid'][0]
620 tmpemail = ldapentry['mail'][0]
621 if ldapentry['mail'][0] == "unknown":
625 #logger.error("LDAP ldapFindHRn : no entry for record %s found"\
631 parent_hrn = get_authority(hrn)
632 peer_authority = None
633 if parent_hrn is not self.authname:
634 peer_authority = parent_hrn
638 'pkey': ldapentry['sshPublicKey'][0],
639 #'uid': ldapentry[1]['uid'][0],
642 #'email': ldapentry[1]['mail'][0],
643 'first_name': ldapentry['givenName'][0],
644 'last_name': ldapentry['sn'][0],
647 'authority': parent_hrn,
648 'peer_authority': peer_authority,
652 except KeyError,error:
653 logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
657 #Asked for all users in ldap
659 for ldapentry in result_data:
660 logger.debug(" LDAP.py LdapFindUser ldapentry name : %s " \
661 %(ldapentry[1]['uid'][0]))
662 tmpname = ldapentry[1]['uid'][0]
663 hrn=self.authname+"."+ tmpname
665 tmpemail = ldapentry[1]['mail'][0]
666 if ldapentry[1]['mail'][0] == "unknown":
670 parent_hrn = get_authority(hrn)
671 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
675 'pkey': ldapentry[1]['sshPublicKey'][0],
676 #'uid': ldapentry[1]['uid'][0],
679 #'email': ldapentry[1]['mail'][0],
680 'first_name': ldapentry[1]['givenName'][0],
681 'last_name': ldapentry[1]['sn'][0],
684 'authority': self.authname,
685 'peer_authority': '',
689 except KeyError,error:
690 logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" \