3 from sfa.util.xrn import Xrn,get_authority
5 from sfa.util.config import Config
6 #from sfa.trust.gid import *
7 from sfa.trust.hierarchy import Hierarchy
8 #from sfa.trust.auth import *
9 from sfa.trust.certificate import *
10 import ldap.modlist as modlist
11 from sfa.util.sfalogging import logger
14 """ Set admin login and server configuration variables."""
17 self.login = 'cn=admin,dc=senslab,dc=info'
19 self.server_ip = "192.168.0.251"
22 def connect(self, bind = True):
23 """Enables connection to the LDAP server.
24 Set the bind parameter to True if a bind is needed
25 (for add/modify/delete operations).
26 Set to False otherwise.
30 self.ldapserv = ldap.open(self.server_ip)
31 except ldap.LDAPError, e:
32 return {'bool' : False, 'message' : e }
34 # Bind with authentification
43 """ Binding method. """
45 # Opens a connection after a call to ldap.open in connect:
46 self.ldapserv = ldap.initialize("ldap://" + self.server_ip )
48 # Bind/authenticate with a user with apropriate rights to add objects
49 self.ldapserv.simple_bind_s(self.login, self.passwd)
51 except ldap.LDAPError, e:
52 return {'bool' : False, 'message' : e }
57 """ Close the LDAP connection """
59 self.ldapserv.unbind_s()
60 except ldap.LDAPError, e:
61 return {'bool' : False, 'message' : e }
68 self.senslabauth=Hierarchy()
70 self.authname=config.SFA_REGISTRY_ROOT_AUTH
71 #authinfo=self.senslabauth.get_auth_info(self.authname)
75 #gid=authinfo.get_gid_object()
76 #self.ldapdictlist = ['type',
84 self.baseDN = "ou=people,dc=senslab,dc=info"
88 def generate_login(self, record):
89 """Generate login for adding a new user in LDAP Directory
90 (four characters minimum length)
91 Record contains first name and last name.
94 #Remove all special characters from first_name/last name
95 lower_first_name = record['first_name'].replace('-','')\
96 .replace('_','').replace('[','')\
97 .replace(']','').replace(' ','')\
99 lower_last_name = record['last_name'].replace('-','')\
100 .replace('_','').replace('[','')\
101 .replace(']','').replace(' ','')\
103 length_last_name = len(lower_last_name)
106 #Try generating a unique login based on first name and last name
108 if length_last_name >= login_max_length :
109 login = lower_last_name[0:login_max_length]
111 logger.debug("login : %s index : %s" %login %index);
112 elif length_last_name >= 4 :
113 login = lower_last_name
115 logger.debug("login : %s index : %s" %login %index);
116 elif length_last_name == 3 :
117 login = lower_first_name[0:1] + lower_last_name
119 logger.debug("login : %s index : %s" %login %index);
120 elif length_last_name == 2:
121 if len ( lower_first_name) >=2:
122 login = lower_first_name[0:2] + lower_last_name
124 logger.debug("login : %s index : %s" %login %index);
126 logger.error("LoginException : \
127 Generation login error with \
128 minimum four characters")
132 logger.error("LDAP generate_login failed : \
133 impossible to generate unique login for %s %s" \
134 %lower_first_name %lower_last_name)
136 filter = '(uid='+ login+ ')'
138 #Check if login already in use
139 while (self.ldapSearch(filter, getAttrs) is not [] ):
143 logger.error("LoginException : Generation login error \
144 with minimum four characters")
147 login = lower_first_name[0,index] + \
148 lower_last_name[0,login_max_length-index]
149 filter = '(uid='+ login+ ')'
151 print "lower_first_name - lower_last_name too short"
154 except ldap.LDAPError,e :
155 logger.log_exc("LDAP generate_login Error %s" %e)
156 #print >>sys.stderr, "ERROR LDAP %s" %(e)
159 def find_max_uidNumber(self):
161 """Find the LDAP max uidNumber (POSIX uid attribute) .
162 Used when adding a new user in LDAP Directory
163 returns integer max uidNumber + 1
166 #Get all the users in the LDAP
167 ldapUserUidNumberMin = 2000
169 getAttrs = "(uidNumber=*)"
170 filter = ['uidNumber']
172 result_data = self.ldapSearch(getAttrs, filter)
174 if result_data == []:
175 max_uidnumber = ldapUserUidNumberMin
176 #Get the highest uidNumber
178 uidNumberList = [r[1]['uidNumber'] for r in result_data ]
179 max_uidnumber = max(uidNumberList) + 1
184 def make_ldap_attributes_from_record(self, record):
187 attrs['objectClass'] = ["top", "person", "inetOrgPerson",\
188 "organizationalPerson", "posixAccount",\
189 "shadowAccount", "systemQuotas",\
192 attrs['givenName'] = str(record['first_name']).lower(),capitalize()
193 attrs['sn'] = str(record['last_name']).lower().capitalize()
194 attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
195 attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
196 attrs['uid'] = self.generate_login(record)
198 attrs['quota'] = '/dev/vdb:2000000:2500000:0:0'
199 attrs['homeDirectory'] = '/senslab/users/' + attrs['uid']
200 attrs['loginShell'] = '/senslab/users/.ssh/welcome.sh'
201 attrs['gidNumber'] = '2000'
202 attrs['uidNumber'] = str(self.find_max_uidNumber())
203 attrs['mail'] = record['mail'].lower()
204 attrs['sshPublicKey'] = record['sshpkey'] #To be filled by N. Turro
205 attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
207 attrs['userPassword']= ""
211 def ldapAdd(self, record = None) :
212 #SFA users are added from here
213 #They get a description attribute which others don't have.
216 result = self.conn.connect()
220 # A dict to help build the "body" of the object
221 attrs = self.make_ldap_attributes_from_record(record)
223 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapAdd attrs %s " %(attrs)
224 # The dn of our new entry/object
225 dn = 'uid=' +attrs['uid'] +","+self.baseDN
228 ldif = modlist.addModlist(attrs)
229 print " \r\n \r\n LDAPapi.PY add attrs %s \r\n ldif %s " %(attrs,ldif)
230 self.conn.ldapserv.add_s(dn,ldif)
231 logger.info("Adding user %s login %s in LDAP" \
232 %attrs['cn'], %attrs['uid'] )
233 except ldap.LDAPError, e:
234 logger.log_exc("LDAP Add Error %s" %e)
235 return {'bool' : False, 'message' : e }
238 return {'bool': True}
244 def ldapDelete(self, record_filter):
245 #Find uid of the person
246 person = self.ldapFindHrn(record_filter)
249 dn = 'uid=' + person['uid'] + "," +self.baseDN
251 return {'bool': False}
254 result = self.conn.connect()
257 self.conn.ldapserv.delete_s(dn)
258 return {'bool': True}
260 except ldap.LDAPError, e:
261 logger.log_exc("LDAP Delete Error %s" %e)
262 print>>sys.stderr, "\r\n LDAP.PY \tldapDelete error : %s" %(e)
263 return {'bool': False}
266 def ldapModify(self, record_filter, new_attributes):
268 Gets the record from one user based on record_filter
269 and changes the attributes according to the specified new_attributes.
270 Does not use this if we need to modify the uid. Use a ModRDN
271 #operation instead ( modify relative DN )
274 person = self.ldapFindHrn(record_filter,[] )
276 # The dn of our existing entry/object
277 dn = 'uid=' + person['uid'] + "," +self.baseDN
283 for k in new_attributes:
286 ldif = modlist.modifyModlist(old,new_attributes)
288 # Connect and bind/authenticate
289 result = self.conn.connect(bind)
292 self.conn.ldapserver.modify_s(dn,ldif)
294 except ldap.LDAPError, e:
295 return {'bool' : False, 'message' : e }
296 return {'bool': True}
300 #TODO Handle OR filtering in the ldap query when
301 #dealing with a list of records instead of doing a for loop in GetPersons
302 def make_ldap_filters_from_record(self, record=None):
306 if 'first_name' in record and 'last_name' in record:
307 req_ldapdict['cn'] = str(record['first_name'])+" "+str(record['last_name'])
308 if 'email' in record :
309 req_ldapdict['mail'] = record['email']
311 splited_hrn = record['hrn'].split(".")
312 if splited_hrn[0] != self.authname :
313 print >>sys.stderr,"i know nothing about",record['hrn'], " my authname is ", self.authname, " not ", splited_hrn[0]
315 req_ldapdict['uid'] = login
318 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t make_ldap_filters_from_record record %s req_ldapdict %s" %(record,req_ldapdict)
319 for k in req_ldapdict:
320 req_ldap += '('+str(k)+'='+str(req_ldapdict[k])+')'
321 if len(req_ldapdict.keys()) >1 :
322 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
324 req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
332 #Returns one matching entry
333 def ldapSearch (self, req_ldap = None, return_fields = None ):
335 self.conn.connect(bind = False)
336 req_ldap = self.make_ldap_filters_from_record(record)
338 if expected_fields == None :
339 return_fields = ['mail','givenName', 'sn', 'uid','sshPublicKey']
341 return_fields = expected_fields
342 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch req_ldap %s return_fields %s " %(req_ldap,return_fields)
345 msg_id = self.conn.ldapserv.search(
346 self.baseDN,ldap.SCOPE_SUBTREE,\
347 req_ldap,return_fields)
348 #Get all the results matching the search from ldap in one shot (1 value)
349 result_type, result_data = self.conn.ldapserv.result(msg_id,1)
351 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch result_data %s" %(result_data)
354 #if result_data is None:
356 ##Asked for a specific user
358 #ldapentry = result_data[0][1]
359 #print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch ldapentry %s" %(ldapentry)
360 #tmpname = ldapentry['uid'][0]
362 #tmpemail = ldapentry['mail'][0]
363 #if ldapentry['mail'][0] == "unknown":
368 #parent_hrn = get_authority(hrn)
369 #peer_authority = None
370 #if parent_hrn is not self.authname:
371 #peer_authority = parent_hrn
377 #'pkey': ldapentry['sshPublicKey'][0],
378 ##'uid': ldapentry[1]['uid'][0],
381 ##'email': ldapentry[1]['mail'][0],
382 #'first_name': ldapentry['givenName'][0],
383 #'last_name': ldapentry['sn'][0],
386 #'authority': parent_hrn,
387 #'peer_authority': peer_authority,
392 #print >>sys.stderr, "\r\n \r\n LDAPapi \t ldapSearch KEyError results %s" %(results)
395 ##Asked for all users in ldap
397 #for ldapentry in result_data:
398 #print>>sys.stderr,"\r\n\t\t LDAP.py ldapentry name : %s " %(ldapentry[1]['uid'][0])
399 #tmpname = ldapentry[1]['uid'][0]
400 #hrn=self.authname+"."+ tmpname
402 #tmpemail = ldapentry[1]['mail'][0]
403 #if ldapentry[1]['mail'][0] == "unknown":
407 #parent_hrn = get_authority(hrn)
408 #parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
412 #'pkey': ldapentry[1]['sshPublicKey'][0],
413 ##'uid': ldapentry[1]['uid'][0],
416 ##'email': ldapentry[1]['mail'][0],
417 #'first_name': ldapentry[1]['givenName'][0],
418 #'last_name': ldapentry[1]['sn'][0],
421 #'authority': self.authname,
422 #'peer_authority': '',
431 except ldap.LDAPError,e :
432 print >>sys.stderr, "ERROR LDAP %s" %(e)
436 def ldapFindHrn(self,record = None, expected_fields = None):
437 self.conn.connect(bind = False)
438 req_ldap = self.make_ldap_filters_from_record(record)
440 if expected_fields == None :
441 return_fields = ['mail','givenName', 'sn', 'uid','sshPublicKey']
443 return_fields = expected_fields
445 result_data = self.ldapSearch(req_ldap, return_fields )
447 if result_data is None:
449 #Asked for a specific user
451 ldapentry = result_data[0][1]
452 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch ldapentry %s" %(ldapentry)
453 tmpname = ldapentry['uid'][0]
455 tmpemail = ldapentry['mail'][0]
456 if ldapentry['mail'][0] == "unknown":
461 parent_hrn = get_authority(hrn)
462 peer_authority = None
463 if parent_hrn is not self.authname:
464 peer_authority = parent_hrn
470 'pkey': ldapentry['sshPublicKey'][0],
471 #'uid': ldapentry[1]['uid'][0],
474 #'email': ldapentry[1]['mail'][0],
475 'first_name': ldapentry['givenName'][0],
476 'last_name': ldapentry['sn'][0],
479 'authority': parent_hrn,
480 'peer_authority': peer_authority,
485 print >>sys.stderr, "\r\n \r\n LDAPapi \t ldapSearch KEyError results %s" %(results)
488 #Asked for all users in ldap
490 for ldapentry in result_data:
491 print>>sys.stderr,"\r\n\t\t LDAP.py ldapentry name : %s " %(ldapentry[1]['uid'][0])
492 tmpname = ldapentry[1]['uid'][0]
493 hrn=self.authname+"."+ tmpname
495 tmpemail = ldapentry[1]['mail'][0]
496 if ldapentry[1]['mail'][0] == "unknown":
500 parent_hrn = get_authority(hrn)
501 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
505 'pkey': ldapentry[1]['sshPublicKey'][0],
506 #'uid': ldapentry[1]['uid'][0],
509 #'email': ldapentry[1]['mail'][0],
510 'first_name': ldapentry[1]['givenName'][0],
511 'last_name': ldapentry[1]['sn'][0],
514 'authority': self.authname,
515 'peer_authority': '',
523 #def ldapFindHrn(self, record_filter = None):
524 ##def ldapFindHrn(self, record_filter = None, columns=None):
527 #self.conn.connect(bind = False)
529 #if 'authority' in record_filter:
531 #if record_filter['authority']==self.authname:
532 ## which is SFA_REGISTRY_ROOT_AUTH
533 ## request all records which are under our authority, ie all ldap entries
536 ##which is NOT SFA_REGISTRY_ROOT_AUTH
539 #if not 'hrn' in record_filter:
540 #print >>sys.stderr,"find : don't know how to handle filter ",record_filter
544 #h=record_filter['hrn']
545 #if isinstance(h,list):
552 #splited_hrn=hrn.split(".")
553 #if splited_hrn[0] != self.authname :
554 #print >>sys.stderr,"i know nothing about",hrn, " my authname is ", self.authname, " not ", splited_hrn[0]
556 #login=splited_hrn[1]
562 #rindex=self.conn.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,ldapfilter, ['mail','givenName', 'sn', 'uid','sshPublicKey'])
563 ##rindex=self.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,ldapfilter, ['mail','givenName', 'sn', 'uid','sshPublicKey'])
564 #ldapresponse=self.conn.ldapserv.result(rindex,1)
565 #for ldapentry in ldapresponse[1]:
567 #tmpname = ldapentry[1]['uid'][0]
569 #if ldapentry[1]['uid'][0] == "savakian":
572 #hrn=self.authname+"."+ tmpname
574 #tmpemail = ldapentry[1]['mail'][0]
575 #if ldapentry[1]['mail'][0] == "unknown":
577 ## uuid=create_uuid()
579 ## RSA_KEY_STRING=ldapentry[1]['sshPublicKey'][0]
581 ## pkey=convert_public_key(RSA_KEY_STRING)
583 ## gid=self.senslabauth.create_gid("urn:publicid:IDN+"+self.authname+"+user+"+ldapentry[1]['uid'][0], uuid, pkey, CA=False)
585 #parent_hrn = get_authority(hrn)
586 #parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
590 #'pkey': ldapentry[1]['sshPublicKey'][0],
591 ##'uid': ldapentry[1]['uid'][0],
594 ##'email': ldapentry[1]['mail'][0],
595 #'first_name': ldapentry[1]['givenName'][0],
596 #'last_name': ldapentry[1]['sn'][0],
599 #'authority': self.authname,
600 #'peer_authority': '',