Пример #1
0
    def __call__(self, environ, context):
        try:
            ip_addr = _get_ip_addr(environ)
            self._basic_security_checks()

            api_key = request.GET.get('api_key')
            try:
                # Request.authorization may raise ValueError on invalid input
                type, params = request.authorization
            except (ValueError, TypeError):
                pass
            else:
                if type.lower() == 'bearer':
                    api_key = params  # bearer token is an api key too

            if api_key is None:
                authuser = self._determine_auth_user(
                    session.get('authuser'),
                    ip_addr=ip_addr,
                )
                needs_csrf_check = request.method not in ['GET', 'HEAD']

            else:
                dbuser = User.get_by_api_key(api_key)
                if dbuser is None:
                    log.info(
                        'No db user found for authentication with API key ****%s from %s',
                        api_key[-4:], ip_addr)
                authuser = AuthUser.make(dbuser=dbuser,
                                         is_external_auth=True,
                                         ip_addr=ip_addr)
                needs_csrf_check = False  # API key provides CSRF protection

            if authuser is None:
                log.info('No valid user found')
                raise webob.exc.HTTPForbidden()

            # set globals for auth user
            request.authuser = authuser
            request.ip_addr = ip_addr
            request.needs_csrf_check = needs_csrf_check

            log.info(
                'IP: %s User: %s Request: %s',
                request.ip_addr,
                request.authuser,
                get_path_info(environ),
            )
            return super(BaseController, self).__call__(environ, context)
        except webob.exc.HTTPException as e:
            return e
Пример #2
0
    def _determine_auth_user(session_authuser, ip_addr):
        """
        Create an `AuthUser` object given the API key/bearer token
        (if any) and the value of the authuser session cookie.
        Returns None if no valid user is found (like not active or no access for IP).
        """

        # Authenticate by session cookie
        # In ancient login sessions, 'authuser' may not be a dict.
        # In that case, the user will have to log in again.
        # v0.3 and earlier included an 'is_authenticated' key; if present,
        # this must be True.
        if isinstance(session_authuser, dict) and session_authuser.get(
                'is_authenticated', True):
            return AuthUser.from_cookie(session_authuser, ip_addr=ip_addr)

        # Authenticate by auth_container plugin (if enabled)
        if any(plugin.is_container_auth
               for plugin in auth_modules.get_auth_plugins()):
            try:
                user_info = auth_modules.authenticate('', '', request.environ)
            except UserCreationError as e:
                from kallithea.lib import helpers as h
                h.flash(e, 'error', logf=log.error)
            else:
                if user_info is not None:
                    username = user_info['username']
                    user = User.get_by_username(username,
                                                case_insensitive=True)
                    return log_in_user(user,
                                       remember=False,
                                       is_external_auth=True,
                                       ip_addr=ip_addr)

        # User is default user (if active) or anonymous
        default_user = User.get_default_user()
        authuser = AuthUser.make(dbuser=default_user, ip_addr=ip_addr)
        if authuser is None:  # fall back to anonymous
            authuser = AuthUser(
                dbuser=default_user)  # TODO: somehow use .make?
        return authuser
Пример #3
0
def log_in_user(user, remember, is_external_auth, ip_addr):
    """
    Log a `User` in and update session and cookies. If `remember` is True,
    the session cookie is set to expire in a year; otherwise, it expires at
    the end of the browser session.

    Returns populated `AuthUser` object.
    """
    # It should not be possible to explicitly log in as the default user.
    assert not user.is_default_user, user

    auth_user = AuthUser.make(dbuser=user,
                              is_external_auth=is_external_auth,
                              ip_addr=ip_addr)
    if auth_user is None:
        return None

    user.update_lastlogin()
    meta.Session().commit()

    # Start new session to prevent session fixation attacks.
    session.invalidate()
    session['authuser'] = cookie = auth_user.to_cookie()

    # If they want to be remembered, update the cookie.
    # NOTE: Assumes that beaker defaults to browser session cookie.
    if remember:
        t = datetime.datetime.now() + datetime.timedelta(days=365)
        session._set_cookie_expires(t)

    session.save()

    log.info(
        'user %s is now authenticated and stored in '
        'session, session attrs %s', user.username, cookie)

    # dumps session attrs back to cookie
    session._update_cookie_out()

    return auth_user
Пример #4
0
    def serve(self, user_id, key_id, client_ip):
        """Verify basic sanity of the repository, and that the user is
        valid and has access - then serve the native VCS protocol for
        repository access."""
        dbuser = User.get(user_id)
        if dbuser is None:
            self.exit('User %r not found' % user_id)
        self.authuser = AuthUser.make(dbuser=dbuser, ip_addr=client_ip)
        log.info('Authorized user %s from SSH %s trusting user id %s and key id %s for %r', dbuser, client_ip, user_id, key_id, self.repo_name)
        if self.authuser is None: # not ok ... but already kind of authenticated by SSH ... but not really not authorized ...
            self.exit('User %s from %s cannot be authorized' % (dbuser.username, client_ip))

        ssh_key = UserSshKeys.get(key_id)
        if ssh_key is None:
            self.exit('SSH key %r not found' % key_id)
        ssh_key.last_seen = datetime.datetime.now()
        Session().commit()

        if HasPermissionAnyMiddleware('repository.write',
                                      'repository.admin')(self.authuser, self.repo_name):
            self.allow_push = True
        elif HasPermissionAnyMiddleware('repository.read')(self.authuser, self.repo_name):
            self.allow_push = False
        else:
            self.exit('Access to %r denied' % self.repo_name)

        self.db_repo = Repository.get_by_repo_name(self.repo_name)
        if self.db_repo is None:
            self.exit("Repository '%s' not found" % self.repo_name)
        assert self.db_repo.repo_name == self.repo_name

        # Set global hook environment up for 'push' actions.
        # If pull actions should be served, the actual hook invocation will be
        # hardcoded to 'pull' when log_pull_action is invoked (directly on Git,
        # or through the Mercurial 'outgoing' hook).
        # For push actions, the action in global hook environment is used (in
        # handle_git_post_receive when it is called as Git post-receive hook,
        # or in log_push_action through the Mercurial 'changegroup' hook).
        set_hook_environment(self.authuser.username, client_ip, self.repo_name, self.vcs_type, 'push')
        return self._serve()
Пример #5
0
    def _dispatch(self, state, remainder=None):
        """
        Parse the request body as JSON, look up the method on the
        controller and if it exists, dispatch to it.
        """
        # Since we are here we should respond as JSON
        response.content_type = 'application/json'

        environ = state.request.environ
        start = time.time()
        ip_addr = self._get_ip_addr(environ)
        self._req_id = None
        if 'CONTENT_LENGTH' not in environ:
            log.debug("No Content-Length")
            raise JSONRPCErrorResponse(retid=self._req_id,
                                       message="No Content-Length in request")
        else:
            length = environ['CONTENT_LENGTH'] or 0
            length = int(environ['CONTENT_LENGTH'])
            log.debug('Content-Length: %s', length)

        if length == 0:
            raise JSONRPCErrorResponse(retid=self._req_id,
                                       message="Content-Length is 0")

        raw_body = environ['wsgi.input'].read(length)

        try:
            json_body = ext_json.loads(raw_body)
        except ValueError as e:
            # catch JSON errors Here
            raise JSONRPCErrorResponse(
                retid=self._req_id,
                message="JSON parse error ERR:%s RAW:%r" % (e, raw_body))

        # check AUTH based on API key
        try:
            self._req_api_key = json_body['api_key']
            self._req_id = json_body['id']
            self._req_method = json_body['method']
            self._request_params = json_body['args']
            if not isinstance(self._request_params, dict):
                self._request_params = {}

            log.debug('method: %s, params: %s', self._req_method,
                      self._request_params)
        except KeyError as e:
            raise JSONRPCErrorResponse(
                retid=self._req_id,
                message='Incorrect JSON query missing %s' % e)

        # check if we can find this session using api_key
        try:
            u = User.get_by_api_key(self._req_api_key)
            auth_user = AuthUser.make(dbuser=u, ip_addr=ip_addr)
            if auth_user is None:
                raise JSONRPCErrorResponse(retid=self._req_id,
                                           message='Invalid API key')
        except Exception as e:
            raise JSONRPCErrorResponse(retid=self._req_id,
                                       message='Invalid API key')

        request.authuser = auth_user
        request.ip_addr = ip_addr

        self._error = None
        try:
            self._func = self._find_method()
        except AttributeError as e:
            raise JSONRPCErrorResponse(retid=self._req_id, message=str(e))

        # now that we have a method, add self._req_params to
        # self.kargs and dispatch control to WGIController
        argspec = inspect.getfullargspec(self._func)
        arglist = argspec.args[1:]
        argtypes = [type(arg) for arg in argspec.defaults or []]
        default_empty = type(NotImplemented)

        # kw arguments required by this method
        func_kwargs = dict(
            itertools.zip_longest(reversed(arglist),
                                  reversed(argtypes),
                                  fillvalue=default_empty))

        # This attribute will need to be first param of a method that uses
        # api_key, which is translated to instance of user at that name
        USER_SESSION_ATTR = 'apiuser'

        # get our arglist and check if we provided them as args
        for arg, default in func_kwargs.items():
            if arg == USER_SESSION_ATTR:
                # USER_SESSION_ATTR is something translated from API key and
                # this is checked before so we don't need validate it
                continue

            # skip the required param check if it's default value is
            # NotImplementedType (default_empty)
            if default == default_empty and arg not in self._request_params:
                raise JSONRPCErrorResponse(
                    retid=self._req_id,
                    message='Missing non optional `%s` arg in JSON DATA' % arg,
                )

        extra = set(self._request_params).difference(func_kwargs)
        if extra:
            raise JSONRPCErrorResponse(
                retid=self._req_id,
                message='Unknown %s arg in JSON DATA' %
                ', '.join('`%s`' % arg for arg in extra),
            )

        self._rpc_args = {}
        self._rpc_args.update(self._request_params)
        self._rpc_args['action'] = self._req_method
        self._rpc_args['environ'] = environ

        log.info('IP: %s Request to %s time: %.3fs' %
                 (self._get_ip_addr(environ), get_path_info(environ),
                  time.time() - start))

        state.set_action(self._rpc_call, [])
        state.set_params(self._rpc_args)
        return state
Пример #6
0
    def _authorize(self, environ, action, repo_name, ip_addr):
        """Authenticate and authorize user.

        Since we're dealing with a VCS client and not a browser, we only
        support HTTP basic authentication, either directly via raw header
        inspection, or by using container authentication to delegate the
        authentication to the web server.

        Returns (user, None) on successful authentication and authorization.
        Returns (None, wsgi_app) to send the wsgi_app response to the client.
        """
        # Use anonymous access if allowed for action on repo.
        default_user = User.get_default_user()
        default_authuser = AuthUser.make(dbuser=default_user, ip_addr=ip_addr)
        if default_authuser is None:
            log.debug(
                'No anonymous access at all')  # move on to proper user auth
        else:
            if self._check_permission(action, default_authuser, repo_name):
                return default_authuser, None
            log.debug(
                'Not authorized to access this repository as anonymous user')

        username = None
        #==============================================================
        # DEFAULT PERM FAILED OR ANONYMOUS ACCESS IS DISABLED SO WE
        # NEED TO AUTHENTICATE AND ASK FOR AUTH USER PERMISSIONS
        #==============================================================

        # try to auth based on environ, container auth methods
        log.debug('Running PRE-AUTH for container based authentication')
        pre_auth = auth_modules.authenticate('', '', environ)
        if pre_auth is not None and pre_auth.get('username'):
            username = pre_auth['username']
        log.debug('PRE-AUTH got %s as username', username)

        # If not authenticated by the container, running basic auth
        if not username:
            self.authenticate.realm = self.config['realm']
            result = self.authenticate(environ)
            if isinstance(result, str):
                paste.httpheaders.AUTH_TYPE.update(environ, 'basic')
                paste.httpheaders.REMOTE_USER.update(environ, result)
                username = result
            else:
                return None, result.wsgi_application

        #==============================================================
        # CHECK PERMISSIONS FOR THIS REQUEST USING GIVEN USERNAME
        #==============================================================
        try:
            user = User.get_by_username_or_email(username)
        except Exception:
            log.error(traceback.format_exc())
            return None, webob.exc.HTTPInternalServerError()

        authuser = AuthUser.make(dbuser=user, ip_addr=ip_addr)
        if authuser is None:
            return None, webob.exc.HTTPForbidden()
        if not self._check_permission(action, authuser, repo_name):
            return None, webob.exc.HTTPForbidden()

        return user, None