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, recordix = 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 msgid = self.conn.ldapserv.search(ldap.baseDN,D.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()
124 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapAdd attrs %s " %(attrs)
125 # A dict to help build the "body" of the object
127 attrs['uidNumber'] = str(max_uidnumber)
128 attrs['objectclass'] = ['top','inetOrgPerson','posixAccount', 'systemQuotas','ldapPuclicKey']
129 attrs['cn'] = str(record['first_name'])+' ' + str(record['last_name'])
130 attrs['sn'] = str(record['last_name'])
131 attrs['givenName'] = str(record['first_name'])
132 attrs['gidNumber'] = '2000'
133 loginslab =str(record['first_name'])+ str(record['last_name'])
134 loginslab= loginslab.lower()
135 #loginslab = loginslab[0:12]
136 attrs['uid']= loginslab
137 attrs['mail'] = record['mail']
138 attrs['quota'] = '/dev/sda3:2000000:2500000:0:0'
139 attrs['homeDirectory'] = '/senslab/users/' + loginslab
140 attrs['loginShell'] = '/senslab/users/.ssh/welcome.sh'
141 attrs['sshPublicKey'] = ''
142 attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
144 # The dn of our new entry/object
145 dn = 'uid=' +attrs['uid'] +","+self.baseDN
148 ldif = modlist.addModlist(attrs)
149 print " \r\n \r\n LDAPTEST.PY add attrs %s \r\n ldif %s " %(attrs,ldif)
150 self.conn.ldapserv.add_s(dn,ldif)
152 except ldap.LDAPError, e:
153 return {'bool' : False, 'message' : e }
156 return {'bool': True}
162 def ldapDelete(self, record_filter):
163 #Find uid of the person
164 person = self.ldapSearch(record_filter, ['uid'])
167 dn = 'uid=' +person['uid'] +","+self.baseDN
169 return {'bool': False}
172 result = self.conn.connect()
175 self.conn.ldapserv.delete_s(dn)
176 return {'bool': True}
178 except ldap.LDAPError, e:
179 print>>sys.stderr, "\r\n LDAP.PY \tldapDelete error : %s" %(e)
180 return {'bool': False}
183 def ldapModify(self, record_filter, new_attributes):
185 Gets the record from one user based on record_filter
186 and changes the attributes according to the specified new_attributes.
187 Does not use this if we need to modify the uid. Use a ModRDMN
188 #operation instead ( modify relative DN )
191 person = self.ldapSearch(record_filter,[] )
193 # The dn of our existing entry/object
194 dn = 'uid=' +person['uid'] +","+self.baseDN
200 for k in new_attributes:
203 ldif = modlist.modifyModlist(old,new_attributes)
205 # Connect and bind/authenticate
206 result = self.conn.connect(bind)
209 self.conn.ldapserver.modify_s(dn,ldif)
211 except ldap.LDAPError, e:
212 return {'bool' : False, 'message' : e }
213 return {'bool': True}
217 #TODO Handle OR filtering in the ldap query when
218 #dealing with a list of records instead of doing a for loop in GetPersons
219 def make_ldap_filters_from_record(self, record=None):
223 if 'first_name' in record and 'last_name' in record:
224 req_ldapdict['cn'] = str(record['first_name'])+" "+str(record['last_name'])
225 if 'email' in record :
226 req_ldapdict['mail'] = record['email']
228 splited_hrn = record['hrn'].split(".")
229 if splited_hrn[0] != self.authname :
230 print >>sys.stderr,"i know nothing about",record['hrn'], " my authname is ", self.authname, " not ", splited_hrn[0]
232 req_ldapdict['uid'] = login
235 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)
236 for k in req_ldapdict:
237 req_ldap += '('+str(k)+'='+str(req_ldapdict[k])+')'
238 if len(req_ldapdict.keys()) >1 :
239 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
241 req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
249 #Returns one matching entry
250 def ldapSearch (self, record = None, expected_fields = None ):
252 self.conn.connect(bind = False)
254 req_ldap = self.make_ldap_filters_from_record(record)
255 if expected_fields == None :
256 return_fields = ['mail','givenName', 'sn', 'uid','sshPublicKey']
257 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch req_ldap %s" %(req_ldap)
259 msg_id=self.conn.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,req_ldap,return_fields)
260 #Get all the results matching the search from ldap in one shot (1 value)
261 result_type, result_data = self.conn.ldapserv.result(msg_id,1)
263 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch result_data %s" %(result_data)
265 #Asked for a specific user
267 ldapentry = result_data[0][1]
268 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch ldapentry %s" %(ldapentry)
269 tmpname = ldapentry['uid'][0]
271 tmpemail = ldapentry['mail'][0]
272 if ldapentry['mail'][0] == "unknown":
276 parent_hrn = get_authority(hrn)
277 peer_authority = None
278 if parent_hrn is not self.authname:
279 peer_authority = parent_hrn
285 'pkey': ldapentry['sshPublicKey'][0],
286 #'uid': ldapentry[1]['uid'][0],
289 #'email': ldapentry[1]['mail'][0],
290 'first_name': ldapentry['givenName'][0],
291 'last_name': ldapentry['sn'][0],
294 'authority': parent_hrn,
295 'peer_authority': peer_authority,
300 #Asked for all users in ldap
302 for ldapentry in result_data[1]:
304 tmpname = ldapentry[1]['uid'][0]
306 if ldapentry[1]['uid'][0] == "savakian":
309 hrn=self.authname+"."+ tmpname
311 tmpemail = ldapentry[1]['mail'][0]
312 if ldapentry[1]['mail'][0] == "unknown":
316 parent_hrn = get_authority(hrn)
317 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
321 'pkey': ldapentry[1]['sshPublicKey'][0],
322 #'uid': ldapentry[1]['uid'][0],
325 #'email': ldapentry[1]['mail'][0],
326 'first_name': ldapentry[1]['givenName'][0],
327 'last_name': ldapentry[1]['sn'][0],
330 'authority': self.authname,
331 'peer_authority': '',
338 except ldap.LDAPError,e :
339 print >>sys.stderr, "ERROR LDAP %s" %(e)
344 #def ldapFindHrn(self, record_filter = None):
345 ##def ldapFindHrn(self, record_filter = None, columns=None):
348 #self.conn.connect(bind = False)
350 #if 'authority' in record_filter:
352 #if record_filter['authority']==self.authname:
353 ## which is SFA_REGISTRY_ROOT_AUTH
354 ## request all records which are under our authority, ie all ldap entries
357 ##which is NOT SFA_REGISTRY_ROOT_AUTH
360 #if not 'hrn' in record_filter:
361 #print >>sys.stderr,"find : don't know how to handle filter ",record_filter
365 #h=record_filter['hrn']
366 #if isinstance(h,list):
373 #splited_hrn=hrn.split(".")
374 #if splited_hrn[0] != self.authname :
375 #print >>sys.stderr,"i know nothing about",hrn, " my authname is ", self.authname, " not ", splited_hrn[0]
377 #login=splited_hrn[1]
383 #rindex=self.conn.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,ldapfilter, ['mail','givenName', 'sn', 'uid','sshPublicKey'])
384 ##rindex=self.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,ldapfilter, ['mail','givenName', 'sn', 'uid','sshPublicKey'])
385 #ldapresponse=self.conn.ldapserv.result(rindex,1)
386 #for ldapentry in ldapresponse[1]:
388 #tmpname = ldapentry[1]['uid'][0]
390 #if ldapentry[1]['uid'][0] == "savakian":
393 #hrn=self.authname+"."+ tmpname
395 #tmpemail = ldapentry[1]['mail'][0]
396 #if ldapentry[1]['mail'][0] == "unknown":
398 ## uuid=create_uuid()
400 ## RSA_KEY_STRING=ldapentry[1]['sshPublicKey'][0]
402 ## pkey=convert_public_key(RSA_KEY_STRING)
404 ## gid=self.senslabauth.create_gid("urn:publicid:IDN+"+self.authname+"+user+"+ldapentry[1]['uid'][0], uuid, pkey, CA=False)
406 #parent_hrn = get_authority(hrn)
407 #parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
411 #'pkey': ldapentry[1]['sshPublicKey'][0],
412 ##'uid': ldapentry[1]['uid'][0],
415 ##'email': ldapentry[1]['mail'][0],
416 #'first_name': ldapentry[1]['givenName'][0],
417 #'last_name': ldapentry[1]['sn'][0],
420 #'authority': self.authname,
421 #'peer_authority': '',