Example #1
0
def personal_changepassword(request):
    if not request.method == "POST":
        return JsonResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED, data={})
    data = ast.literal_eval(request.body.decode('utf-8'))
    OperateLog.create_log(request)
    try:
        with connect_ldap() as c:
            c.search('ou=Users,dc=xiaoneng,dc=cn',
                     search_filter='(objectClass=inetOrgPerson)',
                     attributes=['userPassword', 'cn'],
                     search_scope=SUBTREE)
            ldap_password = ''
            dn = ''
            for i in c.entries:
                cn = i.entry_attributes_as_dict['cn'][0]
                print(cn)
                if i.entry_attributes_as_dict['cn'][0] == request.user.get_username():
                    ldap_password = i.entry_attributes_as_dict['userPassword'][0]
                    dn = i.entry_dn
                    break
            if ldap_password and sha.verify(data['old_password'], ldap_password):
                c.modify(dn, {'userpassword': [(MODIFY_REPLACE, sha.hash(data['new_password']))]})
                # 修改本地密码
                user = User.objects.get(username=cn)
                user.password = sha.hash(data['new_password'])
                user.save()
            else:
                return JsonResponse(status=status.HTTP_400_BAD_REQUEST,
                                    data={"result": False, "error": '旧密码错误, 验证失败'})

        return JsonResponse(status=status.HTTP_200_OK,
                            data={"result": True, "message": "修改成功"})
    except Exception as e:
        return JsonResponse(status=status.HTTP_400_BAD_REQUEST,
                            data={"result": False, "error": str(e.args)})
Example #2
0
    def _attributes_to_ldap_attributes(self, attributes):
        """
        takes the attributes and maps them to the LDAP attributes
        :param attributes: Attributes to be updated
        :type attributes: dict
        :return: dict with attribute name as keys and values
        """
        ldap_attributes = {}
        for fieldname, value in attributes.items():
            if self.map.get(fieldname):
                if fieldname == "password":
                    # Variable value may be either a string or a list
                    # so catch the TypeError exception if we get the wrong
                    # variable type
                    try:
                        pw_hash = ldap_salted_sha1.hash(value[1][0])
                        value[1][0] = pw_hash
                        ldap_attributes[self.map.get(fieldname)] = value
                    except TypeError as e:
                        pw_hash = ldap_salted_sha1.hash(value)
                        ldap_attributes[self.map.get(fieldname)] = pw_hash
                else:
                    ldap_attributes[self.map.get(fieldname)] = value

        return ldap_attributes
Example #3
0
def reset(request):
    passwd = sha.hash(request.GET.get('password', ''))
    if not passwd:
        return Response(status=status.HTTP_400_BAD_REQUEST,
                        data={
                            "result": False,
                            "error": "密码输入为空!"
                        })
    # aeskey = request.session.get('aeskey', '')
    aeskey = request.GET.get('new_key', '')
    if aeskey:
        decry_str = decrypt(aeskey)
        username = decry_str.split(':')[0]
        req_timestamp = decry_str.split(':')[2]
        if time.time() - float(req_timestamp) > 3600:
            return Response(status=status.HTTP_400_BAD_REQUEST,
                            data={
                                "result": False,
                                "error": "重置链接超时"
                            })
        else:
            try:
                with connect_ldap() as ldap_conn:
                    ldap_conn.search(
                        search_base='ou=Users,dc=xiaoneng,dc=cn',
                        search_filter='(objectClass=inetOrgPerson)',
                        search_scope=SUBTREE,
                        attributes=['userPassword', 'cn'])
                    for entry in ldap_conn.entries:
                        if entry.entry_attributes_as_dict['cn'][0] == username:
                            ldap_conn.modify(
                                entry.entry_dn,
                                {'userpassword': [(MODIFY_REPLACE, passwd)]})
                            if ldap_conn.result['result'] == 0:
                                return Response({
                                    "result": True,
                                    "error": "密码重置成功"
                                })
                            else:
                                data = {
                                    "result": False,
                                    "error": "str(ldap_conn.result['message'])"
                                }
                                return Response(
                                    status=status.HTTP_400_BAD_REQUEST,
                                    data=data)
            except Exception as e:
                traceback.print_exc()
                return Response(status=status.HTTP_400_BAD_REQUEST,
                                data={
                                    "result": False,
                                    "error": str(e.args)
                                })
    else:
        return Response(status=status.HTTP_400_BAD_REQUEST,
                        data={
                            "result": False,
                            "error": "未获取到令牌"
                        })
Example #4
0
def bf(h, dictionary):

    f = open(dictionary, 'r')
    lines = f.readlines()
    print('\033[1;34m[*]\033[0m Starting Brute Force - hash = ' + h)
    for i in lines:

        h2 = ldap_salted_sha1.hash(i[:-1])

        if h == h2:

            print('\033[1;32m[+]\033[0m Hash Cracked! - Password = ' + i)
Example #5
0
def personal_changepassword(request):
    if not request.method == "POST":
        return JsonResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED, data={})
    data = ast.literal_eval(request.body.decode('utf-8'))
    user = request.user.get_username()

    OperateLog.create_log(request)

    mode = login_model
    # 校验ldap是否有该用户
    ldap_exit = User.objects.filter(user_profile__create_source=1).filter(username=user).exists()
    # 校验本地是否有该用户
    local_exit = User.objects.filter(user_profile__create_source=2).filter(username=user).exists()

    # ldap
    if mode == 1:
        ldap_change_password(request, **data)
        user = User.objects.filter(user_profile__create_source=1).get(username=user)
        user.password = sha.hash(data["new_password"])
        user.save()
    # 本地
    elif mode == 2:
        user = User.objects.filter(user_profile__create_source=2).get(username=user)
        if sha.verify(data['old_password'], user.password):
            user.password = sha.hash(data["new_password"])
            user.save()
    # 本地+ldap   ldap+本地
    elif mode == 3 or mode == 4:
        if ldap_exit:
            ldap_change_password(request, **data)
            user = User.objects.filter(user_profile__create_source=1).get(username=user)
            user.password = sha.hash(data["new_password"])
            user.save()
        if local_exit:
            user = User.objects.filter(user_profile__create_source=2).get(username=user)
            if sha.verify(data['old_password'], user.password):
                user.password = sha.hash(data["new_password"])
                user.save()
    return JsonResponse(status=status.HTTP_200_OK, data={"info": "修改成功"})
Example #6
0
def userPasswordUpdate(userGroupName):
    while 1:
        passwd1 = getpass.getpass("New password ........................ : ")
        passwd2 = getpass.getpass("Confirm new password ................ : ")
        
        if passwd1 == passwd2:
            break
        else:
            print("\n"+"Error ! - typing doesn't match."+"\n")
    
    oldPassword = {"userPassword": ["*"]}
    newPassword = {"userPassword": [str(ssha.hash(passwd1)).encode("utf-8")]}
    
    modifyAttributes = ldap.modlist.modifyModlist(oldPassword, newPassword)
    
    connect.modify_s("cn="+ userGroupName +","+ peopleBaseDN, modifyAttributes)
    connect.unbind_s()
Example #7
0
def local_user_add(**data):
    user_info = {"username": data["cn"],
                 "password": sha.hash(data["password"]),
                 "email": '*****@*****.**' % data['cn'],
                 "last_name": data["sn"]}
    # permission:[{'id': 16, 'name': '管理员', 'view': 1},
             # {'id': 23, 'name': '行政', 'view': 0},
             # {'id': 22, 'name': '运维', 'view': 1}]
    user = User.objects.create(**user_info)
    permisson = data["permission"]
    for per in permisson:
        if per["view"] == 1:

            # 将用户添加分组
            group = Group.objects.get(pk=per["id"])
            user.groups.add(group)
    return user
Example #8
0
def ldap_user_add(**data):
    cn = data['cn']
    try:
        with connect_ldap() as c:
            login_sets = get_login_model()
            user_search = login_sets.user_ldapsearch
            base_cn = 'cn=%s' % cn
            base_dn = base_cn+','+user_search
            c.add(base_dn,
                  ['inetOrgPerson', 'top', 'ldapPublicKey'],
                  {'sn': data['sn'],
                   'mail': '*****@*****.**' % data['cn'],
                   "userpassword": sha.hash(data['password']),
                   "sshPublicKey": data.get('sshPublicKey', ''),}
                  )
    except Exception as e:
        return str(e.args)
Example #9
0
def ldap_change_password(request, **data):
    try:
        with connect_ldap() as c:
            c.search(get_login_model().user_ldapsearch,
                     search_filter='(objectClass=inetOrgPerson)',
                     attributes=['userPassword', 'cn'],
                     search_scope=SUBTREE)
            ldap_password = ''
            dn = ''
            for i in c.entries:
                if i.entry_attributes_as_dict['cn'][0] == request.user.get_username():
                    ldap_password = i.entry_attributes_as_dict['userPassword'][0]
                    dn = i.entry_dn
                    break
            if ldap_password and sha.verify(data['old_password'], ldap_password):
                c.modify(dn, {'userpassword': [(MODIFY_REPLACE, sha.hash(data['new_password']))]})
    except Exception as e:
        return JsonResponse(status=status.HTTP_400_BAD_REQUEST,
                            data={"error": "ldap密码修改失败", "e": str(e.args)})
Example #10
0
def createUserGroup(userGroupName,choice):
    if choice == "2":
        userFirstName = input("User first name ..................... : ")
        userLastName = input("User last name ...................... : ")
        while 1:
            userUID = input("User UID ............................ : ")
            if len(userUID) != 0:
                break
        
        if len(userLastName) == 0:
            userLastName = userGroupName
        
        createAttributes = {
            "objectClass": ["top".encode("utf-8"), "posixAccount".encode("utf-8"), "inetOrgPerson".encode("utf-8")],
            "uid": [userGroupName.encode("utf-8")],
            "givenName": [userFirstName.encode("utf-8")], # First name
            "sn": [userLastName.encode("utf-8")], # Last name
            "uidNumber": [userUID.encode("utf-8")],
            "homeDirectory": [str("/home/"+ userGroupName).encode("utf-8")],
            "loginShell": ["/bin/bash".encode("utf-8")],
            "gidNumber": [defaultUsersGID.encode("utf-8")],
            "description": ["Domain user".encode("utf-8")],
            "userPassword": [str(ssha.hash(defaultUserPassword)).encode("utf-8")],
            }
        
        connect.add_s("cn="+ userGroupName +","+ peopleBaseDN,ldap.modlist.addModlist(createAttributes))
        connect.unbind_s()
    
    if choice == "4":
        groupDescription = input("Group description ................... : ")
        while 1:
            groupIDNumber = input("Group GID ........................... : ")
            if len(groupIDNumber) != 0:
                break
        
        createAttributes = {
            "objectClass": ["top".encode("utf-8"), "posixGroup".encode("utf-8"), "groupOfNames".encode("utf-8")],
            "gidNumber": [groupIDNumber.encode("utf-8")],
            "description": ["Domain user".encode("utf-8")],
            }
        
        connect.add_s("cn="+ userGroupName +","+ groupBaseDN,ldap.modlist.addModlist(createAttributes))
        connect.unbind_s()
Example #11
0
def encrypt_password(plaintext, encryption):
    '''
    对明文密码进行加密
    加密算法同LDAP,删除了对PLAINTEXT的支持
    :param str plaintext:
    :param str encryption: 加密方式 enum([SSHA, SMD5, MD5, SHA])
    :TODO: To be further about the salt
    '''
    if encryption == 'SSHA':
        return ldap_salted_sha1.hash(plaintext)
    if encryption == 'SMD5':
        return ldap_salted_md5.hash(plaintext)
    if encryption == 'MD5':
        return ldap_md5.hash(plaintext)
    if encryption == 'SHA':
        return ldap_sha1.hash(plaintext)
    if encryption == 'PLAINTEXT':
        raise ValueError("encryption must be one of 'SSHA', 'SMD5', 'SHA', 'MD5'")
    raise ValueError("encryption must be one of 'SSHA', 'SMD5', 'SHA', 'MD5'")
Example #12
0
    def encrypt_password(self, plaintext):
        """
        encrypt password.
        """
        self.valid_encryption()
        # 加密密码
        if self.encryption == 'SSHA':
            return ldap_salted_sha1.hash(plaintext)

        if self.encryption == 'SMD5':
            return ldap_salted_md5.hash(plaintext)

        if self.encryption == 'MD5':
            return ldap_md5.hash(plaintext)

        if self.encryption == 'SHA':
            return ldap_sha1.hash(plaintext)

        raise ValueError(
            "encryption must be one of 'SSHA', 'SMD5', 'SHA', 'MD5'")
Example #13
0
def user_add(request):
    if not request.method == "POST":
        return JsonResponse(status=status.HTTP_405_METHOD_NOT_ALLOWED, data={})

    if not validate_ldap(request):
        return JsonResponse({"error": "您没权限"}, status=status.HTTP_403_FORBIDDEN)

    bod = request.body
    bod = str(bod, encoding="utf-8")
    data = json.loads(bod)
    OperateLog.create_log(request)

    cn = data['cn']
    exits = LdapUser.objects.filter(username=cn).count()
    # TODO 这个查询只会找 oa_platform 的 AUTH_USER 表
    if exits > 0:
        return JsonResponse({"error": "该用户已存在"}, status=status.HTTP_400_BAD_REQUEST)

    permission_dict = dict(data.get('permission'))

    try:
        with connect_ldap() as c:
            base_dn = 'cn=%s, ou=Users,dc=xiaoneng,dc=cn' % cn
            permission_list = permission_update_dn(permission_dict)
            print('per', permission_list)

            c.add(base_dn,
                  ['inetOrgPerson', 'top', 'ldapPublicKey'],
                  {'sn': data['sn'],
                   'mail': '*****@*****.**' % data['cn'],
                   "userpassword": sha.hash(data['password']),
                   "sshPublicKey": data.get('sshPublicKey', ''),
            })
            for role in permission_list:
                role = role.replace(",ou=Users,", ",ou=Roles,")
                c.modify(role, {'uniqueMember': [(MODIFY_ADD, base_dn)]})
            c.modify('cn=users,cn=LDAP,ou=Roles,dc=xiaoneng,dc=cn', {'uniqueMember': [(MODIFY_ADD, base_dn)]})
            return JsonResponse({"info": "新增成功"}, status=status.HTTP_200_OK)
    except Exception as e:
        return JsonResponse({"error": "新增失败", "message": str(e.args)}, status=status.HTTP_400_BAD_REQUEST)
Example #14
0
 def ldap_hash(string):
     return ldap_salted_sha1.hash(string)
Example #15
0
def hash(a):

    h = ldap_salted_sha1.hash(a)
    
    return h
Example #16
0
def core_password(charid):

    import json
    import ldap
    import ldap.modlist
    import common.logger as _logger
    import common.credentials.ldap as _ldap
    import common.ldaphelpers as _ldaphelpers
    import uuid
    import hashlib
    from flask import Response, request
    from passlib.hash import ldap_salted_sha1

    # reset password of charid

    ipaddress = request.headers['X-Real-Ip']
    log_charid = request.args.get('log_charid')  # logging purposes

    _logger.securitylog(__name__,
                        'reset password',
                        detail='target charid {0}'.format(charid),
                        ipaddress=ipaddress,
                        charid=log_charid)

    # initialize connections

    try:
        ldap_conn = ldap.initialize(_ldap.ldap_host, bytes_mode=False)
        ldap_conn.simple_bind_s(_ldap.admin_dn, _ldap.admin_dn_password)
    except ldap.LDAPError as error:
        msg = 'LDAP connection error: {}'.format(error)
        _logger.log('[' + __name__ + '] {}'.format(msg),
                    _logger.LogLevel.ERROR)
        js = json.dumps({'error': msg})
        return Response(js, status=500, mimetype='application/json')

    # find the user. partly to get the dn, partly to validate.

    dn = 'ou=People,dc=triumvirate,dc=rocks'
    filterstr = '(uid={})'.format(charid)
    attrlist = ['characterName', 'authGroup']
    code, result = _ldaphelpers.ldap_search(__name__, dn, filterstr, attrlist)

    if code == False:
        msg = 'unable to fetch ldap information: {}'.format(error)
        _logger.log('[' + __name__ + '] {}'.format(msg),
                    _logger.LogLevel.ERROR)
        js = json.dumps({'error': msg})
        return Response(js, status=500, mimetype='application/json')

    if result == None:
        msg = 'charid {0} not in ldap'.format(charid)
        _logger.log('[' + __name__ + '] {}'.format(msg),
                    _logger.LogLevel.ERROR)
        js = json.dumps({'error': msg})
        return Response(js, status=404, mimetype='application/json')

    (dn, info), = result.items()

    # new password

    password = uuid.uuid4().hex[:8]
    password_hash = ldap_salted_sha1.hash(password)
    password_hash = password_hash.encode('utf-8')

    mod_attrs = [(ldap.MOD_REPLACE, 'userPassword', [password_hash])]

    try:
        ldap_conn.modify_s(dn, mod_attrs)
    except ldap.LDAPError as error:
        msg = 'unable to modify password of {0}: {1}'.format(dn, error)
        _logger.log('[' + __name__ + '] {}'.format(msg),
                    _logger.LogLevel.ERROR)
        js = json.dumps({'error': msg})
        return Response(js, status=500, mimetype='application/json')

    response = {'password': password}
    return Response(json.dumps(response),
                    status=200,
                    mimetype='application/json')
Example #17
0
def ldap_create_stub(
    charname=None, charid=None, isalt=False,
    altof=None, accountstatus='public', authgroups=['public'],
    atoken=None, rtoken=None
    ):


    # make a very basic ldap entry for charname

    function = __name__

    user = dict()

    if charname is not None and charid is None:
        # making a stub based on a charid
        result = _esihelpers.user_search(charname)

        if result == False:
            # damage
            msg = 'ESI search error'
            return False, msg
        elif len(result) is 0:
            # nothing found.
            msg = 'no such character'
            return False, msg
        elif len(result) > 1:
            # too much found
            msg = 'too many results'
            return False, msg

        # okay hopefuly nothing else f****d up by now

        charid = result['character']

    if charid is None:
        msg = 'no charname, no charid'
        return False, msg

    # get affiliations and shit

    affiliations = _esihelpers.esi_affiliations(charid)

    charname = affiliations.get('charname')
    corpid = affiliations.get('corpid')
    corpname = affiliations.get('corporation_name')
    allianceid = affiliations.get('allianceid')
    alliancename = affiliations.get('alliancename')

    cn, dn = ldap_normalize_charname(charname)

    user['uid'] = charid
    user['altof'] = altof
    user['characterName'] = charname
    user['corporation'] = corpid

    if allianceid:
        user['alliance'] = allianceid

    user['cn'] = cn
    user['sn'] = cn
    user['accountStatus'] = accountstatus
    user['authGroup'] = authgroups

    if rtoken:
        user['esiAccessToken'] = atoken
        user['esiRefreshToken'] = rtoken

    # build the stub

    attrs = []

    # generate a bullshit password

    password = uuid.uuid4().hex
    password_hash = ldap_salted_sha1.hash(password)

    user['userPassword'] = password_hash

    # handle rest of crap

    for item in user.keys():

        # authgroup is a repeated attribute so has to be handled carefully

        if item == 'authGroup':
            newgroups = []
            for group in authgroups:
                group = str(group).encode('utf-8')
                newgroups.append(group)
            user['authGroup'] = newgroups
        else:
            user[item] = [ str(user[item]).encode('utf-8') ]
        attrs.append((item, user[item]))

    attrs.append(('objectClass', ['top'.encode('utf-8'), 'pilot'.encode('utf-8'), 'simpleSecurityObject'.encode('utf-8'), 'organizationalPerson'.encode('utf-8')]))

    # ldap binding
    ldap_conn = ldap.initialize(_ldap.ldap_host, bytes_mode=False)
    try:
        ldap_conn.simple_bind_s(_ldap.admin_dn, _ldap.admin_dn_password)
    except ldap.LDAPError as error:
        _logger.log('[' + __name__ + '] LDAP connection error: {}'.format(error),_logger.LogLevel.ERROR)
        return False, error

    # add the stub to ldap

    try:
        ldap_conn.add_s(dn, attrs)
    except Exception as error:
        return False, error
    finally:
        ldap_conn.unbind()

    # no error. done!

    return True, dn
Example #18
0
def Crypter(args):
    if args.encrypt == 'pbkdf2_sha256':
        return pbkdf2_sha256.hash(args.text)
    elif args.encrypt == 'oracle11':
        return oracle11.hash(args.text)
    elif args.encrypt == 'argon2':
        return argon2.hash(args.text)
    elif args.encrypt == 'bcrypt':
        return bcrypt.hash(args.text)
    elif args.encrypt == 'bcrypt_sha256':
        return bcrypt_sha256.hash(args.text)
    elif args.encrypt == 'cisco_asa':
        return cisco_asa.hash(args.text)
    elif args.encrypt == 'cisco_pix':
        return cisco_pix.hash(args.text)
    elif args.encrypt == 'cisco_type7':
        return cisco_type7.hash(args.text)
    elif args.encrypt == 'bigcrypt':
        return bigcrypt.hash(args.text)
    elif args.encrypt == 'bsdi_crypt':
        return bsdi_crypt.hash(args.text)
    elif args.encrypt == 'des_crypt':
        return des_crypt.hash(args.text)
    elif args.encrypt == 'hex_md4':
        return hex_md4.hash(args.text)
    elif args.encrypt == 'hex_md5':
        return hex_md5.hash(args.text)
    elif args.encrypt == 'hex_sha1':
        return hex_sha1.hash(args.text)
    elif args.encrypt == 'hex_sha256':
        return hex_sha256.hash(args.text)
    elif args.encrypt == 'hex_sha512':
        return hex_sha512.hash(args.text)
    elif args.encrypt == 'django_bcrypt':
        return django_bcrypt.hash(args.text)
    elif args.encrypt == 'django_disabled':
        return django_disabled.hash(args.text)
    elif args.encrypt == 'django_bcrypt_sha256':
        return django_bcrypt_sha256.hash(args.text)
    elif args.encrypt == 'django_des_crypt':
        return django_des_crypt.hash(args.text)
    elif args.encrypt == 'django_pbkdf2_sha1':
        return django_pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'django_pbkdf2_sha256':
        return django_pbkdf2_sha256.hash(args.text)
    elif args.encrypt == 'django_salted_md5':
        return django_salted_md5.hash(args.text)
    elif args.encrypt == 'django_salted_sha1':
        return django_salted_sha1.hash(args.text)
    elif args.encrypt == 'fshp':
        return fshp.hash(args.text)
    elif args.encrypt == 'ldap_bcrypt':
        return ldap_bcrypt.hash(args.text)
    elif args.encrypt == 'ldap_md5':
        return ldap_md5.hash(args.text)
    elif args.encrypt == 'ldap_plaintext':
        return ldap_plaintext.hash(args.text)
    elif args.encrypt == 'ldap_sha1':
        return ldap_sha1.hash(args.text)
    elif args.encrypt == 'ldap_bsdi_crypt':
        return ldap_bsdi_crypt.hash(args.text)
    elif args.encrypt == 'ldap_hex_md5':
        return ldap_hex_md5.hash(args.text)
    elif args.encrypt == 'ldap_hex_sha1':
        return ldap_hex_sha1.hash(args.text)
    elif args.encrypt == 'ldap_md5_crypt':
        return ldap_md5_crypt.hash(args.text)
    elif args.encrypt == 'ldap_pbkdf2_sha1':
        return ldap_pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'ldap_pbkdf2_sha256':
        return ldap_pbkdf2_sha256.hash(args.text)
    elif args.encrypt == 'ldap_pbkdf2_sha512':
        return ldap_pbkdf2_sha512.hash(args.text)
    elif args.encrypt == 'ldap_salted_md5':
        return ldap_salted_md5.hash(args.text)
    elif args.encrypt == 'ldap_salted_sha1':
        return ldap_salted_sha1.hash(args.text)
    elif args.encrypt == 'ldap_sha1_crypt':
        return ldap_sha1_crypt.hash(args.text)
    elif args.encrypt == 'ldap_sha256_crypt':
        return ldap_sha256_crypt.hash(args.text)
    elif args.encrypt == 'ldap_sha512_crypt':
        return ldap_sha512_crypt.hash(args.text)
    elif args.encrypt == 'apr_md5_crypt':
        return apr_md5_crypt.hash(args.text)
    elif args.encrypt == 'md5_crypt':
        return md5_crypt.hash(args.text)
    elif args.encrypt == 'plaintext':
        return plaintext.hash(args.text)
    elif args.encrypt == 'unix_disabled':
        return unix_disabled.hash(args.text)
    elif args.encrypt == 'unix_fallback':
        return unix_fallback.hash(args.text)
    elif args.encrypt == 'mssql2000':
        return mssql2000.hash(args.text)
    elif args.encrypt == 'mssql2005':
        return mssql2005.hash(args.text)
    elif args.encrypt == 'mysql323':
        return mysql323.hash(args.text)
    elif args.encrypt == 'mysql41':
        return mysql41.hash(args.text)
    elif args.encrypt == 'atlassian_pbkdf2_sha1':
        return atlassian_pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'cta_pbkdf2_sha1':
        return cta_pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'dlitz_pbkdf2_sha1':
        return dlitz_pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'grub_pbkdf2_sha512':
        return grub_pbkdf2_sha512.hash(args.text)
    elif args.encrypt == 'pbkdf2_sha1':
        return pbkdf2_sha1.hash(args.text)
    elif args.encrypt == 'pbkdf2_sha512':
        return pbkdf2_sha512.hash(args.text)
    elif args.encrypt == 'phpass':
        return phpass.hash(args.text)
    elif args.encrypt == 'roundup_plaintext':
        return roundup_plaintext.hash(args.text)
    elif args.encrypt == 'sun_md5_crypt':
        return sun_md5_crypt.hash(args.text)
    elif args.encrypt == 'scram':
        return scram.hash(args.text)
    elif args.encrypt == 'scrypt':
        return scrypt.hash(args.text)
    elif args.encrypt == 'sha1_crypt':
        return sha1_crypt.hash(args.text)
    elif args.encrypt == 'sha256_crypt':
        return sha256_crypt.hash(args.text)
    elif args.encrypt == 'sha512_crypt':
        return sha512_crypt.hash(args.text)
    elif args.encrypt == 'bsd_nthash':
        return bsd_nthash.hash(args.text)
    elif args.encrypt == 'lmhash':
        return lmhash.hash(args.text)
    elif args.encrypt == 'nthash':
        return nthash.hash(args.text)
Example #19
0
def reset(request):
    mode = get_login_model()
    mod = login_model

    ldap_exit = User.objects.filter(user_profile__create_source=1).filter(
        username=request.user.get_username()).exists()
    local_exit = User.objects.filter(user_profile__create_source=2).filter(
        username=request.user.get_username()).exists()

    if mod != 2:
        passwd = sha.hash(request.GET.get('password', ''))
        if not passwd:
            return Response(status=status.HTTP_400_BAD_REQUEST,
                            data={
                                "result": False,
                                "error": "密码输入为空!"
                            })
        # aeskey = request.session.get('aeskey', '')
        aeskey = request.GET.get('new_key', '')
        if aeskey:
            decry_str = decrypt(aeskey)
            username = decry_str.split(':')[0]
            req_timestamp = decry_str.split(':')[2]
            if time.time() - float(req_timestamp) > 3600:
                return Response(status=status.HTTP_400_BAD_REQUEST,
                                data={
                                    "result": False,
                                    "error": "重置链接超时"
                                })
            else:
                try:
                    with connect_ldap() as ldap_conn:
                        ldap_conn.search(
                            search_base=mode.user_ldapsearch,
                            search_filter='(objectClass=inetOrgPerson)',
                            search_scope=SUBTREE,
                            attributes=['userPassword', 'cn'])
                        for entry in ldap_conn.entries:
                            if entry.entry_attributes_as_dict['cn'][
                                    0] == username:
                                ldap_conn.modify(entry.entry_dn, {
                                    'userpassword': [(MODIFY_REPLACE, passwd)]
                                })
                                if ldap_exit:
                                    user_info = User.objects.filter(
                                        user_profile__create_source=1
                                    ).get(username=request.user.get_username())
                                    user_info.password = passwd
                                    user_info.save()
                                if local_exit:
                                    user_info = User.objects.filter(
                                        user_profile__create_source=2
                                    ).get(username=request.user.get_username())
                                    user_info.password = passwd
                                    user_info.save()
                                if ldap_conn.result['result'] == 0:
                                    return Response({
                                        "result": True,
                                        "error": "密码重置成功"
                                    })
                                else:
                                    data = {
                                        "result": False,
                                        "error":
                                        "str(ldap_conn.result['message'])"
                                    }
                                    return Response(
                                        status=status.HTTP_400_BAD_REQUEST,
                                        data=data)
                except Exception as e:
                    traceback.print_exc()
                    return Response(status=status.HTTP_400_BAD_REQUEST,
                                    data={
                                        "result": False,
                                        "error": str(e.args)
                                    })
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST,
                            data={
                                "result": False,
                                "error": "未获取到令牌"
                            })
    if mod == 2:
        user_info = User.objects.filter(user_profile__create_source=2).get(
            username=request.user.get_username())
        user_info.password = passwd
        user_info.save()
    return Response({"result": True, "error": "密码重置成功"})
Example #20
0
from passlib.hash import ldap_salted_sha1 as lsm

hash_str = lsm.hash('shit')


print(lsm.verify('shits', hash_str))
Example #21
0
def hashed_password(password):
    hash = ssha.hash(password)
    return hash