Exemple #1
0
    def POST(self, USERNAME, PASSWORD, LOGIN_BUTTON="", url=""):

        if LOGIN_BUTTON:
            if user_exists(USERNAME):

                if potential_attack(USERNAME):
                    deactivate_user(USERNAME)
                    logger.security("user account deactivated")

                elif user.login(USERNAME, PASSWORD):
                    username = user.username
                    user_id = user.id
                    msg = '<a href="/users/%(user_id)s">%(username)s</a> logged in' % locals()
                    logger.info("user %s successfully logged in" % USERNAME)
                    logger.activity("session", msg)
                    return redirect_to("/")
            else:
                logger.security("unknown username (%s)" % USERNAME)

            logger.security("failed login attempt", USERNAME)
            error("invalid username or password")

        else:
            # API call
            if user.login(USERNAME, PASSWORD):
                return "OK"
            else:
                return "FAIL"
Exemple #2
0
    def login_button(self):

        if login_form.validate(data):

            values = login_form.evaluate()

            username = values['USERNAME']
            password = values['PASSWORD']
            remember_me = values['REMEMBER_ME']

            as_api = os.environ.get('HTTP_ACCEPT','') == 'application/json'

            if user_exists(username):
                if potential_attack(username):
                    deactivate_user(username)
                    logger.security('user account (%s) deactivated' % username)
                elif user.login(username, password, remember_me):
                    if as_api:
                        logger.info('user %s successfully logged in via api' % username)
                        return '{}'
                    else:
                        username = user.username
                        user_id = user.id
                        msg = '<a href="/users/%(user_id)s">%(username)s</a> logged in' % locals()
                        logger.activity('session', msg)
                        logger.info('user %s successfully logged in' % username)

                        referrer = data.get('referrer')
                        if referrer:
                            return redirect_to(referrer)
                        return redirect_to('/'+user.default_app)
            else:
                logger.security('unknown username (%s)' % username)
            logger.security('failed login attempt', username)

            if as_api:
                return '{"message": "invalid username or password"}'
            else:
                error('invalid username or password')
Exemple #3
0
def generate_response(instance_path, start_time=None):
    """generate response to web request"""

    profiler = None
    debugging = True

    system_timer = SystemTimer(start_time)

    # capture stdout
    real_stdout = sys.stdout
    sys.stdout = StringIO.StringIO()
    try:
        try:
            # initialize context
            system.setup(instance_path, request.server, system_timer)
            system_timer.add('system initializated')

            user.setup()
            system_timer.add('user initializated')

            manager.setup()
            system_timer.add('manager initializated')

            if user.is_disabled:
                # we know who the user is, and their account is disabled
                msg = 'User {user.link} is disabled'
                raise UnauthorizedException(msg.format(user=user))

            debugging = (system.debugging or system.show_errors
                         or user.is_developer or user.is_administrator)

            session = system.session

            if system.track_visits:
                visited(request.subject, session.sid)

            csrf_token = data.pop('csrf_token', None)
            if request.method == 'POST' and system.csrf_validation:
                if csrf_token == session.csrf_token:
                    del session.csrf_token
                else:
                    msg = 'expected:%s got:%s' % (session.csrf_token,
                                                  csrf_token)
                    raise CrossSiteRequestForgeryAttempt(msg)

            requested_app_name = manager.requested_app_name()
            default_app_name = manager.default_app_name()

            os.chdir(system.config.sites_path)

            if not request.route:
                request.route.append(default_app_name)

            for app in manager.apps.values():
                app.initialize(request)

            if manager.can_run(requested_app_name):
                system.app = manager.get_app(requested_app_name)

                profiler = (system.profile or user.profile) \
                    and cProfile.Profile()
                if profiler:
                    profiler.enable()

                system_timer.add('app ready')

                response = system.app.run(request)

                system_timer.add('app returned')

                if profiler:
                    profiler.disable()

            elif manager.can_run_if_login(requested_app_name):
                # as it stands now, an attacker can generate a list of
                # enabled apps by iterating the/a namespace and seeing
                # which ones return a logon form.

                def referrer():
                    """get the referrer"""
                    uri = urllib.urlencode(dict(referrer=request.uri))
                    return uri and "?{}".format(uri) or ''

                response = redirect_to('/login{}'.format(referrer()))

            elif not requested_app_name:
                app = manager.get_app(default_app_name)
                if app:
                    system.app = app
                else:
                    raise Exception(default_app_name + ' app missing')
                response = system.app.run(request)

            elif manager.can_run(default_app_name):
                response = redirect_to('/')

            else:
                response = Page(PAGE_MISSING_MESSAGE).render()
                response.status = '404'

            timeout = session.save_session()
            set_session_cookie(
                response,
                session.sid,
                request.subject,
                timeout,
                system.secure_cookies,
            )

        except UnauthorizedException:
            logger.security('unauthorized access attempt')
            if debugging:
                raise
            else:
                response = Page(UNAUTHORIZED_MESSAGE).render()
                response.status = '403'

        except CrossSiteRequestForgeryAttempt:
            logger.security('cross site forgery attempt')
            if debugging:
                raise
            else:
                response = redirect_to('/')

        except SessionExpiredException:
            response = Page(
                load_template('system_application_session_expired',
                              SESSION_EXPIRED_MESSAGE)).render()

        except:
            t = htmlquote(traceback.format_exc())
            logger.error(t)
            if debugging:
                try:
                    tpl = load_template('system_application_error_developer',
                                        STANDARD_ERROR_MESSAGE)
                    msg = tpl % dict(message=t)
                except:
                    msg = SYSTEM_ERROR_MESSAGE % dict(message=t)
            else:
                try:
                    msg = load_template('system_application_error_user',
                                        FRIENDLY_ERROR_MESSAGE)
                except:
                    msg = FRIENDLY_ERROR_MESSAGE

            try:
                response = Page(msg).render()
            except:
                response = HTMLResponse(msg)

        if profiler:
            stats_s = StringIO.StringIO()
            sortby = 'cumulative'
            ps = pstats.Stats(profiler, stream=stats_s)
            ps.sort_stats(sortby)
            ps.print_stats(.1)
            t = stats_s.getvalue()
            t = t.replace(system.lib_path, '~zoom').replace(
                '/usr/lib/python2.7/dist-packages/',
                '~').replace('/usr/local/lib/python2.7/dist-packages/', '~')

            print(''.join([
                '\n\n  System Performance Metrics\n ' + '=' * 30,
                system_timer.report(),
                system.database.report(),
                system.db.report(), '  Profiler\n ------------\n', t
            ]))
    finally:
        printed_output = sys.stdout.getvalue()
        sys.stdout.close()
        sys.stdout = real_stdout
        logger.complete()

    system.release()

    if hasattr(response, 'printed_output'):
        response.printed_output = printed_output.replace('<', '&lt;').replace(
            '>', '&gt;')

    return response
Exemple #4
0
def generate_response(instance_path, start_time=None):
    """generate response to web request"""

    profiler = None
    debugging = True

    system_timer = SystemTimer(start_time)

    # capture stdout
    real_stdout = sys.stdout
    sys.stdout = StringIO.StringIO()
    try:
        try:
            # initialize context
            system.setup(instance_path, request.server, system_timer)
            system_timer.add('system initializated')

            user.setup()
            system_timer.add('user initializated')

            manager.setup()
            system_timer.add('manager initializated')

            if user.is_disabled:
                # we know who the user is, and their account is disabled
                msg = 'User {user.link} is disabled'
                raise UnauthorizedException(msg.format(user=user))

            debugging = (system.debugging or system.show_errors or
                         user.is_developer or user.is_administrator)

            session = system.session

            if system.track_visits:
                visited(request.subject, session.sid)

            csrf_token = data.pop('csrf_token', None)
            if request.method == 'POST' and system.csrf_validation:
                if csrf_token == session.csrf_token:
                    del session.csrf_token
                else:
                    msg = 'expected:%s got:%s' % (
                        session.csrf_token, csrf_token)
                    raise CrossSiteRequestForgeryAttempt(msg)

            requested_app_name = manager.requested_app_name()
            default_app_name = manager.default_app_name()

            os.chdir(system.config.sites_path)

            if not request.route:
                request.route.append(default_app_name)

            for app in manager.apps.values():
                app.initialize(request)

            if manager.can_run(requested_app_name):
                system.app = manager.get_app(requested_app_name)

                profiler = (system.profile or user.profile) \
                    and cProfile.Profile()
                if profiler:
                    profiler.enable()

                system_timer.add('app ready')

                response = system.app.run(request)

                system_timer.add('app returned')

                if profiler:
                    profiler.disable()

            elif manager.can_run_if_login(requested_app_name):
                # as it stands now, an attacker can generate a list of
                # enabled apps by iterating the/a namespace and seeing
                # which ones return a logon form.

                def referrer():
                    """get the referrer"""
                    uri = urllib.urlencode(dict(referrer=request.uri))
                    return uri and "?{}".format(uri) or ''
                response = redirect_to('/login{}'.format(referrer()))

            elif not requested_app_name:
                app = manager.get_app(default_app_name)
                if app:
                    system.app = app
                else:
                    raise Exception(default_app_name + ' app missing')
                response = system.app.run(request)

            elif manager.can_run(default_app_name):
                response = redirect_to('/')

            else:
                response = Page(PAGE_MISSING_MESSAGE).render()
                response.status = '404'

            timeout = session.save_session()
            set_session_cookie(
                response,
                session.sid,
                request.subject,
                timeout,
                system.secure_cookies,
            )

        except UnauthorizedException:
            logger.security('unauthorized access attempt')
            if debugging:
                raise
            else:
                response = Page(UNAUTHORIZED_MESSAGE).render()
                response.status = '403'

        except CrossSiteRequestForgeryAttempt:
            logger.security('cross site forgery attempt')
            if debugging:
                raise
            else:
                response = redirect_to('/')

        except SessionExpiredException:
            response = Page(load_template(
                'system_application_session_expired',
                SESSION_EXPIRED_MESSAGE)).render()

        except:
            t = htmlquote(traceback.format_exc())
            logger.error(t)
            if debugging:
                try:
                    tpl = load_template(
                        'system_application_error_developer',
                        STANDARD_ERROR_MESSAGE)
                    msg = tpl % dict(message=t)
                except:
                    msg = SYSTEM_ERROR_MESSAGE % dict(message=t)
            else:
                try:
                    msg = load_template(
                        'system_application_error_user',
                        FRIENDLY_ERROR_MESSAGE
                    )
                except:
                    msg = FRIENDLY_ERROR_MESSAGE

            try:
                response = Page(msg).render()
            except:
                response = HTMLResponse(msg)

        if profiler:
            stats_s = StringIO.StringIO()
            sortby = 'cumulative'
            ps = pstats.Stats(profiler, stream=stats_s)
            ps.sort_stats(sortby)
            ps.print_stats(.1)
            t = stats_s.getvalue()
            t = t.replace(
                system.lib_path, '~zoom'
            ).replace(
                '/usr/lib/python2.7/dist-packages/',
                '~'
            ).replace(
                '/usr/local/lib/python2.7/dist-packages/',
                '~'
            )

            print(''.join([
                '\n\n  System Performance Metrics\n ' + '=' * 30,
                system_timer.report(),
                system.database.report(),
                system.db.report(),
                '  Profiler\n ------------\n',
                t
            ]))
    finally:
        printed_output = sys.stdout.getvalue()
        sys.stdout.close()
        sys.stdout = real_stdout
        logger.complete()

    system.release()

    if hasattr(response, 'printed_output'):
        response.printed_output = printed_output.replace(
            '<', '&lt;'
            ).replace(
            '>', '&gt;'
            )

    return response