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.gid import *
9 from sfa.trust.hierarchy import Hierarchy
10 #from sfa.trust.auth import *
11 from sfa.trust.certificate import *
12 import ldap.modlist as modlist
13 from sfa.util.sfalogging import logger
19 """ Set admin login and server configuration variables."""
22 #self.login = 'cn=admin,dc=senslab,dc=info'
24 self.server_ip = "194.199.16.161"
26 #Senslab PROD LDAP parameters
27 #TODO : Use config file /etc/senslab/config.properties if it is possible
28 self.ldapPort = ldap.PORT
29 self.ldapVersion = ldap.VERSION3
30 self.ldapSearchScope = ldap.SCOPE_SUBTREE
33 self.ldapHost = "" #set ldap.OPT_HOST_NAME maybe ?
34 self.ldapPeopleDN = 'ou=People,dc=senslab,dc=info';
35 self.ldapGroupDN = 'ou=Group,dc=senslab,dc=info';
36 self.ldapAdminDN = 'uid=web,ou=Service,dc=senslab,dc=info';
37 self.ldapAdminPassword = 'XNB+1z(C'
39 def connect(self, bind = True):
40 """Enables connection to the LDAP server.
41 Set the bind parameter to True if a bind is needed
42 (for add/modify/delete operations).
43 Set to False otherwise.
47 self.ldapserv = ldap.open(self.server_ip)
48 except ldap.LDAPError, e:
49 return {'bool' : False, 'message' : e }
51 # Bind with authentification
60 """ Binding method. """
62 # Opens a connection after a call to ldap.open in connect:
63 self.ldapserv = ldap.initialize("ldap://" + self.server_ip )
65 # Bind/authenticate with a user with apropriate rights to add objects
66 self.ldapserv.simple_bind_s(self.ldapAdminDN, self.ldapAdminPassword)
68 except ldap.LDAPError, e:
69 return {'bool' : False, 'message' : e }
74 """ Close the LDAP connection """
76 self.ldapserv.unbind_s()
77 except ldap.LDAPError, e:
78 return {'bool' : False, 'message' : e }
83 logger.setLevelDebug()
85 self.senslabauth=Hierarchy()
88 self.authname=config.SFA_REGISTRY_ROOT_AUTH
89 #self.baseDN = "ou=people,dc=senslab,dc=info"
91 self.baseDN = self.conn.ldapPeopleDN
92 #authinfo=self.senslabauth.get_auth_info(self.authname)
95 self.charsPassword = [ '!','$','(',')','*','+',',','-','.',\
96 '0','1','2','3','4','5','6','7','8','9',\
97 'A','B','C','D','E','F','G','H','I','J',\
98 'K','L','M','N','O','P','Q','R','S','T',\
99 'U','V','W','X','Y','Z','_','a','b','c',\
100 'd','e','f','g','h','i','j','k','l','m',\
101 'n','o','p','q','r','s','t','u','v','w',\
103 self.ldapUserQuotaNFS = '/dev/vdb:2000000:2500000:0:0'
104 self.lengthPassword = 8;
105 self.ldapUserHomePath = '/senslab/users/'
106 self.ldapUserGidNumber = '2000'
107 self.ldapUserUidNumberMin = '2000'
108 self.ldapShell = '/bin/bash'
110 #gid=authinfo.get_gid_object()
111 #self.ldapdictlist = ['type',
122 def generate_login(self, record):
123 """Generate login for adding a new user in LDAP Directory
124 (four characters minimum length)
125 Record contains first name and last name.
128 #Remove all special characters from first_name/last name
129 lower_first_name = record['first_name'].replace('-','')\
130 .replace('_','').replace('[','')\
131 .replace(']','').replace(' ','')\
133 lower_last_name = record['last_name'].replace('-','')\
134 .replace('_','').replace('[','')\
135 .replace(']','').replace(' ','')\
137 length_last_name = len(lower_last_name)
140 #Try generating a unique login based on first name and last name
142 if length_last_name >= login_max_length :
143 login = lower_last_name[0:login_max_length]
145 logger.debug("login : %s index : %s" %(login,index))
146 elif length_last_name >= 4 :
147 login = lower_last_name
149 logger.debug("login : %s index : %s" %(login,index))
150 elif length_last_name == 3 :
151 login = lower_first_name[0:1] + lower_last_name
153 logger.debug("login : %s index : %s" %(login,index))
154 elif length_last_name == 2:
155 if len ( lower_first_name) >=2:
156 login = lower_first_name[0:2] + lower_last_name
158 logger.debug("login : %s index : %s" %(login,index))
160 logger.error("LoginException : \
161 Generation login error with \
162 minimum four characters")
166 logger.error("LDAP generate_login failed : \
167 impossible to generate unique login for %s %s" \
168 %(lower_first_name,lower_last_name))
170 filter = '(uid=' + login + ')'
173 #Check if login already in use
174 while (len(self.LdapSearch(filter, getAttrs)) is not 0 ):
178 logger.error("LoginException : Generation login error \
179 with minimum four characters")
182 login = lower_first_name[0:index] + \
183 lower_last_name[0:login_max_length-index]
184 filter = '(uid='+ login+ ')'
186 print "lower_first_name - lower_last_name too short"
188 logger.debug("LDAP.API \t generate_login login %s" %(login))
191 except ldap.LDAPError,e :
192 logger.log_exc("LDAP generate_login Error %s" %e)
197 def generate_password(self):
199 """Generate password for adding a new user in LDAP Directory
200 (8 characters length) return password
204 for index in range(self.lengthPassword):
205 password += self.charsPassword[random.randint(0, \
206 len(self.charsPassword))]
210 def encrypt_password(self, password):
211 """ Use passlib library to make a RFC2307 LDAP encrypted password
212 salt size = 8, use sha-1 algorithm. Returns encrypted password.
215 #Keep consistency with Java Senslab's LDAP API
216 #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
217 return lssha.encrypt(password,salt_size = 8)
221 def find_max_uidNumber(self):
223 """Find the LDAP max uidNumber (POSIX uid attribute) .
224 Used when adding a new user in LDAP Directory
225 returns string max uidNumber + 1
228 #First, get all the users in the LDAP
229 getAttrs = "(uidNumber=*)"
230 filter = ['uidNumber']
232 result_data = self.LdapSearch(getAttrs, filter)
233 #It there is no user in LDAP yet, First LDAP user
234 if result_data == []:
235 max_uidnumber = self.ldapUserUidNumberMin
236 #Otherwise, get the highest uidNumber
239 uidNumberList = [int(r[1]['uidNumber'][0])for r in result_data ]
240 logger.debug("LDAPapi.py \tfind_max_uidNumber \
241 uidNumberList %s " %(uidNumberList))
242 max_uidnumber = max(uidNumberList) + 1
244 return str(max_uidnumber)
246 #TODO ; Get ssh public key from sfa record
247 #To be filled by N. Turro
248 def get_ssh_pkey(self, record):
252 #TODO Handle OR filtering in the ldap query when
253 #dealing with a list of records instead of doing a for loop in GetPersons
254 def make_ldap_filters_from_record(self, record=None):
256 Helper function to make LDAP filter requests out of SFA records.
260 if 'first_name' in record and 'last_name' in record:
261 req_ldapdict['cn'] = str(record['first_name'])+" "\
262 + str(record['last_name'])
263 if 'email' in record :
264 req_ldapdict['mail'] = record['email']
266 req_ldapdict['mail'] = record['mail']
269 splited_hrn = record['hrn'].split(".")
270 if splited_hrn[0] != self.authname :
271 logger.warning(" \r\n LDAP.PY \
272 make_ldap_filters_from_record I know nothing \
273 about %s my authname is %s not %s" \
274 %(record['hrn'], self.authname, splited_hrn[0]) )
277 req_ldapdict['uid'] = login
280 logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
281 record %s req_ldapdict %s" \
282 %(record, req_ldapdict))
284 for k in req_ldapdict:
285 req_ldap += '('+str(k)+'='+str(req_ldapdict[k])+')'
286 if len(req_ldapdict.keys()) >1 :
287 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
289 req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
295 def make_ldap_attributes_from_record(self, record):
296 """When addind a new user to Senslab's LDAP, creates an attributes
297 dictionnary from the SFA record.
302 attrs['objectClass'] = ["top", "person", "inetOrgPerson",\
303 "organizationalPerson", "posixAccount",\
304 "shadowAccount", "systemQuotas",\
307 attrs['givenName'] = str(record['first_name']).lower().capitalize()
308 attrs['sn'] = str(record['last_name']).lower().capitalize()
309 attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
310 attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
311 attrs['uid'] = self.generate_login(record)
313 attrs['quota'] = self.ldapUserQuotaNFS
314 attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
315 attrs['loginShell'] = self.ldapShell
316 attrs['gidNumber'] = '2000'
317 attrs['uidNumber'] = self.find_max_uidNumber()
318 attrs['mail'] = record['mail'].lower()
320 attrs['sshPublicKey'] = self.get_ssh_pkey(record)
323 #Password is automatically generated because SFA user don't go
324 #through the Senslab website used to register new users,
325 #There is no place in SFA where users can enter such information
327 #If the user wants to set his own password , he must go to the Senslab
329 password = self.generate_password()
330 attrs['userPassword']= self.encrypt_password(password)
332 #Account automatically validated (no mail request to admins)
333 #Set to 0 to disable the account, -1 to enable it,
334 attrs['shadowExpire'] = '-1'
336 #Motivation field in Senslab
337 attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
339 attrs['ou'] = "SFA" #Optional: organizational unit
340 #No info about those here:
341 attrs['l'] = 'Grenoble - TBD'#Optional: Locality.
342 attrs['st'] = 'FRANCE - TBD' #Optional: state or province (country).
348 def LdapAddUser(self, record = None) :
349 """Add SFA user to LDAP if it is not in LDAP yet. """
351 user_ldap_attrs = self.make_ldap_attributes_from_record(record)
354 #Check if user already in LDAP wih email, first name and last name
355 filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
356 user_exist = self.LdapSearch(filter_by)
358 logger.warning(" \r\n \t LDAP LdapAddUser user %s %s already exists" \
359 %(user_ldap_attrs['sn'],user_ldap_attrs['mail']))
360 return {'bool': False}
363 result = self.conn.connect()
367 # A dict to help build the "body" of the object
369 logger.debug(" \r\n \t LDAP LdapAddUser attrs %s " %user_ldap_attrs)
371 # The dn of our new entry/object
372 dn = 'uid=' + user_ldap_attrs['uid'] + "," + self.baseDN
375 ldif = modlist.addModlist(user_ldap_attrs)
376 logger.debug("LDAPapi.py add attrs %s \r\n ldif %s"\
377 %(user_ldap_attrs,ldif) )
378 self.conn.ldapserv.add_s(dn,ldif)
380 logger.info("Adding user %s login %s in LDAP" \
381 %(user_ldap_attrs['cn'] ,user_ldap_attrs['uid']))
384 except ldap.LDAPError, e:
385 logger.log_exc("LDAP Add Error %s" %e)
386 return {'bool' : False, 'message' : e }
389 return {'bool': True}
394 def LdapDelete(self, person_dn):
396 Deletes a person in LDAP. Uses the dn of the user.
399 result = self.conn.connect()
402 self.conn.ldapserv.delete_s(person_dn)
404 return {'bool': True}
406 except ldap.LDAPError, e:
407 logger.log_exc("LDAP Delete Error %s" %e)
408 return {'bool': False}
411 def LdapDeleteUser(self, record_filter):
413 Deletes a SFA person in LDAP, based on the user's hrn.
415 #Find uid of the person
416 person = self.LdapFindUser(record_filter,[])
417 logger.debug("LDAPapi.py \t LdapDeleteUser record %s person %s" \
418 %(record_filter,person))
421 dn = 'uid=' + person['uid'] + "," +self.baseDN
423 return {'bool': False}
425 result = self.LdapDelete(dn)
429 def LdapModify(self, dn, old_attributes_dict, new_attributes_dict):
430 """ Modifies a LDAP entry """
432 ldif = modlist.modifyModlist(old_attributes_dict,new_attributes_dict)
433 # Connect and bind/authenticate
434 result = self.conn.connect()
437 self.conn.ldapserv.modify_s(dn,ldif)
439 return {'bool' : True }
440 except ldap.LDAPError, e:
441 logger.log_exc("LDAP LdapModify Error %s" %e)
442 return {'bool' : False }
445 def LdapModifyUser(self, user_uid_login, new_attributes_dict):
447 Gets the record from one user_uid_login based on record_filter
448 and changes the attributes according to the specified new_attributes.
449 Does not use this if we need to modify the uid. Use a ModRDN
450 #operation instead ( modify relative DN )
452 if user_uid_login is None:
453 logger.error("LDAP \t LdapModifyUser Need user_uid_login ")
454 return {'bool': False}
456 #Get all the attributes of the user_uid_login
457 #person = self.LdapFindUser(record_filter,[])
458 req_ldap = "(uid=" + user_uid_login + ')'
459 person_list = self.LdapSearch(req_ldap, [], bind = True)
460 logger.debug("LDAPapi.py \t LdapModifyUser person_list : %s" %(person_list))
461 if person_list and len(person_list) > 1 :
462 logger.error("LDAP \t LdapModifyUser Too many users returned")
463 return {'bool': False}
464 if person_list is None :
465 logger.error("LDAP \t LdapModifyUser User %s doesn't exist "\
467 return {'bool': False}
469 # The dn of our existing entry/object
470 #One result only from ldapSearch
471 person = person_list[0][1]
472 dn = 'uid=' + person['uid'][0] + "," +self.baseDN
473 if new_attributes_dict:
475 for k in new_attributes_dict:
477 logger.debug(" LDAPapi.py \t LdapModifyUser new_attributes %s"\
478 %( new_attributes_dict))
479 result = self.LdapModify(dn, old,new_attributes_dict)
482 logger.error("LDAP \t LdapModifyUser No new attributes given. ")
483 return {'bool': False}
486 def LdapResetPassword(self,record):
488 Resets password for the user whose record is the parameter and changes
489 the corresponding entry in the LDAP.
492 password = self.generate_password()
494 attrs['userPassword'] = self.encrypt_password(password)
495 logger.debug("LDAP LdapModifyUser Error %s" %e)
496 result = self.LdapModifyUser(record, attrs)
500 def LdapSearch (self, req_ldap = None, expected_fields = None, bind = False):
502 Used to search directly in LDAP, by using ldap filters and
504 When req_ldap is None, returns all the entries in the LDAP.
507 result = self.conn.connect(bind )
508 if (result['bool']) :
510 return_fields_list = []
511 if expected_fields == None :
512 return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
514 return_fields_list = expected_fields
515 #No specifc request specified, gert the whole LDAP
519 logger.debug("LDAP.PY \t LdapSearch req_ldap %s \
520 return_fields_list %s" %(req_ldap,return_fields_list))
523 msg_id = self.conn.ldapserv.search(
524 self.baseDN,ldap.SCOPE_SUBTREE,\
525 req_ldap,return_fields_list)
526 #Get all the results matching the search from ldap in one
528 result_type, result_data = \
529 self.conn.ldapserv.result(msg_id,1)
533 logger.debug("LDAP.PY \t LdapSearch result_data %s"\
538 except ldap.LDAPError,e :
539 logger.log_exc("LDAP LdapSearch Error %s" %e)
543 logger.error("LDAP.PY \t Connection Failed" )
547 def LdapFindUser(self,record = None, expected_fields = None):
549 Search a SFA user with a hrn. User should be already registered
551 Returns one matching entry
554 req_ldap = self.make_ldap_filters_from_record(record)
555 return_fields_list = []
556 if expected_fields == None :
557 return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
559 return_fields_list = expected_fields
561 result_data = self.LdapSearch(req_ldap, return_fields_list )
562 logger.debug("LDAP.PY \t LdapFindUser result_data %s" %(result_data))
564 if len(result_data) is 0:
566 #Asked for a specific user
569 ldapentry = result_data[0][1]
570 logger.debug("LDAP.PY \t LdapFindUser ldapentry %s" %(ldapentry))
571 tmpname = ldapentry['uid'][0]
573 tmpemail = ldapentry['mail'][0]
574 if ldapentry['mail'][0] == "unknown":
578 #logger.error("LDAP ldapFindHRn : no entry for record %s found"\
584 parent_hrn = get_authority(hrn)
585 peer_authority = None
586 if parent_hrn is not self.authname:
587 peer_authority = parent_hrn
591 'pkey': ldapentry['sshPublicKey'][0],
592 #'uid': ldapentry[1]['uid'][0],
595 #'email': ldapentry[1]['mail'][0],
596 'first_name': ldapentry['givenName'][0],
597 'last_name': ldapentry['sn'][0],
600 'authority': parent_hrn,
601 'peer_authority': peer_authority,
606 logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
610 #Asked for all users in ldap
612 for ldapentry in result_data:
613 logger.debug(" LDAP.py LdapFindUser ldapentry name : %s " \
614 %(ldapentry[1]['uid'][0]))
615 tmpname = ldapentry[1]['uid'][0]
616 hrn=self.authname+"."+ tmpname
618 tmpemail = ldapentry[1]['mail'][0]
619 if ldapentry[1]['mail'][0] == "unknown":
623 parent_hrn = get_authority(hrn)
624 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
628 'pkey': ldapentry[1]['sshPublicKey'][0],
629 #'uid': ldapentry[1]['uid'][0],
632 #'email': ldapentry[1]['mail'][0],
633 'first_name': ldapentry[1]['givenName'][0],
634 'last_name': ldapentry[1]['sn'][0],
637 'authority': self.authname,
638 'peer_authority': '',
643 logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" %(e))