Example #1
0
def is_valid_token(request):
    if request.POST:
        try:
            token = request.POST['token']
            logger.debug(
                "OAuth2Portal::is_valid_token: Token retrieven in POST datas")

        except Exception as e:
            logger.error(
                "OAuth2Portal::is_valid_token: Error while trying to retrieve 'token' from POST : {}"
                .format(e))
            return HttpResponseForbidden()
        """ Connect to Redis """
        r = REDISBase()
        if not r:
            logger.error(
                "OAuth2Portal::is_valid_token: Unable to connect to REDIS !")
            return HttpResponseServerError()
        logger.debug(
            "OAuth2Portal::is_valid_token: Successfully connected to Redis")

        try:
            data = r.hgetall("oauth2_" + str(token))
            if data in ("", "None", None, {}):
                logger.error(
                    "OAuth2Portal:is_valid_token: None value was retrieven from Redis"
                )
                raise TokenNotFoundError(
                    "Token '{}' not found in Redis".format("oauth2_" +
                                                           str(token)))

            logger.debug(
                "OAuth2Portal::is_valid_token: Oauth2 datas successfully retrieven in Redis : {}"
                .format(data))
            scope = data.get('scope')
            if scope is not None:
                try:
                    scope = literal_eval(scope)
                except:
                    pass
                body = {'active': "true", 'scope': scope}
            else:
                body = {'active': 'true'}

        except Exception as e:
            logger.error(
                "OAuth2Portal:is_valid_token: Exception while retrieving data's token from Redis : {}"
                .format(e))
            body = {"active": "false"}

        logger.debug(
            "OAuth2Portal::is_valid_token: Returning '{}'".format(body))
        return JsonResponse(body)

    else:
        return HttpResponseForbidden()
    def redis_cluster_write():
        """
        Try to connect to the cluster's redis MASTER node and create /delete a key
        """

        r = REDISBase()
        assert (r), "Unable to connect to the Redis master node"
        s = r.set("test", "test")
        assert (s), "Unable to create a key on the Redis master node"
        s = r.delete("test")
        assert (s), "Unable to delete key on the Redis master node"
Example #3
0
    def __init__(self, app_id, token_name):
        self.token_name = token_name
        self.redis_base = REDISBase()
        self.workflow = Workflow.objects.get(pk=app_id)
        self.cluster = Cluster.objects.get()

        self.backend = self.workflow.repository
        if not self.application.enable_registration:
            raise RedirectionNeededError(
                "Registration is not enabled in the workflow '{}'".format(
                    self.workflow.name), self.workflow.get_redirect_uri())
Example #4
0
    def __init__(self, app_id, token_name):
        self.token_name = token_name
        self.redis_base = REDISBase()
        self.application = Application.objects.with_id(ObjectId(app_id))
        self.cluster = Cluster.objects.get()

        self.backend = self.application.getAuthBackend()
        if not self.application.enable_registration:
            raise RedirectionNeededError(
                "Registration is not enabled in the application '{}'".format(
                    self.application.name),
                self.application.get_redirect_uri())
Example #5
0
class Registration(object):
    def __init__(self, app_id, token_name):
        self.token_name = token_name
        self.redis_base = REDISBase()
        self.workflow = Workflow.objects.get(pk=app_id)
        self.cluster = Cluster.objects.get()

        self.backend = self.workflow.repository
        if not self.application.enable_registration:
            raise RedirectionNeededError(
                "Registration is not enabled in the workflow '{}'".format(
                    self.workflow.name), self.workflow.get_redirect_uri())

    def verify_captcha(self, request):
        # Verify captcha:
        captcha_key = request.POST['captcha_token']
        captcha = self.redis_base.hget(captcha_key, 'captcha')
        # Delete the key
        self.redis_base.delete(captcha_key)
        if captcha != request.POST['captcha']:
            raise CredentialsError("Bad captcha")

    def generate_captcha(self, redis_key):
        chars = 'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789'
        captcha_key = get_random_string(6, chars)
        captcha = b64encode(ImageCaptcha().generate(captcha_key).read())
        self.redis_base.hset(redis_key, 'captcha', captcha_key)
        # Expiration of captcha : 1 minute
        self.redis_base.expire(redis_key, 60)
        return captcha
Example #6
0
    def __init__(self, app_id, token_name):
        # DoesNotExists
        self.workflow = Workflow.objects.with_id(ObjectId(app_id))
        self.redis_base = REDISBase()
        self.token_name = token_name
        self.cluster = Cluster.objects.get()

        if not self.workflow.authentication:
            raise RedirectionNeededError(
                "Application '{}' does not need authentication".format(
                    self.workflow.name), self.workflow.get_redirect_uri())
Example #7
0
    def __init__(self, portal_cookie, token_name, workflow):
        self.token_name = token_name
        self.redis_base = REDISBase()
        self.redis_portal_session = REDISPortalSession(self.redis_base,
                                                       portal_cookie)
        self.workflow = workflow

        self.backend_id = self.authenticated_on_backend()
        self.redis_oauth2_session = REDISOauth2Session(
            self.redis_base,
            self.redis_portal_session.get_oauth2_token(self.backend_id))

        if not self.workflow.authentication:
            raise RedirectionNeededError(
                "Workflow '{}' does not need authentication".format(
                    self.workflow.name), self.get_redirect_url())
        self.credentials = ["", ""]
    def __init__(self, token_name, redis_token, app_cookie, portal_cookie):
        self.token_name = token_name
        self.anonymous_token = redis_token
        self.redis_base = REDISBase()
        self.redis_session = REDISAppSession(self.redis_base,
                                             token=redis_token,
                                             cookie=app_cookie)
        self.redis_portal_session = REDISPortalSession(self.redis_base,
                                                       portal_cookie)
        self.application = Application.objects.with_id(
            ObjectId(self.redis_session.keys['application_id']))
        self.backend_id = self.authenticated_on_backend()
        self.redis_oauth2_session = REDISOauth2Session(
            self.redis_base,
            self.redis_portal_session.get_oauth2_token(self.backend_id))

        if not self.application.need_auth:
            raise RedirectionNeededError(
                "Application '{}' does not need authentication".format(
                    self.application.name), self.get_redirect_url())
        self.credentials = ["", ""]
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Vulture 3.  If not, see http://www.gnu.org/licenses/.
"""
__author__ = "Olivier de RĂ©gis"
__credits__ = []
__license__ = "GPLv3"
__version__ = "3.0.0"
__maintainer__ = "Vulture Project"
__email__ = "*****@*****.**"
__doc__ = """This migration script delete reputation list in redis"""

import os
import sys

sys.path.append('/home/vlt-gui/vulture')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'vulture.settings')

import django

django.setup()

from portal.system.redis_sessions import REDISBase

if __name__ == '__main__':
    try:
        r = REDISBase()
        r.delete('ctx_tags')
    except:
        pass
Example #10
0
 def __init__(self, workflow_id):
     assert (workflow_id)
     self.application = Workflow.objects.get(pk=workflow_id)
     self.redis_base = REDISBase()
 def __init__(self, application_id):
     assert (application_id)
     self.application = Application.objects.with_id(
         ObjectId(application_id))
     self.redis_base = REDISBase()
Example #12
0
def handle_disconnect(request, workflow_id=None):
    """ Handle User Disconnection
    If we are here, mod_vulture has already delete the application session in redis
    According to the configuration of App, this handler will:
     - Display a "Logout Message"
     - Destroy the portal session
     - Redirect to the application (ie: display the Login portal)

    :param request: Django request object
    :returns: Self-service portal
    """
    global_config = Cluster.get_global_config()
    """ Try to find the application with the requested URI """
    try:
        workflow = Workflow.objects.get(pk=workflow_id)
    except:
        logger.error(
            "DISCONNECT::handle_disconnect: Unable to find workflow having id '{}'"
            .format(workflow_id))
        return HttpResponseForbidden("Invalid Workflow.")
    """ Get portal_cookie name from cluster """
    portal_cookie_name = global_config.portal_cookie_name
    """ Get portal cookie value (if exists) """
    portal_cookie = request.COOKIES.get(portal_cookie_name, None)
    if portal_cookie:
        logger.debug(
            "DISCONNECT::handle_disconnect: portal_cookie Found: {}".format(
                portal_cookie))
    else:
        logger.error(
            "DISCONNECT::handle_disconnect: portal_cookie not found !")
        return HttpResponseForbidden("Access Denied.")
    """ Connect to Redis """
    r = REDISBase()
    if not r:
        logger.info("PORTAL::self: Unable to connect to REDIS !")
        return HttpResponseServerError()

    portal_session = REDISPortalSession(r, portal_cookie)
    """ The user do not have a portal session: Access is forbidden """
    if not portal_session.exists():
        return HttpResponseForbidden("Invalid session.")

    # FIXME
    """ Destroy portal session if needed """
    if workflow.app_disconnect_portal:
        logger.info(
            "DISCONNECT::handle_disconnect: portal session '{}' has been destroyed"
            .format(portal_cookie))
        portal_session.destroy()

    # FIXME
    """ Display Logout message if needed (otherwise redirect to application) """
    if workflow.app_display_logout_message:
        template = workflow.template
        style = '<link rel="stylesheet" type="text/css" href="/' + str(
            global_config.public_token) + '/templates/portal_%s.css">' % (str(
                template.id))
        logger.debug(
            "DISCONNECT::handle_disconnect: Display template '{}'".format(
                template.name))
        return render_to_response("portal_%s_html_logout.conf" %
                                  (str(template.id)), {
                                      'style': style,
                                      'app_url': workflow.get_redirect_uri()
                                  },
                                  context_instance=RequestContext(request))
    else:
        logger.debug(
            "DISCONNECT::handle_disconnect: Redirecting to redirect_uri '{}'".
            format(workflow.get_redirect_uri()))
        return HttpResponseRedirect(workflow.get_redirect_uri())
Example #13
0
def process_info(request):
    """ API call used to retrieve information about status of running Services, listeners and sessions

    :param request: Django request object
    :return: Json response with services status, running and stopped listeners, token sessions , application sessions and portal sessions
    """
    results = OrderedDict()
    services = (NTP, SSH, MongoDB, RedisSvc, PF, VLTHAProxy, Rsyslogd, IPSEC, ZABBIX)
    for svc in services:
        svc_instance = svc()
        svc_name = svc_instance.service_name
        tmp=svc_instance.status()
        if isinstance(tmp,tuple):
            results["Service "+svc_name] = tmp[0]
        else:
            results["Service "+svc_name] = tmp

    cluster = Cluster.objects.get()
    node = cluster.get_current_node()
    apps, apps_running, l_list, l_list_running = node.get_applications(both=True)
    nb_apps = len(apps)
    nb_running = len(apps_running)
    nb_l=len(l_list)
    nb_l_running=len(l_list_running)
    results['Running applications'] = str(nb_running)+" / "+str(nb_apps)
    results['Running listeners'] = str(nb_l_running)+" / "+str(nb_l)

    app_se = 0
    port_se = 0
    oauth2_se = 0
    pass_se = 0
    tok = 0
    ua = 0

    try:
        r = REDISBase()
        for key in r.r.scan_iter("*"):

            #Vulture key are 'huge', others are modSecurity or mailtrail ones
            if (len(key) < 40 or ":" in key or key.startswith("ctx_") or key.endswith("_rqs") or key.endswith("_limit")) and not key.startswith("col_"):
                continue

            elif key.startswith("col_ua:"):
                    """ User-Agent entries """
                    ua += 1

            elif key.startswith("oauth2_"):
                    """ This is an OAuth2 session """
                    oauth2_se += 1
            elif key.startswith("password_reset_"):
                    """ This is a Password reset temporary token """
                    pass_se += 1
            else:
                m = re.search('[a-z0-9]{64}', key)
                if m:

                    """ Temporary mod_vulture Token """
                    if r.get(key):
                        tok += 1
                    else:
                        """ This is an application session """
                        app_se += 1
                else:
                    """ This is a portal session """
                    port_se += 1
    except Exception as e:
        results['Reputation'] = " Redis Problem: {}".format(str(e))

    try:
        reader = maxminddb.open_database('/var/db/loganalyzer/ip-reputation.mmdb')
        results['Reputation'] = reader.metadata().node_count
        reader.close()
    except Exception as e:
        results['Reputation'] = "Not loaded !"

    results['Application Tokens'] = app_se
    results['Portal Tokens'] = port_se
    results['OAuth2 Tokens'] = oauth2_se
    results['Password Tokens'] = pass_se
    results['Temporary Tokens'] = tok
    results['UA Entries'] = ua

    return JsonResponse(results)