Example #1
0
    def insecurelogin(self, username=None, password=None, return_to=None):
        '''
        Provide insecure login endpoint for HTTP GET-based credential passing
        '''

        # Force a refresh of startup info so that we know to
        # redirect if license stuff has expired.
        startup.initVersionInfo(force=True)

        output = jsonresponse.JsonResponse()

        if not splunk.util.normalizeBoolean(
                cherrypy.config.get('enable_insecure_login')):
            cherrypy.response.status = 403
            output.success = False
            output.addError(
                'The insecure login endpoint is disabled. See web.conf for details.'
            )
            return self.render_json(output)

        if not username or not password:
            cherrypy.response.status = 400
            output.success = False
            output.addError('Missing credentials')
            return self.render_json(output)

        try:
            sessionKey = splunk.auth.getSessionKey(
                username, password, hostPath=self.splunkd_urlhost)
        except Exception, e:
            output.parseRESTException(e)
            output.success = False
            return self.render_json(output)
    def insecurelogin(self, username=None, password=None, return_to=None):
        '''
        Provide insecure login endpoint for HTTP GET-based credential passing
        '''

        # Force a refresh of startup info so that we know to
        # redirect if license stuff has expired.
        startup.initVersionInfo(force=True)

        output = jsonresponse.JsonResponse()

        if not splunk.util.normalizeBoolean(cherrypy.config.get('enable_insecure_login')):
            cherrypy.response.status = 403
            output.success = False
            output.addError('The insecure login endpoint is disabled. See web.conf for details.')
            return self.render_json(output)

        if not username or not password:
            cherrypy.response.status = 400
            output.success = False
            output.addError('Missing credentials')
            return self.render_json(output)

        ua = cherrypy.request.headers.get('user-agent', 'unknown')
        ip = cherrypy.request.remote.ip
        try:
            sessionKey = splunk.auth.getSessionKey(username, password, hostPath=self.splunkd_urlhost)
        except Exception, e:
            logger.error('user=%s action=insecurelogin status=failure session=%s ' \
                'reason=user-initiated useragent="%s" clientip=%s'
                % (username, sessionKey, ua, ip))
            output.parseRESTException(e)
            output.success = False
            return self.render_json(output)
Example #3
0
    def insecurelogin(self, username=None, password=None, return_to=None):
        '''
        Provide insecure login endpoint for HTTP GET-based credential passing
        '''
        
        # Force a refresh of startup info so that we know to 
        # redirect if license stuff has expired.
        startup.initVersionInfo(force=True)

        output = jsonresponse.JsonResponse()

        if not splunk.util.normalizeBoolean(cherrypy.config.get('enable_insecure_login')):
            cherrypy.response.status = 403
            output.success = False
            output.addError('The insecure login endpoint is disabled. See web.conf for details.')
            return self.render_json(output)

        if not username or not password:
            cherrypy.response.status = 400
            output.success = False
            output.addError('Missing credentials')
            return self.render_json(output)

        try:
            sessionKey = splunk.auth.getSessionKey(username, password, hostPath=self.splunkd_urlhost)
        except Exception, e:
            output.parseRESTException(e)
            output.success = False
            return self.render_json(output)
Example #4
0
    def check(fn, self, *a, **kw):
        is_api = util.is_api()
        request = cherrypy.request
        if not handle_api and is_api:
            raise RequestRefused(404)
        if handle_api is ONLY_API and not is_api:
            raise RequestRefused(404)
        _methods = methods
        if _methods:
            if isinstance(_methods, basestring):
                _methods = [ _methods ]
            if request.method not in _methods:
                raise RequestRefused(405)
        
        # verify that version info is good; do it here so that any URI access
        # will trigger the check
        startup.initVersionInfo()

        # add a convenience property to all request objects to get at the
        # current relative URI
        request.relative_uri = request.path_info + (('?' + request.query_string) if request.query_string else '')
        if cherrypy.config.get('root_endpoint') not in ['/', None, '']:
            request.relative_uri = cherrypy.config.get('root_endpoint') + request.relative_uri

        # CSRF protection
        # Disable in tests by setting cherrypy.config.update({'environment': 'test_suite'})
        if verify_session and request.method == 'POST' and not cherrypy.config.get('environment') == 'test_suite':
            is_xhr = util.is_xhr()
            form_key = request.headers.get('X-Splunk-Form-Key') if is_xhr else request.params.get('splunk_form_key')
            # verify that the incoming form key matches server's version
            if not util.isValidFormKey(form_key):
                if is_xhr:
                    logger.warn('CSRF: validation failed because client XHR did not include proper header')
                else:
                    logger.warn('CSRF: validation failed because HTTP POST did not include expected parameter')
                if must_login:
                    if is_xhr:
                        raise cherrypy.HTTPError(401, _('Splunk cannot authenticate the request. CSRF validation failed.'))
                    else:
                        return self.redirect_to_url('/account/login', _qs=[ ('return_to', util.current_url_path()) ] )
                logger.warn('CSRF: skipping 401 redirect response because endpoint did not request protection')

        # basic input cleansing
        if trim_spaces:
            for key, value in kw.iteritems():
                if isinstance(value, basestring):
                    kw[key] = value.strip()
                    if kw[key] != value:
                        logger.debug('Leading/trailing whitespaces were trimmed in "%s" argument' % key)
                
        return fn(self, *a, **kw)
    def logout(self):

        # Force a refresh of startup info so that we know to
        # redirect if license stuff has expired.
        startup.initVersionInfo(force=True)

        # Log to file
        try:
            username = cherrypy.session['user']['name']
            session = cherrypy.session['sessionKey']
            ip = cherrypy.request.remote.ip
            ua = cherrypy.request.headers.get('user-agent', 'unknown')
            logger.info('user=%s action=logout status=success ' \
                'reason=user-initiated useragent="%s" clientip=%s session=%s'
                % (username, ua, ip, session))
        except (KeyError, AttributeError), e:
            # User wasn't logged in, or no session
            pass
Example #6
0
    def logout(self):

        # Force a refresh of startup info so that we know to
        # redirect if license stuff has expired.
        startup.initVersionInfo(force=True)

        # Log to file
        try:
            username = cherrypy.session['user']['name']
            session = cherrypy.session['sessionKey']
            ip = cherrypy.request.remote.ip
            ua = cherrypy.request.headers.get('user-agent', 'unknown')
            logger.info('user=%s action=logout status=success ' \
                'reason=user-initiated useragent="%s" clientip=%s session=%s'
                % (username, ua, ip, session))
        except (KeyError, AttributeError), e:
            # User wasn't logged in, or no session
            pass
    def insecurelogin(self, username=None, password=None, return_to=None):
        '''
        Provide insecure login endpoint for HTTP GET-based credential passing
        '''

        # Force a refresh of startup info so that we know to
        # redirect if license stuff has expired.
        startup.initVersionInfo(force=True)

        output = jsonresponse.JsonResponse()

        if not splunk.util.normalizeBoolean(
                cherrypy.config.get('enable_insecure_login')):
            cherrypy.response.status = 403
            output.success = False
            output.addError(
                'The insecure login endpoint is disabled. See web.conf for details.'
            )
            return self.render_json(output)

        if not username or not password:
            cherrypy.response.status = 400
            output.success = False
            output.addError('Missing credentials')
            return self.render_json(output)

        ua = cherrypy.request.headers.get('user-agent', 'unknown')
        ip = cherrypy.request.remote.ip
        try:
            sessionKey = splunk.auth.getSessionKey(
                username, password, hostPath=self.splunkd_urlhost)
        except Exception, e:
            logger.error('user=%s action=insecurelogin status=failure session=%s ' \
                'reason=user-initiated useragent="%s" clientip=%s'
                % (username, sessionKey, ua, ip))
            output.parseRESTException(e)
            output.success = False
            return self.render_json(output)
    def login(self, username=None, password=None, return_to=None, cval=None, newpassword=None, **kwargs):

        # Force a refresh of startup info so that we know to
        # redirect if license stuff has expired.
        startup.initVersionInfo(force=True)

        updateCheckerBaseURL = self.getUpdateCheckerBaseURL()

        # set a long lived uid cookie
        self.updateCookieUID()

        templateArgs = self.getLoginTemplateArgs(return_to=return_to)

        if not return_to:
            return_to = '/'
        if return_to[0] != '/':
            return_to = '/' + return_to

        #dont allow new login if session established.
        if cherrypy.session.get('sessionKey') and return_to:
            raise cherrypy.HTTPRedirect(util.make_url_internal(return_to))

        # Storm
        if cherrypy.config.get('storm_enabled'):
            return self.handleStormLogin(return_to=return_to, **kwargs)

        #
        # GET
        #
        if cherrypy.request.method == 'GET' and newpassword is None:

            # free license will auth on anything so statically seed
            if cherrypy.config.get('is_free_license'):

                # Start with a clean and minty fresh session
                cherrypy.session.regenerate()

                cherrypy.session['user'] = {
                    'name': 'admin',
                    'fullName': 'Administrator',
                    'id': 1
                }
                sessionKey = splunk.auth.getSessionKey("admin", "freeneedsnopassword", hostPath=self.splunkd_urlhost)
                cherrypy.session['sessionKey'] = sessionKey

                if not updateCheckerBaseURL:
                    return self.redirect_to_url('/app/%s' % splunk.getDefault('namespace'))


            # check for previously successful login
            templateArgs['hasLoggedIn'] = self.hasLoggedIn()

            if templateArgs['return_to'] is None and cherrypy.config.get('root_endpoint') not in ['/', None, '']:
                templateArgs['return_to'] = util.make_url_internal(cherrypy.config.get('root_endpoint'))

            # otherwise, show page
            return self.render_template('account/login.html', templateArgs)

        #
        # POST
        #

        # Check that the cookie we set when the login page was loaded has made it to us intact
        if 'cval' not in cherrypy.request.cookie or not self.cookieTest(cval):
            templateArgs['bad_cookies'] = 1
            return self.render_template('account/login.html', templateArgs)

        ua = cherrypy.request.headers.get('user-agent', 'unknown')
        ip = cherrypy.request.remote.ip
        
        if username:
            username = username.strip().lower()
        
        try:
            sessionKey = splunk.auth.getSessionKey(username, password, hostPath=self.splunkd_urlhost, newPassword=newpassword)
        except splunk.AuthenticationFailed, e:
            logger.error('user=%s action=login status=failure ' \
                         'reason=user-initiated useragent="%s" clientip=%s ERROR=%s'
                         % (username, ua, ip, str(e.msg)))

            templateArgs['invalid_password'] = 1

            forced_password_change = str(e.msg).count('fpc')
            forced_password_message = str(e.extendedMessages)

            if forced_password_change:
                templateArgs['fpc'] = True
                # cache current credentials in memory only
                credentials = {'username': username, 'password': password}
                with AccountController.credential_lock:
                    AccountController.credential_cache[cherrypy.session.id] = credentials
                cherrypy.session['cval'] = cval
                cherrypy.session['fpc'] = True  # forced password change

                templateArgs['err'] = _(forced_password_message)
                logger.info('user=%s action=login status=%s' % (username, forced_password_message))
                
                return self.render_template('account/passwordchange.html', templateArgs)
            else:
                return self.render_template('account/login.html', templateArgs)
Example #9
0
    def login(self,
              username=None,
              password=None,
              return_to=None,
              cval=None,
              **kwargs):

        # Force a refresh of startup info so that we know to
        # redirect if license stuff has expired.
        startup.initVersionInfo(force=True)

        updateCheckerBaseURL = self.getUpdateCheckerBaseURL()

        # set a long lived uid cookie
        self.updateCookieUID()

        templateArgs = self.getLoginTemplateArgs(return_to=return_to,
                                                 cval=cval)

        # Storm
        if cherrypy.config.get('storm_enabled'):
            return self.handleStormLogin(**kwargs)

        #
        # GET
        #
        if cherrypy.request.method == 'GET':

            # free license will auth on anything so statically seed
            if cherrypy.config.get('is_free_license'):

                # Start with a clean and minty fresh session
                cherrypy.session.regenerate()

                cherrypy.session['user'] = {
                    'name': 'admin',
                    'fullName': 'Administrator',
                    'id': 1
                }
                sessionKey = splunk.auth.getSessionKey(
                    "admin",
                    "freeneedsnopassword",
                    hostPath=self.splunkd_urlhost)
                cherrypy.session['sessionKey'] = sessionKey

                if not updateCheckerBaseURL:
                    return self.redirect_to_url('/app/%s' %
                                                splunk.getDefault('namespace'))

            # check for previously successful login
            templateArgs['hasLoggedIn'] = self.hasLoggedIn()

            # otherwise, show page
            return self.render_template('account/login.html', templateArgs)

        #
        # POST
        #

        # Check that the cookie we set when the login page was loaded has made it to us intact
        if 'cval' not in cherrypy.request.cookie or not self.cookieTest(cval):
            templateArgs['bad_cookies'] = 1
            templateArgs['cval'] = self.updateCookieTest()
            return self.render_template('account/login.html', templateArgs)

        try:
            sessionKey = splunk.auth.getSessionKey(
                username, password, hostPath=self.splunkd_urlhost)
        except splunk.AuthenticationFailed, e:
            templateArgs['invalid_password'] = 1
            templateArgs['cval'] = self.updateCookieTest()
            return self.render_template('account/login.html', templateArgs)
Example #10
0
    def check(fn, self, *a, **kw):
        is_api = util.is_api()
        request = cherrypy.request
        if not handle_api and is_api:
            raise RequestRefused(404)
        if handle_api is ONLY_API and not is_api:
            raise RequestRefused(404)
        _methods = methods
        if _methods:
            if isinstance(_methods, basestring):
                _methods = [_methods]
            if request.method not in _methods:
                raise RequestRefused(405)

        # verify that version info is good; do it here so that any URI access
        # will trigger the check
        startup.initVersionInfo()

        # add a convenience property to all request objects to get at the
        # current relative URI
        request.relative_uri = request.path_info + (
            ('?' + request.query_string) if request.query_string else '')
        if cherrypy.config.get('root_endpoint') not in ['/', None, '']:
            request.relative_uri = cherrypy.config.get(
                'root_endpoint') + request.relative_uri

        # CSRF protection
        # Disable in tests by setting cherrypy.config.update({'environment': 'test_suite'})
        if verify_session and request.method == 'POST' and not cherrypy.config.get(
                'environment') == 'test_suite':
            is_xhr = util.is_xhr()
            form_key = request.headers.get(
                'X-Splunk-Form-Key') if is_xhr else request.params.get(
                    'splunk_form_key')
            # verify that the incoming form key matches server's version
            if not util.isValidFormKey(form_key):
                if is_xhr:
                    logger.warn(
                        'CSRF: validation failed because client XHR did not include proper header'
                    )
                else:
                    logger.warn(
                        'CSRF: validation failed because HTTP POST did not include expected parameter'
                    )
                if must_login:
                    if is_xhr:
                        raise cherrypy.HTTPError(
                            401,
                            _('Splunk cannot authenticate the request. CSRF validation failed.'
                              ))
                    else:
                        return self.redirect_to_url(
                            '/account/login',
                            _qs=[('return_to', util.current_url_path())])
                logger.warn(
                    'CSRF: skipping 401 redirect response because endpoint did not request protection'
                )

        # basic input cleansing
        if trim_spaces:
            for key, value in kw.iteritems():
                if isinstance(value, basestring):
                    kw[key] = value.strip()
                    if kw[key] != value:
                        logger.debug(
                            'Leading/trailing whitespaces were trimmed in "%s" argument'
                            % key)

        return fn(self, *a, **kw)
    def login(self,
              username=None,
              password=None,
              return_to=None,
              cval=None,
              newpassword=None,
              **kwargs):

        # Force a refresh of startup info so that we know to
        # redirect if license stuff has expired.
        startup.initVersionInfo(force=True)

        updateCheckerBaseURL = self.getUpdateCheckerBaseURL()

        # set a long lived uid cookie
        self.updateCookieUID()

        templateArgs = self.getLoginTemplateArgs(return_to=return_to)

        if not return_to:
            return_to = '/'
        if return_to[0] != '/':
            return_to = '/' + return_to

        #dont allow new login if session established.
        if cherrypy.session.get('sessionKey') and return_to:
            raise cherrypy.HTTPRedirect(util.make_url_internal(return_to))

        # Storm
        if cherrypy.config.get('storm_enabled'):
            return self.handleStormLogin(return_to=return_to, **kwargs)

        #
        # GET
        #
        if cherrypy.request.method == 'GET' and newpassword is None:

            # free license will auth on anything so statically seed
            if cherrypy.config.get('is_free_license'):

                # Start with a clean and minty fresh session
                cherrypy.session.regenerate()

                cherrypy.session['user'] = {
                    'name': 'admin',
                    'fullName': 'Administrator',
                    'id': 1
                }
                sessionKey = splunk.auth.getSessionKey(
                    "admin",
                    "freeneedsnopassword",
                    hostPath=self.splunkd_urlhost)
                cherrypy.session['sessionKey'] = sessionKey

                if not updateCheckerBaseURL:
                    return self.redirect_to_url('/app/%s' %
                                                splunk.getDefault('namespace'))

            # check for previously successful login
            templateArgs['hasLoggedIn'] = self.hasLoggedIn()

            if templateArgs['return_to'] is None and cherrypy.config.get(
                    'root_endpoint') not in ['/', None, '']:
                templateArgs['return_to'] = util.make_url_internal(
                    cherrypy.config.get('root_endpoint'))

            # otherwise, show page
            return self.render_template('account/login.html', templateArgs)

        #
        # POST
        #

        # Check that the cookie we set when the login page was loaded has made it to us intact
        if 'cval' not in cherrypy.request.cookie or not self.cookieTest(cval):
            templateArgs['bad_cookies'] = 1
            return self.render_template('account/login.html', templateArgs)

        ua = cherrypy.request.headers.get('user-agent', 'unknown')
        ip = cherrypy.request.remote.ip

        if username:
            username = username.strip().lower()

        try:
            sessionKey = splunk.auth.getSessionKey(
                username,
                password,
                hostPath=self.splunkd_urlhost,
                newPassword=newpassword)
        except splunk.AuthenticationFailed, e:
            logger.error('user=%s action=login status=failure ' \
                         'reason=user-initiated useragent="%s" clientip=%s ERROR=%s'
                         % (username, ua, ip, str(e.msg)))

            templateArgs['invalid_password'] = 1

            forced_password_change = str(e.msg).count('fpc')
            forced_password_message = str(e.extendedMessages)

            if forced_password_change:
                templateArgs['fpc'] = True
                # cache current credentials in memory only
                credentials = {'username': username, 'password': password}
                with AccountController.credential_lock:
                    AccountController.credential_cache[
                        cherrypy.session.id] = credentials
                cherrypy.session['cval'] = cval
                cherrypy.session['fpc'] = True  # forced password change

                templateArgs['err'] = _(forced_password_message)
                logger.info('user=%s action=login status=%s' %
                            (username, forced_password_message))

                return self.render_template('account/passwordchange.html',
                                            templateArgs)
            else:
                return self.render_template('account/login.html', templateArgs)
Example #12
0
    def login(self, username=None, password=None, return_to=None, cval=None, **kwargs):
        
        # Force a refresh of startup info so that we know to 
        # redirect if license stuff has expired.
        startup.initVersionInfo(force=True)

        updateCheckerBaseURL = self.getUpdateCheckerBaseURL()
        
        # set a long lived uid cookie
        self.updateCookieUID()
        
        templateArgs = self.getLoginTemplateArgs(return_to=return_to, cval=cval)

        # Storm
        if cherrypy.config.get('storm_enabled'):
            return self.handleStormLogin(**kwargs)
		
        #
        # GET
        #
        if cherrypy.request.method == 'GET':

            # free license will auth on anything so statically seed
            if cherrypy.config.get('is_free_license'):

                # Start with a clean and minty fresh session
                cherrypy.session.regenerate()

                cherrypy.session['user'] = {
                    'name': 'admin',
                    'fullName': 'Administrator',
                    'id': 1
                }
                sessionKey = splunk.auth.getSessionKey("admin", "freeneedsnopassword", hostPath=self.splunkd_urlhost)
                cherrypy.session['sessionKey'] = sessionKey
                
                if not updateCheckerBaseURL:
                    return self.redirect_to_url('/app/%s' % splunk.getDefault('namespace'))


            # check for previously successful login
            templateArgs['hasLoggedIn'] = self.hasLoggedIn()
            
            # otherwise, show page
            return self.render_template('account/login.html', templateArgs)

        #
        # POST
        #

        # Check that the cookie we set when the login page was loaded has made it to us intact
        if 'cval' not in cherrypy.request.cookie or not self.cookieTest(cval):
            templateArgs['bad_cookies'] = 1
            templateArgs['cval'] = self.updateCookieTest()
            return self.render_template('account/login.html', templateArgs)

        try:
            sessionKey = splunk.auth.getSessionKey(username, password, hostPath=self.splunkd_urlhost)
        except splunk.AuthenticationFailed, e:
            templateArgs['invalid_password'] = 1
            templateArgs['cval'] = self.updateCookieTest()
            return self.render_template('account/login.html', templateArgs)