Merge branch 'master' into senslab2
[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, error:
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         self.ldapPort = ldap.PORT
45         self.ldapVersion  = ldap.VERSION3
46         self.ldapSearchScope = ldap.SCOPE_SUBTREE
47
48
49     def connect(self, bind = True):
50         """Enables connection to the LDAP server.
51         Set the bind parameter to True if a bind is needed
52         (for add/modify/delete operations).
53         Set to False otherwise.
54         
55         """
56         try:
57             self.ldapserv = ldap.open(self.ldapHost)
58         except ldap.LDAPError, error:
59             return {'bool' : False, 'message' : error }
60         
61         # Bind with authentification
62         if(bind): 
63             return self.bind()
64         
65         else:     
66             return {'bool': True} 
67     
68     def bind(self):
69         """ Binding method. """
70         try:
71             # Opens a connection after a call to ldap.open in connect:
72             self.ldapserv = ldap.initialize("ldap://" + self.ldapHost)
73                 
74             # Bind/authenticate with a user with apropriate rights to add objects
75             self.ldapserv.simple_bind_s(self.ldapAdminDN, self.ldapAdminPassword)
76
77         except ldap.LDAPError, error:
78             return {'bool' : False, 'message' : error }
79
80         return {'bool': True}
81     
82     def close(self):
83         """ Close the LDAP connection """
84         try:
85             self.ldapserv.unbind_s()
86         except ldap.LDAPError, error:
87             return {'bool' : False, 'message' : error }
88             
89         
90 class LDAPapi :
91     def __init__(self):
92         logger.setLevelDebug() 
93         #SFA related config
94         self.senslabauth=Hierarchy()
95         config=Config()
96         
97         self.authname=config.SFA_REGISTRY_ROOT_AUTH
98
99         self.conn =  ldap_co() 
100         self.ldapUserQuotaNFS = self.conn.config.LDAP_USER_QUOTA_NFS 
101         self.ldapUserUidNumberMin = self.conn.config.LDAP_USER_UID_NUMBER_MIN 
102         self.ldapUserGidNumber = self.conn.config.LDAP_USER_GID_NUMBER 
103         self.ldapUserHomePath = self.conn.config.LDAP_USER_HOME_PATH 
104         
105         self.lengthPassword = 8
106         self.baseDN = self.conn.ldapPeopleDN
107         #authinfo=self.senslabauth.get_auth_info(self.authname)
108         
109         
110         self.charsPassword = [ '!','$','(',')','*','+',',','-','.',\
111                                 '0','1','2','3','4','5','6','7','8','9',\
112                                 'A','B','C','D','E','F','G','H','I','J',\
113                                 'K','L','M','N','O','P','Q','R','S','T',\
114                                 'U','V','W','X','Y','Z','_','a','b','c',\
115                                 'd','error','f','g','h','i','j','k','l','m',\
116                                 'n','o','p','q','r','s','t','u','v','w',\
117                                 'x','y','z','\'']
118         
119         self.ldapShell = '/bin/bash'
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         login_filter = '(uid=' + login + ')'
171         
172         try :
173             #Check if login already in use
174             while (len(self.LdapSearch(login_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                         login_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,error :
192             logger.log_exc("LDAP generate_login Error %s" %error)
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         length = len(self.charsPassword)
205         for index in range(self.lengthPassword):
206             char_index = random.randint(0,length-1)
207             password += self.charsPassword[char_index]
208
209         return password
210
211     def encrypt_password(self, password):
212         """ Use passlib library to make a RFC2307 LDAP encrypted password
213         salt size = 8, use sha-1 algorithm. Returns encrypted password.
214         
215         """
216         #Keep consistency with Java Senslab's LDAP API 
217         #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
218         return lssha.encrypt(password,salt_size = 8)
219     
220
221
222     def find_max_uidNumber(self):
223             
224         """Find the LDAP max uidNumber (POSIX uid attribute) .
225         Used when adding a new user in LDAP Directory 
226         returns string  max uidNumber + 1
227         
228         """
229         #First, get all the users in the LDAP
230         getAttrs = "(uidNumber=*)"
231         login_filter = ['uidNumber']
232
233         result_data = self.LdapSearch(getAttrs, login_filter) 
234         #It there is no user in LDAP yet, First LDAP user
235         if result_data == []:
236             max_uidnumber = self.ldapUserUidNumberMin
237         #Otherwise, get the highest uidNumber
238         else:
239             
240             uidNumberList = [int(r[1]['uidNumber'][0])for r in result_data ]
241             logger.debug("LDAPapi.py \tfind_max_uidNumber  \
242                                     uidNumberList %s " %(uidNumberList))
243             max_uidnumber = max(uidNumberList) + 1
244             
245         return str(max_uidnumber)
246          
247          
248     def get_ssh_pkey(self, record):
249         """TODO ; Get ssh public key from sfa record  
250         To be filled by N. Turro ? or using GID pl way?
251         
252         """
253         return 'A REMPLIR '
254
255     def make_ldap_filters_from_record(self, record=None):
256         """TODO Handle OR filtering in the ldap query when 
257         dealing with a list of records instead of doing a for loop in GetPersons   
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, error:
393                 logger.log_exc("LDAP Add Error %s" %error)
394                 return {'bool' : False, 'message' : error }
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, error:
415                 logger.log_exc("LDAP Delete Error %s" %error)
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, error:
449                 logger.log_exc("LDAP LdapModify Error %s" %error)
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,error :
552                 logger.log_exc("LDAP LdapSearch Error %s" %error)
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,error:
619                 logger.log_exc("LDAPapi \t LdaFindUser KEyError %s" \
620                                 %error )
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,error:
656                     logger.log_exc("LDAPapi.PY \t LdapFindUser EXCEPTION %s" %(error))
657                     return
658         return results   
659