Completion of the LDAP api.
[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 = "192.168.0.251"
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.ldapUserDN = 'uid=web,ou=Service,dc=senslab,dc=info';
37         self.ldapUserPassword = '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.login, self.passwd)
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         self.authname=config.SFA_REGISTRY_ROOT_AUTH
88         self.baseDN = "ou=people,dc=senslab,dc=info"
89         self.conn =  ldap_co()  
90         #authinfo=self.senslabauth.get_auth_info(self.authname)
91         
92         
93         self.charsPassword = [ '!','$','(',')','*','+',',','-','.',\
94                                 '0','1','2','3','4','5','6','7','8','9',\
95                                 'A','B','C','D','E','F','G','H','I','J',\
96                                 'K','L','M','N','O','P','Q','R','S','T',\
97                                 'U','V','W','X','Y','Z','_','a','b','c',\
98                                 'd','e','f','g','h','i','j','k','l','m',\
99                                 'n','o','p','q','r','s','t','u','v','w',\
100                                 'x','y','z','\'']
101         self.ldapUserQuotaNFS = '/dev/vdb:2000000:2500000:0:0'
102         self.lengthPassword = 8;
103         self.ldapUserHomePath = '/senslab/users/' 
104         self.ldapUserGidNumber = '2000'
105         self.ldapUserUidNumberMin = '2000' 
106         self.ldapShell = '/bin/bash'
107         #self.auth=Auth()
108         #gid=authinfo.get_gid_object()
109         #self.ldapdictlist = ['type',
110                         #'pkey',
111                         #'uid',
112                         #'serial',
113                         #'authority',
114                         #'peer_authority',
115                         #'pointer' ,
116                         #'hrn']
117           
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         filter = '(uid='+ login+ ')'
169         try :
170             #Check if login already in use
171             while (self.LdapSearch(filter, getAttrs) is not [] ):
172             
173                 index += 1
174                 if index >= 9:
175                     logger.error("LoginException : Generation login error \
176                                     with minimum four characters")
177                 else:
178                     try:
179                         login = lower_first_name[0,index] + \
180                                     lower_last_name[0,login_max_length-index]
181                         filter = '(uid='+ login+ ')'
182                     except KeyError:
183                         print "lower_first_name - lower_last_name too short"
184             return login
185                     
186         except  ldap.LDAPError,e :
187             logger.log_exc("LDAP generate_login Error %s" %e)
188
189         
190
191     def generate_password(self):
192     
193         """Generate password for adding a new user in LDAP Directory 
194         (8 characters length) return password
195         
196         """
197         password = str()
198         for index in range(self.lengthPassword):
199             password += self.charsPassword[random.randint(0, \
200                                             len(self.charsPassword))]
201
202         return password
203
204     def encrypt_password(self, password):
205        """ Use passlib library to make a RFC2307 LDAP encrypted password
206        salt size = 8, use sha-1 algorithm. Returns encrypted password.
207        
208        """
209        #Keep consistency with Java Senslab's LDAP API 
210        #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
211        return lssha.encrypt(password,salt_size = 8)
212     
213
214
215     def find_max_uidNumber(self):
216             
217         """Find the LDAP max uidNumber (POSIX uid attribute) .
218         Used when adding a new user in LDAP Directory 
219         returns string  max uidNumber + 1
220         
221         """
222         #First, get all the users in the LDAP
223         getAttrs = "(uidNumber=*)"
224         filter = ['uidNumber']
225
226         result_data = self.LdapSearch(getAttrs, filter) 
227         #It there is no user in LDAP yet, First LDAP user
228         if result_data == []:
229             max_uidnumber = self.ldapUserUidNumberMin
230         #Otherwise, get the highest uidNumber
231         else:
232             uidNumberList = [r[1]['uidNumber'] for r in result_data ]
233             max_uidnumber = max(uidNumberList) + 1
234             
235         return str(max_uidnumber)
236         
237     #TODO ; Get ssh public key from sfa record   
238     #To be filled by N. Turro                
239     def get_ssh_pkey(self, record):
240         return
241          
242          
243     #TODO Handle OR filtering in the ldap query when 
244     #dealing with a list of records instead of doing a for loop in GetPersons   
245     def make_ldap_filters_from_record(self, record=None):
246         """
247         Helper function to make LDAP filter requests out of SFA records.
248         """
249         req_ldapdict = {}
250         if record :
251             if 'first_name' in record  and 'last_name' in record:
252                 req_ldapdict['cn'] = str(record['first_name'])+" "\
253                                         + str(record['last_name'])
254             if 'email' in record :
255                 req_ldapdict['mail'] = record['email']
256             if 'mail' in record:
257                 req_ldapdict['mail'] = record['mail']
258                 
259             if 'hrn' in record :
260                 splited_hrn = record['hrn'].split(".")
261                 if splited_hrn[0] != self.authname :
262                     logger.warning(" \r\n LDAP.PY \
263                         make_ldap_filters_from_record I know nothing \
264                         about %s my authname is %s not %s" \
265                         %(record['hrn'], self.authname, splited_hrn[0]) )
266                         
267                 login=splited_hrn[1]
268                 req_ldapdict['uid'] = login
269             
270             req_ldap=''
271             logger.debug("\r\n \t LDAP.PY make_ldap_filters_from_record \
272                                 record %s req_ldapdict %s" \
273                                 %(record, req_ldapdict))
274             
275             for k in req_ldapdict:
276                 req_ldap += '('+str(k)+'='+str(req_ldapdict[k])+')'
277             if  len(req_ldapdict.keys()) >1 :
278                 req_ldap = req_ldap[:0]+"(&"+req_ldap[0:]
279                 size = len(req_ldap)
280                 req_ldap= req_ldap[:(size-1)] +')'+ req_ldap[(size-1):]
281         else:
282             req_ldap = "(cn=*)"
283         
284         return req_ldap
285         
286     def make_ldap_attributes_from_record(self, record):
287         """When addind a new user to Senslab's LDAP, creates an attributes 
288         dictionnary from the SFA record.
289         
290         """
291
292         attrs = {}
293         attrs['objectClass'] = ["top", "person", "inetOrgPerson",\
294                                     "organizationalPerson", "posixAccount",\
295                                     "shadowAccount", "systemQuotas",\
296                                     "ldapPublicKey"]
297         
298         attrs['givenName'] = str(record['first_name']).lower(),capitalize()
299         attrs['sn'] = str(record['last_name']).lower().capitalize()
300         attrs['cn'] = attrs['givenName'] + ' ' + attrs['sn']
301         attrs['gecos'] = attrs['givenName'] + ' ' + attrs['sn']
302         attrs['uid'] = self.generate_login(record)   
303                     
304         attrs['quota'] = self.ldapUserQuotaNFS 
305         attrs['homeDirectory'] = self.ldapUserHomePath + attrs['uid']
306         attrs['loginShell'] = self.ldapShell
307         attrs['gidNumber'] = '2000'     
308         attrs['uidNumber'] = self.find_max_uidNumber()
309         attrs['mail'] = record['mail'].lower()
310         
311         attrs['sshPublicKey'] = self.get_ssh_pkey(record) 
312         
313
314         #Password is automatically generated because SFA user don't go 
315         #through the Senslab website  used to register new users, 
316         #There is no place in SFA where users can enter such information
317         #yet.
318         #If the user wants to set his own password , he must go to the Senslab 
319         #website.
320         password = self.generate_password()
321         attrs['userPassword']= self.encrypt_password(password)
322         
323         #Account automatically validated (no mail request to admins)
324         #Set to 0 to disable the account, -1 to enable it,
325         attrs['shadowExpire'] = '-1'
326
327         #Motivation field in Senslab
328         attrs['description'] = 'SFA USER FROM OUTSIDE SENSLAB'
329         
330         attrs['ou'] = "SFA"         #Optional: organizational unit
331         #No info about those here:
332         attrs['l'] = ''             #Optional: Locality. 
333         attrs['st'] = ''            #Optional: state or province (country).
334
335         return attrs
336
337
338
339     def LdapAddUser(self, record = None) :
340         """Add SFA user to LDAP if it is not in LDAP  yet. """
341         
342         user_ldap_attrs = self.make_ldap_attributes_from_record(record)
343
344         
345         #Check if user already in LDAP wih email, first name and last name
346         filter_by = self.make_ldap_filters_from_record(user_ldap_attrs)
347         user_exist = self.LdapSearch(filter_by)
348         if user_exist:
349             logger.warning(" \r\n \t LDAP LdapAddUser user %s %s already exists" \
350                             %(user_ldap_attrs['sn'],user_ldap_attrs['mail'])) 
351             return {'bool': False}
352         
353         #Bind to the server
354         result = self.conn.connect()
355         
356         if(result['bool']):
357             
358             # A dict to help build the "body" of the object
359             
360             logger.debug(" \r\n \t LDAP LdapAddUser attrs %s " %user_ldap_attrs)
361
362             # The dn of our new entry/object
363             dn = 'uid=' + user_ldap_attrs['uid'] + "," + self.baseDN 
364
365             try:
366                 ldif = modlist.addModlist(user_ldap_attrs)
367                 logger.debug("\r\n \tLDAPapi.PY add attrs %s \r\n  ldif %s"\
368                                 %(user_ldap_attrs,ldif) )
369                 self.conn.ldapserv.add_s(dn,ldif)
370                 
371                 logger.info("Adding user %s login %s in LDAP" \
372                         %user_ldap_attrs['cn'] %user_ldap_attrs['uid'])
373                         
374                         
375             except ldap.LDAPError, e:
376                 logger.log_exc("LDAP Add Error %s" %e)
377                 return {'bool' : False, 'message' : e }
378         
379             self.conn.close()
380             return {'bool': True}  
381         else: 
382             return result
383
384         
385     def LdapDelete(self, person_dn):
386         """
387         Deletes a person in LDAP. Uses the dn of the user.
388         """
389         #Connect and bind   
390         result =  self.conn.connect()
391         if(result['bool']):
392             try:
393                 self.conn.ldapserv.delete_s(person_dn)
394                 self.conn.close()
395                 return {'bool': True}
396             
397             except ldap.LDAPError, e:
398                 logger.log_exc("LDAP Delete Error %s" %e)
399                 return {'bool': False}
400         
401     
402     def LdapDeleteUser(self, record_filter): 
403         """
404         Deletes a SFA person in LDAP, based on the user's hrn.
405         """
406         #Find uid of the  person 
407         person = self.LdapFindUser(record_filter)
408         
409         if person:
410             dn = 'uid=' + person['uid'] + "," +self.baseDN 
411         else:
412             return {'bool': False}
413         
414         result = self.LdapDelete(dn)
415         return result
416         
417
418     def LdapModify(self, dn, old_attributes_dict, new_attributes_dict): 
419         """ Modifies a LDAP entry """
420          
421         ldif = modlist.modifyModlist(old_attributes_dict,new_attributes)
422         # Connect and bind/authenticate    
423         result = self.conn.connect(bind) 
424         if (result['bool']): 
425             try:
426                 self.conn.ldapserver.modify_s(dn,ldif)
427                 self.conn.close()
428                 return {'bool' : True }
429             except ldap.LDAPError, e:
430                 logger.log_exc("LDAP LdapModify Error %s" %e)
431                 return {'bool' : False }
432     
433         
434     def LdapModifyUser(self, record_filter, new_attributes):
435         """
436         Gets the record from one user based on record_filter 
437         and changes the attributes according to the specified new_attributes.
438         Does not use this if we need to modify the uid. Use a ModRDN 
439         #operation instead ( modify relative DN )
440         """
441         if record_filter is None:
442             logger.error("LDAP \t LdapModifyUser Need record filter ")
443             return {'bool': False} 
444         
445         #Get all the attributes of the user 
446         person = self.LdapFindUser(record_filter,[])
447         if person and len(person) > 1 :
448             logger.error("LDAP \t LdapModifyUser Too many users returned")
449             return {'bool': False}
450         if person is None :
451             logger.error("LDAP \t LdapModifyUser  User %s doesn't exist "\
452                         %(record_filter['hrn']))
453             return {'bool': False} 
454         
455         # The dn of our existing entry/object
456         dn  = 'uid=' + person['uid'] + "," +self.baseDN  
457         if new_attributes_dict:
458             old = {}
459             for k in new_attributes:
460                 old[k] =  person[k]
461                 
462             result = self.LdapModify(dn, old,new_attributes)
463             return result
464         else:
465             logger.error("LDAP \t LdapModifyUser  No new attributes given. ")
466             return {'bool': False} 
467             
468             
469     def LdapResetPassword(self,record):
470         """
471         Resets password for the user whose record is the parameter and changes
472         the corresponding entry in the LDAP.
473         
474         """
475         password = self.generate_password()
476         attrs = {}
477         attrs['userPassword'] = self.encrypt_password(password)
478         logger.debug("LDAP LdapModifyUser Error %s" %e)
479         result = self.LdapModifyUser(record, attrs)
480         return result
481         
482
483     def LdapSearch (self, req_ldap = None, expected_fields = None ):
484         """
485         Used to search directly in LDAP, by using ldap filters and
486         return fields. 
487         When req_ldap is None, returns all the entries in the LDAP.
488         
489         """
490         result = self.conn.connect(bind = False)
491         if (result['bool']) :
492             
493             return_fields_list = []
494             if expected_fields == None : 
495                 return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
496             else : 
497                 return_fields_list = expected_fields
498   
499             logger.debug("LDAP.PY \t LdapSearch  req_ldap %s \
500                             return_fields_list %s" %(req_ldap,return_fields_list))
501
502             try:
503                 msg_id = self.conn.ldapserv.search(
504                                             self.baseDN,ldap.SCOPE_SUBTREE,\
505                                             req_ldap,return_fields_list)     
506                 #Get all the results matching the search from ldap in one 
507                 #shot (1 value)
508                 result_type, result_data = \
509                                         self.conn.ldapserv.result(msg_id,1)
510
511                 self.conn.close()
512
513                 logger.debug("LDAP.PY \t LdapSearch  result_data %s"\
514                             %(result_data))
515
516                 return result_data
517             
518             except  ldap.LDAPError,e :
519                 logger.log_exc("LDAP LdapSearch Error %s" %e)
520                 return []
521             
522             else:
523                 logger.error("LDAP.PY \t Connection Failed" )
524                 return 
525             
526
527     def LdapFindUser(self,record = None, expected_fields = None):
528         """
529         Search a SFA user with a hrn. User should be already registered 
530         in Senslab LDAP. 
531         Returns one matching entry 
532         """   
533
534         req_ldap = self.make_ldap_filters_from_record(record) 
535         return_fields_list = []
536         if expected_fields == None : 
537             return_fields_list = ['mail','givenName', 'sn', 'uid','sshPublicKey']
538         else : 
539             return_fields_list = expected_fields
540             
541         result_data = self.LdapSearch(req_ldap,  return_fields_list )
542         logger.debug("LDAP.PY \t LdapFindUser  result_data %s" %(result_data))
543            
544         if len(result_data) is 0:
545             return None
546         #Asked for a specific user
547         if record :
548             #try:
549             ldapentry = result_data[0][1]
550             logger.debug("LDAP.PY \t LdapFindUser ldapentry %s" %(ldapentry))
551             tmpname = ldapentry['uid'][0]
552
553             tmpemail = ldapentry['mail'][0]
554             if ldapentry['mail'][0] == "unknown":
555                 tmpemail = None
556                     
557             #except IndexError: 
558                 #logger.error("LDAP ldapFindHRn : no entry for record %s found"\
559                             #%(record))
560                 #return None
561                 
562             try:
563                 hrn = record['hrn']
564                 parent_hrn = get_authority(hrn)
565                 peer_authority = None
566                 if parent_hrn is not self.authname:
567                     peer_authority = parent_hrn
568
569                 results=  {     
570                             'type': 'user',
571                             'pkey': ldapentry['sshPublicKey'][0],
572                             #'uid': ldapentry[1]['uid'][0],
573                             'uid': tmpname ,
574                             'email':tmpemail,
575                             #'email': ldapentry[1]['mail'][0],
576                             'first_name': ldapentry['givenName'][0],
577                             'last_name': ldapentry['sn'][0],
578                             #'phone': 'none',
579                             'serial': 'none',
580                             'authority': parent_hrn,
581                             'peer_authority': peer_authority,
582                             'pointer' : -1,
583                             'hrn': hrn,
584                             }
585             except KeyError:
586                 lorrer.log_exc("LDAPapi \t LdapSearch KEyError results %s" \
587                                 %(results) )
588                 pass 
589         else:
590         #Asked for all users in ldap
591             results = []
592             for ldapentry in result_data:
593                 logger.debug(" LDAP.py LdapFindUser ldapentry name : %s " \
594                                 %(ldapentry[1]['uid'][0]))
595                 tmpname = ldapentry[1]['uid'][0]
596                 hrn=self.authname+"."+ tmpname
597                 
598                 tmpemail = ldapentry[1]['mail'][0]
599                 if ldapentry[1]['mail'][0] == "unknown":
600                     tmpemail = None
601
602         
603                 parent_hrn = get_authority(hrn)
604                 parent_auth_info = self.senslabauth.get_auth_info(parent_hrn)
605                 try:
606                     results.append(  {  
607                             'type': 'user',
608                             'pkey': ldapentry[1]['sshPublicKey'][0],
609                             #'uid': ldapentry[1]['uid'][0],
610                             'uid': tmpname ,
611                             'email':tmpemail,
612                             #'email': ldapentry[1]['mail'][0],
613                             'first_name': ldapentry[1]['givenName'][0],
614                             'last_name': ldapentry[1]['sn'][0],
615                             #'phone': 'none',
616                             'serial': 'none',
617                             'authority': self.authname,
618                             'peer_authority': '',
619                             'pointer' : -1,
620                             'hrn': hrn,
621                             } ) 
622                 except KeyError:
623                     pass
624         return results   
625