3 from sfa.util.xrn import Xrn,get_authority
5 from sfa.util.config import *
6 from sfa.trust.gid import *
7 from sfa.trust.hierarchy import *
8 from sfa.trust.auth import *
9 from sfa.trust.certificate import *
10 import ldap.modlist as modlist
14 #def __init__(self, param, level):
16 Constructeur permettant l'initialisation des attributs de la classe
17 :param param: Parametres de connexion au serveur LDAP
18 :type param: dictionnary.
19 :param level: Niveau de criticite de l'execution de l'objet ('critical, warning')
23 self.__level = 'warning'
26 self.login = 'cn=admin,dc=senslab,dc=info'
29 print "\r\n INIT OK !"
31 def connect(self, bind = True):
33 Methode permettant la connexion a un serveur LDAP
34 @param bool bind : Force ou non l'authentification au serveur
35 @return array : Retour d'un tableau
38 self.ldapserv = ldap.open("192.168.0.251")
39 except ldap.LDAPError, e:
40 return {'bool' : False, 'message' : e }
42 # Bind non anonyme avec authentification
52 Methode permettant l'authentification a un serveur LDAP
53 @return array : Retour d'un tableau
58 self.ldapserv = ldap.initialize("ldap://192.168.0.251")
59 # Bind/authenticate with a user with apropriate rights to add objects
60 self.ldapserv.simple_bind_s(self.login, self.passwd)
62 except ldap.LDAPError, e:
63 return {'bool' : False, 'message' : e }
65 print "\r\n BIND OK !"
70 Methode permettant la deconnexion a un serveur LDAP
72 # Fermeture de la connexion
74 self.ldapserv.unbind_s()
75 except ldap.LDAPError, e:
81 self.senslabauth=Hierarchy()
83 self.authname=config.SFA_REGISTRY_ROOT_AUTH
84 authinfo=self.senslabauth.get_auth_info(self.authname)
88 gid=authinfo.get_gid_object()
89 self.ldapdictlist = ['type',
97 self.baseDN = "ou=people,dc=senslab,dc=info"
102 def ldapAdd(self, record = None) :
103 #SFA users are added from here
104 #They get a uidNumber range 9000 - 9999 (recerved for SFA)
105 #They get a description attribute which others don't have.
106 result = self.conn.connect(bind = False)
108 #Find all the external SFA users in the LDAP
109 msg_id = self.conn.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,"(description=*)",[])
110 result_type, result_data = self.conn.ldapserv.result(msg_id,1)
111 #First external SFA user
112 if result_data == []:
114 #Get the highest uidNumber
117 for r in result_data:
118 if r[1]['uidNumber'] > max_uidnumber :
119 max_uidnumber = r[1]['uidNumber']
120 max_uidnumber = max_uidnumber +1
122 result = self.conn.connect()
125 # A dict to help build the "body" of the object
127 attrs['uidNumber'] = str(max_uidnumber)
128 attrs['objectClass'] = [ 'organizationalPerson', 'inetOrgPerson', 'posixAccount', 'top', 'ldapPublicKey', 'systemQuotas']
129 #['top','inetOrgPerson','posixAccount', 'systemQuotas','ldapPuclicKey']
130 attrs['cn'] = str(record['first_name'])+' ' + str(record['last_name'])
131 attrs['sn'] = str(record['last_name'])
132 attrs['givenName'] = str(record['first_name'])
133 attrs['gidNumber'] = '2000'
134 loginslab =str(record['first_name'])+ str(record['last_name'])
135 loginslab= loginslab.lower()
136 #loginslab = loginslab[0:12]
137 attrs['uid']= loginslab
138 attrs['mail'] = record['mail']
139 attrs['quota'] = '/dev/sda3:2000000:2500000:0:0'
140 attrs['homeDirectory'] = '/senslab/users/' + loginslab
141 attrs['loginShell'] = '/senslab/users/.ssh/welcome.sh'
142 #To be filled by Nicolas Turro
143 attrs['sshPublicKey'] = record['sshpkey']
144 attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
145 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapAdd attrs %s " %(attrs)
146 # The dn of our new entry/object
147 dn = 'uid=' +attrs['uid'] +","+self.baseDN
150 ldif = modlist.addModlist(attrs)
151 print " \r\n \r\n LDAPapi.PY add attrs %s \r\n ldif %s " %(attrs,ldif)
152 self.conn.ldapserv.add_s(dn,ldif)
154 except ldap.LDAPError, e:
155 return {'bool' : False, 'message' : e }
158 return {'bool': True}
164 def ldapDelete(self, record_filter):
165 #Find uid of the person
166 person = self.ldapSearch(record_filter)
169 dn = 'uid=' +person['uid'] +","+self.baseDN
171 return {'bool': False}
174 result = self.conn.connect()
177 self.conn.ldapserv.delete_s(dn)
178 return {'bool': True}
180 except ldap.LDAPError, e:
181 print>>sys.stderr, "\r\n LDAP.PY \tldapDelete error : %s" %(e)
182 return {'bool': False}
185 def ldapModify(self, record_filter, new_attributes):
187 Gets the record from one user based on record_filter
188 and changes the attributes according to the specified new_attributes.
189 Does not use this if we need to modify the uid. Use a ModRDMN
190 #operation instead ( modify relative DN )
193 person = self.ldapSearch(record_filter,[] )
195 # The dn of our existing entry/object
196 dn = 'uid=' +person['uid'] +","+self.baseDN
202 for k in new_attributes:
205 ldif = modlist.modifyModlist(old,new_attributes)
207 # Connect and bind/authenticate
208 result = self.conn.connect(bind)
211 self.conn.ldapserver.modify_s(dn,ldif)
213 except ldap.LDAPError, e:
214 return {'bool' : False, 'message' : e }
215 return {'bool': True}
219 #TODO Handle OR filtering in the ldap query when
220 #dealing with a list of records instead of doing a for loop in GetPersons
221 def make_ldap_filters_from_record(self, record=None):
225 if 'first_name' in record and 'last_name' in record:
226 req_ldapdict['cn'] = str(record['first_name'])+" "+str(record['last_name'])
227 if 'email' in record :
228 req_ldapdict['mail'] = record['email']
230 splited_hrn = record['hrn'].split(".")
231 if splited_hrn[0] != self.authname :
232 print >>sys.stderr,"i know nothing about",record['hrn'], " my authname is ", self.authname, " not ", splited_hrn[0]
234 req_ldapdict['uid'] = login
237 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)
238 for k in req_ldapdict:
239 req_ldap += '('+str(k)+'='+str(req_ldapdict[k])+')'
240 if len(req_ldapdict.keys()) >1 :
241 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
243 req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
251 #Returns one matching entry
252 def ldapSearch (self, record = None, expected_fields = None ):
254 self.conn.connect(bind = False)
256 req_ldap = self.make_ldap_filters_from_record(record)
258 if expected_fields == None :
259 return_fields = ['mail','givenName', 'sn', 'uid','sshPublicKey']
261 return_fields = expected_fields
262 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch req_ldap %s return_fields %s " %(req_ldap,return_fields)
265 msg_id=self.conn.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,req_ldap,return_fields)
266 #Get all the results matching the search from ldap in one shot (1 value)
267 result_type, result_data = self.conn.ldapserv.result(msg_id,1)
269 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch result_data %s" %(result_data)
271 if result_data is None:
273 #Asked for a specific user
275 ldapentry = result_data[0][1]
276 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch ldapentry %s" %(ldapentry)
277 tmpname = ldapentry['uid'][0]
279 tmpemail = ldapentry['mail'][0]
280 if ldapentry['mail'][0] == "unknown":
285 parent_hrn = get_authority(hrn)
286 peer_authority = None
287 if parent_hrn is not self.authname:
288 peer_authority = parent_hrn
294 'pkey': ldapentry['sshPublicKey'][0],
295 #'uid': ldapentry[1]['uid'][0],
298 #'email': ldapentry[1]['mail'][0],
299 'first_name': ldapentry['givenName'][0],
300 'last_name': ldapentry['sn'][0],
303 'authority': parent_hrn,
304 'peer_authority': peer_authority,
309 print >>sys.stderr, "\r\n \r\n LDAPapi \t ldapSearch KEyError results %s" %(results)
312 #Asked for all users in ldap
314 for ldapentry in result_data:
315 print>>sys.stderr,"\r\n\t\t LDAP.py ldapentry name : %s " %(ldapentry[1]['uid'][0])
316 tmpname = ldapentry[1]['uid'][0]
317 hrn=self.authname+"."+ tmpname
319 tmpemail = ldapentry[1]['mail'][0]
320 if ldapentry[1]['mail'][0] == "unknown":
324 parent_hrn = get_authority(hrn)
325 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
329 'pkey': ldapentry[1]['sshPublicKey'][0],
330 #'uid': ldapentry[1]['uid'][0],
333 #'email': ldapentry[1]['mail'][0],
334 'first_name': ldapentry[1]['givenName'][0],
335 'last_name': ldapentry[1]['sn'][0],
338 'authority': self.authname,
339 'peer_authority': '',
348 except ldap.LDAPError,e :
349 print >>sys.stderr, "ERROR LDAP %s" %(e)
354 #def ldapFindHrn(self, record_filter = None):
355 ##def ldapFindHrn(self, record_filter = None, columns=None):
358 #self.conn.connect(bind = False)
360 #if 'authority' in record_filter:
362 #if record_filter['authority']==self.authname:
363 ## which is SFA_REGISTRY_ROOT_AUTH
364 ## request all records which are under our authority, ie all ldap entries
367 ##which is NOT SFA_REGISTRY_ROOT_AUTH
370 #if not 'hrn' in record_filter:
371 #print >>sys.stderr,"find : don't know how to handle filter ",record_filter
375 #h=record_filter['hrn']
376 #if isinstance(h,list):
383 #splited_hrn=hrn.split(".")
384 #if splited_hrn[0] != self.authname :
385 #print >>sys.stderr,"i know nothing about",hrn, " my authname is ", self.authname, " not ", splited_hrn[0]
387 #login=splited_hrn[1]
393 #rindex=self.conn.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,ldapfilter, ['mail','givenName', 'sn', 'uid','sshPublicKey'])
394 ##rindex=self.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,ldapfilter, ['mail','givenName', 'sn', 'uid','sshPublicKey'])
395 #ldapresponse=self.conn.ldapserv.result(rindex,1)
396 #for ldapentry in ldapresponse[1]:
398 #tmpname = ldapentry[1]['uid'][0]
400 #if ldapentry[1]['uid'][0] == "savakian":
403 #hrn=self.authname+"."+ tmpname
405 #tmpemail = ldapentry[1]['mail'][0]
406 #if ldapentry[1]['mail'][0] == "unknown":
408 ## uuid=create_uuid()
410 ## RSA_KEY_STRING=ldapentry[1]['sshPublicKey'][0]
412 ## pkey=convert_public_key(RSA_KEY_STRING)
414 ## gid=self.senslabauth.create_gid("urn:publicid:IDN+"+self.authname+"+user+"+ldapentry[1]['uid'][0], uuid, pkey, CA=False)
416 #parent_hrn = get_authority(hrn)
417 #parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
421 #'pkey': ldapentry[1]['sshPublicKey'][0],
422 ##'uid': ldapentry[1]['uid'][0],
425 ##'email': ldapentry[1]['mail'][0],
426 #'first_name': ldapentry[1]['givenName'][0],
427 #'last_name': ldapentry[1]['sn'][0],
430 #'authority': self.authname,
431 #'peer_authority': '',