Added ldapModify , ldapAdd, ldapDelete.
[sfa.git] / sfa / senslab / LDAPapi.py
1
2 import string
3 from sfa.util.xrn import Xrn,get_authority 
4 import ldap
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
11
12 class ldap_co:
13     def __init__(self):
14     #def __init__(self, param, level):
15         """
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')
20         :type level: string.
21         """
22
23         self.__level = 'warning'
24         #self.__param = param
25         #self.__level = level
26         self.login = 'cn=admin,dc=senslab,dc=info'
27     
28         self.passwd='sfa'  
29         print "\r\n INIT OK !"
30     
31     def connect(self, bind = True):
32         """
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
36         """
37         try:
38             self.ldapserv = ldap.open("192.168.0.251")
39         except ldap.LDAPError, e:
40             return {'bool' : False, 'message' : e }
41         
42         # Bind non anonyme avec authentification
43         if(bind): 
44             return self.bind()
45         
46         else:     
47             return {'bool': True}
48     
49     
50     def bind(self):
51         """
52         Methode permettant l'authentification a un serveur LDAP
53         @return array : Retour d'un tableau
54         """
55         try:
56             print "\r\n BIND ??!"
57             # Open a connection
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)
61             print "\r\n BIND ???"
62         except ldap.LDAPError, e:
63             return {'bool' : False, 'message' : e }
64         
65         print "\r\n BIND OK !"
66         return {'bool': True}
67     
68     def close(self):
69         """
70         Methode permettant la deconnexion a un serveur LDAP
71         """
72         # Fermeture de la connexion
73         try:
74             self.ldapserv.unbind_s()
75         except ldap.LDAPError, e:
76             pass
77             
78         
79 class LDAPapi :
80         def __init__(self):
81                 self.senslabauth=Hierarchy()
82                 config=Config()
83                 self.authname=config.SFA_REGISTRY_ROOT_AUTH
84                 authinfo=self.senslabauth.get_auth_info(self.authname)
85         
86         
87                 self.auth=Auth()
88                 gid=authinfo.get_gid_object()
89                 self.ldapdictlist = ['type',
90                                 'pkey',
91                                 'uid',
92                                 'serial',
93                                 'authority',
94                                 'peer_authority',
95                                 'pointer' ,
96                                 'hrn']
97                 self.baseDN = "ou=people,dc=senslab,dc=info"
98                 self.conn =  ldap_co()    
99                           
100
101                               
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)
107             if (result['bool']): 
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 == []:
113                     max_uidnumber = 9000
114                 #Get the highest uidNumber
115                 else:
116                     max_uidnumber = 0
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
121             
122             result = self.conn.connect()
123             if(result['bool']):
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
126                 attrs = {}
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'
143                 
144                 # The dn of our new entry/object
145                 dn = 'uid=' +attrs['uid'] +","+self.baseDN 
146  
147                 try:
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)
151
152                 except ldap.LDAPError, e:
153                     return {'bool' : False, 'message' : e }
154             
155                 self.close()
156                 return {'bool': True}  
157             else: 
158                 return result
159                 return  
160          
161          
162         def ldapDelete(self, record_filter): 
163             #Find uid of the  person 
164             person = self.ldapSearch(record_filter, ['uid'])
165            
166             if person:
167                 dn = 'uid=' +person['uid'] +","+self.baseDN 
168             else:
169                 return {'bool': False}
170             
171             #Connect and bind   
172             result =  self.conn.connect()
173             if(result['bool']):
174                 try:
175                     self.conn.ldapserv.delete_s(dn)
176                     return {'bool': True}
177                 
178                 except ldap.LDAPError, e:
179                     print>>sys.stderr, "\r\n LDAP.PY \tldapDelete error : %s" %(e)  
180                     return {'bool': False}
181                     
182                     
183         def ldapModify(self, record_filter, new_attributes):
184             """
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 )
189             """
190             
191             person = self.ldapSearch(record_filter,[] )
192             if person:
193                 # The dn of our existing entry/object
194                 dn  = 'uid=' +person['uid'] +","+self.baseDN 
195             else:
196                 return
197             
198             if new_attributes:
199                 old = {}
200                 for k in new_attributes:
201                     old[k] =  person[k]
202                     
203                 ldif = modlist.modifyModlist(old,new_attributes)
204                 
205                 # Connect and bind/authenticate    
206                 result = self.conn.connect(bind) 
207                 if (result['bool']): 
208                     try:
209                         self.conn.ldapserver.modify_s(dn,ldif)
210                         self.close()
211                     except ldap.LDAPError, e:
212                         return {'bool' : False, 'message' : e }
213                 return {'bool': True}  
214                 
215                 
216                 
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):
220             
221             req_ldapdict = {}
222             if record :
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']
227                 if 'hrn' in record :
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]
231                     login=splited_hrn[1]
232                     req_ldapdict['uid'] = login
233                 
234                 req_ldap=''
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:]
240                     size = len(req_ldap)
241                     req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
242             else:
243                 req_ldap = "(cn*)"
244             
245             return req_ldap
246
247             
248             
249         #Returns one matching entry                                
250         def ldapSearch (self, record = None, expected_fields = None ):
251             
252             self.conn.connect(bind = False)
253             #self.connect()
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)
258             try:
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)
262                 #results = []
263                 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch  result_data %s" %(result_data) 
264                 
265                 #Asked for a specific user
266                 if record:
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]
270    
271                     tmpemail = ldapentry['mail'][0]
272                     if ldapentry['mail'][0] == "unknown":
273                         tmpemail = None
274                         
275                     hrn = record['hrn']
276                     parent_hrn = get_authority(hrn)
277                     peer_authority = None
278                     if parent_hrn is not self.authname:
279                         peer_authority = parent_hrn
280                             
281
282                                     
283                     results=  { 
284                                 'type': 'user',
285                                 'pkey': ldapentry['sshPublicKey'][0],
286                                 #'uid': ldapentry[1]['uid'][0],
287                                 'uid': tmpname ,
288                                 'email':tmpemail,
289                                 #'email': ldapentry[1]['mail'][0],
290                                 'first_name': ldapentry['givenName'][0],
291                                 'last_name': ldapentry['sn'][0],
292                                 #'phone': 'none',
293                                 'serial': 'none',
294                                 'authority': parent_hrn,
295                                 'peer_authority': peer_authority,
296                                 'pointer' : -1,
297                                 'hrn': hrn,
298                                 } 
299                 else:
300                 #Asked for all users in ldap
301                     results = []
302                     for ldapentry in result_data[1]:
303                          
304                         tmpname = ldapentry[1]['uid'][0]
305                         
306                         if ldapentry[1]['uid'][0] == "savakian":
307                             tmpname = 'avakian'
308
309                         hrn=self.authname+"."+ tmpname
310                         
311                         tmpemail = ldapentry[1]['mail'][0]
312                         if ldapentry[1]['mail'][0] == "unknown":
313                             tmpemail = None
314
315                 
316                         parent_hrn = get_authority(hrn)
317                         parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
318
319                         results.append(  {      
320                                 'type': 'user',
321                                 'pkey': ldapentry[1]['sshPublicKey'][0],
322                                 #'uid': ldapentry[1]['uid'][0],
323                                 'uid': tmpname ,
324                                 'email':tmpemail,
325                                 #'email': ldapentry[1]['mail'][0],
326                                 'first_name': ldapentry[1]['givenName'][0],
327                                 'last_name': ldapentry[1]['sn'][0],
328 #                               'phone': 'none',
329                                 'serial': 'none',
330                                 'authority': self.authname,
331                                 'peer_authority': '',
332                                 'pointer' : -1,
333                                 'hrn': hrn,
334                                 } )   
335                 return results
336
337             
338             except  ldap.LDAPError,e :
339                 print >>sys.stderr, "ERROR LDAP %s" %(e)
340                
341         
342
343         
344         #def ldapFindHrn(self, record_filter = None):        
345         ##def ldapFindHrn(self, record_filter = None, columns=None):
346
347                 #results = [] 
348                 #self.conn.connect(bind = False)
349                 ##self.connect()
350                 #if 'authority' in record_filter:
351                 ## ask for authority
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
355                                 #ldapfilter="cn=*"
356                         #else:
357                                 ##which is NOT SFA_REGISTRY_ROOT_AUTH
358                                 #return []
359                 #else :
360                         #if not 'hrn' in record_filter:
361                                 #print >>sys.stderr,"find : don't know how to handle filter ",record_filter
362                                 #return []
363                         #else:
364                                 #hrns=[]
365                                 #h=record_filter['hrn']
366                                 #if  isinstance(h,list):
367                                         #hrns=h
368                                 #else : 
369                                         #hrns.append(h)
370         
371                                 #ldapfilter="(|"
372                                 #for hrn in hrns:
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]
376                                         #else :
377                                                 #login=splited_hrn[1]
378                                                 #ldapfilter+="(uid="
379                                                 #ldapfilter+=login
380                                                 #ldapfilter+=")"
381                                 #ldapfilter+=")"
382         
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]:
387                          
388                         #tmpname = ldapentry[1]['uid'][0]
389                         
390                         #if ldapentry[1]['uid'][0] == "savakian":
391                             #tmpname = 'avakian'
392
393                         #hrn=self.authname+"."+ tmpname
394                         
395                         #tmpemail = ldapentry[1]['mail'][0]
396                         #if ldapentry[1]['mail'][0] == "unknown":
397                             #tmpemail = None
398 ##                      uuid=create_uuid() 
399                 
400 ##                      RSA_KEY_STRING=ldapentry[1]['sshPublicKey'][0]
401                 
402 ##                      pkey=convert_public_key(RSA_KEY_STRING)
403                 
404 ##                      gid=self.senslabauth.create_gid("urn:publicid:IDN+"+self.authname+"+user+"+ldapentry[1]['uid'][0], uuid, pkey, CA=False)
405                 
406                         #parent_hrn = get_authority(hrn)
407                         #parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
408
409                         #results.append(  {     
410                                 #'type': 'user',
411                                 #'pkey': ldapentry[1]['sshPublicKey'][0],
412                                 ##'uid': ldapentry[1]['uid'][0],
413                                 #'uid': tmpname ,
414                                 #'email':tmpemail,
415                                 ##'email': ldapentry[1]['mail'][0],
416                                 #'first_name': ldapentry[1]['givenName'][0],
417                                 #'last_name': ldapentry[1]['sn'][0],
418 ##                              'phone': 'none',
419                                 #'serial': 'none',
420                                 #'authority': self.authname,
421                                 #'peer_authority': '',
422                                 #'pointer' : -1,
423                                 #'hrn': hrn,
424                                 #} )
425                 #return results