Esempio n. 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
    def __call__(self, request):
        self.origin = get_origin(request.environ)
        self.app_id = self.origin
        page = request.path_info_pop()

        # To be able to see what the server considers its origin to be:
        if page == 'origin':
            return self.origin
        elif page is None:
            return json.dumps([self.origin])

        with YubiAuth() as auth:
            try:
                username = '******' + request.params['username']
                password = request.params['password']
                data = request.params.get('data', None)

                self.auth = auth
                if page == 'enroll':
                    return self.enroll(username, password)
                elif page == 'bind':
                    return self.bind(username, password, data)
                elif page == 'sign':
                    return self.sign(username, password)
                elif page == 'verify':
                    return self.verify(username, password, data)
                else:
                    raise exc.HTTPNotFound()
            except Exception:
                return exc.HTTPBadRequest(comment=traceback.format_exc())
Esempio n. 3
0
 def __init__(self, session=Session()):
     super(Client, self).__init__(session)
     self.auth = YubiAuth(session)
Esempio n. 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
Esempio n. 5
0
 def __init__(self):
     from yubiauth.core.model import User as _user
     self.User = _user
     self.auth = YubiAuth()
Esempio n. 6
0
class YubiAuthUsers(CollectionApp):
    base_url = '/auth/users'
    item_name = 'Users'
    caption = 'YubiAuth Users'
    columns = ['Username', 'YubiKeys']
    template = 'auth/list'

    def __init__(self):
        from yubiauth.core.model import User as _user
        self.User = _user
        self.auth = YubiAuth()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        del self.auth

    def _size(self):
        return self.auth.session.query(self.User).count()

    def _get(self, offset=0, limit=None):
        users = self.auth.session.query(self.User).order_by(self.User.name) \
            .offset(offset).limit(limit)

        return map(lambda user: {
            'id': user.id,
            'label': user.name,
            'Username': '******' % (user.id,
                                                                  user.name),
            'YubiKeys': ', '.join(user.yubikeys.keys())
        }, users)

    def _labels(self, ids):
        users = self.auth.session.query(self.User.name) \
            .filter(self.User.id.in_(map(int, ids))).all()
        return map(lambda x: x[0], users)

    def _delete(self, ids):
        self.auth.session.query(self.User) \
            .filter(self.User.id.in_(map(int, ids))).delete('fetch')
        self.auth.commit()

    def create(self, request):
        return self.render_forms(request, [CreateUserForm(self.auth)],
                                 success_msg='User created!')

    def show(self, request):
        id = int(request.path_info_pop())
        user = self.auth.get_user(id)
        if 'unassign' in request.params:
            del user.yubikeys[request.params['unassign']]
            self.auth.commit()
        msg = None
        if 'password' in request.params:
            msg = 'Password set!'
        return self.render_forms(request,
                                 [SetPasswordForm(user, self.auth),
                                 AssignYubiKeyForm(user, self.auth)],
                                 'auth/user', user=user,
                                 success_msg=msg)
Esempio n. 7
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
Esempio n. 8
0
def setup():
    auth = YubiAuth()
    for user in auth.query_users():
        auth.get_user(user['id']).delete()
    auth.commit()
    del auth
def setup():
    auth = YubiAuth()
    for user in auth.query_users():
        auth.get_user(user['id']).delete()
    auth.commit()
    del auth
Esempio n. 10
0
 def __init__(self, session=Session()):
     super(Client, self).__init__(session)
     self.auth = YubiAuth(session)
Esempio n. 11
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
Esempio n. 12
0
 def __init__(self):
     from yubiauth.core.model import User as _user
     self.User = _user
     self.auth = YubiAuth()
Esempio n. 13
0
class YubiAuthUsers(CollectionApp):
    base_url = '/auth/users'
    item_name = 'Users'
    caption = 'YubiAuth Users'
    columns = ['Username', 'YubiKeys']
    template = 'auth/list'

    def __init__(self):
        from yubiauth.core.model import User as _user
        self.User = _user
        self.auth = YubiAuth()

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        del self.auth

    def _size(self):
        return self.auth.session.query(self.User).count()

    def _get(self, offset=0, limit=None):
        users = self.auth.session.query(self.User).order_by(self.User.name) \
            .offset(offset).limit(limit)

        return map(
            lambda user: {
                'id':
                user.id,
                'label':
                user.name,
                'Username':
                '******' % (user.id, user.name),
                'YubiKeys':
                ', '.join(user.yubikeys.keys())
            }, users)

    def _labels(self, ids):
        users = self.auth.session.query(self.User.name) \
            .filter(self.User.id.in_(map(int, ids))).all()
        return map(lambda x: x[0], users)

    def _delete(self, ids):
        self.auth.session.query(self.User) \
            .filter(self.User.id.in_(map(int, ids))).delete('fetch')
        self.auth.commit()

    def create(self, request):
        return self.render_forms(request, [CreateUserForm(self.auth)],
                                 success_msg='User created!')

    def show(self, request):
        id = int(request.path_info_pop())
        user = self.auth.get_user(id)
        if 'unassign' in request.params:
            del user.yubikeys[request.params['unassign']]
            self.auth.commit()
        msg = None
        if 'password' in request.params:
            msg = 'Password set!'
        return self.render_forms(request, [
            SetPasswordForm(user, self.auth),
            AssignYubiKeyForm(user, self.auth)
        ],
                                 'auth/user',
                                 user=user,
                                 success_msg=msg)