Beispiel #1
0
    def config_set_password(self, username, password):
        """config user set password: <username> <new password>"""
        rec = {'userPassword': ["{SHA}" + LDAP.hashPassword(password)]}

        user, domain = self.udFromUname(username)

        if Settings.sambaDN and domain==Settings.defaultDomain:
            rec['sambaNTPassword'] = [Utils.createNTHash(password)]
            rec['sambaLMPassword'] = [Utils.createLMHash(password)]

        self.setUserAttr(username, rec)    
Beispiel #2
0
            user, domain = uname.split('@')
        
        emailAddress = user + '@' + domain
        givenName = ""
        sName = ""
        #Generate sane givenNamen and sName
        if len(namesname) > 0:
            givenName = str.join(' ',namesname[0:-1])
            sName = str.join('', namesname[-1:])

       
        #Generate LDAP Entry
        if Settings.sambaDN and domain==Settings.defaultDomain:            
            #Generate Samba Passwords
            LM = Utils.createLMHash(password) 
            NT = Utils.createNTHash(password) 
 
            # Acquire local SID
            l = LDAP.createLDAPConnection(Settings.LDAPServer, 'o='+Settings.LDAPBase, Settings.LDAPManager, Settings.LDAPPass)
            dc = "%s,o=%s" % (LDAP.domainToDC(domain), Settings.LDAPBase)
            domainData =  LDAP.getDomInfo(l, dc, Settings.SMBDomain)
            
            SID = str(domainData['sambaSID'][0])


            # Acquire UID offset
            uidOffset =  int(domainData['uidNumber'][0])

            # Make RID
            SIDOffset = 2*uidOffset
Beispiel #3
0
    def addUserToSmbDomain(self, data):
        """ Add a user to a samba domain"""
        # Hall out some data
        relevantData, domainUsers, domainData = self.getDomainData()
        timeNow = int(time.time())

        if data['userSettings.userPassword']:
            clearPassword = data['userSettings.userPassword'].encode(
                'ascii', 'replace')
        else:
            clearPassword = sha.sha("%s%s%s" % (random.randint(
                1, 2000), time.time(), random.randint(1, 4000))).hexdigest()
            data['userSettings.userPassword'] = clearPassword

        LM, NT = (Utils.createLMHash(clearPassword),
                  Utils.createNTHash(clearPassword))

        # Grab some data
        user = data['userSettings.uid'].encode('ascii', 'replace').lower()

        # SMB template
        newRecord = {
            'sambaPrimaryGroupSID':
            relevantData['sambaPrimaryGroupSID'],
            'sambaSID':
            relevantData['sambaSID'],
            'uidNumber':
            relevantData['uidNumber'],
            'gidNumber':
            513,
            'sambaPasswordHistory':
            '0000000000000000000000000000000000000000000000000000000000000000',
            'sambaPwdMustChange':
            2147483647,
            'sambaPwdCanChange':
            timeNow,
            'sambaNTPassword':
            NT,
            'sambaLMPassword':
            LM,
            'gecos':
            'System User',
            'o':
            self.ldapOrg,
            'objectClass': [
                'top', 'inetOrgPerson', 'posixAccount', 'shadowAccount',
                'SambaSamAccount', 'thusaUser'
            ],
            'sambaAcctFlags':
            '[U          ]',
            'sambaPwdLastSet':
            timeNow,

            # set this later..
            'employeeType': []
        }

        self.validateSettings(data, newRecord)
        print self.ldapify(newRecord)
        # Add user element
        self.connect()
        addElement(self.ldapConnector, 'uid=%s,%s' % (user, self.userDN),
                   self.ldapify(newRecord))

        # Add user to domain group if not already there
        if user not in domainUsers.get('memberUid'):
            newDomainUsers = copy.deepcopy(domainUsers)
            if not newDomainUsers.get('memberUid'):
                newDomainUsers['memberUid'] = [user]
            else:
                newDomainUsers['memberUid'].append(user)
            modifyElement(self.ldapConnector,
                          'cn=Domain Users,ou=Groups,' + self.baseDC,
                          domainUsers, newDomainUsers)

        # increment nextUid
        newDom = copy.deepcopy(domainData)
        newDom['uidNumber'] = [str(relevantData['uidNumber'] + 1)]
        modifyElement(self.ldapConnector,
                      'sambaDomainName=%s,%s' % (self.smbDomain, self.baseDC),
                      domainData, newDom)

        # Disconnect ourselves.
        self.disconnect()

        # Return the record we have added
        return self.ldapify(newRecord)
Beispiel #4
0
    def validateSettings(self, data, newRecord):
        """ Validates a form into the ldap record. Must be interchangable between add and edit """
        user = data['userSettings.uid'].encode('ascii', 'replace').lower()
        newRecord['uid'] = user

        # Set employeeType values
        empVals = []
        if data.get('userPermissions.employeeType'):
            empVals.append('squid')

        if data.get('userPermissions.tumsAdmin', None):
            # Tums Admin overrides every other setting
            empVals.append('tumsAdmin')
        else:
            if data.get('userPermissions.tumsUser', None):
                tuenc = 'tumsUser[%s]' % ','.join(
                    data['userPermissions.tumsUser'])
                empVals.append(tuenc.encode("ascii", "replace"))

            if data.get('userPermissions.tumsReports', None):
                empVals.append('tumsReports')

        if empVals:
            newRecord['employeeType'] = empVals
        elif newRecord.get('employeeType'):
            del newRecord['employeeType']

        # Account is active
        if data.get('userPermissions.accountStatus'):
            newRecord['accountStatus'] = 'active'
        elif newRecord.get('accountStatus'):
            del newRecord['accountStatus']

        # Mail forwarding addresses
        mFA = []
        for i in xrange(10):
            # Reap data into list
            if data.get('mailSettings.mailForwardingAddress%s' % i):
                ad = data['mailSettings.mailForwardingAddress%s' % i].replace(
                    ' ', '').replace('\r', '')
                if ad:
                    mFA.append(ad)
        if mFA:
            newRecord['mailForwardingAddress'] = [
                le.encode("ascii", "replace") for le in mFA
            ]
        elif newRecord.get('mailForwardingAddress'):
            del newRecord['mailForwardingAddress']

        # Mail aliases
        mAA = []
        for i in xrange(10):
            # Reap data into list
            if data.get('mailSettings.mailAlternateAddress%s' % i):
                ad = data['mailSettings.mailAlternateAddress%s' % i].replace(
                    ' ', '').replace('\r', '')
                if ad:
                    mAA.append(ad)
        if mAA:
            newRecord['mailAlternateAddress'] = [
                le.encode("ascii", "replace").strip('\r') for le in mAA
            ]
        elif newRecord.get('mailAlternateAddress'):
            del newRecord['mailAlternateAddress']

        # Password
        if data['userSettings.userPassword']:
            newRecord['userPassword'] = "******" + hashPassword(
                data['userSettings.userPassword'].encode("ascii", "replace"))

            if self.sambaDN:
                newRecord['sambaPwdLastSet'] = int(time.time())
                clearPassword = data['userSettings.userPassword'].encode(
                    'ascii', 'replace')
                newRecord['sambaLMPassword'] = Utils.createLMHash(
                    clearPassword)
                newRecord['sambaNTPassword'] = Utils.createNTHash(
                    clearPassword)
                if newRecord.get('sambaPwdMustChange'):
                    del newRecord['sambaPwdMustChange']

        sn = data.get('userSettings.sn') or '-'
        gn = data.get('userSettings.givenName') or user.capitalize()

        newRecord['sn'] = sn
        newRecord['givenName'] = gn
        newRecord['cn'] = "%s %s" % (gn, sn)

        # FTP data
        if data.get('userAccess.ftpGlobal'):
            ftp = self.sysconf.FTP
            if ftp.get('globals', None):
                if newRecord['uid'] not in ftp['globals']:
                    ftp['globals'].append(user)
            else:
                ftp['globals'] = [user]

            self.sysconf.FTP = ftp
        else:
            ftp = self.sysconf.FTP
            newGlobals = []
            globals = ftp.get('globals', [])
            for id in globals:
                if id != user:
                    newGlobals.append(id)
            ftp['globals'] = newGlobals
            self.sysconf.FTP = ftp

        if self.sambaDN:
            newRecord['loginShell'] = data.get(
                'userAccess.ftpEnabled', False) and '/bin/bash' or '/bin/false'
            newRecord['homeDirectory'] = '/home/%s' % user

        emailAddress = str("%s@%s" % (user, self.domain))
        newRecord['mailMessageStore'] = '/var/spool/mail/' + emailAddress
        newRecord['mail'] = emailAddress
Beispiel #5
0
    def validateFormData(self, dc, data, newRecord):
        newRecord['uid'] = [data['userSettings.uid'].encode("utf-8").lower()]
        sn = data['userSettings.sn'] or u""
        if sn:
            newRecord['sn'] = [sn.encode("utf-8")]
        else:
            newRecord['sn'] = [" "]

        shell = '/bin/false'
        if data['userAccess.ftpEnabled']:
            shell = '/bin/bash'

        if Settings.sambaDN and self.domain==Settings.defaultDomain:
            newRecord['loginShell'] = [shell]

        uid = data['userSettings.uid'].encode("utf-8").lower()
        if data['userAccess.ftpGlobal']:
            ftp = self.sysconf.FTP
            if ftp.get('globals', None):
                if uid not in ftp['globals']:
                    ftp['globals'].append(uid)
            else:
                ftp['globals'] = [uid]
            
            self.sysconf.FTP = ftp
        else:
            ftp = self.sysconf.FTP
            newGlobals = []
            globals = ftp.get('globals', [])
            for id in globals:
                if id != uid:
                    newGlobals.append(id)
            ftp['globals'] = newGlobals
            self.sysconf.FTP = ftp

        # Disable password change date
        if data.get('sambaPwdMustChange'):
            del data['sambaPwdMustChange']
        
        if data.get('sambaPwdLastSet'):
            data['sambaPwdLastSet'] = [str(int(time.time()))]

        if data['userSettings.givenName']:
            newRecord['givenName'] = [data['userSettings.givenName'].encode("utf-8")]
        else:
            newRecord['givenName'] = [data['userSettings.uid'].encode("utf-8").capitalize()]

        newRecord['cn'] =  ["%s %s" % (newRecord['givenName'][0], sn.encode("utf-8"))]

        newRecord['employeeType'] = []
        if data['userPermissions.employeeType']:
            newRecord['employeeType'].append('squid')

        if data.get('userPermissions.tumsAdmin', None):
            newRecord['employeeType'].append('tumsAdmin')
        elif data.get('userPermissions.tumsUser', None):
            tuenc = 'tumsUser[%s]' % ','.join(data['userPermissions.tumsUser'])
            newRecord['employeeType'].append(tuenc.encode())

        if data.get('userPermissions.tumsReports', None):
            newRecord['employeeType'].append('tumsReports')

        if data['userPermissions.accountStatus']:
            newRecord['accountStatus'] = [ 'active' ]
        elif newRecord.get('accountStatus',False):
            del newRecord['accountStatus']

        mFA = []
        for i in xrange(10):
            if data['mailSettings.mailForwardingAddress%s' % i]:
                ad = data['mailSettings.mailForwardingAddress%s' % i].replace(' ', '').replace('\r','')
                if ad:
                    mFA.append(ad)
        if mFA:
            newRecord['mailForwardingAddress'] = [ le.encode() for le in mFA ]
        else:
            try:
                del newRecord['mailForwardingAddress']
            except:
                pass

        mAA = []
        for i in xrange(10):
            if data['mailSettings.mailAlternateAddress%s' % i]:
                ad = data['mailSettings.mailAlternateAddress%s' % i].replace(' ', '').replace('\r','')
                if ad:
                    mAA.append(ad)
        if mAA:
            newRecord['mailAlternateAddress'] = [ le.encode().strip('\r') for le in mAA ]
        else:
            try:
                del newRecord['mailAlternateAddress']
            except:
                pass

        if data['userSettings.userPassword']:
            newRecord['userPassword'] = ["{SHA}"+LDAP.hashPassword(data['userSettings.userPassword'])]

            if Settings.sambaDN and self.domain==Settings.defaultDomain:
                newRecord['sambaLMPassword'] = Utils.createLMHash(data['userSettings.userPassword'])
                newRecord['sambaNTPassword'] = Utils.createNTHash(data['userSettings.userPassword'])

        return newRecord
Beispiel #6
0
    def submitForm(self, ctx, form, data):
        user = data['userSettings.uid'].encode("utf-8").lower()
        data['userSettings.uid'] = user
        emailAddress = str("%s@%s" % (user, self.domain))
        if not data['userSettings.sn']:
            data['userSettings.sn'] = "-"
        if not data['userSettings.givenName']:
            data['userSettings.givenName'] = user.capitalize()

        if data['userPermissions.copyto']:
            address = emailAddress
            mailConf = self.sysconf.Mail
            if mailConf.get('copys', []):
                mailConf['copys'].append(
                    (address, data['userPermissions.copyto']))
            else:
                mailConf['copys'] = [(address, data['userPermissions.copyto'])]
            self.sysconf.Mail = mailConf
            # We need to restart exim if a copyto was set
            WebUtils.system(
                '/usr/local/tcs/tums/configurator --exim; /etc/init.d/exim4 restart'
            )

        if data['userSettings.userPassword']:
            clearPassword = data['userSettings.userPassword'].encode()
        else:
            clearPassword = sha.sha("%s" % random.randint(1, 4000)).hexdigest()

        LM = Utils.createLMHash(clearPassword)
        NT = Utils.createNTHash(clearPassword)

        if Settings.sambaDN and self.domain == Settings.defaultDomain:
            # Acquire local SID
            l = LDAP.createLDAPConnection(Settings.LDAPServer,
                                          'o=' + Settings.LDAPBase,
                                          Settings.LDAPManager,
                                          Settings.LDAPPass)
            dc = "%s,o=%s" % (LDAP.domainToDC(self.domain), Settings.LDAPBase)
            domainData = LDAP.getDomInfo(l, dc, Settings.SMBDomain)

            SID = str(domainData['sambaSID'][0])

            # Acquire UID offset
            uidOffset = int(domainData['uidNumber'][0])

            # Make RID
            SIDOffset = 2 * uidOffset

            # Append user to Domain Users
            try:
                domainUsers = LDAP.getDomUsers(l, dc)
                newDomainUsers = copy.deepcopy(domainUsers)
                if not newDomainUsers.get('memberUid',
                                          None):  # Very very new domain
                    newDomainUsers['memberUid'] = []
                newDomainUsers['memberUid'].append(user)
                LDAP.modifyElement(l, 'cn=Domain Users,ou=Groups,' + dc,
                                   domainUsers, newDomainUsers)
            except:
                pass  # User already in group

            # Increment UID for domain
            newDom = copy.deepcopy(domainData)
            newDom['uidNumber'] = [str(uidOffset + 1)]
            try:
                LDAP.modifyElement(
                    l, 'sambaDomainName=%s,%s,o=%s' %
                    (Settings.SMBDomain, LDAP.domainToDC(
                        self.domain), Settings.LDAPBase), domainData, newDom)
            except:
                pass  # User has a uid or something

            timeNow = str(int(time.time()))
            # LDAP template for SAMBA
            shell = '/bin/false'
            if data['userAccess.ftpEnabled']:
                shell = '/bin/bash'
            newRecord = {
                'sambaPrimaryGroupSID':
                [SID + "-" + str(1000 + SIDOffset + 1)],
                'sambaSID': [SID + "-" + str(1000 + SIDOffset)],
                'gidNumber': ['513'],
                'uidNumber': [str(uidOffset)],
                'sambaPasswordHistory': [
                    '0000000000000000000000000000000000000000000000000000000000000000'
                ],
                'sambaPwdMustChange': ['2147483647'],
                'sambaPwdCanChange': [timeNow],
                'sambaNTPassword': [NT],
                'sambaLMPassword': [LM],
                'gecos': ['System User'],
                'sn': [data['userSettings.sn'].encode("utf-8")],
                'givenName': [data['userSettings.givenName'].encode("utf-8")],
                'cn': [
                    "%s %s" % (data['userSettings.givenName'].encode("utf-8"),
                               data['userSettings.sn'].encode("utf-8"))
                ],
                'o': [Settings.LDAPOrganisation],
                'objectClass': [
                    'top', 'inetOrgPerson', 'posixAccount', 'shadowAccount',
                    'SambaSamAccount', 'thusaUser'
                ],
                'loginShell': [shell],
                'sambaPwdLastSet': [timeNow],
                'sambaAcctFlags': ['[U          ]'],
                'mailMessageStore': ['/var/spool/mail/' + emailAddress],
                'mail': [emailAddress],
                'homeDirectory': ['/home/%s' % user],
                'uid': [user],
                'employeeType': []
            }
            l.unbind_s()
        else:
            # LDAP Template for without samba
            newRecord = {
                'sn': [data['userSettings.sn'].encode("utf-8")],
                'givenName': [data['userSettings.givenName'].encode("utf-8")],
                'cn': [
                    "%s %s" % (data['userSettings.givenName'].encode("utf-8"),
                               data['userSettings.sn'].encode("utf-8"))
                ],
                'o': [Settings.LDAPOrganisation],
                'objectClass': ['top', 'inetOrgPerson', 'thusaUser'],
                'mailMessageStore': ['/var/spool/mail/' + emailAddress],
                'mail': [emailAddress],
                'uid': [user],
                'employeeType': []
            }

        self.validateAttributes(data, newRecord)

        self.addEntry(newRecord, user, data['userPermissions.accountStatus'],
                      data['userAccess.vpnEnabled'])

        # Create Home directory and restart NSCD
        if Settings.sambaDN and self.domain == Settings.defaultDomain:
            WebUtils.system('/etc/init.d/nscd restart')
            WebUtils.system('mkdir /home/%s; chown %s:Domain\ Users /home/%s' %
                            (user, user, user))

        WebUtils.system(
            '/usr/local/tcs/tums/configurator --ftp; /etc/init.d/vsftpd restart'
        )
        return url.root.child('Users').child('Edit').child(
            self.domain).child(user)