Debugging OARrestapi - modifications because of the mirgation to OAR2.5.
[sfa.git] / sfa / senslab / LDAPapi.py
1
2 import string
3 import random
4 from passlib.hash import ldap_salted_sha1 as lssha
5 from sfa.util.xrn import Xrn,get_authority 
6 import ldap
7 from sfa.util.config import Config
8 from sfa.trust.hierarchy import Hierarchy
9 from sfa.trust.certificate import *
10 import ldap.modlist as modlist
11 from sfa.util.sfalogging import logger
12 import os.path
13
14 #API for OpenLDAP
15
16
17 class ldap_config():
18     def __init__(self, config_file =  '/etc/sfa/ldap_config.py'):
19         self.load(config_file)
20
21     def load(self, config_file):
22         try:
23             execfile(config_file, self.__dict__)
24             self.config_file = config_file
25             # path to configuration data
26             self.config_path = os.path.dirname(config_file)
27         except IOError, e:
28             raise IOError, "Could not find or load the configuration file: %s" % config_file
29         
30 class ldap_co:
31     """ Set admin login and server configuration variables."""
32     
33     def __init__(self):
34         #Senslab PROD LDAP parameters 
35         LdapConfig = ldap_config()
36         self.config = LdapConfig
37         self.ldapHost = LdapConfig.LDAP_IP_ADDRESS 
38         self.ldapPeopleDN = LdapConfig.LDAP_PEOPLE_DN
39         self.ldapGroupDN = LdapConfig.LDAP_GROUP_DN
40         self.ldapAdminDN = LdapConfig.LDAP_WEB_DN
41         self.ldapAdminPassword = LdapConfig.LDAP_WEB_PASSWORD
42         
43         
44
45         self.ldapPort = ldap.PORT
46         self.ldapVersion  = ldap.VERSION3
47         self.ldapSearchScope = ldap.SCOPE_SUBTREE
48
49
50     def connect(self, bind = True):
51         """Enables connection to the LDAP server.
52         Set the bind parameter to True if a bind is needed
53         (for add/modify/delete operations).
54         Set to False otherwise.
55         
56         """
57         try:
58             self.ldapserv = ldap.open(self.ldapHost)
59         except ldap.LDAPError, e:
60             return {'bool' : False, 'message' : e }
61         
62         # Bind with authentification
63         if(bind): 
64             return self.bind()
65         
66         else:     
67             return {'bool': True} 
68     
69     def bind(self):
70         """ Binding method. """
71         try:
72             # Opens a connection after a call to ldap.open in connect:
73             self.ldapserv = ldap.initialize("ldap://" + self.ldapHost)
74                 
75             # Bind/authenticate with a user with apropriate rights to add objects
76             self.ldapserv.simple_bind_s(self.ldapAdminDN, self.ldapAdminPassword)
77
78         except ldap.LDAPError, e:
79             return {'bool' : False, 'message' : e }
80
81         return {'bool': True}
82     
83     def close(self):
84         """ Close the LDAP connection """
85         try:
86             self.ldapserv.unbind_s()
87         except ldap.LDAPError, e:
88             return {'bool' : False, 'message' : e }
89             
90         
91 class LDAPapi :
92     def __init__(self):
93         #logger.setLevelDebug() 
94         #SFA related config
95         self.senslabauth=Hierarchy()
96         config=Config()
97         
98         self.authname=config.SFA_REGISTRY_ROOT_AUTH
99
100         self.conn =  ldap_co() 
101         self.ldapUserQuotaNFS = self.conn.config.LDAP_USER_QUOTA_NFS 
102         self.ldapUserUidNumberMin = self.conn.config.LDAP_USER_UID_NUMBER_MIN 
103         self.ldapUserGidNumber = self.conn.config.LDAP_USER_GID_NUMBER 
104         self.ldapUserHomePath = self.conn.config.LDAP_USER_HOME_PATH 
105         
106         self.lengthPassword = 8; 
107         self.baseDN = self.conn.ldapPeopleDN
108         #authinfo=self.senslabauth.get_auth_info(self.authname)
109         
110         
111         self.charsPassword = [ '!','$','(',')','*','+',',','-','.',\
112                                 '0','1','2','3','4','5','6','7','8','9',\
113                                 'A','B','C','D','E','F','G','H','I','J',\
114                                 'K','L','M','N','O','P','Q','R','S','T',\
115                                 'U','V','W','X','Y','Z','_','a','b','c',\
116                                 'd','e','f','g','h','i','j','k','l','m',\
117                                 'n','o','p','q','r','s','t','u','v','w',\
118                                 'x','y','z','\'']
119         
120         self.ldapShell = '/bin/bash'
121
122     
123     def generate_login(self, record):
124         """Generate login for adding a new user in LDAP Directory 
125         (four characters minimum length)
126         Record contains first name and last name.
127         
128         """ 
129         #Remove all special characters from first_name/last name
130         lower_first_name = record['first_name'].replace('-','')\
131                                         .replace('_','').replace('[','')\
132                                         .replace(']','').replace(' ','')\
133                                         .lower()
134         lower_last_name = record['last_name'].replace('-','')\
135                                         .replace('_','').replace('[','')\
136                                         .replace(']','').replace(' ','')\
137                                         .lower()  
138         length_last_name = len(lower_last_name)
139         login_max_length = 8
140         
141         #Try generating a unique login based on first name and last name
142         getAttrs = ['uid']
143         if length_last_name >= login_max_length :
144             login = lower_last_name[0:login_max_length]
145             index = 0;
146             logger.debug("login : %s index : %s" %(login,index))
147         elif length_last_name >= 4 :
148             login = lower_last_name
149             index = 0
150             logger.debug("login : %s index : %s" %(login,index))
151         elif length_last_name == 3 :
152             login = lower_first_name[0:1] + lower_last_name
153             index = 1
154             logger.debug("login : %s index : %s" %(login,index))
155         elif length_last_name == 2:
156             if len ( lower_first_name) >=2:
157                 login = lower_first_name[0:2] + lower_last_name
158                 index = 2
159                 logger.debug("login : %s index : %s" %(login,index))
160             else:
161                 logger.error("LoginException : \
162                             Generation login error with \
163                             minimum four characters")
164             
165                 
166         else :
167             logger.error("LDAP generate_login failed : \
168                             impossible to generate unique login for %s %s" \
169                             %(lower_first_name,lower_last_name))
170             
171         filter = '(uid=' + login + ')'
172         
173         try :
174             #Check if login already in use
175             while (len(self.LdapSearch(filter, getAttrs)) is not 0 ):
176             
177                 index += 1
178                 if index >= 9:
179                     logger.error("LoginException : Generation login error \
180                                     with minimum four characters")
181                 else:
182                     try:
183                         login = lower_first_name[0:index] + \
184                                     lower_last_name[0:login_max_length-index]
185                         filter = '(uid='+ login+ ')'
186                     except KeyError:
187                         print "lower_first_name - lower_last_name too short"
188                         
189             logger.debug("LDAP.API \t generate_login login %s" %(login))
190             return login
191                     
192         except  ldap.LDAPError,e :
193             logger.log_exc("LDAP generate_login Error %s" %e)
194             return None
195
196         
197
198     def generate_password(self):
199     
200         """Generate password for adding a new user in LDAP Directory 
201         (8 characters length) return password
202         
203         """
204         password = str()
205         length = len(self.charsPassword)
206         for index in range(self.lengthPassword):
207             char_index = random.randint(0,length-1)
208             password += self.charsPassword[char_index]
209
210         return password
211
212     def encrypt_password(self, password):
213        """ Use passlib library to make a RFC2307 LDAP encrypted password
214        salt size = 8, use sha-1 algorithm. Returns encrypted password.
215        
216        """
217        #Keep consistency with Java Senslab's LDAP API 
218        #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
219        return lssha.encrypt(password,salt_size = 8)
220     
221
222
223     def find_max_uidNumber(self):
224             
225         """Find the LDAP max uidNumber (POSIX uid attribute) .
226         Used when adding a new user in LDAP Directory 
227         returns string  max uidNumber + 1
228         
229         """
230         #First, get all the users in the LDAP
231         getAttrs = "(uidNumber=*)"
232         filter = ['uidNumber']
233
234         result_data = self.LdapSearch(getAttrs, filter) 
235         #It there is no user in LDAP yet, First LDAP user
236         if result_data == []:
237             max_uidnumber = self.ldapUserUidNumberMin
238         #Otherwise, get the highest uidNumber
239         else:
240             
241             uidNumberList = [int(r[1]['uidNumber'][0])for r in result_data ]
242             logger.debug("LDAPapi.py \tfind_max_uidNumber  \
243                                     uidNumberList %s " %(uidNumberList))
244             max_uidnumber = max(uidNumberList) + 1
245             
246         return str(max_uidnumber)
247         
248     #TODO ; Get ssh public key from sfa record   
249     #To be filled by N. Turro                
250     def get_ssh_pkey(self, record):
251         return 'A REMPLIR '
252          
253          
254     #TODO Handle OR filtering in the ldap query when 
255     #dealing with a list of records instead of doing a for loop in GetPersons   
256     def make_ldap_filters_from_record(self, record=None):
257         """
258         Helper function to make LDAP filter requests out of SFA records.
259         """
260         req_ldapdict = {}
261         if record :
262             if 'first_name' in record  and 'last_name' in record:
263                 req_ldapdict['cn'] = str(record['first_name'])+" "\
264                                         + str(record['last_name'])
265             if 'email' in record :
266                 req_ldapdict['mail'] = record['email']
267             if 'mail' in record:
268                 req_ldapdict['mail'] = record['mail']
269                 
270             #Hrn should not be part of the filter because the hrn 
271             #presented by a certificate of a SFA user not imported in 
272             #Senslab  does not include the senslab login in it 
273             #Plus, the SFA user may already have an account with senslab
274             #using another login.
275                 
276             #if 'hrn' in record :
277                 #splited_hrn = record['hrn'].split(".")
278                 #if splited_hrn[0] != self.authname :
279                     #logger.warning(" \r\n LDAP.PY \
280                         #make_ldap_filters_from_record I know nothing \
281                         #about %s my authname is %s not %s" \
282                         #%(record['hrn'], self.authname, splited_hrn[0]) )
283                         
284                 #login=splited_hrn[1]
285                 #req_ldapdict['uid'] = login
286             
287             req_ldap=''
288             logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
289                                 record %s req_ldapdict %s" \
290                                 %(record, req_ldapdict))
291             
292             for k in req_ldapdict:
293                 req_ldap += '('+str(k)+'='+str(req_ldapdict[k])+')'
294             if  len(req_ldapdict.keys()) >1 :
295                 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
296                 size = len(req_ldap)
297                 req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
298         else:
299             req_ldap = "(cn=*)"
300         
301         return req_ldap
302         
303     def make_ldap_attributes_from_record(self, record):
304         """When addind a new user to Senslab's LDAP, creates an attributes 
305         dictionnary from the SFA record.
306         
307         """
308
309         attrs = {}
310         attrs['objectClass'] = ["top", "person", "inetOrgPerson",\
311                                     "organizationalPerson", "posixAccount",\
312                                     "shadowAccount", "systemQuotas",\
313                                     "ldapPublicKey"]
314         
315         attrs['givenName'] = str(record['first_name']).lower().capitalize()
316         attrs['sn'] = str(record['last_name']).lower().capitalize()
317         attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
318         attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
319         attrs['uid'] = self.generate_login(record)   
320                     
321         attrs['quota'] = self.ldapUserQuotaNFS 
322         attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
323         attrs['loginShell'] = self.ldapShell
324         attrs['gidNumber'] = self.ldapUserGidNumber
325         attrs['uidNumber'] = self.find_max_uidNumber()
326         attrs['mail'] = record['mail'].lower()
327         
328         attrs['sshPublicKey'] = self.get_ssh_pkey(record) 
329         
330
331         #Password is automatically generated because SFA user don't go 
332         #through the Senslab website  used to register new users, 
333         #There is no place in SFA where users can enter such information
334         #yet.
335         #If the user wants to set his own password , he must go to the Senslab 
336         #website.
337         password = self.generate_password()
338         attrs['userPassword']= self.encrypt_password(password)
339         
340         #Account automatically validated (no mail request to admins)
341         #Set to 0 to disable the account, -1 to enable it,
342         attrs['shadowExpire'] = '-1'
343
344         #Motivation field in Senslab
345         attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
346
347         attrs['ou'] = 'SFA'         #Optional: organizational unit
348         #No info about those here:
349         attrs['l'] = 'To be defined'#Optional: Locality. 
350         attrs['st'] = 'To be defined' #Optional: state or province (country).
351
352         return attrs
353
354
355
356     def LdapAddUser(self, record = None) :
357         """Add SFA user to LDAP if it is not in LDAP  yet. """
358         
359         user_ldap_attrs = self.make_ldap_attributes_from_record(record)
360
361         
362         #Check if user already in LDAP wih email, first name and last name
363         filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
364         user_exist = self.LdapSearch(filter_by)
365         if user_exist:
366             logger.warning(" \r\n \t LDAP LdapAddUser user %s %s already exists" \
367                             %(user_ldap_attrs['sn'],user_ldap_attrs['mail'])) 
368             return {'bool': False}
369         
370         #Bind to the server
371         result = self.conn.connect()
372         
373         if(result['bool']):
374             
375             # A dict to help build the "body" of the object
376             
377             logger.debug(" \r\n \t LDAP LdapAddUser attrs %s " %user_ldap_attrs)
378
379             # The dn of our new entry/object
380             dn = 'uid=' + user_ldap_attrs['uid'] + "," + self.baseDN 
381
382             try:
383                 ldif = modlist.addModlist(user_ldap_attrs)
384                 logger.debug("LDAPapi.py add attrs %s \r\n  ldif %s"\
385                                 %(user_ldap_attrs,ldif) )
386                 self.conn.ldapserv.add_s(dn,ldif)
387                 
388                 logger.info("Adding user %s login %s in LDAP" \
389                         %(user_ldap_attrs['cn'] ,user_ldap_attrs['uid']))
390                         
391                         
392             except ldap.LDAPError, e:
393                 logger.log_exc("LDAP Add Error %s" %e)
394                 return {'bool' : False, 'message' : e }
395         
396             self.conn.close()
397             return {'bool': True}  
398         else: 
399             return result
400
401         
402     def LdapDelete(self, person_dn):
403         """
404         Deletes a person in LDAP. Uses the dn of the user.
405         """
406         #Connect and bind   
407         result =  self.conn.connect()
408         if(result['bool']):
409             try:
410                 self.conn.ldapserv.delete_s(person_dn)
411                 self.conn.close()
412                 return {'bool': True}
413             
414             except ldap.LDAPError, e:
415                 logger.log_exc("LDAP Delete Error %s" %e)
416                 return {'bool': False}
417         
418     
419     def LdapDeleteUser(self, record_filter): 
420         """
421         Deletes a SFA person in LDAP, based on the user's hrn.
422         """
423         #Find uid of the  person 
424         person = self.LdapFindUser(record_filter,[])
425         logger.debug("LDAPapi.py \t LdapDeleteUser record %s person %s" \
426         %(record_filter,person))
427
428         if person:
429             dn = 'uid=' + person['uid'] + "," +self.baseDN 
430         else:
431             return {'bool': False}
432         
433         result = self.LdapDelete(dn)
434         return result
435         
436
437     def LdapModify(self, dn, old_attributes_dict, new_attributes_dict): 
438         """ Modifies a LDAP entry """
439          
440         ldif = modlist.modifyModlist(old_attributes_dict,new_attributes_dict)
441         # Connect and bind/authenticate    
442         result = self.conn.connect() 
443         if (result['bool']): 
444             try:
445                 self.conn.ldapserv.modify_s(dn,ldif)
446                 self.conn.close()
447                 return {'bool' : True }
448             except ldap.LDAPError, e:
449                 logger.log_exc("LDAP LdapModify Error %s" %e)
450                 return {'bool' : False }
451     
452         
453     def LdapModifyUser(self, user_record, new_attributes_dict):
454         """
455         Gets the record from one user_uid_login based on record_filter 
456         and changes the attributes according to the specified new_attributes.
457         Does not use this if we need to modify the uid. Use a ModRDN 
458         #operation instead ( modify relative DN )
459         """
460         if user_record is None:
461             logger.error("LDAP \t LdapModifyUser Need user record  ")
462             return {'bool': False} 
463         
464         #Get all the attributes of the user_uid_login 
465         #person = self.LdapFindUser(record_filter,[])
466         req_ldap = self.make_ldap_filters_from_record(user_record)
467         person_list = self.LdapSearch(req_ldap,[])
468         logger.debug("LDAPapi.py \t LdapModifyUser person_list : %s" %(person_list))
469         if person_list and len(person_list) > 1 :
470             logger.error("LDAP \t LdapModifyUser Too many users returned")
471             return {'bool': False}
472         if person_list is None :
473             logger.error("LDAP \t LdapModifyUser  User %s doesn't exist "\
474                         %(user_uid_login))
475             return {'bool': False} 
476         
477         # The dn of our existing entry/object
478         #One result only from ldapSearch
479         person = person_list[0][1]
480         dn  = 'uid=' + person['uid'][0] + "," +self.baseDN  
481        
482         if new_attributes_dict:
483             old = {}
484             for k in new_attributes_dict:
485                 if k not in person:
486                     old[k] =  ''
487                 else :
488                     old[k] = person[k]
489             logger.debug(" LDAPapi.py \t LdapModifyUser  new_attributes %s"\
490                                 %( new_attributes_dict))  
491             result = self.LdapModify(dn, old,new_attributes_dict)
492             return result
493         else:
494             logger.error("LDAP \t LdapModifyUser  No new attributes given. ")
495             return {'bool': False} 
496             
497             
498     def LdapResetPassword(self,record):
499         """
500         Resets password for the user whose record is the parameter and changes
501         the corresponding entry in the LDAP.
502         
503         """
504         password = self.generate_password()
505         attrs = {}
506         attrs['userPassword'] = self.encrypt_password(password)
507         logger.debug("LDAP LdapResetPassword encrypt_password %s"\
508                     %(attrs['userPassword']))
509         result = self.LdapModifyUser(record, attrs)
510         return result
511         
512         
513     def LdapSearch (self, req_ldap = None, expected_fields = None ):
514         """
515         Used to search directly in LDAP, by using ldap filters and
516         return fields. 
517         When req_ldap is None, returns all the entries in the LDAP.
518       
519         """
520         result = self.conn.connect(bind = False)
521         if (result['bool']) :
522             
523             return_fields_list = []
524             if expected_fields == None : 
525                 return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
526             else : 
527                 return_fields_list = expected_fields
528             #No specifc request specified, gert the whole LDAP    
529             if req_ldap == None:
530                req_ldap = '(cn=*)'
531                
532             logger.debug("LDAP.PY \t LdapSearch  req_ldap %s \
533                             return_fields_list %s" %(req_ldap,return_fields_list))
534
535             try:
536                 msg_id = self.conn.ldapserv.search(
537                                             self.baseDN,ldap.SCOPE_SUBTREE,\
538                                             req_ldap,return_fields_list)     
539                 #Get all the results matching the search from ldap in one 
540                 #shot (1 value)
541                 result_type, result_data = \
542                                         self.conn.ldapserv.result(msg_id,1)
543
544                 self.conn.close()
545
546                 logger.debug("LDAP.PY \t LdapSearch  result_data %s"\
547                             %(result_data))
548
549                 return result_data
550             
551             except  ldap.LDAPError,e :
552                 logger.log_exc("LDAP LdapSearch Error %s" %e)
553                 return []
554             
555             else:
556                 logger.error("LDAP.PY \t Connection Failed" )
557                 return 
558             
559
560     def LdapFindUser(self,record = None, expected_fields = None):
561         """
562         Search a SFA user with a hrn. User should be already registered 
563         in Senslab LDAP. 
564         Returns one matching entry 
565         """   
566
567         req_ldap = self.make_ldap_filters_from_record(record) 
568         return_fields_list = []
569         if expected_fields == None : 
570             return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
571         else : 
572             return_fields_list = expected_fields
573             
574         result_data = self.LdapSearch(req_ldap,  return_fields_list )
575         logger.debug("LDAP.PY \t LdapFindUser  result_data %s" %(result_data))
576            
577         if len(result_data) is 0:
578             return None
579         #Asked for a specific user
580         if record :
581             #try:
582             ldapentry = result_data[0][1]
583             logger.debug("LDAP.PY \t LdapFindUser ldapentry %s" %(ldapentry))
584             tmpname = ldapentry['uid'][0]
585
586             tmpemail = ldapentry['mail'][0]
587             if ldapentry['mail'][0] == "unknown":
588                 tmpemail = None
589                     
590             #except IndexError: 
591                 #logger.error("LDAP ldapFindHRn : no entry for record %s found"\
592                             #%(record))
593                 #return None
594                 
595             try:
596                 hrn = record['hrn']
597                 parent_hrn = get_authority(hrn)
598                 peer_authority = None
599                 if parent_hrn is not self.authname:
600                     peer_authority = parent_hrn
601
602                 results =  {    
603                             'type': 'user',
604                             'pkey': ldapentry['sshPublicKey'][0],
605                             #'uid': ldapentry[1]['uid'][0],
606                             'uid': tmpname ,
607                             'email':tmpemail,
608                             #'email': ldapentry[1]['mail'][0],
609                             'first_name': ldapentry['givenName'][0],
610                             'last_name': ldapentry['sn'][0],
611                             #'phone': 'none',
612                             'serial': 'none',
613                             'authority': parent_hrn,
614                             'peer_authority': peer_authority,
615                             'pointer' : -1,
616                             'hrn': hrn,
617                             }
618             except KeyError,e:
619                 logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
620                                 %e )
621                 return
622         else:
623         #Asked for all users in ldap
624             results = []
625             for ldapentry in result_data:
626                 logger.debug(" LDAP.py LdapFindUser ldapentry name : %s " \
627                                 %(ldapentry[1]['uid'][0]))
628                 tmpname = ldapentry[1]['uid'][0]
629                 hrn=self.authname+"."+ tmpname
630                 
631                 tmpemail = ldapentry[1]['mail'][0]
632                 if ldapentry[1]['mail'][0] == "unknown":
633                     tmpemail = None
634
635         
636                 parent_hrn = get_authority(hrn)
637                 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
638                 try:
639                     results.append(  {  
640                             'type': 'user',
641                             'pkey': ldapentry[1]['sshPublicKey'][0],
642                             #'uid': ldapentry[1]['uid'][0],
643                             'uid': tmpname ,
644                             'email':tmpemail,
645                             #'email': ldapentry[1]['mail'][0],
646                             'first_name': ldapentry[1]['givenName'][0],
647                             'last_name': ldapentry[1]['sn'][0],
648                             #'phone': 'none',
649                             'serial': 'none',
650                             'authority': self.authname,
651                             'peer_authority': '',
652                             'pointer' : -1,
653                             'hrn': hrn,
654                             } ) 
655                 except KeyError,e:
656                     logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" %(e))
657                     return
658         return results   
659