Cleaning.
[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, record_filter = None):
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         #def connect (self):
101            #self.ldapserv=ldap.open("192.168.0.251")
102            
103         #def authenticate(self):
104             #self.l = ldap.initialize("ldaps://192.168.0.251:636/")
105             #login = 'cn=admin,dc=senslab,dc=info'
106     
107             #passwd='sfa-ldap'  
108             ## Bind/authenticate with a user with apropriate rights to add objects
109             #self.l = simple_bind_s(login,passwd)
110                               
111         def ldapAdd(self, recordix = None) :
112             attrs = {'cn': ['Bruce Wayne'], 'objectClass': ['top', 'inetOrgPerson', 'posixAccount', 'systemQuotas', 'ldapPublicKey'], 'loginShell': '/senslab/users/.ssh/welcome.sh', 'sshPublicKey': '', 'quota': '/dev/sda3:2000000:2500000:0:0', 'gidNumber': '2000', 'sn': 'Wayne', 'homeDirectory': '/senslab/users/batman', 'mail': 'bw@gotham.com', 'givenName': 'Bruce', 'uid': 'batman','description' :'SFA USER FROM OUTSIDE SENSLAB'}
113             result = self.conn.connect()
114             if(result['bool']):
115                 # The dn of our new entry/object
116                 dn = self.baseDN  
117                 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t  ldapAdd  attrs %s " %(attrs)
118                 # A dict to help build the "body" of the object
119                 #attrs = {}
120                 #attrs['objectclass'] = ['top','inetOrgPerson','posixAccount', 'systemQuotas','ldapPuclicKey']
121                 #attrs['cn'] = str(record['first_name'])+' ' + str(record['last_name'])
122                 #attrs['sn'] = str(record['last_name'])
123                 #attrs['givenName'] = str(record['first_name'])
124                 #attrs['gidNumber'] = '2000'
125                 #loginslab =str(record['first_name'])+ str(record['last_name'])
126                 #loginslab= loginslab.lower()
127                 ##loginslab  = loginslab[0:12]
128                 #attrs['uid']= loginslab
129                 #attrs['mail'] = record['mail']
130                 #attrs['quota'] = '/dev/sda3:2000000:2500000:0:0'
131                 #attrs['homeDirectory'] = '/senslab/users/' + loginslab
132                 #attrs['loginShell'] = '/senslab/users/.ssh/welcome.sh'
133                 #attrs['sshPublicKey'] = ''
134                 #attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
135                 category ="ou=people, dc=senslab, dc=info"   
136                 try:
137                         ldif = modlist.addModlist(attrs)
138                         print " \r\n \r\n LDAPTEST.PY add attrs %s \r\n  ldif %s  " %(attrs,ldif)
139                         self.conn.ldapserv.add_s('%s,%s' %(dn, category),ldif)
140                 except ldap.LDAPError, e:
141                     return {'bool' : False, 'message' : e }
142             
143                 self.close()
144                 return {'bool': True}  
145             else: 
146                 return result
147                 return   
148                                
149         def parse_record(self, record):
150             req_ldapdict = {}
151             if 'first_name' in record  and 'last_name' in record:
152                 req_ldapdict['cn'] = str(record['first_name'])+" "+str(record['last_name'])
153             if 'email' in record :
154                 req_ldapdict['mail'] = record['email']
155             if 'hrn' in record :
156                 splited_hrn = record['hrn'].split(".")
157                 if splited_hrn[0] != self.authname :
158                         print >>sys.stderr,"i know nothing about",record['hrn'], " my authname is ", self.authname, " not ", splited_hrn[0]
159                 login=splited_hrn[1]
160                 req_ldapdict['uid'] = login
161                 
162             req_ldap=''
163             print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t   parse_record record %s req_ldapdict %s" %(record,req_ldapdict)
164             for k in req_ldapdict:
165                 req_ldap += '('+str(k)+'='+str(req_ldapdict[k])+')'
166             if  len(req_ldapdict.keys()) >1 :
167                 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
168                 size = len(req_ldap)
169                 req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
170             
171             return req_ldap
172             
173         def parse_ldapresults(self, ldapentry):
174             return
175             
176             
177                                        
178         def ldapSearch (self, record ):
179             
180             self.conn.connect(bind = False)
181             #self.connect()
182             req_ldap = self.parse_record(record)
183             print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch  req_ldap %s" %(req_ldap)
184             try:
185                 msg_id=self.conn.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,req_ldap, ['mail','givenName', 'sn', 'uid','sshPublicKey'])     
186                 #Get all the results matching the search from ldap in one shot (1 value)
187                 result_type, result_data=self.conn.ldapserv.result(msg_id,1)
188                 results = []
189                 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch  result_data %s" %(result_data) 
190
191                 ldapentry = result_data[0][1]
192                 print >>sys.stderr, "\r\n \r\n \t LDAP.PY \t\t ldapSearch  ldapentry %s" %(ldapentry) 
193                 tmpname = ldapentry['uid'][0]
194                 
195                 if ldapentry['uid'][0] == "savakian":
196                     tmpname = 'avakian'
197
198                 tmpemail = ldapentry['mail'][0]
199                 if ldapentry['mail'][0] == "unknown":
200                     tmpemail = None
201                     
202                 hrn = record['hrn']
203                 parent_hrn = get_authority(hrn)
204                 peer_authority = None
205                 if parent_hrn is not self.authname:
206                     peer_authority = parent_hrn
207                         
208                 results.append(  {      
209                                 'type': 'user',
210                                 'pkey': ldapentry['sshPublicKey'][0],
211                                 #'uid': ldapentry[1]['uid'][0],
212                                 'uid': tmpname ,
213                                 'email':tmpemail,
214                                 #'email': ldapentry[1]['mail'][0],
215                                 'first_name': ldapentry['givenName'][0],
216                                 'last_name': ldapentry['sn'][0],
217 #                               'phone': 'none',
218                                 'serial': 'none',
219                                 'authority': parent_hrn,
220                                 'peer_authority': peer_authority,
221                                 'pointer' : -1,
222                                 'hrn': hrn,
223                                 } )
224                 return results
225
226             
227             except  ldap.LDAPError,e :
228                 print >>sys.stderr, "ERROR LDAP %s" %(e)
229                
230         
231
232         
233         def ldapFindHrn(self, record_filter = None):        
234         #def ldapFindHrn(self, record_filter = None, columns=None):
235
236                 results = [] 
237                 self.conn.connect(bind = False)
238                 #self.connect()
239                 if 'authority' in record_filter:
240                 # ask for authority
241                         if record_filter['authority']==self.authname:
242                                 # which is SFA_REGISTRY_ROOT_AUTH
243                                 # request all records which are under our authority, ie all ldap entries
244                                 ldapfilter="cn=*"
245                         else:
246                                 #which is NOT SFA_REGISTRY_ROOT_AUTH
247                                 return []
248                 else :
249                         if not 'hrn' in record_filter:
250                                 print >>sys.stderr,"find : don't know how to handle filter ",record_filter
251                                 return []
252                         else:
253                                 hrns=[]
254                                 h=record_filter['hrn']
255                                 if  isinstance(h,list):
256                                         hrns=h
257                                 else : 
258                                         hrns.append(h)
259         
260                                 ldapfilter="(|"
261                                 for hrn in hrns:
262                                         splited_hrn=hrn.split(".")
263                                         if splited_hrn[0] != self.authname :
264                                                 print >>sys.stderr,"i know nothing about",hrn, " my authname is ", self.authname, " not ", splited_hrn[0]
265                                         else :
266                                                 login=splited_hrn[1]
267                                                 ldapfilter+="(uid="
268                                                 ldapfilter+=login
269                                                 ldapfilter+=")"
270                                 ldapfilter+=")"
271         
272                 rindex=self.conn.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,ldapfilter, ['mail','givenName', 'sn', 'uid','sshPublicKey'])
273                 #rindex=self.ldapserv.search(self.baseDN,ldap.SCOPE_SUBTREE,ldapfilter, ['mail','givenName', 'sn', 'uid','sshPublicKey'])
274                 ldapresponse=self.conn.ldapserv.result(rindex,1)
275                 for ldapentry in ldapresponse[1]:
276                          
277                         tmpname = ldapentry[1]['uid'][0]
278                         
279                         if ldapentry[1]['uid'][0] == "savakian":
280                             tmpname = 'avakian'
281
282                         hrn=self.authname+"."+ tmpname
283                         
284                         tmpemail = ldapentry[1]['mail'][0]
285                         if ldapentry[1]['mail'][0] == "unknown":
286                             tmpemail = None
287 #                       uuid=create_uuid() 
288                 
289 #                       RSA_KEY_STRING=ldapentry[1]['sshPublicKey'][0]
290                 
291 #                       pkey=convert_public_key(RSA_KEY_STRING)
292                 
293 #                       gid=self.senslabauth.create_gid("urn:publicid:IDN+"+self.authname+"+user+"+ldapentry[1]['uid'][0], uuid, pkey, CA=False)
294                 
295                         parent_hrn = get_authority(hrn)
296                         parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
297
298                         results.append(  {      
299                                 'type': 'user',
300                                 'pkey': ldapentry[1]['sshPublicKey'][0],
301                                 #'uid': ldapentry[1]['uid'][0],
302                                 'uid': tmpname ,
303                                 'email':tmpemail,
304                                 #'email': ldapentry[1]['mail'][0],
305                                 'first_name': ldapentry[1]['givenName'][0],
306                                 'last_name': ldapentry[1]['sn'][0],
307 #                               'phone': 'none',
308                                 'serial': 'none',
309                                 'authority': self.authname,
310                                 'peer_authority': '',
311                                 'pointer' : -1,
312                                 'hrn': hrn,
313                                 } )
314                 return results