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'):
17 self.load(config_file)
19 def load(self, config_file):
21 execfile(config_file, self.__dict__)
22 self.config_file = config_file
23 # path to configuration data
24 self.config_path = os.path.dirname(config_file)
25 except IOError, error:
26 raise IOError, "Could not find or load the configuration file: %s" % config_file
29 """ Set admin login and server configuration variables."""
32 #Senslab PROD LDAP parameters
33 LdapConfig = ldap_config()
34 self.config = LdapConfig
35 self.ldapHost = LdapConfig.LDAP_IP_ADDRESS
36 self.ldapPeopleDN = LdapConfig.LDAP_PEOPLE_DN
37 self.ldapGroupDN = LdapConfig.LDAP_GROUP_DN
38 self.ldapAdminDN = LdapConfig.LDAP_WEB_DN
39 self.ldapAdminPassword = LdapConfig.LDAP_WEB_PASSWORD
42 self.ldapPort = ldap.PORT
43 self.ldapVersion = ldap.VERSION3
44 self.ldapSearchScope = ldap.SCOPE_SUBTREE
47 def connect(self, bind = True):
48 """Enables connection to the LDAP server.
49 Set the bind parameter to True if a bind is needed
50 (for add/modify/delete operations).
51 Set to False otherwise.
55 self.ldapserv = ldap.open(self.ldapHost)
56 except ldap.LDAPError, error:
57 return {'bool' : False, 'message' : error }
59 # Bind with authentification
67 """ Binding method. """
69 # Opens a connection after a call to ldap.open in connect:
70 self.ldapserv = ldap.initialize("ldap://" + self.ldapHost)
72 # Bind/authenticate with a user with apropriate rights to add objects
73 self.ldapserv.simple_bind_s(self.ldapAdminDN, self.ldapAdminPassword)
75 except ldap.LDAPError, error:
76 return {'bool' : False, 'message' : error }
81 """ Close the LDAP connection """
83 self.ldapserv.unbind_s()
84 except ldap.LDAPError, error:
85 return {'bool' : False, 'message' : error }
90 logger.setLevelDebug()
92 self.senslabauth = Hierarchy()
95 self.authname = config.SFA_REGISTRY_ROOT_AUTH
98 self.ldapUserQuotaNFS = self.conn.config.LDAP_USER_QUOTA_NFS
99 self.ldapUserUidNumberMin = self.conn.config.LDAP_USER_UID_NUMBER_MIN
100 self.ldapUserGidNumber = self.conn.config.LDAP_USER_GID_NUMBER
101 self.ldapUserHomePath = self.conn.config.LDAP_USER_HOME_PATH
103 self.lengthPassword = 8
104 self.baseDN = self.conn.ldapPeopleDN
105 #authinfo=self.senslabauth.get_auth_info(self.authname)
108 self.charsPassword = [ '!','$','(',')','*','+',',','-','.',\
109 '0','1','2','3','4','5','6','7','8','9',\
110 'A','B','C','D','E','F','G','H','I','J',\
111 'K','L','M','N','O','P','Q','R','S','T',\
112 'U','V','W','X','Y','Z','_','a','b','c',\
113 'd','e','f','g','h','i','j','k','l','m',\
114 'n','o','p','q','r','s','t','u','v','w',\
117 self.ldapShell = '/bin/bash'
120 def generate_login(self, record):
121 """Generate login for adding a new user in LDAP Directory
122 (four characters minimum length)
123 Record contains first name and last name.
126 #Remove all special characters from first_name/last name
127 lower_first_name = record['first_name'].replace('-','')\
128 .replace('_','').replace('[','')\
129 .replace(']','').replace(' ','')\
131 lower_last_name = record['last_name'].replace('-','')\
132 .replace('_','').replace('[','')\
133 .replace(']','').replace(' ','')\
135 length_last_name = len(lower_last_name)
138 #Try generating a unique login based on first name and last name
140 if length_last_name >= login_max_length :
141 login = lower_last_name[0:login_max_length]
143 logger.debug("login : %s index : %s" %(login,index))
144 elif length_last_name >= 4 :
145 login = lower_last_name
147 logger.debug("login : %s index : %s" %(login,index))
148 elif length_last_name == 3 :
149 login = lower_first_name[0:1] + lower_last_name
151 logger.debug("login : %s index : %s" %(login,index))
152 elif length_last_name == 2:
153 if len ( lower_first_name) >=2:
154 login = lower_first_name[0:2] + lower_last_name
156 logger.debug("login : %s index : %s" %(login,index))
158 logger.error("LoginException : \
159 Generation login error with \
160 minimum four characters")
164 logger.error("LDAP generate_login failed : \
165 impossible to generate unique login for %s %s" \
166 %(lower_first_name,lower_last_name))
168 login_filter = '(uid=' + login + ')'
171 #Check if login already in use
172 while (len(self.LdapSearch(login_filter, getAttrs)) is not 0 ):
176 logger.error("LoginException : Generation login error \
177 with minimum four characters")
180 login = lower_first_name[0:index] + \
181 lower_last_name[0:login_max_length-index]
182 login_filter = '(uid='+ login+ ')'
184 print "lower_first_name - lower_last_name too short"
186 logger.debug("LDAP.API \t generate_login login %s" %(login))
189 except ldap.LDAPError,error :
190 logger.log_exc("LDAP generate_login Error %s" %error)
195 def generate_password(self):
197 """Generate password for adding a new user in LDAP Directory
198 (8 characters length) return password
202 length = len(self.charsPassword)
203 for index in range(self.lengthPassword):
204 char_index = random.randint(0,length-1)
205 password += self.charsPassword[char_index]
209 def encrypt_password(self, password):
210 """ Use passlib library to make a RFC2307 LDAP encrypted password
211 salt size = 8, use sha-1 algorithm. Returns encrypted password.
214 #Keep consistency with Java Senslab's LDAP API
215 #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
216 return lssha.encrypt(password,salt_size = 8)
220 def find_max_uidNumber(self):
222 """Find the LDAP max uidNumber (POSIX uid attribute) .
223 Used when adding a new user in LDAP Directory
224 returns string max uidNumber + 1
227 #First, get all the users in the LDAP
228 getAttrs = "(uidNumber=*)"
229 login_filter = ['uidNumber']
231 result_data = self.LdapSearch(getAttrs, login_filter)
232 #It there is no user in LDAP yet, First LDAP user
233 if result_data == []:
234 max_uidnumber = self.ldapUserUidNumberMin
235 #Otherwise, get the highest uidNumber
238 uidNumberList = [int(r[1]['uidNumber'][0])for r in result_data ]
239 logger.debug("LDAPapi.py \tfind_max_uidNumber \
240 uidNumberList %s " %(uidNumberList))
241 max_uidnumber = max(uidNumberList) + 1
243 return str(max_uidnumber)
246 def get_ssh_pkey(self, record):
247 """TODO ; Get ssh public key from sfa record
248 To be filled by N. Turro ? or using GID pl way?
253 def make_ldap_filters_from_record(self, record=None):
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 Helper function to make LDAP filter requests out of SFA records.
261 if 'first_name' in record and 'last_name' in record:
262 req_ldapdict['cn'] = str(record['first_name'])+" "\
263 + str(record['last_name'])
264 if 'email' in record :
265 req_ldapdict['mail'] = record['email']
267 req_ldapdict['mail'] = record['mail']
268 if 'enabled' in record:
269 if record['enabled'] == True :
270 req_ldapdict['shadowExpire'] = '-1'
272 req_ldapdict['shadowExpire'] = '0'
274 #Hrn should not be part of the filter because the hrn
275 #presented by a certificate of a SFA user not imported in
276 #Senslab does not include the senslab login in it
277 #Plus, the SFA user may already have an account with senslab
278 #using another login.
280 #if 'hrn' in record :
281 #splited_hrn = record['hrn'].split(".")
282 #if splited_hrn[0] != self.authname :
283 #logger.warning(" \r\n LDAP.PY \
284 #make_ldap_filters_from_record I know nothing \
285 #about %s my authname is %s not %s" \
286 #%(record['hrn'], self.authname, splited_hrn[0]) )
288 #login=splited_hrn[1]
289 #req_ldapdict['uid'] = login
292 logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
293 record %s req_ldapdict %s" \
294 %(record, req_ldapdict))
296 for k in req_ldapdict:
297 req_ldap += '('+ str(k)+ '=' + str(req_ldapdict[k]) + ')'
298 if len(req_ldapdict.keys()) >1 :
299 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
301 req_ldap = req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
307 def make_ldap_attributes_from_record(self, record):
308 """When addind a new user to Senslab's LDAP, creates an attributes
309 dictionnary from the SFA record.
314 attrs['objectClass'] = ["top", "person", "inetOrgPerson",\
315 "organizationalPerson", "posixAccount",\
316 "shadowAccount", "systemQuotas",\
319 attrs['givenName'] = str(record['first_name']).lower().capitalize()
320 attrs['sn'] = str(record['last_name']).lower().capitalize()
321 attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
322 attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
323 attrs['uid'] = self.generate_login(record)
325 attrs['quota'] = self.ldapUserQuotaNFS
326 attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
327 attrs['loginShell'] = self.ldapShell
328 attrs['gidNumber'] = self.ldapUserGidNumber
329 attrs['uidNumber'] = self.find_max_uidNumber()
330 attrs['mail'] = record['mail'].lower()
332 attrs['sshPublicKey'] = record['pkey']
334 attrs['sshPublicKey'] = self.get_ssh_pkey(record)
337 #Password is automatically generated because SFA user don't go
338 #through the Senslab website used to register new users,
339 #There is no place in SFA where users can enter such information
341 #If the user wants to set his own password , he must go to the Senslab
343 password = self.generate_password()
344 attrs['userPassword']= self.encrypt_password(password)
346 #Account automatically validated (no mail request to admins)
347 #Set to 0 to disable the account, -1 to enable it,
348 attrs['shadowExpire'] = '-1'
350 #Motivation field in Senslab
351 attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
353 attrs['ou'] = 'SFA' #Optional: organizational unit
354 #No info about those here:
355 attrs['l'] = 'To be defined'#Optional: Locality.
356 attrs['st'] = 'To be defined' #Optional: state or province (country).
362 def LdapAddUser(self, record) :
363 """Add SFA user to LDAP if it is not in LDAP yet. """
365 user_ldap_attrs = self.make_ldap_attributes_from_record(record)
368 #Check if user already in LDAP wih email, first name and last name
369 filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
370 user_exist = self.LdapSearch(filter_by)
372 logger.warning(" \r\n \t LDAP LdapAddUser user %s %s already exists" \
373 %(user_ldap_attrs['sn'],user_ldap_attrs['mail']))
374 return {'bool': False}
377 result = self.conn.connect()
381 # A dict to help build the "body" of the object
383 logger.debug(" \r\n \t LDAP LdapAddUser attrs %s " %user_ldap_attrs)
385 # The dn of our new entry/object
386 dn = 'uid=' + user_ldap_attrs['uid'] + "," + self.baseDN
389 ldif = modlist.addModlist(user_ldap_attrs)
390 logger.debug("LDAPapi.py add attrs %s \r\n ldif %s"\
391 %(user_ldap_attrs,ldif) )
392 self.conn.ldapserv.add_s(dn,ldif)
394 logger.info("Adding user %s login %s in LDAP" \
395 %(user_ldap_attrs['cn'] ,user_ldap_attrs['uid']))
398 except ldap.LDAPError, error:
399 logger.log_exc("LDAP Add Error %s" %error)
400 return {'bool' : False, 'message' : error }
403 return {'bool': True}
408 def LdapDelete(self, person_dn):
410 Deletes a person in LDAP. Uses the dn of the user.
413 result = self.conn.connect()
416 self.conn.ldapserv.delete_s(person_dn)
418 return {'bool': True}
420 except ldap.LDAPError, error:
421 logger.log_exc("LDAP Delete Error %s" %error)
422 return {'bool': False}
425 def LdapDeleteUser(self, record_filter):
427 Deletes a SFA person in LDAP, based on the user's hrn.
429 #Find uid of the person
430 person = self.LdapFindUser(record_filter,[])
431 logger.debug("LDAPapi.py \t LdapDeleteUser record %s person %s" \
432 %(record_filter, person))
435 dn = 'uid=' + person['uid'] + "," +self.baseDN
437 return {'bool': False}
439 result = self.LdapDelete(dn)
443 def LdapModify(self, dn, old_attributes_dict, new_attributes_dict):
444 """ Modifies a LDAP entry """
446 ldif = modlist.modifyModlist(old_attributes_dict,new_attributes_dict)
447 # Connect and bind/authenticate
448 result = self.conn.connect()
451 self.conn.ldapserv.modify_s(dn,ldif)
453 return {'bool' : True }
454 except ldap.LDAPError, error:
455 logger.log_exc("LDAP LdapModify Error %s" %error)
456 return {'bool' : False }
459 def LdapModifyUser(self, user_record, new_attributes_dict):
461 Gets the record from one user_uid_login based on record_filter
462 and changes the attributes according to the specified new_attributes.
463 Does not use this if we need to modify the uid. Use a ModRDN
464 #operation instead ( modify relative DN )
466 if user_record is None:
467 logger.error("LDAP \t LdapModifyUser Need user record ")
468 return {'bool': False}
470 #Get all the attributes of the user_uid_login
471 #person = self.LdapFindUser(record_filter,[])
472 req_ldap = self.make_ldap_filters_from_record(user_record)
473 person_list = self.LdapSearch(req_ldap,[])
474 logger.debug("LDAPapi.py \t LdapModifyUser person_list : %s" %(person_list))
475 if person_list and len(person_list) > 1 :
476 logger.error("LDAP \t LdapModifyUser Too many users returned")
477 return {'bool': False}
478 if person_list is None :
479 logger.error("LDAP \t LdapModifyUser User %s doesn't exist "\
481 return {'bool': False}
483 # The dn of our existing entry/object
484 #One result only from ldapSearch
485 person = person_list[0][1]
486 dn = 'uid=' + person['uid'][0] + "," +self.baseDN
488 if new_attributes_dict:
490 for k in new_attributes_dict:
495 logger.debug(" LDAPapi.py \t LdapModifyUser new_attributes %s"\
496 %( new_attributes_dict))
497 result = self.LdapModify(dn, old,new_attributes_dict)
500 logger.error("LDAP \t LdapModifyUser No new attributes given. ")
501 return {'bool': False}
506 def LdapMarkUserAsDeleted(self, record):
511 new_attrs['shadowExpire'] = '0'
512 logger.debug(" LDAPapi.py \t LdapMarkUserAsDeleted ")
513 ret = self.LdapModifyUser(record, new_attrs)
517 def LdapResetPassword(self,record):
519 Resets password for the user whose record is the parameter and changes
520 the corresponding entry in the LDAP.
523 password = self.generate_password()
525 attrs['userPassword'] = self.encrypt_password(password)
526 logger.debug("LDAP LdapResetPassword encrypt_password %s"\
527 %(attrs['userPassword']))
528 result = self.LdapModifyUser(record, attrs)
532 def LdapSearch (self, req_ldap = None, expected_fields = None ):
534 Used to search directly in LDAP, by using ldap filters and
536 When req_ldap is None, returns all the entries in the LDAP.
539 result = self.conn.connect(bind = False)
540 if (result['bool']) :
542 return_fields_list = []
543 if expected_fields == None :
544 return_fields_list = ['mail','givenName', 'sn', 'uid', \
545 'sshPublicKey', 'shadowExpire']
547 return_fields_list = expected_fields
548 #No specifc request specified, get the whole LDAP
552 logger.debug("LDAP.PY \t LdapSearch req_ldap %s \
553 return_fields_list %s" \
554 %(req_ldap, return_fields_list))
557 msg_id = self.conn.ldapserv.search(
558 self.baseDN,ldap.SCOPE_SUBTREE,\
559 req_ldap, return_fields_list)
560 #Get all the results matching the search from ldap in one
562 result_type, result_data = \
563 self.conn.ldapserv.result(msg_id,1)
567 logger.debug("LDAP.PY \t LdapSearch result_data %s"\
572 except ldap.LDAPError,error :
573 logger.log_exc("LDAP LdapSearch Error %s" %error)
577 logger.error("LDAP.PY \t Connection Failed" )
580 def LdapFindUser(self, record = None, is_user_enabled=None, \
581 expected_fields = None):
583 Search a SFA user with a hrn. User should be already registered
585 Returns one matching entry
590 custom_record['enabled'] = is_user_enabled
592 custom_record.update(record)
595 req_ldap = self.make_ldap_filters_from_record(custom_record)
596 return_fields_list = []
597 if expected_fields == None :
598 return_fields_list = ['mail','givenName', 'sn', 'uid', \
601 return_fields_list = expected_fields
603 result_data = self.LdapSearch(req_ldap, return_fields_list )
604 logger.debug("LDAP.PY \t LdapFindUser result_data %s" %(result_data))
606 if len(result_data) is 0:
608 #Asked for a specific user
611 ldapentry = result_data[0][1]
612 logger.debug("LDAP.PY \t LdapFindUser ldapentry %s" %(ldapentry))
613 tmpname = ldapentry['uid'][0]
615 tmpemail = ldapentry['mail'][0]
616 if ldapentry['mail'][0] == "unknown":
620 #logger.error("LDAP ldapFindHRn : no entry for record %s found"\
626 parent_hrn = get_authority(hrn)
627 peer_authority = None
628 if parent_hrn is not self.authname:
629 peer_authority = parent_hrn
633 'pkey': ldapentry['sshPublicKey'][0],
634 #'uid': ldapentry[1]['uid'][0],
637 #'email': ldapentry[1]['mail'][0],
638 'first_name': ldapentry['givenName'][0],
639 'last_name': ldapentry['sn'][0],
642 'authority': parent_hrn,
643 'peer_authority': peer_authority,
647 except KeyError,error:
648 logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
652 #Asked for all users in ldap
654 for ldapentry in result_data:
655 logger.debug(" LDAP.py LdapFindUser ldapentry name : %s " \
656 %(ldapentry[1]['uid'][0]))
657 tmpname = ldapentry[1]['uid'][0]
658 hrn=self.authname+"."+ tmpname
660 tmpemail = ldapentry[1]['mail'][0]
661 if ldapentry[1]['mail'][0] == "unknown":
665 parent_hrn = get_authority(hrn)
666 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
670 'pkey': ldapentry[1]['sshPublicKey'][0],
671 #'uid': ldapentry[1]['uid'][0],
674 #'email': ldapentry[1]['mail'][0],
675 'first_name': ldapentry[1]['givenName'][0],
676 'last_name': ldapentry[1]['sn'][0],
679 'authority': self.authname,
680 'peer_authority': '',
684 except KeyError,error:
685 logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" %(error))