peba.py 文件源码

python
阅读 27 收藏 0 点赞 0 评论 0

项目:PEBA 作者: dtag-dev-sec 项目源码 文件源码
def authenticate(username, token):
    """ Authenticate user from cache or in ES """

    # check for user in cache
    authtoken = getCache(username, "user")
    if authtoken is not False:
        if len(authtoken) == 128:
            tokenhash = hashlib.sha512(token.encode('utf-8')).hexdigest()
            if authtoken == tokenhash:
                return True
        elif len(authtoken) == 32:
            tokenhash = hashlib.md5(token.encode('utf-8')).hexdigest()
            if authtoken == tokenhash:
                return True
        else:
            app.logger.error('authenticate(): Hash "{0}" for user "{1}" is not matching md5 or sha512 length! Needs to be checked in memcache!'.format(authtoken, username))

    # query ES
    else:
        try:
            res = es.search(index=app.config['WSUSERINDEX'], body={
                  "query": {
                    "term": {
                      "peerName.keyword": username
                    }
                  }
                })

            if res["hits"]["total"] > 1:
                app.logger.error('authenticate(): More than one user "%s" in ES index "users" found!' % username)
            elif res["hits"]["total"] < 1:
                app.logger.error('authenticate(): No user "%s" in ES index "users" found!' % username)
            elif res["hits"]["total"] == 1:
                authtoken = res["hits"]["hits"][0]["_source"]["token"]
                getOnly = res["hits"]["hits"][0]["_source"]["getOnly"]
                community = res["hits"]["hits"][0]["_source"]["community"]

                if len(authtoken) == 128:
                    tokenhash = hashlib.sha512(token.encode('utf-8')).hexdigest()
                    if authtoken == tokenhash:
                        # add user and token to cache for 24h
                        setCache(username, authtoken, (60 * 60 * 24), "user")
                        return True
                elif len(authtoken) == 32:
                    tokenhash = hashlib.md5(token.encode('utf-8')).hexdigest()
                    if authtoken == tokenhash:
                        # add user and token to cache for 24h
                        setCache(username, authtoken, (60 * 60 * 24),"user")
                        return True
                else:
                    app.logger.error('authenticate(): Hash "{0}" for user "{1}" is not matching md5 or sha512 length! Needs to be checked in ES index!'.format(authtoken, username))
                    return False

        except ElasticsearchException as err:
            app.logger.error('ElasticSearch error: %s' %  err)

    return False
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号