root/lib/octofuss/users/__init__.py @ a0262d65402e841ba795780fac249f10bda80490

Revision a0262d65402e841ba795780fac249f10bda80490, 106.2 KB (checked in by iacopo <iacopo@…>, 6 years ago)

Home directory backup and tar with new policy.
Security check do actions only if home dir starts with "/home"

git-svn-id:  https://labs.truelite.it/svn/octofuss/trunk@345 5a101938-5c21-0410-9b5a-a83d6f3706a9

  • Property mode set to 100644
Line 
1#!/usr/bin/env python
2# -*- coding: latin-1 -*-
3#
4#
5#  File: __init__.py
6#
7#  Copyright (C) 2007 Iacopo Pecchi <iacopo@truelite.it>
8#
9#  This program is free software; you can redistribute it and/or modify
10#  it under the terms of the GNU General Public License as published by
11#  the Free Software Foundation; either version 2 of the License, or
12#  (at your option) any later version.
13#
14
15
16import os
17#import subprocess
18import datetime
19import gtk
20from octofuss.error import UserError
21from octofuss.error import GroupError
22from octofuss.error import LdapError
23from octofuss.error import MissingPermission
24from octofuss.error import MissingConfigurationFile
25from octofuss.error import ConfigurationError
26
27from octofuss import ldap
28
29from octofuss.ldap import objectclass
30from octofuss.ldap.objectclass import *
31
32
33passwdfile="/etc/passwd"
34shadowfile="/etc/shadow"
35groupfile="/etc/group"
36startUnixUID = 3000
37startLdapUID = 20000
38supLimit = 40000
39
40class Entry:
41        #An  has some objectClass associated with him.
42        # First: add all objectClasses
43        def __init__(self):
44                """ Default constructor. Name is a string, Groups is a list of Group object """
45                self.objectClass = {}
46
47        def __addObjectClass(self, name, objectClass):
48                """ Add an object class to entry """
49                if not self.objectClass.has_key(name):
50                        self.objectClass[name] = objectClass
51                else:
52                        raise UserError("User objectClass already present!")
53
54        def getRequiredAttrs(self):
55                """ Return a dictionary of required attributes without repetitions """
56                req = {}       
57                for obj in self.objectClass.keys():
58                # For each objectClass
59                        for attr in self.objectClass[obj].getRequiredAttrs().values():
60                        # For each required attribute
61                                if not req.has_key(attr.getName()):
62                                        req[attr.getName()]=attr                               
63                return req
64
65        def getOptionalAttrs(self):
66                """ Return a dictionary of optional attributes without repetitions """
67                opt = {}       
68                for obj in self.objectClass:
69                # For each objectClass
70                        for attr in self.objectClass[obj].getOptionalAttrs().values():
71                        # For each required attribute
72                                if not opt.has_key(attr.getName()):
73                                        opt[attr.getName()]=attr                               
74                return opt
75
76
77        def setAttribute(self, key, value, check=True):
78                """ Set the value for the attribute for each objectClass (set the value for all repetitions) """
79                found = False
80                if isinstance(value, Attribute):
81                        #For each object class
82                        for objKey in self.objectClass.keys():
83                                # If key found
84                                if key in self.objectClass[objKey].required.keys():
85                                        found = True
86                                        self.objectClass[objKey].required[key] = value
87                                if key in self.objectClass[objKey].optional.keys():
88                                        found = True
89                                        self.objectClass[objKey].optional[key] = value
90
91                        if not found:
92                                raise UserError("Could not set user attribute: object class key not found")
93                else:
94                        if isinstance(value, str):
95                                #For each object class
96                                for objKey in self.objectClass.keys():
97                                        # If key found
98                                        if key in self.objectClass[objKey].required.keys():
99                                                found = True
100                                                self.objectClass[objKey].required[key].setValue(value,check)
101                                        if key in self.objectClass[objKey].optional.keys():
102                                                found = True
103                                                self.objectClass[objKey].optional[key].setValue(value,check)
104                                if not found:
105                                        raise UserError("Could not set user attribute: object class key not found")
106                        else:
107                                raise UserError("Value is not a valid attribute!")
108                                         
109
110        def getAttribute(self, key):
111                """ Get the value of an attribute """
112                values = []
113                # For each objectClass
114                for obj in self.objectClass.keys(): 
115                        if self.objectClass[obj].required.has_key(key):
116                                values.append(self.objectClass[obj].required[key])
117                        if self.objectClass[obj].optional.has_key(key):
118                                values.append(self.objectClass[obj].optional[key])
119                #print "\nVal: ", values[0]
120                return values[0] 
121
122        def getDict(self):
123                """ Return user in a dict. This is used during inserting user in ldap """
124                dictionary = {}
125                for obj in self.objectClass.keys():
126                        for attr in self.objectClass[obj].required.keys():
127                                if self.objectClass[obj].required[attr].getValue():
128                                        dictionary[attr] =  self.objectClass[obj].required[attr].getValue() 
129
130                        for attr in self.objectClass[obj].optional.keys():
131                                if self.objectClass[obj].optional[attr].getValue():
132                                        dictionary[attr] =  self.objectClass[obj].optional[attr].getValue() 
133                dictionary['objectClass'] = self.objectClass.keys()
134               
135                return dictionary
136
137        def getDictLdapForm(self):
138                """ Return user in a dict. This is used during inserting user in ldap """
139                dictionary = {}
140                for obj in self.objectClass.keys():
141                        for attr in self.objectClass[obj].required.keys():
142                                if self.objectClass[obj].required[attr].getValue():
143                                        if type( self.objectClass[obj].required[attr].getValue()) == list:
144                                                dictionary[attr] =  self.objectClass[obj].required[attr].getValue() 
145                                        else:
146                                                dictionary[attr] =  [self.objectClass[obj].required[attr].getValue()] 
147
148
149                        for attr in self.objectClass[obj].optional.keys():
150                                if self.objectClass[obj].optional[attr].getValue():
151                                        if type(self.objectClass[obj].optional[attr].getValue()) == list:
152                                                dictionary[attr] =  self.objectClass[obj].optional[attr].getValue() 
153                                        else:
154                                                dictionary[attr] = [self.objectClass[obj].optional[attr].getValue()]
155 
156                dictionary['objectClass'] = self.objectClass.keys()
157               
158                return dictionary
159
160        def check(self):
161                """ Check every attribute of each object class """
162                for objClass in self.objectClass.keys():        # Each object class
163                        for attr in self.objectClass[objClass].required.keys():  # Each required attribute
164                                if not self.objectClass[objClass].required[attr].check():
165                                        print "REQ: "+ attr
166                                        print  self.objectClass[objClass].required[attr].getValue()
167                                        return False
168       
169                        for attr in self.objectClass[objClass].optional.keys():  # Each optional attribute
170                                if self.objectClass[objClass].optional[attr].getValue():
171                                        if not self.objectClass[objClass].optional[attr].check() and isSettable():
172                                                print "OPT: " +attr
173                                                print self.objectClass[objClass].optional[attr].getValue()
174                                                return False
175                                       
176                return True
177
178                               
179                               
180                                 
181
182
183
184                                       
185         
186class UnixUser(Entry):
187        def __init__(self):
188                Entry.__init__(self)
189                self.objectClass['posixAccount'] = objectclass.PosixAccount()
190
191        def getName(self):
192                return self.objectClass['posixAccount'].getAttribute('cn')
193
194        def getPassword(self):
195                return self.objectClass['posixAccount'].getAttribute('userPassword')
196               
197        def getUid(self):
198                return self.objectClass['posixAccount'].getAttribute('uid')
199
200        def getUidNumber(self):
201                return self.objectClass['posixAccount'].getAttribute('uidNumber')
202
203        def getGid(self):
204                return self.objectClass['posixAccount'].getAttribute('gidNumber')
205
206        def getGecos(self):
207                return self.objectClass['posixAccount'].getAttribute('gecos')
208
209        def getHome(self):
210                return self.objectClass['posixAccount'].getAttribute('homeDirectory')
211
212        def getShell(self):
213                return self.objectClass['posixAccount'].getAttribute('loginShell')
214
215        def getAttribute(self, objectClass, attribute):
216                """ Return attribute's value if attribute exists. """
217                try:   
218                       return self.objectClass[objectClass].getAttribute(attribute)
219                except:
220                       return None
221
222
223       
224class LdapUser(UnixUser):
225        def __init__(self,objectClassList=None):
226                UnixUser.__init__(self)
227                self.objectClass['top'] = objectclass.Top()
228                if objectClassList != None:
229                        for obj in objectClassList:
230                                if obj == 'inetOrgPerson':
231                                        self.objectClass['inetOrgPerson'] = objectclass.InetOrgPerson()
232                                if obj == 'shadowAccount':
233                                        self.objectClass['shadowAccount'] = objectclass.ShadowAccount()
234                                if obj == 'sambaSamAccount':
235                                        self.objectClass['sambaSamAccount'] = objectclass.SambaSamAccount()
236
237
238class UnixGroup(Entry):
239        def __init__(self):
240                Entry.__init__(self)
241                self.objectClass['posixGroup'] = objectclass.PosixGroup()
242
243        def getName(self):
244                return self.objectClass['posixGroup'].getAttribute('cn')
245
246        def getGid(self):
247                return self.objectClass['posixGroup'].getAttribute('gidNumber')               
248
249        def getUsersList(self):
250                return self.objectClass['posixGroup'].getAttribute('memberUid')
251
252        def setUserList(self, userlist):
253                """ Set memberUid attribute to userlist """
254                if isinstance(userlist, list):
255                        self.objectClass['posixGroup'].getAttribute('memberUid').setValue(userlist)
256                else:
257                        raise GroupError("Argument is not a list")
258
259        def hasUser(self, userName):
260                """ Returns true if group contains username """
261                if userName and isinstance(userName, str):
262                        if userName in self.objectClass['posixGroup'].getAttribute("memberUid").getValue():
263                                return True
264                        else:
265                                return False
266                else:
267                        raise UserError("Invalid username argument")
268       
269               
270
271        def addUser(self, user):
272                if isinstance(user, str):
273                        if not self.hasUser(user):
274                                self.objectClass['posixGroup'].getAttribute('memberUid').setValue(user)
275                else:
276                        raise GroupError("Argument is not a list")
277
278               
279
280       
281        def removeUser(self,userName):
282                """ Remove user from memberUid attribute list """
283                if userName and isinstance(userName, str):
284                        userlist = self.objectClass['posixGroup'].getAttribute('memberUid').getValue() 
285                        if userName in userlist:
286                                ind = userlist.index(userName)
287                                del(userlist[ind])
288                                self.setUserList(userlist)
289                        else:
290                                raise UserError("User not in group")
291                else:
292                        raise UserError("Not a valid username")
293               
294
295
296class LdapGroup(UnixGroup):
297        def __init__(self,objectClassList = None):
298                UnixGroup.__init__(self)
299                self.objectClass['top'] = objectclass.Top()
300                #self.objectClass['sambaGroupMapping'] =  objectclass.SambaGroupMapping()
301                if objectClassList != None:
302                        for obj in objectClassList:
303                                if obj == "sambaGroupMapping":
304                                        self.objectClass[obj] =  objectclass.SambaGroupMapping()
305                                if obj == "groupOfNames":
306                                        self.objectClass[obj] = objectclass.GroupOfNames()
307                                #if obj == "top":
308                                #        self.objectClass[obj] = objectClass.Top()
309
310
311
312
313
314def __groups():
315        """ Creates group list """
316        groupList = {}
317        data = os.popen("cat "+groupfile,"r").readlines()
318        for line in data:
319                groupName,password,gid,usersString = line.strip().split(":")
320                if usersString == "":
321                        users = []
322                else: 
323                        users = usersString.split(",")
324                group = UnixGroup()
325                group.setAttribute("cn",groupName)
326                group.setAttribute("gidNumber",gid)
327                for us in users: 
328                        group.setAttribute("memberUid",us)
329
330                if groupList.has_key(group.getName().getValue()):
331                        raise GroupError("Duplicate group in unix group file")
332
333                groupList[groupName]=group
334                #print "Unix group: ", group.getAttribute("cn").getValue(),  group.getAttribute("userPassword").getValue(),  group.getAttribute("gidNumber").getValue(),group.getAttribute("memberUid").getValue()
335
336
337
338        return groupList
339
340
341def __ldap_group():
342        """ Create ldap groups """ 
343        global grouplist
344        list = ldap.search(filter="(objectClass=posixGroup)", findattr=[])
345        objectList = {}
346        for group in list:
347                try:
348                        #TODO: guardare a quale object class appartiene il gruppo e passarla all'oggetto ldapgroup
349                        obj = group[0][1]['objectClass']
350                        ldapgroup = LdapGroup(obj)
351                        req = ldapgroup.getRequiredAttrs()
352                        opt = ldapgroup.getOptionalAttrs()
353
354                        # Insert required attributes
355                        for param in req.keys():
356                                try:
357                                        # The value of param could is a list. We have to decide when attribute is multiple.
358                                        if isinstance(req[param], ListAttribute):
359                                                value = group[0][1][param]                                       
360                                                for elem in value:
361                                                        ldapgroup.setAttribute(param,elem)
362
363                                        else:
364                                                value = group[0][1][param][0]                                       
365                                                ldapgroup.setAttribute(param,value)
366
367                                except Exception, e:
368                                        print e
369                                        raise GroupError("Could not add ldap group: required attribute missing!")
370
371                        # Insert optional attributes
372                        attrs_missing = []
373                        for param in opt.keys():
374                                try:
375                                        # The value of param could is a list. We have to decide when attribute is multiple.
376                                        if isinstance(opt[param], ListAttribute):
377                                                value = group[0][1][param]                                       
378                                                for elem in value:
379                                                        ldapgroup.setAttribute(param,elem)
380
381                                        else:
382                                                value = group[0][1][param][0]                                       
383                                                ldapgroup.setAttribute(param,value)
384
385                                except:
386                                        attrs_missing.append(param)
387                                        #print "Attribute %s not found"  % param
388
389                        #print "Ldap Group added: ", ldapgroup.getName().getValue()
390
391                except GroupError, e:
392                        print e
393                        try:
394                                p = ""
395                                for i in attrs_missing: p = p +" "+ i
396                                print "Group  not  added: option missing:\n"+p
397
398                        except:
399                                print "eccezione"
400                                pass
401                        continue
402                except NameError,e:
403                        print e
404                        print "Group not added: empty name"
405                        continue 
406                       
407                if grouplist.has_key(ldapgroup.getName().getValue()):
408                        print "Ldap group "+ldapgroup.getName().getValue()+" already present in system groups."
409                        continue 
410                if objectList.has_key(ldapgroup.getName().getValue()):
411                        raise GroupError("Duplicate group name in ldap server")
412
413                # add user to list
414                objectList[ldapgroup.getName().getValue()]=ldapgroup
415 
416                 
417        return objectList
418
419
420
421def __ldap_user():
422        # Manca da convertire l'assegnazione dei parametri come viene fatto nella funzione di creazione gruppi ldap.
423        list = ldap.search(filter="(uid=*)", findattr=[])
424
425        objectList = {} 
426        # Parsing the list and create users object
427        for user in list:
428                #print user,"\n"
429                try:
430                        #TODO: guardare a quale object class appartiene l'utente e passarla all'oggetto ldapuser
431                        #print user[0][1]['objectClass']
432                        obj = user[0][1]['objectClass']
433
434                        ldapuser = LdapUser(obj)
435                        req = ldapuser.getRequiredAttrs()
436                        opt = ldapuser.getOptionalAttrs()
437
438
439                        # Insert required attributes
440                        for param in req.keys():
441                                try:
442                                        # The value of param could is a list. We have to decide when attribute is multiple.
443                                        if isinstance(req[param], ListAttribute):
444                                                value = user[0][1][param]                                       
445                                                for elem in value:
446                                                        ldapuser.setAttribute(param,elem)
447
448                                        else:
449                                                value = user[0][1][param][0]                                       
450                                                ldapuser.setAttribute(param,value)
451
452                                except Exception,e:
453                                        raise UserError(str(e))
454                                       
455
456                        # Insert optional attributes
457                        for param in opt.keys():
458                                try:
459                                        # The value of param could is a list. We have to decide when attribute is multiple.
460                                        if isinstance(opt[param], ListAttribute):
461                                                value = user[0][1][param]                                       
462                                                for elem in value:
463                                                        ldapuser.setAttribute(param,elem)
464
465                                        else:
466                                                value = user[0][1][param][0]                                       
467                                                ldapuser.setAttribute(param,value)
468
469                                except:
470                                        pass
471                                        #print "Attribute %s not found"  % param
472
473                        #print "Ldap User added: ", ldapuser.getName().getValue()
474
475                except UserError, e:
476                        print "Warning: User '"+ldapuser.getUid().getValue()+"' not added. Option missing: "+str(e)
477                        continue
478                except NameError, e:
479                        print e
480                        print "User not added: empty name"
481                        continue 
482
483                # add user to list
484                if objectList.has_key(ldapuser.getName().getValue()):
485                        raise UserError("Incongruous ldap tree\nDuplicate user name in ldap server: "+ldapuser.getName().getValue())
486                objectList[ldapuser.getName().getValue()]=ldapuser
487 
488                 
489        return objectList
490
491 
492def showDialog(message, type):
493        dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,type, gtk.BUTTONS_OK, message)
494        dialog.run()
495        dialog.destroy()   
496       
497
498
499def __local():
500        """ Create unix user list """
501        global grouplist
502        global passwdfile
503        userlist = {}
504        data = os.popen("cat "+passwdfile,"r").readlines()
505        for line in data:
506                #User groups
507                found = False
508                username,password,uid,gid,gecos,home,shell = line.strip().split(":")
509
510                user = UnixUser()
511                # Setting user attributes
512                user.setAttribute("cn",username)
513                #user.setAttribute("userPassword",password)
514                user.setAttribute("homeDirectory",home)
515                user.setAttribute("loginShell",shell)
516                user.setAttribute("gecos",gecos)       
517                user.setAttribute("gidNumber",gid)   
518                user.setAttribute("uidNumber",uid)       
519                # Set uidNumber to username
520                user.setAttribute("uid",username)       
521   
522
523
524
525                if userlist.has_key(user.getName().getValue()):
526                        raise UserError("Duplicate user in unix user file")
527                userlist[user.getName().getValue()]= user
528                #print "Unix user: ", user.getAttribute("cn").getValue(),  user.getAttribute("userPassword").getValue(), user.getAttribute("uidNumber").getValue(), user.getAttribute("gidNumber").getValue() , user.getAttribute("gecos").getValue(),  user.getAttribute("homeDirectory").getValue(),user.getAttribute("loginShell").getValue()
529
530
531        return userlist
532
533if not (os.access(passwdfile,os.F_OK)):
534        raise MissingConfigurationFile("Missing configuration file!")
535#if not (os.access(shadowfile,os.F_OK)):
536#        raise MissingConfigurationFile("Missing configuration file!")
537if not (os.access(groupfile,os.F_OK)):
538        raise MissingConfigurationFile("Missing configuration file!")
539
540"""
541if not (os.access(passwdfile,os.R_OK) and os.access(passwdfile,os.W_OK)):
542        raise MissingPermission("Missing permissions on configuration file!")
543
544if not (os.access(shadowfile,os.R_OK) and os.access(shadowfile,os.W_OK)):
545        raise MissingPermission("Missing permissions on configuration file!")
546
547if not (os.access(groupfile,os.R_OK) and os.access(groupfile,os.W_OK)):
548        raise MissingPermission("Missing permissions on configuration file!")
549"""
550
551def __getCurrentId():
552        """ Return the id of the octofuss user """
553        out = os.popen("id -u")
554        id = out.read()
555        res = int(id)
556
557        #out = subprocess.Popen("id -u", stdout=subprocess.PIPE, shell=True )
558        #res = int(out.communicate()[0])
559        return res
560
561
562if not __getCurrentId() == 0:
563        raise MissingPermission("Missing permission to manage users")
564# First = create UNIX groups
565grouplist =  __groups()
566# Second = create LDAP groups
567ldapgrouplist = __ldap_group()
568#Third = create LDAP users
569ldaplist = __ldap_user()
570#Fourth = create UNIX users
571locallist =  __local()
572
573
574def updateMainGroup():
575        """ Add user name to memberUid of local group because main group is never added before """
576        global locallist
577        global grouplist
578        for user in locallist:
579                gid = locallist[user].getGid().getValue()
580                for group in  grouplist.keys():
581                        if gid ==  grouplist[group].getGid().getValue():
582                                #Adding main group to group list
583                                grouplist[group].setAttribute("memberUid",locallist[user].getName().getValue())                 
584
585
586updateMainGroup()
587
588
589
590class  InheritableSingleton (object):
591    instances = {}
592
593    def __new__(cls, *args, **kargs): 
594        """ Singleton that create a user and a group list """
595        if InheritableSingleton.instances.get(cls) is None:
596                InheritableSingleton.instances[cls] = object.__new__(cls, *args, **kargs)
597                global grouplist     
598                global locallist
599                global ldaplist
600                global ldapgrouplist
601                InheritableSingleton.instances["groupList"]=  grouplist
602                InheritableSingleton.instances["ldapGroupList"]=  ldapgrouplist
603                InheritableSingleton.instances["ldapList"]= ldaplist
604                InheritableSingleton.instances["unixList"]= locallist
605
606               
607
608
609        return InheritableSingleton.instances[cls]
610                       
611
612class Backend(InheritableSingleton):
613               
614        global passwdfile
615        global shadowfile
616        global groupfile
617        ldapUid = startLdapUID
618        ldapMaxUid = supLimit
619        def groupsByUser(self, username):
620                """ Search all groups of username """
621                if self.isUser(username):
622
623                        groups = []
624                        # Unix groups
625                        for group in InheritableSingleton.instances['groupList'].keys():
626                                if username in InheritableSingleton.instances['groupList'][group].getUsersList().getValue():
627                                        groups.append(group)
628                        # Ldap groups
629                        for group in InheritableSingleton.instances['ldapGroupList'].keys():
630                                if username in InheritableSingleton.instances['ldapGroupList'][group].getUsersList().getValue():
631                                        groups.append(group)
632                        #We must add if is not already present "main user group"
633                        #print self.getUser(username).getName().getValue()
634                        #print self.getUser(username).getGid().getValue()
635
636                        mainGroupName = self.getGroupByGid(self.getUser(username).getGid().getValue()).getName().getValue()
637                        if mainGroupName:
638                                if not mainGroupName in groups:
639                                        groups.append(mainGroupName)
640                       
641                        return groups
642                               
643                else:
644                        raise UserError("User doesn't exist!")
645
646        def usersByGroup(self,groupname):
647                """ Search all users of group """
648                group = self.getGroup(groupname)
649                return group.getUsersList().getValue()
650       
651        def getUsersList(self):
652                """ Print a sorted list of users """
653                list = []
654                list = InheritableSingleton.instances['unixList'].keys() +  InheritableSingleton.instances['ldapList'].keys() 
655
656                list.sort()
657                return list
658                       
659
660        def getLdapUsers(self):
661                """ Print a sorted list of ldap users """
662                list = []
663                list =  InheritableSingleton.instances['ldapList'].keys() 
664                list.sort()
665                return list
666
667        def getUnixUsers(self):
668                """ Print a sorted list of unix users """
669                list = []
670                list = InheritableSingleton.instances['unixList'].keys() 
671                list.sort()
672                return list
673
674        def getGroupsList(self):
675                """ Print a sorted list of groups """
676                list = []
677                list = InheritableSingleton.instances['groupList'].keys() +  InheritableSingleton.instances['ldapGroupList'].keys() 
678                list.sort()
679                return list
680
681
682        def getLdapGroups(self):
683                """ Print a sorted list of ldap groups """
684                list = []
685                list =  InheritableSingleton.instances['ldapGroupList'].keys() 
686                list.sort()
687                return list
688
689
690        def getUnixGroups(self):
691                """ Print a sorted list of unix groups """
692                list = []
693                list = InheritableSingleton.instances['groupList'].keys() 
694                list.sort()
695                return list
696
697        def isUnixUser(self,username):
698                """ Returns true if username user exists """
699                if username in InheritableSingleton.instances['unixList'].keys():
700                        return True
701                else:
702                        return False
703
704        def isLdapUser(self,username):
705                """ Returns true if username user exists """
706                if username in InheritableSingleton.instances['ldapList'].keys():
707                        return True
708                else:
709                        return False
710
711        def isUnixGroup(self,groupname):
712                """ Returns true if username user exists """
713                if groupname in InheritableSingleton.instances['groupList'].keys():
714                        return True
715                else:
716                        return False
717
718        def isLdapGroup(self,groupname):
719                """ Returns true if username user exists """
720                if groupname in InheritableSingleton.instances['ldapGroupList'].keys():
721                        return True
722                else:
723                        return False
724
725
726
727        def isUser(self, username):
728                """ Returns true if username user exists """
729                if username in InheritableSingleton.instances['unixList'].keys() or username in InheritableSingleton.instances['ldapList'].keys():
730                        return True
731                else:
732                        return False
733
734        def isGroup(self, groupname):
735                """ Returns if groupname group exists """
736                if groupname in InheritableSingleton.instances['groupList'].keys() or groupname in InheritableSingleton.instances['ldapGroupList'].keys():
737                        return True
738                else:
739                        return False
740
741        def getUser(self, username):               
742                """ Returns UnixUser or LdapUser from given username """
743                if self.isUser(username):
744                        for user in  InheritableSingleton.instances['unixList'].keys():
745                                if username == user:
746                                        return InheritableSingleton.instances['unixList'][username]
747
748                        for user in InheritableSingleton.instances['ldapList']:
749                                if username == user:
750                                        return InheritableSingleton.instances['ldapList'][username]
751                else:
752                        raise UserError("User doesn't exist!")
753
754        def getGroup(self, groupname):
755                """ Returns UnixGroup or LdapGroup from given groupname """
756                if self.isGroup(groupname):
757                        for group in  InheritableSingleton.instances['groupList'].keys():
758                                if groupname == group:
759                                        return InheritableSingleton.instances['groupList'][groupname]
760
761                        for group in InheritableSingleton.instances['ldapGroupList']:
762                                if groupname == group:
763                                        return InheritableSingleton.instances['ldapGroupList'][groupname]
764                else:
765                        raise GroupError("Group doesn't exist!")
766
767        def getGroupByGid(self, gid):
768                """ Returns group by gid=groupId """
769                for group in  InheritableSingleton.instances['groupList'].keys():
770                        if gid ==  InheritableSingleton.instances['groupList'][group].getGid().getValue():
771                                return InheritableSingleton.instances['groupList'][group]
772
773                for group in  InheritableSingleton.instances['ldapGroupList'].keys():
774                        if gid ==  InheritableSingleton.instances['ldapGroupList'][group].getGid().getValue():
775                                return InheritableSingleton.instances['ldapGroupList'][group]
776
777                raise GroupError("Given gid doesn't exist!")
778       
779
780        # Promemoria da cancellare
781        # Seguono dei metodi privati che aggiungono, modificano, cancellano utenti e gruppi Unix utilizzando
782        # i binari useradd, userdel, usermod e groupadd, groupdel, groupmod
783        # Questi metodi non aggiornano la lista di oggetti in memoria e non creano le home directory degli utenti
784       
785        def __addUnixGroup(self, groupname, gid="" ):
786                """ Add  a unix group to local system """ 
787                """ This method use groupadd. groupadd doesn't add users to /etc/group """
788                if gid:
789                        #p = subprocess.Popen("groupadd" + " -g "+ gid +" "+groupname , shell=True)
790                        sts = os.system("groupadd" + " -g " + gid +" "+groupname)
791                        if sts != 0:
792                        #sts = os.waitpid(p.pid, 0)
793                        #if sts[1] != 0:
794                                raise GroupError("Problems adding group!")
795                else:
796                        #p = subprocess.Popen("groupadd" +" "+groupname , shell=True)
797                        sts = os.system("groupadd" +" "+groupname)
798                        if sts != 0:
799                        #sts = os.waitpid(p.pid, 0)
800                        #if sts[1] != 0:
801                                raise GroupError("Problems adding group!")
802
803        def __deleteUnixGroup(self, groupname):
804                """ Remove group from local system """
805                sts = os.system("groupdel" +" "+groupname)
806                if sts != 0:
807                #p = subprocess.Popen("groupdel " + groupname , shell=True)
808                #sts = os.waitpid(p.pid, 0)
809                #if sts[1] != 0:
810                        raise GroupError("Problems deleteing group!") 
811
812        def __modifyUnixGroup(self, oldname, newname):
813                """ Modify the name of group  """
814                sts = os.system("groupmod" +" -n "+newname+" "+oldname)
815                if sts != 0:
816                #p = subprocess.Popen("groupmod" +" -n "+newname+" "+oldname, shell=True)
817                #sts = os.waitpid(p.pid, 0)
818                #if sts[1] != 0:
819                        raise GroupError("Problems modifying group!")
820
821               
822               
823       
824        def __addUnixUser(self, username, password, home="", uid="",  gid="", shell="/bin/sh", grouplist=[]):
825                """ Add unix user """
826                useradd = "useradd "
827                string  = "" 
828               
829                 
830                if username and password:
831                       
832                        string = username+":"+password+"\n" 
833                       
834                        if home:
835                                useradd = useradd + " -d " + home + " "
836                        else:
837                                useradd = useradd + " -d " + "/nonexistent" + " "
838
839                        useradd = useradd + " -s " + shell + " "
840
841                        if gid:
842                                useradd = useradd + " -g "+ gid + " "
843
844                        if uid:
845                                useradd = useradd + " -u "+ uid + " "
846
847                        groups = ""
848                        if len(grouplist) > 0:
849                                for a in grouplist:
850                                       groups = groups + a+"," 
851                                groups = groups.strip(",")
852                                useradd = useradd + " -G "+ groups + " "
853                        useradd = useradd + username
854                        print useradd
855                        sts = os.system(useradd)
856                        if sts != 0:
857                        #p = subprocess.Popen(useradd, shell=True)
858                        #sts = os.waitpid(p.pid, 0)               
859                        #if sts[1] != 0:
860                                print "Removing user..."
861                                os.system("userdel "+username)
862                                raise UserError("Problem adding user!")
863                else:
864                        raise UserError("Username or password not valid!")
865                       
866                p = os.popen("chpasswd",'w') 
867                p.write(string)
868                p.close()
869                #p = subprocess.Popen("chpasswd",shell=True, stdin=subprocess.PIPE).communicate(input=string)
870                #print p
871               
872               
873                 
874
875        def createHomeDirectory(self, name, uid, gid, path="/home"):
876                """ Create home directory with owner and group """
877                # Check if home already exists
878                if name:
879                        dir = os.path.join(path,name)
880                        if not os.path.isdir(dir):
881                                #os.mkdir(dir)
882                                os.system("/bin/cp -a /etc/skel "+dir)
883                                os.chown(dir, int(uid), int(gid))
884                                os.system("chown -R "+uid+"."+gid+" "+dir)
885                                os.chmod(dir,0700)
886                               
887                        else:
888                                raise UserError("Home directory "+dir+" already exists!")
889                else:
890                        raise UserError("Directory  must be not null!")
891
892
893
894        def getNewUnixID(self):
895                """ Get a new unix id returning max of ID + 1. Check Unix and Ldap users ID """       
896                # Inferior limit of Unix UID
897                global startUnixUID
898                # Inferior limit of Ldap UID
899                global startLdapUID
900
901                all = []               
902                # ALL = UnixUID + LdapUID
903                for unixUser in  InheritableSingleton.instances["unixList"].keys():
904                        uid =  int(InheritableSingleton.instances["unixList"][unixUser].getUidNumber().getValue())
905                        if uid < startLdapUID:
906                                all.append(int(uid))
907
908                for ldapUser in  InheritableSingleton.instances["ldapList"].keys():
909                        uid =  int(InheritableSingleton.instances["ldapList"][ldapUser].getUidNumber().getValue())
910                        if uid < startLdapUID:
911                                all.append(int(uid))
912
913                for unixGroup in  InheritableSingleton.instances["groupList"].keys():
914                        uid =  int(InheritableSingleton.instances["groupList"][unixGroup].getGid().getValue())
915                        if uid < startLdapUID:
916                                all.append(int(uid))
917
918                for ldapGroup in  InheritableSingleton.instances["ldapGroupList"].keys():
919                        uid =  int(InheritableSingleton.instances["ldapGroupList"][ldapGroup].getGid().getValue())
920                        if uid < startLdapUID:
921                                all.append(int(uid))
922                       
923
924                # NewUID = MAX(ALL) + 1
925                if all:
926                        newUid = max(all) + 1
927                else:
928                        newUid = 1 
929               
930                # If NewUID < Inf Unix   =>   NewUID = Inf Unix
931                if newUid < startUnixUID:
932                        newUid = startUnixUID
933
934                # If NewUID > Inf Ldap   =>   End of possible values! CHANGE USERS RANGE
935                if newUid >= startLdapUID:
936                        raise ConfigurationError("No more UID available. Check range!")
937
938       
939                # Return NewUID
940                return newUid
941
942
943
944        def getNewLdapID(self):
945                """ Get a new unix id returning max of ID + 1. Check Unix and Ldap users ID """       
946                # Inferior limit of Unix UID
947                global startUnixUID
948                # Inferior limit of Ldap UID
949                global startLdapUID
950                maxLimit = supLimit # Set to avoid nobody user with id > 60000
951                all = []               
952                # ALL = UnixUID + LdapUID
953                for unixUser in  InheritableSingleton.instances["unixList"].keys():
954                        uid =   int(InheritableSingleton.instances["unixList"][unixUser].getUidNumber().getValue())
955                        if uid >= startLdapUID and uid < maxLimit:
956                                all.append(int(uid))
957
958                for ldapUser in  InheritableSingleton.instances["ldapList"].keys():
959                        uid =   int(InheritableSingleton.instances["ldapList"][ldapUser].getUidNumber().getValue())
960                        if uid >= startLdapUID and uid < maxLimit:
961                                all.append(int(uid))
962
963
964                for unixGroup in  InheritableSingleton.instances["groupList"].keys():
965                        uid =  int(InheritableSingleton.instances["groupList"][unixGroup].getGid().getValue())
966                        if uid >= startLdapUID and uid < maxLimit:
967                                all.append(int(uid))
968
969
970
971                for ldapGroup in  InheritableSingleton.instances["ldapGroupList"].keys():
972                        uid =  int(InheritableSingleton.instances["ldapGroupList"][ldapGroup].getGid().getValue())
973                        if uid >= startLdapUID and uid < maxLimit:
974                                all.append(int(uid))
975
976
977
978
979                if all:
980                        # NewUID = MAX(ALL) + 1
981                        newUid = max(all) + 1
982                else:
983                        newUid = 1
984               
985                # If NewUID < Inf Unix   =>   NewUID = Inf Unix
986                if newUid < startLdapUID:
987                        newUid = startLdapUID
988
989                # If NewUID > Inf Ldap   =>   End of possible values! CHANGE USERS RANGE
990                if newUid >= maxLimit:
991                        raise ConfigurationError("No more UID available. Check range!")
992
993       
994                # Return NewUID
995                return newUid
996
997
998        """   
999        def getNewLdapUid(self):
1000                global startLdapUID
1001                list = []
1002                for ldapUser in  InheritableSingleton.instances["ldapList"].keys():
1003                        uid = InheritableSingleton.instances["ldapList"][ldapUser].getUidNumber().getValue()
1004                        list.append(int(uid))
1005                print list
1006                value = max(list)
1007                newValue = value + 1
1008                if newValue < int(startLdapUID):
1009                        if newValue >= 65000:
1010                                raise UserError("Problem, ldap uid too big...!!")
1011                        if not int(startLdapUID) in list:
1012                                return int(startLdapUID)
1013                else:
1014                        return newValue
1015        """
1016               
1017               
1018               
1019
1020        def __deleteUnixUser(self, username, dir=False):
1021                """ Delete unix group """ 
1022                if username:
1023                        user = username
1024                        if dir:
1025                                user = "-r "+user
1026                        p = subprocess.Popen("userdel "+user, shell=True)
1027                        sts = os.waitpid(p.pid, 0)             
1028                        if sts[1] != 0:
1029                                raise UserError("Problem deleting user!")
1030                else:
1031                        raise UserError("Username must be not empty!")
1032
1033
1034        def __modifyUnixUser(self, username, grouplist=[], newname="" ):
1035                """ Modify username and group of user """
1036                if username:
1037                        usermod = "usermod"
1038                        if ( not grouplist ) and ( not newname):
1039                                raise UserError("You have to pass something to change to this method")
1040                        groups = ""
1041                        if len(grouplist) > 0:
1042                                for a in grouplist:
1043                                       groups = groups + a+"," 
1044                                groups = groups.strip(",")
1045                                usermod = usermod + " -G "+ groups + " "
1046                        if newname:
1047                                usermod = usermod + " -l " + newname + " " + username
1048                        else:
1049                                usermod = usermod + " " + username
1050                        #At first we change user attributes
1051                        p = subprocess.Popen(usermod, shell=True)
1052                        sts = os.waitpid(p.pid, 0)               
1053                        if sts[1] != 0:
1054                                raise UserError("Problem modifying user!")
1055                       
1056                       
1057                else:
1058                        raise UserError("Username must be not null!")
1059
1060                       
1061
1062        def __changePasswordUnixUser(self, username, password):
1063                """  Change user password """               
1064                try:       
1065                        if username and password:
1066                                string = username+":"+password+"\n"
1067                                p = subprocess.Popen("chpasswd",shell=True, stdin=subprocess.PIPE).communicate(input=string)
1068                except:
1069                        raise UserError("Error changing password!")
1070
1071        def changeLdapPassword(self, username,password):
1072                """ Change ldap password of user username  """
1073                try:
1074                        if self.isUser(username):
1075                                if not password:
1076                                        raise UserError("Password must be not empty!")
1077                                        return
1078                                #Change password
1079
1080                                user = self.getUser(username)     
1081                                user.setAttribute("userPassword", password)
1082                                self.modifyLdapUser(user)
1083                               
1084                        else:
1085                                raise UserError("User passed is not a valid user")
1086
1087
1088                except Exception, e:
1089                        raise UserError("Could not change password: "+str(e))
1090
1091        def __addFlagToSambaAcct(self,acctFlag, flagToAdd):
1092                """ add the flag to pos in acct """
1093                flags = ["[","U","X","H","N","T","M","W","S","L","I","D","]"] 
1094                ret = ""
1095                for i in flags:
1096                        if i in acctFlag:
1097                                ret += i
1098                        elif i == flagToAdd:
1099                                ret += i
1100                        else:
1101                                ret += " "
1102                return ret
1103
1104        def __removeFlagFromSambaAcct(self,acctFlag, flagToRemove):
1105                """ add the flag to pos in acct """
1106                flags = ["[","U","X","H","N","T","M","W","S","L","I","D","]"] 
1107                ret = ""
1108                for i in flags:
1109                        if i == flagToRemove:
1110                                ret += " " 
1111                        elif i in acctFlag:
1112                                ret += i
1113                        else:
1114                                ret += " "
1115                return ret
1116
1117                       
1118               
1119                       
1120
1121
1122                       
1123        def disableLdapUser(self, username):
1124                """ Change ldap password of user username  """
1125                try:
1126                        if self.isLdapUser(username):
1127                                import re
1128                                user = self.getUser(username)     
1129                                flags = user.getAttribute('sambaSamAccount','sambaAcctFlags')
1130                                newFlag = self.__addFlagToSambaAcct(flags.getValue(),"D")
1131                                user.setAttribute("sambaAcctFlags", newFlag)
1132                                user.setAttribute("loginShell", "/bin/false")
1133                                passwordHash = user.getPassword().getValue()
1134                                newPass = re.sub('(?P<name>{.*})','\g<name>?', passwordHash)
1135                                user.setAttribute("userPassword",newPass,False)
1136                                self.modifyLdapUser(user)
1137                               
1138                        else:
1139                                raise UserError("User passed is not a valid user")
1140
1141
1142                except Exception, e:
1143                        print e
1144                        raise UserError("Could not change password")
1145
1146
1147        def enableLdapUser(self, username):
1148                """ Change ldap password of user username  """
1149                try:
1150                        if self.isLdapUser(username):
1151                                import re
1152                                user = self.getUser(username)
1153                                flags = user.getAttribute('sambaSamAccount','sambaAcctFlags')
1154                                newFlag = self.__removeFlagFromSambaAcct(flags.getValue(), "D")
1155                                user.setAttribute("sambaAcctFlags", newFlag)
1156                                user.setAttribute("loginShell", "/bin/sh")
1157                                passwordHash = user.getPassword().getValue()
1158                                newPass = re.sub('(?P<name>{.*})(\?)','\g<name>', passwordHash)
1159                                user.setAttribute("userPassword",newPass,False)
1160                                self.modifyLdapUser(user)
1161                               
1162                        else:
1163                                raise UserError("User passed is not a valid user")
1164
1165
1166                except Exception, e:
1167                        raise UserError("Could not change password: "+str(e))
1168
1169        def isEnabled(self, username):
1170                """ Returns true if user is enabled. None if the user is nobody or invalid """
1171                try:
1172                        if self.isLdapUser(username):
1173                                user = self.getUser(username)
1174                                flags = user.getAttribute('sambaSamAccount','sambaAcctFlags')
1175                                if flags != None:
1176                                        if "D" in flags.getValue():
1177                                                return False 
1178                                        else:
1179                                                return True 
1180                                else:
1181                                        return None
1182                                               
1183                        else:                       
1184                                raise UserError("User passed is not a valid user")
1185                except Exception, e:
1186                        print e
1187                        raise UserError("Problems: "+str(e))
1188
1189
1190
1191               
1192               
1193               
1194                 
1195               
1196
1197       
1198        def prova(self):
1199                #self.__addUnixGroup("prova")
1200                #self.__modifyUnixGroup("prova", "provina")
1201                #self.__deleteUnixGroup("provina")
1202                #self.__addUnixUser("paolo", "paolo", "/home/paolo", uid="3002", grouplist=["cdrom","plugdev"])
1203                #self.__deleteUnixUser("prova", True)
1204                #self.__modifyUnixUser("ciao",grouplist=[],newname="carlo")
1205                #self.__changePasswordUnixUser("carlo", "prova")
1206                #print self.__getUnixNewUid()
1207                #print self.__getLdapNewUid()
1208                pass
1209
1210       
1211        def addUnixGroup2(self, l):                                                             
1212                """ Add unix group to local system and update memory list of groups """
1213                """ l argument must be an instance of UnixGroup """
1214                # Check l == UnixGroup
1215                if not isinstance(l, UnixGroup):
1216                        raise GroupError("Not a valid unix group!")
1217
1218                # Check l'attributes ( l.check() )
1219                if not l.check():
1220                        raise GroupError("Invalid Unix Group attributes! ")
1221
1222                # Does l group exist?
1223                if self.isGroup(l.getName().getValue()):
1224                        raise GroupError("Group already exists!")
1225
1226                # Check users attribute of the group:
1227                        # 1. users exist?
1228                for user in l.getUsersList().getValue():
1229                        if not self.isUser(user):
1230                                raise GroupError("Group contains users that doesn't exist!")
1231
1232                # Insert group
1233                self.__addUnixGroup(l.getName().getValue(), l.getGid().getValue())               
1234
1235                # Updating memory group list
1236                InheritableSingleton.instances['groupList'][l.getName().getValue()] = l
1237
1238                # Add users to group
1239                for user in l.getUsersList().getValue():
1240                        self.__appendUserToUnixGroup(user, l.getName().getValue())
1241
1242               
1243       
1244
1245
1246
1247        def deleteUnixGroup2(self, groupname):
1248                """ Delete Unix group from local system and update memory group list """
1249                # Check groupname == string
1250                if not isinstance(groupname, str):
1251                        raise GroupError("Groupname must be a string!")
1252                # Check groupname is a valid group
1253                if not self.isGroup(groupname):
1254                        raise GroupError("Group doesn't exist")
1255
1256                #Check users in group
1257                usList = self.getGroup(groupname).getUsersList().getValue()
1258               
1259                curGroupGID = self.getGroup(groupname).getGid().getValue()
1260                found = False
1261                #Because of usList doesn't contain users main group, we have to search it       
1262                for us in InheritableSingleton.instances['unixList'].keys():
1263                        if  InheritableSingleton.instances['unixList'][us].getGid().getValue() == curGroupGID:
1264                                found = True
1265
1266       
1267                if not usList:
1268                        if not found:
1269                                # Delete groupname
1270                                self.__deleteUnixGroup(groupname)
1271                        else:
1272                                raise GroupError("Could not delete group: group not empty")
1273                else:
1274                        raise GroupError("Could not delete group: group not empty")
1275
1276                # Update memory group list
1277                del(InheritableSingleton.instances['groupList'][groupname])
1278
1279
1280
1281        def modifyUnixGroup2(self, groupname, newname="", users=[]):
1282                """ Modify groupname and user that are part of this group """
1283                """ Old users will be replaced by users list """
1284                # Check gruopname == string
1285                if not isinstance(groupname, str):
1286                        raise GroupError("Groupname must be a string!")
1287
1288                # Check groupname is a valid group
1289                if not self.isGroup(groupname):
1290                        raise GroupError("Group doesn't exist")
1291
1292                if ( not newname ) and ( not users  ):
1293                        raise GroupError("All arguments are empty!")
1294
1295                # Check newname (if not empty)
1296                if newname:
1297                        # 1. Newname is a string
1298                        if not isinstance(newname, str):
1299                                raise GroupError("new name argument must be a string!")
1300                        # 2. Newname is not a group
1301                        if self.isGroup(newname):
1302                                raise GroupError("New group name already exist!")
1303                        # Modify group name
1304                        self.__modifyUnixGroup(groupname, newname)
1305
1306
1307                        # Check users (if not empty)
1308                        if users:
1309                                # 1. users exists
1310                                for user in users:
1311                                        if not self.isUser(user):
1312                                                print "Warning: User \""+user+"\" doesn't exist but is in unix group." 
1313                                                #TODO
1314                                                #raise GroupError("User doesn't exist!")
1315                                # Update users list       
1316                                self.__usersToUnixGroup(users, newname)
1317                else:
1318                        # Check users (if not empty)
1319                        if users:
1320                                # 1. users exists
1321                                for user in users:
1322                                        if not self.isUser(user):
1323                                                print "Warning: User \""+user+"\" doesn't exist but is in unix group." 
1324                                                #TODO: decide what to do
1325                                                #raise GroupError("User doesn't exist!")
1326                                # Update users list       
1327                                self.__usersToUnixGroup(users, groupname)
1328
1329
1330                # Update group in memory
1331                oldGroup = self.getGroup(groupname) 
1332                if newname:
1333                        # Delete old group
1334                        del(InheritableSingleton.instances['groupList'][groupname])
1335
1336                        # Update name
1337                        oldGroup.setAttribute("cn", newname)
1338                        if users:
1339                                # Update users
1340                                oldGroup.setUserList(users) 
1341
1342                        # Write to memory
1343                        InheritableSingleton.instances['groupList'][oldGroup.getName().getValue()] = oldGroup
1344                else:
1345                        if users:
1346                                InheritableSingleton.instances['groupList'][groupname].setUserList(users)
1347
1348
1349
1350               
1351
1352               
1353
1354
1355
1356        def addUnixUser2(self,l, maingroup="", groups=[]):
1357                """ Add unix user to local system and update memory list of users. Groups argument are Unix groups """
1358                """ l argument must be an instance of Unix User """
1359
1360       
1361                # Check l == UnixUser
1362                if not isinstance(l, UnixUser):
1363                        raise UserError("Not a valid unix user!")
1364                # Check l'attributes ( l.check() )
1365                if not l.check():
1366                        raise UserError("Invalid user attributes!")
1367
1368                # Does l User exist?
1369                if self.isUser(l.getName().getValue()):
1370                        raise UserError("User already exists!")
1371
1372                # Check groups:
1373                        # 1. groups is a list?
1374                if not isinstance(groups, list):
1375                        raise UserError("Check groups argument!")
1376                        # 2. groups exist?
1377                for group in groups:
1378                        if not self.isGroup(group): 
1379                                raise UserError("Group doesn't exist!")
1380
1381                # If maingroup = "" group will be automatically created
1382                if maingroup:
1383                        if not isinstance(maingroup, str):
1384                                raise UserError("Maingroup must be a string!") 
1385                        if not self.isGroup(maingroup):
1386                                # Create group with gid = userUid
1387                                g = UnixGroup()
1388                                g.setAttribute("cn", maingroup)
1389                                g.setAttribute("gidNumber", l.getUidNumber().getValue())
1390                                self.addUnixGroup2(g)
1391                               
1392                                # Updating group
1393                                InheritableSingleton.instances['groupList'][g.getName().getValue()] = g
1394
1395
1396                                # Insert user
1397                                #_addUnixUser(self, username, password, home="", uid="",  gid="", shell="/bin/sh", grouplist=[]):
1398                                self.__addUnixUser(l.getName().getValue(), l.getPassword().getValue(),l.getHome().getValue(), l.getUidNumber().getValue(), l.getUidNumber().getValue(),l.getShell().getValue(),groups)
1399
1400                        else:
1401                                # MainGroup exist
1402                                g = self.getGroup(maingroup)
1403                                # Insert user
1404                                #_addUnixUser(self, username, password, home="", uid="",  gid="", shell="/bin/sh", grouplist=[]):
1405                                self.__addUnixUser(l.getName().getValue(), l.getPassword().getValue(),l.getHome().getValue(), l.getUidNumber().getValue(), g.getGid().getValue(),l.getShell().getValue(),groups)
1406
1407                else:
1408                        if self.isGroup(l.getName().getValue()):
1409                                # Exist a group with same name of user
1410                                # User will be added to this group
1411                                print "Warning: a group with this name already exists. User will be added to this group."
1412                                g = self.getGroup(l.getName().getValue())
1413
1414                                # Insert user
1415                                #_addUnixUser(self, username, password, home="", uid="",  gid="", shell="/bin/sh", grouplist=[]):
1416                                self.__addUnixUser(l.getName().getValue(), l.getPassword().getValue(),l.getHome().getValue(), l.getUidNumber().getValue(), g.getGid().getValue(),l.getShell().getValue(),groups)
1417
1418
1419                               
1420                        else:
1421                                # Group will be created automatically with same name and gid of user
1422                                g = UnixGroup()
1423                                g.setAttribute("cn",l.getName().getValue() )
1424                                g.setAttribute("gidNumber",l.getUidNumber().getValue())
1425                                self.addUnixGroup2(g)
1426                               
1427                                # Updating group
1428                                InheritableSingleton.instances['groupList'][g.getName().getValue()] = g
1429
1430                                # Insert user
1431                                #_addUnixUser(self, username, password, home="", uid="",  gid="", shell="/bin/sh", grouplist=[]):
1432                                self.__addUnixUser(l.getName().getValue(), l.getPassword().getValue(),l.getHome().getValue(), l.getUidNumber().getValue(), g.getGid().getValue(),l.getShell().getValue(),groups)
1433
1434
1435
1436
1437                # Updating memory user list
1438                InheritableSingleton.instances['unixList'][l.getName().getValue()] = l
1439
1440               
1441                # Updating memory group list (add user to groups)
1442                # Update every group whose user is part
1443               
1444                # for each group
1445                for group in groups:
1446                        if not InheritableSingleton.instances['groupList'][group].hasUser(l.getName().getValue()):
1447                                InheritableSingleton.instances['groupList'][group].addUser(l.getName().getValue())
1448
1449                # Create user directory
1450                # __createHomeDirectory(self, name, uid, gid, path="/home/"):
1451                self.createHomeDirectory(l.getName().getValue(), l.getUidNumber().getValue(), l.getGid().getValue())
1452
1453
1454
1455         
1456
1457        def deleteUnixUser2(self, username, home=False):
1458                """ Delete Unix user from local system and update memory user list """
1459                # Check username == string
1460                if not isinstance(username, str):
1461                        raise UserError("Not a valid argument!")
1462                # Check username is a valid user
1463                if not self.isUser(username):
1464                        raise UserError("User doesn't exist!")
1465
1466                # Delete username
1467                self.__deleteUnixUser(username, home)               
1468 
1469                # Update memory user list
1470                del(InheritableSingleton.instances['unixList'][username])
1471               
1472
1473                # Update memory group list (username's groups)
1474                for group in InheritableSingleton.instances['groupList'].keys():
1475                        if InheritableSingleton.instances['groupList'][group].hasUser(username):
1476                                InheritableSingleton.instances['groupList'][group].removeUser(username)
1477
1478                for group in InheritableSingleton.instances['ldapGroupList'].keys():
1479                        if InheritableSingleton.instances['ldapGroupList'][group].hasUser(username):
1480                                InheritableSingleton.instances['ldapGroupList'][group].removeUser(username)
1481
1482
1483                               
1484                       
1485                       
1486        def modifyUnixUser2(self, username, newname="", groups=[]):
1487                """ Modify username and/or group list. Main group could not be modified. """
1488                """ Newname is the new username """
1489                """ Groups are the new groups. Old groups will be removed """
1490                # Check username == string
1491                if not isinstance(username, str):
1492                        raise UserError("Not a valid argument!")
1493                # Check username is a valid user
1494                if not self.isUser(username):
1495                        raise UserError("User doesn't exist!")
1496
1497                if ( not newname ) and ( not groups  ):
1498                        raise UserError("All arguments are empty!")
1499
1500
1501                # Check newname (if not empty)
1502                if newname: 
1503                        # 1. Newname is a string
1504                        if not isinstance(newname, str):
1505                                raise UserError("Newname must be a string!")
1506                        # 2. Newname is not a user
1507                        if self.isUser(newname):
1508                                raise UserError("User with newname already exist!")
1509                        for group in groups:
1510                                if not self.isGroup(group):
1511                                        raise UserError("Group doesn't exist!")
1512                        #__modifyUnixUser(self, username, grouplist=[], newname="" ):
1513                        self.__modifyUnixUser(username, groups, newname)
1514
1515
1516                else:
1517                        for group in groups:
1518                                if not self.isGroup(group):
1519                                        raise UserError("Group doesn't exist!")
1520                        #__modifyUnixUser(self, username, grouplist=[], newname="" ):
1521                        self.__modifyUnixUser(username, groups, newname)
1522
1523
1524
1525                # Update user in memory
1526                if newname:
1527                        oldUser = InheritableSingleton.instances['unixList'][username]
1528                        del(InheritableSingleton.instances['unixList'][username])
1529                        oldUser.setAttribute("cn", newname)
1530                        oldUser.setAttribute("uid", newname)
1531                        InheritableSingleton.instances['unixList'][newname] = oldUser
1532               
1533                        #Update username in groups
1534                        for group in  InheritableSingleton.instances['groupList'].keys():
1535                                if InheritableSingleton.instances['groupList'][group].hasUser(username):
1536                                        InheritableSingleton.instances['groupList'][group].removeUser(username)
1537                                if group in groups:
1538                                        print "TRRR: "+group
1539
1540                                        InheritableSingleton.instances['groupList'][group].addUser(newname)
1541                               
1542                        for group in  InheritableSingleton.instances['ldapGroupList'].keys():
1543                                if InheritableSingleton.instances['ldapGroupList'][group].hasUser(username):
1544                                        InheritableSingleton.instances['ldapGroupList'][group].removeUser(username)
1545                                if group in groups:
1546                                        print "TRRR: "+group
1547
1548                                        InheritableSingleton.instances['ldapGroupList'][group].addUser(newname)
1549                else:
1550                        for group in  InheritableSingleton.instances['groupList'].keys():
1551                                if InheritableSingleton.instances['groupList'][group].hasUser(username):
1552                                        InheritableSingleton.instances['groupList'][group].removeUser(username)
1553                                if group in groups:
1554                                        print "TRRR: "+group
1555                                        InheritableSingleton.instances['groupList'][group].addUser(username)
1556                               
1557                        for group in  InheritableSingleton.instances['ldapGroupList'].keys():
1558                                if InheritableSingleton.instances['ldapGroupList'][group].hasUser(username):
1559                                        InheritableSingleton.instances['ldapGroupList'][group].removeUser(username)
1560                                if group in groups:
1561                                        print "TRRR: "+group
1562
1563                                        InheritableSingleton.instances['ldapGroupList'][group].addUser(username)
1564
1565                       
1566
1567
1568
1569
1570
1571        def addLdapGroup2(self, l, users=[]):
1572                """ Add a ldap user group and update memory groups """
1573                # Check l == LdapUser
1574                if not isinstance(l, LdapGroup):
1575                        raise GroupError("User must be an LdapUser instance")
1576                # Check l'attributes ( l.check() )
1577                if not l.check():
1578                        raise GroupError("Invalid user attributes!")
1579                # Does l User exist?
1580                if self.isGroup(l.getName().getValue()):
1581                        raise GroupError("Group already exists!")
1582
1583                # Check groups:
1584                        # 1. groups is a list?
1585
1586                if not isinstance(users, list):
1587                        raise GroupError("Groups argument must be a list!")
1588                for user in users:
1589                        if not self.isUser(user):
1590                                raise UserError("User doesn't exist")
1591               
1592               
1593                # Add user to ldapGroup                       
1594                if users:
1595                        l.setUserList(users)
1596               
1597                # Insert group
1598                self.__addLdapGroup(l)
1599
1600               
1601                # Updating memory user list
1602                InheritableSingleton.instances['ldapGroupList'][l.getName().getValue()]=l
1603
1604               
1605               
1606
1607               
1608       
1609        def __addLdapGroup(self, l):
1610                """ Add an ldap group to ldap server """
1611                # Insert tree insert position in global configuration
1612                try:
1613                        conn = ldap.conn()
1614                        if isinstance(l, LdapGroup):
1615                                dn=ldap.groupprefix+l.getName().getValue()+ldap.grouppostfix
1616                                d = l.getDict()       
1617                                modList = ldap.modlist.addModlist(d)
1618                                ret = conn.add_s(dn, modList)
1619                        else:
1620                                print "Not a valid Ldap Group!"
1621                except:
1622                        raise LdapError("Error: group not added!")
1623
1624        def deleteLdapGroup2(self, groupname):
1625                """ Delete group from ldap server and update memory group list """
1626                # Check groupname == strin
1627                if not isinstance(groupname, str):
1628                        raise GroupError("Groupname must be a string!")
1629                # Check groupname is a valid group
1630                if not self.isGroup(groupname):
1631                        raise GroupError("Group doesn't exist")
1632
1633                # Check if there are users in that group!!
1634                usList = self.getGroup(groupname).getUsersList().getValue()
1635               
1636
1637 
1638                curGroupGID = self.getGroup(groupname).getGid().getValue()
1639                found = False
1640                print curGroupGID
1641                #Because of usList doesn't contain users main group, we have to search it       
1642                for us in InheritableSingleton.instances['ldapList'].keys():
1643                        if  InheritableSingleton.instances['ldapList'][us].getGid().getValue() == curGroupGID:
1644                                found = True
1645                       
1646                       
1647                                                                                               
1648                       
1649                print usList
1650                if not usList:
1651                        if not found:
1652                                # Delete groupname
1653                                self.__deleteLdapGroup(groupname)
1654                        else:
1655                                raise GroupError("Could not delete group: group not empty")
1656                else:
1657                        raise GroupError("Could not delete group: group not empty")
1658
1659                # Update memory group list
1660                del(InheritableSingleton.instances['ldapGroupList'][groupname])
1661
1662
1663
1664
1665        def __deleteLdapGroup(self, groupname):
1666                """ Delete a group from ldap tree """ 
1667                try:
1668                        conn = ldap.conn()
1669                        if isinstance(groupname, str) and groupname:
1670                               
1671                                dn =ldap.groupprefix+groupname+ldap.grouppostfix
1672                                result = conn.delete_s(dn)
1673
1674                except:
1675                        raise LdapError("Error: could not delete group")     
1676
1677
1678        def modifyLdapGroup2(self, l, users=[]):
1679                """ Modify groupname and user that are part of this group """
1680                """ Old users will be replaced by users list """
1681                # Check gruopname == string
1682                if not isinstance(l, LdapGroup):
1683                        raise GroupError("Invalid group name.")
1684                # Check groupname is a valid group
1685                if not self.isGroup(l.getName().getValue()):
1686                        GroupError("Group doesn't exist!")
1687
1688
1689                # Check users (if not empty)
1690                        # 1. users exists
1691                for user in users:
1692                        if not self.isUser(user):
1693                                raise UserError("User doesn't exist!")
1694
1695                 
1696                # Update users               
1697                l.setUserList(users)
1698                # Modify group
1699                print l.getUsersList().getValue()
1700                self.__modifyLdapGroup(l)
1701
1702                # Update group in memory
1703                InheritableSingleton.instances['ldapGroupList'][l.getName().getValue()]=l
1704
1705
1706
1707
1708        def __modifyLdapGroup(self, l):
1709                """ Modify an ldap group """
1710                try:
1711                        if isinstance(l, LdapGroup):
1712                                dn=ldap.groupprefix+l.getName().getValue()+ldap.grouppostfix
1713                                d = l.getDict()       
1714                                ret = ldap.modifyEntry(dn,d) 
1715                        else:
1716                                print "Not a valid Ldap Group!"
1717                except:
1718                        raise LdapError("Error: could not modify group ")     
1719                       
1720        def modifyLdapGroup(self, l):
1721                  """ Modify an ldap group """
1722                  try:
1723                          if isinstance(l, LdapGroup):
1724                                  dn=ldap.groupprefix+l.getName().getValue()+ldap.grouppostfix
1725                                  d = l.getDict()       
1726                                  ret = ldap.modifyEntry(dn,d) 
1727                          else:
1728                                  print "Not a valid Ldap Group!"
1729                  except:
1730                          raise LdapError("Error: could not modify group ")     
1731
1732       
1733        def addLdapUser2(self,l, groups=[]):
1734                """ Add user to ldap server and update memory list of users """
1735                """ l argument must be an instance of LdapUser """
1736                # Check l == LdapUser
1737                if not isinstance(l, LdapUser):
1738                        raise UserError("Invalid user argument!")
1739                # Check l'attributes ( l.check() )
1740                if not l.check():
1741                        raise UserError("Invalid user attributes!")
1742
1743                # Does l User exist?
1744                if self.isUser(l.getName().getValue()):
1745                        raise UserError("User already exists!")
1746
1747                if os.path.isdir("/home/"+l.getName().getValue()):
1748                        raise UserError("Directory already exist")
1749
1750                # Check groups:
1751                if not isinstance(groups, list):
1752                        raise UserError("Invalid group argument!")
1753
1754                for group in groups:
1755                        if not self.isGroup(group):
1756                                raise GroupError("Group doesn't exist!")
1757
1758                # Insert user
1759                self.__addLdapUser(l)
1760
1761                               
1762                # Add user to the memberUid attribute of his main group
1763                mainGroup = self.getGroupByGid(l.getGid().getValue())
1764                mainGroup.addUser(l.getName().getValue())
1765                self.__modifyLdapGroup(mainGroup)
1766               
1767               
1768
1769                # Updating memory user list
1770                InheritableSingleton.instances['ldapList'][l.getName().getValue()]=l
1771
1772
1773
1774
1775
1776               # Update ldap group (can be ldap o unix)
1777                for group in groups:
1778                        g = self.getGroup(group)
1779                        groupUser = g.getUsersList().getValue()
1780                       
1781                        if isinstance(g, LdapGroup):
1782                                if not l.getName().getValue() in groupUser:
1783                                        groupUser.append(l.getName().getValue())
1784                                        self.modifyLdapGroup2(g, groupUser)
1785
1786                        if isinstance(g, UnixGroup):
1787                                if not l.getName().getValue() in groupUser:
1788                                        groupUser.append(l.getName().getValue())
1789                                        self.modifyUnixGroup2(g.getName().getValue(),"", groupUser)
1790
1791                # Updating memory group list (add user to groups)
1792                for group in  InheritableSingleton.instances['groupList'].keys():
1793                        if group in groups:
1794                                InheritableSingleton.instances['groupList'][group].addUser(l.getName().getValue())
1795                       
1796                for group in  InheritableSingleton.instances['ldapGroupList'].keys():
1797                        if group in groups:
1798                                InheritableSingleton.instances['ldapGroupList'][group].addUser(l.getName().getValue())
1799
1800                #Home directory work
1801                #Trying to create home
1802                self.createHomeDirectory(l.getName().getValue(),l.getUidNumber().getValue(),l.getGid().getValue())
1803               
1804               
1805               
1806
1807
1808
1809
1810
1811               
1812               
1813
1814
1815
1816       
1817        def __addLdapUser(self, l):
1818                """ Add an ldap user to ldap server """
1819                # Insert tree insert position in global configuration
1820                try:
1821                        conn = ldap.conn()
1822                        if isinstance(l, LdapUser):
1823                                dn=ldap.userprefix+l.getName().getValue()+ldap.userpostfix
1824                                d = l.getDict()       
1825                                modList = ldap.modlist.addModlist(d)
1826                                ret = conn.add_s(dn, modList)
1827                        else:
1828                                print "Not a valid Ldap User!"
1829                except Exception, e:
1830                        print e
1831                        print e.args
1832                        raise LdapError("Error: user not added!")
1833               
1834        def deleteLdapUser2(self, username):
1835                """ Delete user from ldap server and update memory user list """
1836                # Check username == string
1837                if not isinstance(username, str):
1838                        raise UserError("Invalid argument!")
1839                # Check username is a valid user
1840                if not self.isUser(username):
1841                        raise UserError("User doesn't exist!")
1842
1843                # Delete username
1844                self.__deleteLdapUser(username)
1845
1846
1847                # Delete user name from memberUid of user main group
1848                userObj = self.getUser(username)
1849                mainGroup = self.getGroupByGid(userObj.getGid().getValue())
1850                if mainGroup.hasUser(username):
1851                        mainGroup.removeUser(username)
1852                self.__modifyLdapGroup(mainGroup)
1853
1854
1855 
1856                #Delete user from ldap groups
1857                self.__removeUserFromLdapGroups(username)
1858
1859                #Delete user from unix groups
1860                self.__removeUserFromUnixGroups(username) # TODO: check, sometimes doesn't remove users
1861
1862               # Update memory user list
1863                del(InheritableSingleton.instances['ldapList'][username])
1864
1865               
1866                # Update memory group list (username's groups)
1867                for group in InheritableSingleton.instances['groupList'].keys():
1868                        if InheritableSingleton.instances['groupList'][group].hasUser(username):
1869                                InheritableSingleton.instances['groupList'][group].removeUser(username)
1870
1871                for group in InheritableSingleton.instances['ldapGroupList'].keys():
1872                        if InheritableSingleton.instances['ldapGroupList'][group].hasUser(username):
1873                                InheritableSingleton.instances['ldapGroupList'][group].removeUser(username)
1874
1875
1876                #Remove home directory and save it /var/backups
1877                #Create backup
1878                home = userObj.getHome().getValue()
1879               
1880                if home and home.startswith("/home/"):
1881                        try:
1882                                now = datetime.datetime.now()
1883                                stringTime = now.strftime("%Y%m%d%h%m%S")
1884                                #Security check
1885                                # Do all action only if /home direcotry starts with /home
1886                                if home.endswith("/"):
1887                                        fileBackup = home[0:-1] + "-" + stringTime + ".bck"
1888                                else:
1889                                        fileBackup = home + "-" + stringTime + ".bck"
1890                                print fileBackup
1891                                compress = self.dialogYesNo("Home backup in process\nDo you want to compress the backup and remove home directory?")
1892                                if compress == -8:
1893                                        #Compress
1894                                        fileBackup = fileBackup+".tar.gz" 
1895                                        r = os.system("tar cvzf "+fileBackup+" "+home) 
1896                                        #Remove original
1897                                        if r == 0:
1898                                                r = os.system("rm -rf "+home)   
1899                                                if r != 0:
1900                                                        raise Exception("Could not delete home directory after compression.")
1901
1902                                        else:
1903                                                raise Exception("Could not compress and delete home directory!\nTry without compress it.")
1904                                elif compress == -9:
1905                                        #Rename
1906                                        r = os.rename(home,fileBackup)
1907                                if r != 0 and r != None:
1908                                        raise Exception
1909                                else:
1910                                        showDialog("Backup done: "+fileBackup, gtk.MESSAGE_INFO)
1911                        except Exception,e:
1912                                print e
1913                                showDialog("Problems doing backup of "+username+"'s home directory!",gtk.MESSAGE_ERROR)
1914                else:
1915                        print "Home doesn't exist"
1916
1917               
1918
1919
1920        def dialogYesNo(self, message):
1921                dialog = gtk.MessageDialog(None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_YES_NO,message )
1922                dialog.show()
1923                # Close dialog on user response
1924                resp = dialog.run()
1925                dialog.destroy()
1926                return resp
1927
1928       
1929               
1930
1931
1932
1933        def __deleteLdapUser(self, username):
1934                """ Delete a user from ldap tree """ 
1935                try:
1936                        conn = ldap.conn()
1937                        if isinstance(username, str) and username:
1938                               
1939                                dn =ldap.userprefix+username+ldap.userpostfix
1940                                result = conn.delete_s(dn)
1941                                #How to decide if delete has happened?
1942                except Exception, e:
1943                        error = e[0]['desc']
1944                        raise LdapError("Error: could not delete user %s" % username + "\n"+error)     
1945
1946        def modifyLdapUser2(self, l):
1947                # modifyLdapUser
1948                pass
1949
1950        def modifyLdapUser(self, l):
1951                """ Modify an ldap user """
1952                try:
1953                        if isinstance(l, LdapUser):
1954                                dn=ldap.userprefix+l.getName().getValue()+ldap.userpostfix
1955                                d = l.getDict()       
1956
1957                                ret = ldap.modifyEntry(dn,d) 
1958                                InheritableSingleton.instances['ldapList'][l.getName().getValue()]=l
1959                        else:
1960                                print "Not a valid Ldap User!"
1961                       
1962                except:
1963                        raise LdapError("Error: could not modify user ")     
1964
1965        def __appendUserToUnixGroup(self, username, group):
1966                """ Add user to group in /etc/group """
1967                if not isinstance(username, str):
1968                        raise UserError("Username must be a string")
1969                if not isinstance(group, str):
1970                        raise GroupError("Group must be a string")
1971
1972                groupFile = open("/etc/group",'r') 
1973                groupLines = groupFile.readlines() 
1974                groupFile.close()
1975                newGroup = []
1976                for line in groupLines:
1977                        # Split :
1978                        # Take last (it's the list of unix users)
1979                        # Find username and remove it
1980                        if line.startswith(group+":"):
1981                                groupSplit = line.strip("\n").split(":")
1982                                usersList = groupSplit[len(groupSplit)-1].split(",")
1983                                if not username in usersList:
1984                                        if groupSplit[3]:
1985                                                line = groupSplit[0]+":"+groupSplit[1]+":"+groupSplit[2]+":"+groupSplit[3]+","+username
1986                                        else:
1987                                                line = groupSplit[0]+":"+groupSplit[1]+":"+groupSplit[2]+":"+groupSplit[3]+username
1988                       
1989                        newGroup.append(line)
1990       
1991                # Write together
1992                groupFile = open("/etc/group", "w") 
1993                groupFile.write("")
1994                groupFile.close()
1995
1996                groupFile = open(groupfile, "a") 
1997                for line in newGroup:
1998                        groupFile.write(line) 
1999                groupFile.close()
2000
2001        def __usersToUnixGroup(self, users, group):
2002                """ Add user to group in /etc/group """
2003                if not isinstance(users, list):
2004                        raise UserError("Username must be a string")
2005                if not isinstance(group, str):
2006                        raise GroupError("Group must be a string")
2007
2008                groupFile = open("/etc/group",'r') 
2009                groupLines = groupFile.readlines() 
2010                groupFile.close()
2011                newGroup = []
2012                for line in groupLines:
2013                        # Split :
2014                        # Take last (it's the list of unix users)
2015                        # Find username and remove it
2016                        if line.startswith(group+":"):
2017                                groupSplit = line.strip("\n").split(":")
2018                                usersList = groupSplit[len(groupSplit)-1].split(",")
2019                                userString = ""
2020                                for user in users:
2021                                        userString = userString + user + ","
2022                                userString = userString.strip(",")
2023                                line = groupSplit[0]+":"+groupSplit[1]+":"+groupSplit[2]+":"+userString+"\n"       
2024                        newGroup.append(line)
2025       
2026                # Write together
2027                groupFile = open("/etc/group", "w") 
2028                groupFile.write("")
2029                groupFile.close()
2030
2031                groupFile = open(groupfile, "a") 
2032                for line in newGroup:
2033                        groupFile.write(line) 
2034                groupFile.close()
2035
2036
2037               
2038
2039                               
2040
2041        def __removeUserFromUnixGroups(self,username):
2042                """ Remove an user from unix groups """
2043                global groupfile
2044                if username:
2045                        # group
2046                        groupFile = open(groupfile,'r') 
2047                        groupLines = groupFile.readlines() 
2048                        groupFile.close()
2049                        newGroup = []
2050                        for line in groupLines:
2051                                # Split :
2052                                # Take last (it's the list of unix users)
2053                                # Find username and remove it
2054                                groupSplit = line.strip("\n").split(":")
2055                                usersList = groupSplit[len(groupSplit)-1].split(",")
2056                                if username in usersList:
2057                                        ind = usersList.index(username)
2058                                        del usersList[ind]
2059                                        if username in usersList:
2060                                                print "Warning: duplicate user in group"
2061                                newLine = groupSplit[0]+":"+groupSplit[1]+":"+groupSplit[2]+":" 
2062                               
2063                                 
2064                                for user in usersList:
2065                                        if user:
2066                                                newLine = newLine + user + ","
2067                                newLine = newLine.strip(",")+"\n"
2068                                newGroup.append(newLine)
2069
2070                        # Write together
2071                        groupFile = open(groupfile, "w") 
2072                        groupFile.write("")
2073                        groupFile.close()
2074
2075                        groupFile = open(groupfile, "a") 
2076                        for line in newGroup:
2077                                groupFile.write(line) 
2078                        groupFile.close()
2079                       
2080
2081                else:
2082                        raise UserError("Not a valid group or group does not exist!")           
2083
2084        def __addUserToUnixGroup(self, username, groups):
2085                """ Add user to /etc/group """
2086                if not self.isUser(username):
2087                        raise UserError("User doesn't exist")
2088               
2089                for g in groups:
2090                        if not self.isGroup(g):
2091                                raise GroupError("Invalid group!\nGroup doesn't exist.")
2092                groupFile = open("/etc/group",'r') 
2093                groupLines = groupFile.readlines() 
2094                groupFile.close()
2095                newGroup = []
2096
2097                for line in groupLines:
2098                       
2099                        groupStart = line.strip().split(":")[0]
2100                        if groupStart in groups:
2101                                groupSplit = line.strip("\n").split(":")
2102                                usersList = groupSplit[len(groupSplit)-1].split(",")
2103                                if not username in usersList:
2104                                        usersList.append(username)
2105                                newLine = ""
2106                                newLine = groupSplit[0]+":"+groupSplit[1]+":"+groupSplit[2]+":" 
2107                                for us in usersList:
2108                                        newLine = newLine + us + ","
2109                                newLine = newLine.strip(",")+"\n"
2110                                newGroup.append(newLine)
2111                        else:
2112                                newGroup.append(line)
2113
2114                # Write together
2115                groupFile = open(groupfile, "w") 
2116                groupFile.write("")
2117                groupFile.close()
2118
2119                groupFile = open(groupfile, "a") 
2120                for line in newGroup:
2121                        groupFile.write(line) 
2122                groupFile.close()
2123               
2124                               
2125                                       
2126                                       
2127                               
2128
2129               
2130
2131        def updateUserLocalGroups(self, username, groups):
2132                """ Remove username from unix group and add user to groups """
2133                try:
2134                        #Check if group are unix group
2135                        for gr in groups:
2136                                if not self.isGroup(gr):
2137                                        raise GroupError("Not a valid group!")
2138
2139                                groupInstance = self.getGroup(gr)
2140                               
2141                                if not isinstance(groupInstance, UnixGroup):
2142                                        raise GroupError("Not a valid group!")
2143                               
2144                        #Remove user from /etc/group
2145                        self.__removeUserFromUnixGroups(username)
2146
2147                        #Remove user from memory groups
2148                        for group in InheritableSingleton.instances['groupList'].keys():
2149                                if InheritableSingleton.instances['groupList'][group].hasUser(username):
2150                                        InheritableSingleton.instances['groupList'][group].removeUser(username)
2151
2152                         
2153                       
2154
2155                        #Add user to /etc/group
2156                        self.__addUserToUnixGroup(username, groups)
2157                        #Add user to groups in memory
2158                        for group in InheritableSingleton.instances['groupList'].keys():
2159                                if group in groups:
2160                                        if not InheritableSingleton.instances['groupList'][group].hasUser(username):
2161                                                InheritableSingleton.instances['groupList'][group].addUser(username)
2162                except Exception, e:
2163                        print e.args
2164                       
2165                        raise UserError("Problem updating system groups:\n"+str(e))
2166
2167
2168
2169
2170
2171
2172
2173        def __removeUserFromLdapGroups(self,username):
2174                """ Remove user from all ldap groups """ 
2175                if username:
2176                        groups =  self.groupsByUser(username)
2177                        for group in groups:
2178                                ldapGroup = self.getGroup(group)
2179
2180                                if isinstance(ldapGroup, LdapGroup):
2181                                        # Take the group
2182                                                                         
2183                                        # Modify memberUid, remove username
2184                                        usersList = ldapGroup.getUsersList().getValue()
2185                                        if username in usersList:
2186                                                ind = usersList.index(username) 
2187                                                del(usersList[ind])
2188                                                ldapGroup.setUserList(usersList)
2189                                        # Modify ldap entry
2190                                                self.__modifyLdapGroup(ldapGroup)
2191                else:
2192                        raise UserError("Not a valid user")
2193               
2194
2195        def addUserToUnixGroup(self, username, group):
2196                """ Add an user to unix group """
2197                #Group could be a string or a list o groups
2198                if not isinstance(username, str) and username:
2199                        raise UserError("Username argument not a string")
2200
2201                if isinstance(group, str):
2202                        if self.isGroup(group):
2203                                #Add username to group                               
2204                                g = None
2205                                g=self.getGroup(group)
2206                                if not g.hasUser(username):
2207                                        g.addUser(username)                                 
2208                                        self.deleteUnixGroup(g.getName().getValue())
2209                                        self.addUnixGroup(g)
2210                        else:
2211                                raise UserError("User does not exist")
2212
2213                else:
2214                        if isinstance(group, list):
2215                                for gr in group:
2216                                        if self.isGroup(gr):
2217                                                #Add username to group
2218                                                g = None
2219                                                g = self.getGroup(gr)
2220                                                if not g.hasUser(username):
2221                                                        g.addUser(username)                                 
2222                                                        self.deleteUnixGroup(g.getName().getValue())
2223                                                        self.addUnixGroup(g)
2224
2225                                        else:
2226                                                raise GroupError("Group does not exist")
2227               
2228                                 
2229                        else:
2230                                raise GroupError("Not a valid group argument")
2231
2232       
2233                       
2234               
2235        def addUserToLdapGroup(self, username, group):
2236                """ Add an user to unix group """
2237                #Group could be a string or a list o groups
2238                if not isinstance(username, str) and username:
2239                        raise UserError("Username argument not a string")
2240
2241                if isinstance(group, str):
2242                        if self.isGroup(group):
2243                                #Add username to group                               
2244                                g = None
2245                                g=self.getGroup(group)
2246                                if not g.hasUser(username):
2247                                        g.addUser(username)                                 
2248                                        self.modifyLdapGroup(g)
2249                        else:
2250                                Error("User does not exist")
2251
2252                else:
2253                        if isinstance(group, list):
2254                                for gr in group:
2255                                        if self.isGroup(gr):
2256                                                #Add username to group
2257                                                g = None
2258                                                g = self.getGroup(gr)
2259                                               
2260                                                if not g.hasUser(username):
2261                                                        g.addUser(username)                                 
2262                                                        self.modifyLdapGroup(g)
2263
2264                                        else:
2265                                                raise GroupError("Group does not exist")
2266               
2267                                 
2268                        else:
2269                                raise GroupError("Not a valid group argument")
2270
2271
2272        def searchLocalSid(self):
2273                """ Returns the samba sid of the server"""
2274                res = ldap.search(filter="(sambaDomainName=*)",findattr=["sambaSID"]) 
2275                return res[0][0][1]['sambaSID'][0]
2276               
2277
2278        def getUserSID(self, uid):
2279                """ Return user security id  """
2280               
2281                #out = os.popen("net getlocalsid")
2282                #res = out.read()
2283                #out = subprocess.Popen("net getlocalsid", stdout=subprocess.PIPE, shell=True )
2284                #res = out.communicate()[0]
2285                #sidPrefix = res.split(":")[1].strip()
2286                sidPrefix = self.searchLocalSid()
2287                sidPostfix = (int(uid)*2) + 1000                 
2288                return sidPrefix+"-"+str(sidPostfix)
2289 
2290        def getGroupSID(self, gid):
2291                """ Return group security id """
2292                #out = os.popen("net getlocalsid")
2293                #res = out.read()
2294                #out = subprocess.Popen("net getlocalsid", stdout=subprocess.PIPE, shell=True )
2295                #res = out.communicate()[0]
2296                #sidPrefix = res.split(":")[1].strip()
2297                sidPrefix = self.searchLocalSid()
2298                sidPostfix = int(gid)                 
2299                return sidPrefix+"-"+str(sidPostfix)
2300
2301
2302
2303        def genPassword(self,pwlen=8):
2304                """ Generate a random password """
2305                from random import sample
2306                import string
2307                password = "".join(sample(string.ascii_letters+string.digits,pwlen))
2308                return password
2309
2310
2311backendSingleton = Backend()
2312
2313               
2314
2315           
2316       
2317if __name__ == "__main__":
2318        b = Backend()
2319        print b.searchLocalSid() 
2320        """
2321        g = UnixGroup()
2322        g.setAttribute("cn","GroupAntani")
2323        gid = b.getNewUnixID()
2324        g.setAttribute("gidNumber", str(gid))
2325        g.setAttribute("memberUid","pippo")
2326
2327        #b.addUnixGroup2(g)
2328        #b.deleteUnixGroup2("GroupAntani")
2329        #b.modifyUnixGroup2("GroupAntani", "gruppo")
2330        #b.modifyUnixGroup2("ploii", "ploi", ["giorgio","pluto"])
2331        """
2332        """
2333        u = UnixUser()
2334        u.setAttribute("cn","carly")
2335        uid = b.getNewUnixID()
2336        u.setAttribute("gidNumber", str(uid))
2337        u.setAttribute("homeDirectory","/home/carly")
2338        u.setAttribute("uid","carly")
2339        u.setAttribute("uidNumber", str(uid))
2340        u.setAttribute("gecos","")
2341        u.setAttribute("loginShell","/bin/bash")
2342        u.setAttribute("userPassword","carly")
2343        """
2344        #b.addUnixUser2(u,"", ["dhcp"])
2345        #print b.groupsByUser("carly")
2346        #b.deleteUnixUser2("carly", True)
2347        #b.modifyUnixUser2("carl","" , groups=["list","irc","src"])
2348        #b.deleteUnixGroup2("jackpop")
2349        """
2350        g = LdapGroup()
2351        g.setAttribute("cn","catalogo")
2352        uid = b.getNewLdapID()
2353        g.setAttribute("gidNumber", "20033")
2354
2355        g.setAttribute("sambaSID","S-1-5-21-3532783127-313077556-2689386559-553")
2356        g.setAttribute("sambaGroupType","2")
2357
2358        b.addLdapGroup2(g,["pippo"])
2359        """
2360        #b.deleteLdapGroup2("provaGrouppiiii")
2361       
2362        #b.modifyLdapGroup2(g,["pluto","prova","admin","giorgio"])
2363        """
2364        n = LdapUser()
2365        n.setAttribute("cn","bonzio")
2366        n.setAttribute("sn","bonzio")
2367        uid = b.getNewLdapID()
2368        n.setAttribute("gidNumber", "513")
2369        n.setAttribute("homeDirectory","/bin/bash")
2370        n.setAttribute("uid","bonzio")
2371        n.setAttribute("uidNumber", str(uid))
2372        n.setAttribute("sambaSID","S-1-5-21-3532783127-313077556-2689386559-5002")
2373        """
2374        #b.addLdapUser2(n,["direzione","scanner","Domain Users","users"])
2375        #b.removeUserFromUnixGroups("claus")
2376        #b.removeUserFromLdapGroups("bonzio")
2377
2378        #b.deleteLdapUser2("bonzio")
2379       
2380        """
2381        b.updateUserLocalGroups("aa",["floppy","cdrom"])
2382
2383        """
2384
2385               
2386
2387
2388
2389
2390
2391               
Note: See TracBrowser for help on using the browser.