Beispiel #1
0
def setup():
    auth = YubiAuth()
    for user in auth.query_users():
        auth.get_user(user['id']).delete()
    auth.commit()
    auth.create_user('user1', 'pass1')
    auth.create_user('user2', 'pass2')
    auth.commit()
    del auth
Beispiel #2
0
def setup():
    auth = YubiAuth()
    for user in auth.query_users():
        auth.get_user(user['id']).delete()
    auth.commit()
    auth.create_user('user1', 'pass1')
    auth.create_user('user2', 'pass2')
    auth.commit()
    del auth
Beispiel #3
0
class Client(Controller):

    """
    Main class for accessing user data.
    """
    def __init__(self, session=Session()):
        super(Client, self).__init__(session)
        self.auth = YubiAuth(session)

    def _user_for_otp(self, otp):
        if settings['yubikey_id']:
            yubikey = self.auth.get_yubikey(otp[:-32])
            if yubikey.enabled and len(yubikey.users) == 1:
                return yubikey.users[0]
        raise ValueError("Unable to locate user!")

    def authenticate(self, username, password, otp=None):
        try:
            if not username and otp:
                user = self._user_for_otp(otp)
            else:
                user = self.auth.get_user(username)
        except Exception as e:
            if settings['use_ldap'] and settings['ldap_auto_import'] \
                    and ldapauth.authenticate(username, password):
                user = self.auth.create_user(username, None)
                user.attributes['_ldap_auto_imported'] = True
                log.info('Auto-created LDAP user: %s', username)
            else:
                log.info('Authentication failed. No such user: %s', username)
                raise e

        if user.validate_password(password):
            pw = 'valid password' if password else 'None (valid)'
            if authenticate_otp(user, otp, password):
                log.info(
                    'Authentication successful. '
                    'Username: %s, password: <%s>, OTP: %s',
                    username, pw, otp)
                return user
        else:
            pw = 'invalid password' if password else 'None (invalid)'
            # Consume the OTP even if the password was incorrect.
            if otp:
                validate_otp(otp)
        log.info(
            'Authentication failed. Username: %s, password: <%s>, OTP: %s',
            username, pw, otp)
        raise ValueError("Invalid credentials!")

    def create_session(self, username, password, otp=None):
        user = self.authenticate(username, password, otp)
        prefix = otp[:-32] if otp else None
        user_session = UserSession({}, **session_config)
        user_session['user_id'] = user.id
        user_session['username'] = user.name
        user_session['prefix'] = prefix if prefix else None
        user_session.save()
        return user_session

    def get_session(self, sessionId):
        user_session = UserSession({}, id=sessionId, **session_config)
        if user_session.is_new:
            user_session.delete()
            raise ValueError("Session not found!")
        return user_session

    def create_attribute(self, *args, **kwargs):
        attribute = AttributeType(*args, **kwargs)
        self.session.add(attribute)
        return attribute

    def get_attributes(self):
        return self.session.query(AttributeType).all()

    def generate_revocation(self, prefix):
        yubikey = self.auth.get_yubikey(prefix)
        code = base64.urlsafe_b64encode(uuid.uuid4().get_bytes())
        yubikey.attributes[REVOKE_KEY] = code
        return code

    def revoke(self, code):
        kwargs = {REVOKE_KEY: code}
        keys = self.auth.query_yubikeys(**kwargs)
        if not len(keys) == 1:
            log.error('Revocation failed. Matching keys: %d, Code: %s',
                      len(keys), code)
            raise ValueError('Invalid revocation code!')
        yubikey = keys[0]
        yubikey.enabled = False
        del yubikey.attributes[REVOKE_KEY]
        log.info('Revocation successful. '
                 'YubiKey [%s] has been revoked using code: %s',
                 yubikey.prefix, code)

    def register(self, username, password, otp=None, attributes=None):
        if not settings['registration']:
            raise ValueError('User registration disabled!')

        if attributes is None:
            attributes = {}

        validate_attributes(self.get_attributes(), attributes)

        if otp and not validate_otp(otp):
            raise ValueError('Invalid OTP!')

        user = self.auth.create_user(username, password)
        user.attributes.update(attributes)
        if otp:
            user.assign_yubikey(otp)
        log.info('User %s registered with attributes: %r', username,
                 attributes)
        return user
Beispiel #4
0
class Client(Controller):
    """
    Main class for accessing user data.
    """
    def __init__(self, session=Session()):
        super(Client, self).__init__(session)
        self.auth = YubiAuth(session)

    def _user_for_otp(self, otp):
        if settings['yubikey_id']:
            yubikey = self.auth.get_yubikey(otp[:-32])
            if yubikey.enabled and len(yubikey.users) == 1:
                return yubikey.users[0]
        raise ValueError("Unable to locate user!")

    def authenticate(self, username, password, otp=None):
        try:
            if not username and otp:
                user = self._user_for_otp(otp)
            else:
                user = self.auth.get_user(username)
        except Exception as e:
            if settings['use_ldap'] and settings['ldap_auto_import'] \
                    and ldapauth.authenticate(username, password):
                user = self.auth.create_user(username, None)
                user.attributes['_ldap_auto_imported'] = True
                log.info('Auto-created LDAP user: %s', username)
            else:
                log.info('Authentication failed. No such user: %s', username)
                raise e

        if user.validate_password(password):
            pw = 'valid password' if password else 'None (valid)'
            if authenticate_otp(user, otp, password):
                log.info(
                    'Authentication successful. '
                    'Username: %s, password: <%s>, OTP: %s', username, pw, otp)
                return user
        else:
            pw = 'invalid password' if password else 'None (invalid)'
            # Consume the OTP even if the password was incorrect.
            if otp:
                validate_otp(otp)
        log.info(
            'Authentication failed. Username: %s, password: <%s>, OTP: %s',
            username, pw, otp)
        raise ValueError("Invalid credentials!")

    def create_session(self, username, password, otp=None):
        user = self.authenticate(username, password, otp)
        prefix = otp[:-32] if otp else None
        user_session = UserSession({}, **session_config)
        user_session['user_id'] = user.id
        user_session['username'] = user.name
        user_session['prefix'] = prefix if prefix else None
        user_session.save()
        return user_session

    def get_session(self, sessionId):
        user_session = UserSession({}, id=sessionId, **session_config)
        if user_session.is_new:
            user_session.delete()
            raise ValueError("Session not found!")
        return user_session

    def create_attribute(self, *args, **kwargs):
        attribute = AttributeType(*args, **kwargs)
        self.session.add(attribute)
        return attribute

    def get_attributes(self):
        return self.session.query(AttributeType).all()

    def generate_revocation(self, prefix):
        yubikey = self.auth.get_yubikey(prefix)
        code = base64.urlsafe_b64encode(uuid.uuid4().get_bytes())
        yubikey.attributes[REVOKE_KEY] = code
        return code

    def revoke(self, code):
        kwargs = {REVOKE_KEY: code}
        keys = self.auth.query_yubikeys(**kwargs)
        if not len(keys) == 1:
            log.error('Revocation failed. Matching keys: %d, Code: %s',
                      len(keys), code)
            raise ValueError('Invalid revocation code!')
        yubikey = keys[0]
        yubikey.enabled = False
        del yubikey.attributes[REVOKE_KEY]
        log.info(
            'Revocation successful. '
            'YubiKey [%s] has been revoked using code: %s', yubikey.prefix,
            code)

    def register(self, username, password, otp=None, attributes=None):
        if not settings['registration']:
            raise ValueError('User registration disabled!')

        if attributes is None:
            attributes = {}

        validate_attributes(self.get_attributes(), attributes)

        if otp and not validate_otp(otp):
            raise ValueError('Invalid OTP!')

        user = self.auth.create_user(username, password)
        user.attributes.update(attributes)
        if otp:
            user.assign_yubikey(otp)
        log.info('User %s registered with attributes: %r', username,
                 attributes)
        return user