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