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