Example #1
0
    def editUser(self, userDN, fields):
        t = {
            'name': 'cn',
            'surname': 'sn',
            'homeDirectory': 'homeDirectory',
            'address': 'homePostalAddress',
            'mail': 'mail',
            'phone': 'homePhone',
            'loginShell': 'loginShell',
            'password': '******'
        }
        change = {}
        for i in t.keys():
            if not userDN.has_key(t[i]): userDN[t[i]] = ['']
            if not fields.has_key(i): fields[i] = ''
            if userDN[t[i]][0] <> fields[i]:
                change[t[i]] = fields[i]

        if change == {}: return
        if change.has_key('userPassword'):
            from passlib.hash import ldap_salted_sha1
            change['userPassword'] = \
                    ldap_salted_sha1.encrypt(
                            change['userPassword'])

        con = self.__getCon()
        for i in change.keys():
            con.modify("uid=%s" % userDN['uid'][0], i, change[i])

        del con
Example #2
0
    def editUser(self, userDN, fields):
        t = {'name':'cn',
             'surname':'sn', 'homeDirectory': 'homeDirectory',
             'address':'homePostalAddress', 'mail':'mail',
             'phone':'homePhone', 'loginShell': 'loginShell',
             'password':'******'
             }
        change = {}
        for i in t.keys():
            if not userDN.has_key(t[i])   : userDN[t[i]] = ['']
            if not fields.has_key(i): fields[i] = ''
            if userDN[t[i]][0] <> fields[i]:
                change[t[i]] = fields[i]

        if change == {}: return
        if change.has_key('userPassword'):
            from passlib.hash import ldap_salted_sha1
            change['userPassword'] = \
                    ldap_salted_sha1.encrypt(
                            change['userPassword'])

        con = self.__getCon()
        for i in change.keys():
                con.modify("uid=%s" % userDN['uid'][0], i, change[i])

        del con
Example #3
0
File: LDAPapi.py Project: tubav/sfa
 def encrypt_password(self, password):
     """ Use passlib library to make a RFC2307 LDAP encrypted password
     salt size = 8, use sha-1 algorithm. Returns encrypted password.
     
     """
     #Keep consistency with Java Senslab's LDAP API 
     #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytres
     return lssha.encrypt(password, salt_size = 8)
Example #4
0
    def encrypt_password(password):
        """

        Use passlib library to make a RFC2307 LDAP encrypted password salt size
        is 8, use sha-1 algorithm.

        :param password:  password not encrypted.
        :type password: string
        :returns: Returns encrypted password.
        :rtype: string

        """
        #Keep consistency with Java Iotlab's LDAP API
        #RFC2307SSHAPasswordEncryptor so set the salt size to 8 bytes
        return lssha.encrypt(password, salt_size=8)
Example #5
0
    def save(self, *args, **kwargs):
        """
        save the model and set implicit attributes like sambaSID etc
        """
        # userGroups is given as kwarg by the view as list of strings
        # we get the corresponding ldapgroups and check which are new
        # and which can be deleted
        userGroups = kwargs.pop('userGroups', [])
        newUserGroups = map(lambda g: get_or_none(LdapGroup, cn=g), userGroups)
        newUserGroups = filter(None, newUserGroups)
        currentUserGroups = LdapGroup.objects.filter(
            memberUid__contains=self.uid)
        deletedGroups = [
            g for g in currentUserGroups if g not in newUserGroups
        ]
        for group in deletedGroups:
            group.memberUid.remove(self.uid)
            group.save()
        for group in newUserGroups:
            if self.uid not in group.memberUid:
                group.memberUid.append(self.uid)
                group.save()

        # implicit attributes
        self.cn = self.givenName + ' ' + self.sn
        self.sambaSID = settings.SAMBA_SID + '-' + str(self.uidNumber * 2 +
                                                       1000)
        self.homeDirectory = '/home/' + self.uid
        self.loginShell = settings.DEFAULT_SHELL
        # build unix timestamp from given date format (dd.mm.yyyy)
        if self.deIappBirthday:
            self.deIappBirthday = date2timestamp(self.deIappBirthday)
        # password is given as kwarg by the view
        # sha1, lm/nt hashes are build from this password and will be saved
        password = kwargs.pop('password', False)
        if password:
            from passlib.hash import ldap_salted_sha1 as lss
            from passlib.hash import lmhash
            from passlib.hash import nthash
            self.userPassword = lss.encrypt(password)
            self.sambaLMPassword = lmhash.encrypt(password).upper()
            self.sambaNTPassword = nthash.encrypt(password).upper()
        super(LdapUser, self).save(*args, **kwargs)
Example #6
0
    def save(self, *args, **kwargs):
        """
        save the model and set implicit attributes like sambaSID etc
        """
        # userGroups is given as kwarg by the view as list of strings
        # we get the corresponding ldapgroups and check which are new
        # and which can be deleted
        userGroups = kwargs.pop('userGroups', [])
        newUserGroups = map(lambda g: get_or_none(LdapGroup, cn=g), userGroups)
        newUserGroups = filter(None, newUserGroups)
        currentUserGroups = LdapGroup.objects.filter(memberUid__contains=self.uid)
        deletedGroups = [g for g in currentUserGroups if g not in newUserGroups]
        for group in deletedGroups:
            group.memberUid.remove(self.uid)
            group.save()
        for group in newUserGroups:
            if self.uid not in group.memberUid:
                group.memberUid.append(self.uid)
                group.save()

        # implicit attributes
        self.cn = self.givenName + ' ' + self.sn
        self.sambaSID = settings.SAMBA_SID + '-' + str(self.uidNumber * 2 + 1000)
        self.homeDirectory = '/home/' + self.uid
        self.loginShell = settings.DEFAULT_SHELL
        # build unix timestamp from given date format (dd.mm.yyyy)
        if self.deIappBirthday:
            self.deIappBirthday = date2timestamp(self.deIappBirthday)
        # password is given as kwarg by the view
        # sha1, lm/nt hashes are build from this password and will be saved
        password = kwargs.pop('password', False)
        if password:
            from passlib.hash import ldap_salted_sha1 as lss
            from passlib.hash import lmhash
            from passlib.hash import nthash
            self.userPassword = lss.encrypt(password)
            self.sambaLMPassword = lmhash.encrypt(password).upper()
            self.sambaNTPassword = nthash.encrypt(password).upper()
        super(LdapUser, self).save(*args, **kwargs)
Example #7
0
def pass_encrypt(passwd):
    return ssha.encrypt(passwd, salt_size=16)
Example #8
0
def hashPassword(password):
    """ Generate a password in SSHA format suitable for ldap """
    return ldap_salted_sha1.encrypt(password)
Example #9
0
def make_secret(password):
    return ldap_salted_sha1.encrypt(password)
Example #10
0
def ldap_create_password(raw_password):
    return ldap_salted_sha1.encrypt(raw_password)
Example #11
0
 def ___void___encrypt_password___(self, password):
     self.password = passlib___ldap_salted_sha1.encrypt(password)
Example #12
0
def hashPassword(password):
    """ Generate a password in SSHA format suitable for ldap """
    return ldap_salted_sha1.encrypt(password)
Example #13
0
 def get_pwhash_for_user(self, textplain_passwd):
     # Only needed for that
     from passlib.hash import ldap_salted_sha1
     password_hash = ldap_salted_sha1.encrypt(textplain_passwd)
     return password_hash
Example #14
0
def add_member(request):
    """Add kiberpipa memeber with all the stuff"""
    if not request.user.is_staff:
        return

    form = NewMemberForm(request.POST or None)

    if request.method == "POST" and form.is_valid():
        # create ldap record
        password = "".join(random.sample(string.letters + string.digits, 8))
        password_hash = ldap_salted_sha1.encrypt(password)

        uid = int(
            subprocess.Popen(
                "getent passwd | awk -F: '$3 < 3000 { print $3 }' | sort -n | tail -1",
                stdout=subprocess.PIPE,
                shell=True,
            )
            .communicate()[0]
            .strip()
        )
        uid += 1
        gid = int(
            subprocess.Popen(
                "getent group | awk -F: '$3 < 3000 { print $3 }' | sort -n | tail -1",
                stdout=subprocess.PIPE,
                shell=True,
            )
            .communicate()[0]
            .strip()
        )
        gid += 1

        ldif_template = get_template("org/member_add.ldif").render(
            Context(dict(data=form.cleaned_data, password_hash=password_hash, uid=uid, gid=gid))
        )

        with tempfile.NamedTemporaryFile() as f:
            f.write(ldif_template.encode("utf-8"))
            f.flush()
            subprocess.check_call(
                "sudo -u root ldapadd -D cn=admin,dc=kiberpipa,dc=org -f %s -w %s" % (f.name, settings.LDAP_PASSWORD),
                shell=True,
            )

        # create home folder
        # TODO: dogbert login
        # subprocess.check_call('sudo -u root mkdir -p /home/%s' % form.cleaned_data['username'],
        #                      shell=True)
        # TODO: chown it (sudoers should be very strict about this)
        # subprocess.check_call('sudo -u root chown -p /home/%s' % form.cleaned_data['username'],
        #                      shell=True)

        # TODO: add member to redmine group

        # add him to pipa-org
        if form.cleaned_data["add_to_private_mailinglist"]:
            mailman_list = List.objects.get(id=2)
            try:
                mailman_list.subscribe(form.cleaned_data["email"])
            except:
                pass  # member is already subscribed

        # send email to new user
        html = get_template("mail/member_add_welcome_email.html").render(
            Context(dict(username=form.cleaned_data["username"], password=password))
        )
        send_mail(u"Dobrodošel/a v Kiberpipi!", html, settings.DEFAULT_FROM_EMAIL, [form.cleaned_data["email"]])

        # add a diary we added a member
        diary = Diary(
            log_formal=u"Dodal novega člana: %s (%s %s)"
            % (form.cleaned_data["username"], form.cleaned_data["firstname"], form.cleaned_data["surname"]),
            author=request.user,
            length=datetime.time(1),  # 1h
            task=Project.objects.get(id=2),
        )
        diary.save()

        return render_to_response(
            "org/member_add_success.html",
            {"email": form.cleaned_data["email"]},
            context_instance=RequestContext(request),
        )

    return render_to_response("org/member_add.html", {"form": form}, context_instance=RequestContext(request))
Example #15
0
def ldap_create(raw_password):
    return ldap_salted_sha1.encrypt(raw_password)
Example #16
0
}

currentUid = 10
rownb = 0


def getField(row, idx, fieldname):
    if row[idx] is '':
        raise Exception("Empty " + fieldname + " on row " + str(rownb))
    return row[idx]


for row in inputReader:
    employeeNumber = row[0]  # user id
    uid = getField(row, 1, 'uid')  # login
    userPassword = ldap_salted_sha1.encrypt(getField(
        row, 2, 'userPassword'))  # password
    mail = getField(row, 3, 'mail')  # email
    givenName = row[4]  # first name
    sn = row[5]  # second name
    o = row[6]  # org / company
    title = row[7]  # job situation
    telephoneNumber = row[8]  # phone number
    currentGroups = getField(row, 9,
                             'groups').replace(' ', '').split(GROUP_SEPARATOR)

    for currentGroup in currentGroups:
        if not groups.has_key(currentGroup):
            groups[currentGroup] = {'users': [], 'id': currentUid}
            currentUid += 1
        groups[currentGroup]['users'].append("uid=" + uid + ",ou=users," +
                                             LDAP_ROOT_DN)
Example #17
0
    },
}

currentUid = 10
rownb = 0

def getField(row, idx, fieldname):
    if row[idx] is '':
        raise Exception("Empty "+fieldname+" on row " + str(rownb))
    return row[idx]


for row in inputReader:
    employeeNumber   = row[0] # user id
    uid              = getField(row, 1, 'uid') # login
    userPassword     = ldap_salted_sha1.encrypt(getField(row, 2, 'userPassword')) # password
    mail             = getField(row, 3, 'mail') # email
    givenName        = row[4] # first name
    sn               = row[5] # second name
    o                = row[6] # org / company
    title            = row[7] # job situation
    telephoneNumber  = row[8] # phone number
    currentGroups    = getField(row, 9, 'groups').replace(' ', '').split(GROUP_SEPARATOR)

    for currentGroup in currentGroups:
        if not groups.has_key(currentGroup):
            groups[currentGroup] = {'users': [], 'id': currentUid}
            currentUid += 1
        groups[currentGroup]['users'].append("uid="+uid+",ou=users," + LDAP_ROOT_DN)

    rownb += 1
Example #18
0
def pass_encrypt(passwd):
    return ssha.encrypt(passwd, salt_size=16)
Example #19
0
def add_member(request):
    """Add kiberpipa memeber with all the stuff"""
    if not request.user.is_staff:
        return

    form = NewMemberForm(request.POST or None)

    if request.method == "POST" and form.is_valid():
        # create ldap record
        password = ''.join(random.sample(string.letters + string.digits, 8))
        password_hash = ldap_salted_sha1.encrypt(password)

        ldif_template = get_template('org/member_add.ldif').render(Context(dict(
            data=form.cleaned_data,
            password_hash=password_hash,
        )))

        with tempfile.NamedTemporaryFile() as f:
            f.write(ldif_template.encode('utf-8'))
            f.flush()
            
            p = subprocess.Popen('sudo -u root ldapadd -D cn=admin,dc=kiberpipa,dc=org -f %s -w %s' % (f.name, settings.LDAP_PASSWORD),
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 shell=True)
            
            stdout, stderr = p.communicate()
            if p.returncode != 0:
                raise Exception("Failed adding a member to opendalp.")

        # add him to pipa-org
        if form.cleaned_data['add_to_private_mailinglist']:
            mailman_list = List.objects.get(id=2)
            try:
                mailman_list.subscribe(form.cleaned_data['email'])
            except:
                pass  # member is already subscribed

        # send email to new user
        html = get_template('mail/member_add_welcome_email.html').render(
            Context(dict(
                username=form.cleaned_data['username'],
                password=password,
        )))
        send_mail(u'Dobrodošel/a v Kiberpipi!',
                  html,
                  settings.DEFAULT_FROM_EMAIL,
                  [form.cleaned_data['email']])

        # add a diary we added a member
        diary = Diary(
            log_formal=u"Dodal novega člana: %s (%s %s)" % (form.cleaned_data['username'],
                                                            form.cleaned_data['firstname'],
                                                            form.cleaned_data['surname']),
            author=request.user,
            length=datetime.time(1),  # 1h
            task=Project.objects.get(id=2),
        )
        diary.save()

        return render_to_response(
            'org/member_add_success.html',
            {'email': form.cleaned_data['email']},
            context_instance=RequestContext(request))

    return render_to_response(
        'org/member_add.html',
        {'form': form},
        context_instance=RequestContext(request))
Example #20
0
def main(roles, orgs):
    currentRoleUid = len(roles) + 1
    currentOrgUid = len(orgs) + 1
    rownb = 0

    if os.path.isfile(USERS_FILE):
        inputUsersReader = csv.reader(
            open(USERS_FILE, 'r'), delimiter=CSV_DELIMITER, quotechar=CSV_QUOTECHAR)

        if HEADER:
            next(inputUsersReader)

        for row in inputUsersReader:
            employeeNumber = row[0].strip()  # user id
            uid = getField(rownb, row[1].strip(), 'uid')  # login
            userPassword = ldap_salted_sha1.encrypt(
                getField(rownb, row[2].strip(), 'userPassword'))  # password
            mail = getField(rownb, row[3].strip(), 'mail')  # email
            if not mail.strip():
                uid + '@empty.com'
            givenName = row[4].strip()  # first name
            sn = row[5].strip()  # second name
            if not sn.strip():
                sn = uid
            o = row[6].strip()  # org / company
            title = row[7].strip()  # job situation
            telephoneNumber = row[8].strip()  # phone number
            postalAddress = row[9].strip()  # address

            currentRoles = getField(rownb, row[11], 'roles').replace(
                ' ', '').split(ROLE_SEPARATOR)
            for currentRole in currentRoles:
                currentRole = currentRole.strip()
                if not currentRole in roles:
                    roles[currentRole] = {'users': [], 'id': currentRoleUid}
                    currentRoleUid += 1
                roles[currentRole]['users'].append(
                    "uid=" + uid + ",ou=users," + LDAP_ROOT_DN)

            currentOrg = getField(rownb, row[6].strip(), 'org')
            if not currentOrg in orgs:
                orgs[currentOrg] = {'users': [], 'id': currentOrgUid}
                currentOrgUid += 1
            orgs[currentOrg]['users'].append(
                "uid=" + uid + ",ou=users," + LDAP_ROOT_DN)

            user = [
                '# user, ' + uid,
                'dn: uid=' + uid + ',ou=users,' + LDAP_ROOT_DN,
                'objectClass: inetOrgPerson',
                'objectClass: organizationalPerson',
                'objectClass: person',
                'objectClass: shadowAccount',
                'objectClass: top',
                'uid: ' + uid,
                'userPassword: '******'sn: ' + sn,
                'cn: ' + givenName + ' ' + sn,
                'mail: ' + mail
            ]

            if employeeNumber.strip() is not '':
                user.append('employeeNumber: ' + employeeNumber)
            if givenName.strip() is not '':
                user.append('givenName: ' + givenName)
            if title.strip() is not '':
                user.append('title: ' + title)
            if telephoneNumber.strip() is not '':
                user.append('telephoneNumber: ' + telephoneNumber)
            if postalAddress.strip() is not '':
                user.append(
                    'postalAddress:: ' + base64.b64encode(postalAddress.encode('windows-1252')).decode('utf8'))
            print(EOL.join(user) + EOL)

            rownb += 1

    for roleName, roleValues in roles.items():
        if roleName:
            role = [
                '# role, ' + roleName,
                'dn: cn=' + roleName + ',ou=roles,' + LDAP_ROOT_DN,
                'objectClass: groupOfMembers',
                'objectClass: top',
                'cn: ' + roleName
            ]
            # print(roleValues['users'])
            for member in roleValues['users']:
                role.append('member: ' + member)
            print(EOL.join(role) + EOL)

    if os.path.isfile(ORGS_FILE):
        inputOrgsReader = csv.reader(
            open(ORGS_FILE, 'r'), delimiter=CSV_DELIMITER, quotechar=CSV_QUOTECHAR)

        if HEADER:
            next(inputOrgsReader)

        for row in inputOrgsReader:
            ou = getField(rownb, row[1].strip(), 'ou')  # ou (obj 2)
            o1 = ou.lower()  # o (obj 1)
            o2 = getField(rownb, row[2].strip(), 'o2')  # o (obj 2)
            businessCategory = row[3].strip()  # businessCategory (obj 1)
            postalAddress = row[4].strip()  # postalAddress (obj 1)
            description = row[5].strip()  # description (obj 1)
            registered = row[6].strip()  # businessCategory (obj 2)

            org1 = [
                '# org, organization, ' + o1,
                'dn: o=' + o1 + ', ou=orgs, ' + LDAP_ROOT_DN,
                'objectClass: organization',
                'objectClass: top',
                'o: ' + o1,
                'businessCategory: ' + businessCategory
            ]

            if postalAddress:
                org1.append('postalAddress:: ' + base64.b64encode(postalAddress.encode(
                    'windows-1252')).decode('utf8'))

            print(EOL.join(org1) + EOL)

            org2 = [
                '# org, groupOfMembers, ' + o1,
                'dn: cn=' + o1 + ', ou=orgs, ' + LDAP_ROOT_DN,
                'objectClass: groupOfMembers',
                'objectClass: top',
                'cn: ' + o1,
                'o: ' + o2,
                'ou: ' + ou,
                'seeAlso: o=' + o1 + ', ou=orgs, ' + LDAP_ROOT_DN
            ]
            if description:
                org2.append('description:: ' + base64.b64encode(description.encode(
                    'windows-1252')).decode('utf8'))
            if registered:
                org2.append('businessCategory: REGISTERED')

            for orgName, orgValues in orgs.items():
                if orgName.lower() == o1:
                    for member in orgValues['users']:
                        org2.append('member: ' + member)

            print(EOL.join(org2) + EOL)