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 = "192.168.0.251"
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.ldapUserDN = 'uid=web,ou=Service,dc=senslab,dc=info';
37 self.ldapUserPassword = '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.login, self.passwd)
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()
87 self.authname=config.SFA_REGISTRY_ROOT_AUTH
88 self.baseDN = "ou=people,dc=senslab,dc=info"
90 #authinfo=self.senslabauth.get_auth_info(self.authname)
93 self.charsPassword = [ '!','$','(',')','*','+',',','-','.',\
94 '0','1','2','3','4','5','6','7','8','9',\
95 'A','B','C','D','E','F','G','H','I','J',\
96 'K','L','M','N','O','P','Q','R','S','T',\
97 'U','V','W','X','Y','Z','_','a','b','c',\
98 'd','e','f','g','h','i','j','k','l','m',\
99 'n','o','p','q','r','s','t','u','v','w',\
101 self.ldapUserQuotaNFS = '/dev/vdb:2000000:2500000:0:0'
102 self.lengthPassword = 8;
103 self.ldapUserHomePath = '/senslab/users/'
104 self.ldapUserGidNumber = '2000'
105 self.ldapUserUidNumberMin = '2000'
106 self.ldapShell = '/bin/bash'
108 #gid=authinfo.get_gid_object()
109 #self.ldapdictlist = ['type',
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 filter = '(uid='+ login+ ')'
170 #Check if login already in use
171 while (self.LdapSearch(filter, getAttrs) is not [] ):
175 logger.error("LoginException : Generation login error \
176 with minimum four characters")
179 login = lower_first_name[0,index] + \
180 lower_last_name[0,login_max_length-index]
181 filter = '(uid='+ login+ ')'
183 print "lower_first_name - lower_last_name too short"
186 except ldap.LDAPError,e :
187 logger.log_exc("LDAP generate_login Error %s" %e)
191 def generate_password(self):
193 """Generate password for adding a new user in LDAP Directory
194 (8 characters length) return password
198 for index in range(self.lengthPassword):
199 password += self.charsPassword[random.randint(0, \
200 len(self.charsPassword))]
204 def encrypt_password(self, password):
205 """ Use passlib library to make a RFC2307 LDAP encrypted password
206 salt size = 8, use sha-1 algorithm. Returns encrypted password.
209 #Keep consistency with Java Senslab's LDAP API
210 #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
211 return lssha.encrypt(password,salt_size = 8)
215 def find_max_uidNumber(self):
217 """Find the LDAP max uidNumber (POSIX uid attribute) .
218 Used when adding a new user in LDAP Directory
219 returns string max uidNumber + 1
222 #First, get all the users in the LDAP
223 getAttrs = "(uidNumber=*)"
224 filter = ['uidNumber']
226 result_data = self.LdapSearch(getAttrs, filter)
227 #It there is no user in LDAP yet, First LDAP user
228 if result_data == []:
229 max_uidnumber = self.ldapUserUidNumberMin
230 #Otherwise, get the highest uidNumber
232 uidNumberList = [r[1]['uidNumber'] for r in result_data ]
233 max_uidnumber = max(uidNumberList) + 1
235 return str(max_uidnumber)
237 #TODO ; Get ssh public key from sfa record
238 #To be filled by N. Turro
239 def get_ssh_pkey(self, record):
243 #TODO Handle OR filtering in the ldap query when
244 #dealing with a list of records instead of doing a for loop in GetPersons
245 def make_ldap_filters_from_record(self, record=None):
247 Helper function to make LDAP filter requests out of SFA records.
251 if 'first_name' in record and 'last_name' in record:
252 req_ldapdict['cn'] = str(record['first_name'])+" "\
253 + str(record['last_name'])
254 if 'email' in record :
255 req_ldapdict['mail'] = record['email']
257 req_ldapdict['mail'] = record['mail']
260 splited_hrn = record['hrn'].split(".")
261 if splited_hrn[0] != self.authname :
262 logger.warning(" \r\n LDAP.PY \
263 make_ldap_filters_from_record I know nothing \
264 about %s my authname is %s not %s" \
265 %(record['hrn'], self.authname, splited_hrn[0]) )
268 req_ldapdict['uid'] = login
271 logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
272 record %s req_ldapdict %s" \
273 %(record, req_ldapdict))
275 for k in req_ldapdict:
276 req_ldap += '('+str(k)+'='+str(req_ldapdict[k])+')'
277 if len(req_ldapdict.keys()) >1 :
278 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
280 req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
286 def make_ldap_attributes_from_record(self, record):
287 """When addind a new user to Senslab's LDAP, creates an attributes
288 dictionnary from the SFA record.
293 attrs['objectClass'] = ["top", "person", "inetOrgPerson",\
294 "organizationalPerson", "posixAccount",\
295 "shadowAccount", "systemQuotas",\
298 attrs['givenName'] = str(record['first_name']).lower(),capitalize()
299 attrs['sn'] = str(record['last_name']).lower().capitalize()
300 attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
301 attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
302 attrs['uid'] = self.generate_login(record)
304 attrs['quota'] = self.ldapUserQuotaNFS
305 attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
306 attrs['loginShell'] = self.ldapShell
307 attrs['gidNumber'] = '2000'
308 attrs['uidNumber'] = self.find_max_uidNumber()
309 attrs['mail'] = record['mail'].lower()
311 attrs['sshPublicKey'] = self.get_ssh_pkey(record)
314 #Password is automatically generated because SFA user don't go
315 #through the Senslab website used to register new users,
316 #There is no place in SFA where users can enter such information
318 #If the user wants to set his own password , he must go to the Senslab
320 password = self.generate_password()
321 attrs['userPassword']= self.encrypt_password(password)
323 #Account automatically validated (no mail request to admins)
324 #Set to 0 to disable the account, -1 to enable it,
325 attrs['shadowExpire'] = '-1'
327 #Motivation field in Senslab
328 attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
330 attrs['ou'] = "SFA" #Optional: organizational unit
331 #No info about those here:
332 attrs['l'] = '' #Optional: Locality.
333 attrs['st'] = '' #Optional: state or province (country).
339 def LdapAddUser(self, record = None) :
340 """Add SFA user to LDAP if it is not in LDAP yet. """
342 user_ldap_attrs = self.make_ldap_attributes_from_record(record)
345 #Check if user already in LDAP wih email, first name and last name
346 filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
347 user_exist = self.LdapSearch(filter_by)
349 logger.warning(" \r\n \t LDAP LdapAddUser user %s %s already exists" \
350 %(user_ldap_attrs['sn'],user_ldap_attrs['mail']))
351 return {'bool': False}
354 result = self.conn.connect()
358 # A dict to help build the "body" of the object
360 logger.debug(" \r\n \t LDAP LdapAddUser attrs %s " %user_ldap_attrs)
362 # The dn of our new entry/object
363 dn = 'uid=' + user_ldap_attrs['uid'] + "," + self.baseDN
366 ldif = modlist.addModlist(user_ldap_attrs)
367 logger.debug("\r\n \tLDAPapi.PY add attrs %s \r\n ldif %s"\
368 %(user_ldap_attrs,ldif) )
369 self.conn.ldapserv.add_s(dn,ldif)
371 logger.info("Adding user %s login %s in LDAP" \
372 %user_ldap_attrs['cn'] %user_ldap_attrs['uid'])
375 except ldap.LDAPError, e:
376 logger.log_exc("LDAP Add Error %s" %e)
377 return {'bool' : False, 'message' : e }
380 return {'bool': True}
385 def LdapDelete(self, person_dn):
387 Deletes a person in LDAP. Uses the dn of the user.
390 result = self.conn.connect()
393 self.conn.ldapserv.delete_s(person_dn)
395 return {'bool': True}
397 except ldap.LDAPError, e:
398 logger.log_exc("LDAP Delete Error %s" %e)
399 return {'bool': False}
402 def LdapDeleteUser(self, record_filter):
404 Deletes a SFA person in LDAP, based on the user's hrn.
406 #Find uid of the person
407 person = self.LdapFindUser(record_filter)
410 dn = 'uid=' + person['uid'] + "," +self.baseDN
412 return {'bool': False}
414 result = self.LdapDelete(dn)
418 def LdapModify(self, dn, old_attributes_dict, new_attributes_dict):
419 """ Modifies a LDAP entry """
421 ldif = modlist.modifyModlist(old_attributes_dict,new_attributes)
422 # Connect and bind/authenticate
423 result = self.conn.connect(bind)
426 self.conn.ldapserver.modify_s(dn,ldif)
428 return {'bool' : True }
429 except ldap.LDAPError, e:
430 logger.log_exc("LDAP LdapModify Error %s" %e)
431 return {'bool' : False }
434 def LdapModifyUser(self, record_filter, new_attributes):
436 Gets the record from one user based on record_filter
437 and changes the attributes according to the specified new_attributes.
438 Does not use this if we need to modify the uid. Use a ModRDN
439 #operation instead ( modify relative DN )
441 if record_filter is None:
442 logger.error("LDAP \t LdapModifyUser Need record filter ")
443 return {'bool': False}
445 #Get all the attributes of the user
446 person = self.LdapFindUser(record_filter,[])
447 if person and len(person) > 1 :
448 logger.error("LDAP \t LdapModifyUser Too many users returned")
449 return {'bool': False}
451 logger.error("LDAP \t LdapModifyUser User %s doesn't exist "\
452 %(record_filter['hrn']))
453 return {'bool': False}
455 # The dn of our existing entry/object
456 dn = 'uid=' + person['uid'] + "," +self.baseDN
457 if new_attributes_dict:
459 for k in new_attributes:
462 result = self.LdapModify(dn, old,new_attributes)
465 logger.error("LDAP \t LdapModifyUser No new attributes given. ")
466 return {'bool': False}
469 def LdapResetPassword(self,record):
471 Resets password for the user whose record is the parameter and changes
472 the corresponding entry in the LDAP.
475 password = self.generate_password()
477 attrs['userPassword'] = self.encrypt_password(password)
478 logger.debug("LDAP LdapModifyUser Error %s" %e)
479 result = self.LdapModifyUser(record, attrs)
483 def LdapSearch (self, req_ldap = None, expected_fields = None ):
485 Used to search directly in LDAP, by using ldap filters and
487 When req_ldap is None, returns all the entries in the LDAP.
490 result = self.conn.connect(bind = False)
491 if (result['bool']) :
493 return_fields_list = []
494 if expected_fields == None :
495 return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
497 return_fields_list = expected_fields
499 logger.debug("LDAP.PY \t LdapSearch req_ldap %s \
500 return_fields_list %s" %(req_ldap,return_fields_list))
503 msg_id = self.conn.ldapserv.search(
504 self.baseDN,ldap.SCOPE_SUBTREE,\
505 req_ldap,return_fields_list)
506 #Get all the results matching the search from ldap in one
508 result_type, result_data = \
509 self.conn.ldapserv.result(msg_id,1)
513 logger.debug("LDAP.PY \t LdapSearch result_data %s"\
518 except ldap.LDAPError,e :
519 logger.log_exc("LDAP LdapSearch Error %s" %e)
523 logger.error("LDAP.PY \t Connection Failed" )
527 def LdapFindUser(self,record = None, expected_fields = None):
529 Search a SFA user with a hrn. User should be already registered
531 Returns one matching entry
534 req_ldap = self.make_ldap_filters_from_record(record)
535 return_fields_list = []
536 if expected_fields == None :
537 return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
539 return_fields_list = expected_fields
541 result_data = self.LdapSearch(req_ldap, return_fields_list )
542 logger.debug("LDAP.PY \t LdapFindUser result_data %s" %(result_data))
544 if len(result_data) is 0:
546 #Asked for a specific user
549 ldapentry = result_data[0][1]
550 logger.debug("LDAP.PY \t LdapFindUser ldapentry %s" %(ldapentry))
551 tmpname = ldapentry['uid'][0]
553 tmpemail = ldapentry['mail'][0]
554 if ldapentry['mail'][0] == "unknown":
558 #logger.error("LDAP ldapFindHRn : no entry for record %s found"\
564 parent_hrn = get_authority(hrn)
565 peer_authority = None
566 if parent_hrn is not self.authname:
567 peer_authority = parent_hrn
571 'pkey': ldapentry['sshPublicKey'][0],
572 #'uid': ldapentry[1]['uid'][0],
575 #'email': ldapentry[1]['mail'][0],
576 'first_name': ldapentry['givenName'][0],
577 'last_name': ldapentry['sn'][0],
580 'authority': parent_hrn,
581 'peer_authority': peer_authority,
586 lorrer.log_exc("LDAPapi \t LdapSearch KEyError results %s" \
590 #Asked for all users in ldap
592 for ldapentry in result_data:
593 logger.debug(" LDAP.py LdapFindUser ldapentry name : %s " \
594 %(ldapentry[1]['uid'][0]))
595 tmpname = ldapentry[1]['uid'][0]
596 hrn=self.authname+"."+ tmpname
598 tmpemail = ldapentry[1]['mail'][0]
599 if ldapentry[1]['mail'][0] == "unknown":
603 parent_hrn = get_authority(hrn)
604 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
608 'pkey': ldapentry[1]['sshPublicKey'][0],
609 #'uid': ldapentry[1]['uid'][0],
612 #'email': ldapentry[1]['mail'][0],
613 'first_name': ldapentry[1]['givenName'][0],
614 'last_name': ldapentry[1]['sn'][0],
617 'authority': self.authname,
618 'peer_authority': '',