Changeset - 710512deb83d
[Not reviewed]
default
0 8 0
Mads Kiilerich (mads) - 5 years ago 2020-11-01 23:50:29
mads@kiilerich.com
Grafted from: 7755b166b92b
lib: move some auth low level helper functions to utils2
8 files changed with 80 insertions and 85 deletions:
0 comments (0 inline, 0 general)
kallithea/lib/auth.py
Show inline comments
 
@@ -24,13 +24,9 @@ Original author and date, and relevant c
 
:copyright: (c) 2013 RhodeCode GmbH, and others.
 
:license: GPLv3, see LICENSE.md for more details.
 
"""
 
import hashlib
 
import itertools
 
import logging
 
import os
 
import string
 

	
 
import bcrypt
 
import ipaddr
 
from decorator import decorator
 
from sqlalchemy.orm import joinedload
 
@@ -42,7 +38,6 @@ from webob.exc import HTTPForbidden, HTT
 
import kallithea
 
from kallithea.lib import webutils
 
from kallithea.lib.utils import get_repo_group_slug, get_repo_slug, get_user_group_slug
 
from kallithea.lib.utils2 import ascii_bytes, ascii_str, safe_bytes
 
from kallithea.lib.vcs.utils.lazy import LazyProperty
 
from kallithea.lib.webutils import url
 
from kallithea.model import db, meta
 
@@ -52,70 +47,6 @@ from kallithea.model.user import UserMod
 
log = logging.getLogger(__name__)
 

	
 

	
 
class PasswordGenerator(object):
 
    """
 
    This is a simple class for generating password from different sets of
 
    characters
 
    usage::
 

	
 
        passwd_gen = PasswordGenerator()
 
        #print 8-letter password containing only big and small letters
 
            of alphabet
 
        passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
 
    """
 
    ALPHABETS_NUM = r'''1234567890'''
 
    ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
 
    ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
 
    ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
 
    ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
 
        + ALPHABETS_NUM + ALPHABETS_SPECIAL
 
    ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
 
    ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
 
    ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
 
    ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
 

	
 
    def gen_password(self, length, alphabet=ALPHABETS_FULL):
 
        assert len(alphabet) <= 256, alphabet
 
        l = []
 
        while len(l) < length:
 
            i = ord(os.urandom(1))
 
            if i < len(alphabet):
 
                l.append(alphabet[i])
 
        return ''.join(l)
 

	
 

	
 
def get_crypt_password(password):
 
    """
 
    Cryptographic function used for bcrypt password hashing.
 

	
 
    :param password: password to hash
 
    """
 
    return ascii_str(bcrypt.hashpw(safe_bytes(password), bcrypt.gensalt(10)))
 

	
 

	
 
def check_password(password, hashed):
 
    """
 
    Checks password match the hashed value using bcrypt.
 
    Remains backwards compatible and accept plain sha256 hashes which used to
 
    be used on Windows.
 

	
 
    :param password: password
 
    :param hashed: password in hashed form
 
    """
 
    # sha256 hashes will always be 64 hex chars
 
    # bcrypt hashes will always contain $ (and be shorter)
 
    if len(hashed) == 64 and all(x in string.hexdigits for x in hashed):
 
        return hashlib.sha256(password).hexdigest() == hashed
 
    try:
 
        return bcrypt.checkpw(safe_bytes(password), ascii_bytes(hashed))
 
    except ValueError as e:
 
        # bcrypt will throw ValueError 'Invalid hashed_password salt' on all password errors
 
        log.error('error from bcrypt checking password: %s', e)
 
        return False
 
    log.error('check_password failed - no method found for hash length %s', len(hashed))
 
    return False
 

	
 

	
 
PERM_WEIGHTS = db.Permission.PERM_WEIGHTS
 

	
 
def bump_permission(permissions, key, new_perm):
kallithea/lib/auth_modules/__init__.py
Show inline comments
 
@@ -20,9 +20,9 @@ import logging
 
import traceback
 
from inspect import isfunction
 

	
 
from kallithea.lib.auth import AuthUser, PasswordGenerator
 
from kallithea.lib.auth import AuthUser
 
from kallithea.lib.compat import hybrid_property
 
from kallithea.lib.utils2 import asbool
 
from kallithea.lib.utils2 import asbool, PasswordGenerator
 
from kallithea.model import db, meta, validators
 
from kallithea.model.user import UserModel
 
from kallithea.model.user_group import UserGroupModel
kallithea/lib/auth_modules/auth_internal.py
Show inline comments
 
@@ -28,7 +28,7 @@ Original author and date, and relevant c
 

	
 
import logging
 

	
 
from kallithea.lib import auth, auth_modules
 
from kallithea.lib import auth_modules, utils2
 
from kallithea.lib.compat import hybrid_property
 

	
 

	
 
@@ -78,7 +78,7 @@ class KallitheaAuthPlugin(auth_modules.K
 
        }
 
        log.debug('user data: %s', user_data)
 

	
 
        password_match = auth.check_password(password, userobj.password)
 
        password_match = utils2.check_password(password, userobj.password)
 
        if userobj.is_default_user:
 
            log.info('user %s authenticated correctly as anonymous user',
 
                     username)
kallithea/lib/utils2.py
Show inline comments
 
@@ -29,12 +29,16 @@ Original author and date, and relevant c
 

	
 
import binascii
 
import datetime
 
import hashlib
 
import json
 
import logging
 
import os
 
import re
 
import string
 
import time
 
import urllib.parse
 

	
 
import bcrypt
 
import urlobject
 
from dateutil import relativedelta
 
from sqlalchemy.engine import url as sa_url
 
@@ -59,6 +63,9 @@ except ImportError:
 
    pass
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
# mute pyflakes "imported but unused"
 
assert asbool
 
assert aslist
 
@@ -549,3 +556,67 @@ def ask_ok(prompt, retries=4, complaint=
 
        if retries < 0:
 
            raise IOError
 
        print(complaint)
 

	
 

	
 
class PasswordGenerator(object):
 
    """
 
    This is a simple class for generating password from different sets of
 
    characters
 
    usage::
 

	
 
        passwd_gen = PasswordGenerator()
 
        #print 8-letter password containing only big and small letters
 
            of alphabet
 
        passwd_gen.gen_password(8, passwd_gen.ALPHABETS_BIG_SMALL)
 
    """
 
    ALPHABETS_NUM = r'''1234567890'''
 
    ALPHABETS_SMALL = r'''qwertyuiopasdfghjklzxcvbnm'''
 
    ALPHABETS_BIG = r'''QWERTYUIOPASDFGHJKLZXCVBNM'''
 
    ALPHABETS_SPECIAL = r'''`-=[]\;',./~!@#$%^&*()_+{}|:"<>?'''
 
    ALPHABETS_FULL = ALPHABETS_BIG + ALPHABETS_SMALL \
 
        + ALPHABETS_NUM + ALPHABETS_SPECIAL
 
    ALPHABETS_ALPHANUM = ALPHABETS_BIG + ALPHABETS_SMALL + ALPHABETS_NUM
 
    ALPHABETS_BIG_SMALL = ALPHABETS_BIG + ALPHABETS_SMALL
 
    ALPHABETS_ALPHANUM_BIG = ALPHABETS_BIG + ALPHABETS_NUM
 
    ALPHABETS_ALPHANUM_SMALL = ALPHABETS_SMALL + ALPHABETS_NUM
 

	
 
    def gen_password(self, length, alphabet=ALPHABETS_FULL):
 
        assert len(alphabet) <= 256, alphabet
 
        l = []
 
        while len(l) < length:
 
            i = ord(os.urandom(1))
 
            if i < len(alphabet):
 
                l.append(alphabet[i])
 
        return ''.join(l)
 

	
 

	
 
def get_crypt_password(password):
 
    """
 
    Cryptographic function used for bcrypt password hashing.
 

	
 
    :param password: password to hash
 
    """
 
    return ascii_str(bcrypt.hashpw(safe_bytes(password), bcrypt.gensalt(10)))
 

	
 

	
 
def check_password(password, hashed):
 
    """
 
    Checks password match the hashed value using bcrypt.
 
    Remains backwards compatible and accept plain sha256 hashes which used to
 
    be used on Windows.
 

	
 
    :param password: password
 
    :param hashed: password in hashed form
 
    """
 
    # sha256 hashes will always be 64 hex chars
 
    # bcrypt hashes will always contain $ (and be shorter)
 
    if len(hashed) == 64 and all(x in string.hexdigits for x in hashed):
 
        return hashlib.sha256(password).hexdigest() == hashed
 
    try:
 
        return bcrypt.checkpw(safe_bytes(password), ascii_bytes(hashed))
 
    except ValueError as e:
 
        # bcrypt will throw ValueError 'Invalid hashed_password salt' on all password errors
 
        log.error('error from bcrypt checking password: %s', e)
 
        return False
 
    log.error('check_password failed - no method found for hash length %s', len(hashed))
 
    return False
kallithea/model/user.py
Show inline comments
 
@@ -38,7 +38,7 @@ from tg.i18n import ugettext as _
 

	
 
from kallithea.lib import webutils
 
from kallithea.lib.exceptions import DefaultUserException, UserOwnsReposException
 
from kallithea.lib.utils2 import generate_api_key, get_current_authuser
 
from kallithea.lib.utils2 import check_password, generate_api_key, get_crypt_password, get_current_authuser
 
from kallithea.model import db, forms, meta
 

	
 

	
 
@@ -72,7 +72,6 @@ class UserModel(object):
 
        }
 
        # raises UserCreationError if it's not allowed
 
        check_allowed_create_user(user_data, cur_user)
 
        from kallithea.lib.auth import get_crypt_password
 

	
 
        new_user = db.User()
 
        for k, v in form_data.items():
 
@@ -110,7 +109,6 @@ class UserModel(object):
 
        if not cur_user:
 
            cur_user = getattr(get_current_authuser(), 'username', None)
 

	
 
        from kallithea.lib.auth import check_password, get_crypt_password
 
        from kallithea.lib.hooks import check_allowed_create_user, log_create_user
 
        user_data = {
 
            'username': username, 'password': password,
 
@@ -194,7 +192,6 @@ class UserModel(object):
 
                                   email_kwargs=email_kwargs)
 

	
 
    def update(self, user_id, form_data, skip_attrs=None):
 
        from kallithea.lib.auth import get_crypt_password
 
        skip_attrs = skip_attrs or []
 
        user = self.get(user_id)
 
        if user.is_default_user:
 
@@ -215,8 +212,6 @@ class UserModel(object):
 
                setattr(user, k, v)
 

	
 
    def update_user(self, user, **kwargs):
 
        from kallithea.lib.auth import get_crypt_password
 

	
 
        user = db.User.guess_instance(user)
 
        if user.is_default_user:
 
            raise DefaultUserException(
 
@@ -381,13 +376,12 @@ class UserModel(object):
 
        return expected_token == token
 

	
 
    def reset_password(self, user_email, new_passwd):
 
        from kallithea.lib import auth
 
        from kallithea.lib.celerylib import tasks
 
        user = db.User.get_by_email(user_email)
 
        if user is not None:
 
            if not self.can_change_password(user):
 
                raise Exception('trying to change password for external user')
 
            user.password = auth.get_crypt_password(new_passwd)
 
            user.password = get_crypt_password(new_passwd)
 
            meta.Session().commit()
 
            log.info('change password for %s', user_email)
 
        if new_passwd is None:
kallithea/tests/functional/test_admin_users.py
Show inline comments
 
@@ -20,7 +20,7 @@ from webob.exc import HTTPNotFound
 
import kallithea
 
from kallithea.controllers.admin.users import UsersController
 
from kallithea.lib import webutils
 
from kallithea.lib.auth import check_password
 
from kallithea.lib.utils2 import check_password
 
from kallithea.model import db, meta, validators
 
from kallithea.model.user import UserModel
 
from kallithea.tests import base
kallithea/tests/functional/test_login.py
Show inline comments
 
@@ -8,8 +8,7 @@ from tg.util.webtest import test_context
 

	
 
import kallithea.lib.celerylib.tasks
 
from kallithea.lib import webutils
 
from kallithea.lib.auth import check_password
 
from kallithea.lib.utils2 import generate_api_key
 
from kallithea.lib.utils2 import check_password, generate_api_key
 
from kallithea.model import db, meta, validators
 
from kallithea.model.api_key import ApiKeyModel
 
from kallithea.model.user import UserModel
kallithea/tests/scripts/manual_test_concurrency.py
Show inline comments
 
@@ -38,7 +38,7 @@ from paste.deploy import appconfig
 
from sqlalchemy import engine_from_config
 

	
 
import kallithea.config.application
 
from kallithea.lib.auth import get_crypt_password
 
from kallithea.lib.utils2 import get_crypt_password
 
from kallithea.model import db, meta
 
from kallithea.model.base import init_model
 
from kallithea.model.repo import RepoModel
0 comments (0 inline, 0 general)