Exemple #1
0
def application(environ, start_response):
    """
    WSGI application. Handles all requests.
    :param environ: WSGI enviroment.
    :param start_response: WSGI start response.
    :return: Depends on the request. Always a WSGI response where start_response first have to be initialized.
    """

    response = None

    session = Session(environ)

    http_helper = HttpHandler(environ, start_response, session, logger)



    parameters = http_helper.query_dict()

    test = Test(environ, start_response, session, logger, LOOKUP, config, parameters)
    path = http_helper.path()

    http_helper.log_request()

    if http_helper.verify_static(path):
        return http_helper.handle_static(path)

    if test.verify(path):
        return test.handle(path)

    if response is None:
        response = http_helper.http404()

    http_helper.log_response(response)
    return response
Exemple #2
0
def application(environ, start_response):
    """
    WSGI application. Handles all requests.
    :param environ: WSGI enviroment.
    :param start_response: WSGI start response.
    :return: Depends on the request. Always a WSGI response where start_response first have to be initialized.
    """
    try:
        start_response = start_response_intercept(start_response)
        session = Session(environ)

        http_helper = HttpHandler(environ, start_response, session, logger)
        path = http_helper.path()

        environ = sphandler.verify_sp_user_validity(session, environ, path)
        http_helper.log_request()
        response = None
        if server_conf.OP_FRONTEND and ophandler.verify_provider_requests(
                path):
            response = ophandler.handle_provider_requests(
                environ, start_response, path, session)
        if server_conf.IDP_FRONTEND and idphandler.verify_provider_requests(
                path, environ):
            response = idphandler.handle_provider_requests(
                environ, start_response, path)
        elif sphandler.verify_sp_requests(path):
            response = sphandler.handle_sp_requests(environ, start_response,
                                                    path, session)
        elif http_helper.verify_static(path):
            return http_helper.handle_static(path)

        if response is None:
            response = http_helper.http404()

        http_helper.log_response(response)
        #Catch all unauthorized attempts and present a better web page.
        if start_response.status[0:3] == "401":
            mte = LOOKUP.get_template("unauthorized.mako")
            message = None
            if len(response) == 1:
                message = str(response[0])
            if message is None or len(message.strip()) == 0:
                message = "You are not authorized!"
            argv = {
                "message": message,
            }
            return [mte.render(**argv)]
        return response
    except Exception, excp:
        urn = uuid4().urn
        logger.error("uuid: " + str(urn) + str(exception_trace(excp)))
        argv = {
            "log_id": str(urn),
        }
        mte = LOOKUP.get_template("bad_request.mako")
        resp = BadRequest(mte.render(**argv))
        return resp(environ, start_response)
def handle_path(environ, start_response, response_encoder):
    path = environ.get('PATH_INFO', '').lstrip('/')
    session = environ['beaker.session']
    http_helper = HttpHandler(environ, start_response, session, LOGGER)

    parameters = http_helper.query_dict()
    if path == "favicon.ico":
        return static(environ, start_response, "static/favicon.ico")
    if path.startswith("static/"):
        return static(environ, start_response, path)

    # TODO This is all web frameworks which should be imported via dirg-util
    if path.startswith("_static/"):
        return static(environ, start_response, path)
    if path.startswith("export/"):
        return static(environ, start_response, path)
    if path == "":
        return op_config(environ, start_response, "test_instance_list.mako")
    if path == "config_page":
        return op_config(environ, start_response, "op_config.mako")
    if path == "create_new_config_file":
        return handle_create_new_config_file(response_encoder, session,
                                             parameters)
    if path == "get_op_config":
        return handle_get_op_config(session, response_encoder)
    if path == "does_op_config_exist":
        return handle_does_op_config_exist(session, response_encoder)
    if path == "download_config_file":
        return handle_download_config_file(response_encoder, parameters)
    if path == "upload_config_file":
        return handle_upload_config_file(parameters, session, response_encoder)
    if path == "start_op_tester":
        return handle_start_test_instance(session, response_encoder,
                                          parameters)
    if path == "get_redirect_url":
        return handle_get_redirect_url(session, response_encoder, parameters)
    if path == "request_instance_ids":
        return handle_request_instance_ids(response_encoder, parameters)
    if path == "submit_contact_info":
        return handle_submit_contact_info(response_encoder, parameters)
    if path == "load_existing_config":
        return handle_load_existing_config(response_encoder, session,
                                           parameters)
    if path == "load_existing_contact_info":
        return handle_load_existing_contact_info(response_encoder, parameters)
    if path == "restart_test_instance":
        return handle_restart_test_instance(response_encoder, parameters)
    return http_helper.http404()
Exemple #4
0
 def authenticate(self, environ, start_response, reference, key, redirect_uri, **kwargs):
     session = Session(environ)
     params = HttpHandler.query_dictionary(environ)
     paramstr = None
     for tmpkey, value in params.items():
         tmpparamstr = None
         if type(value) is list:
             for v in value:
                 if tmpparamstr is None:
                     tmpparamstr = ""
                 else:
                     tmpparamstr += "&"
                 tmpparamstr = urllib.urlencode({tmpkey: v})
         else:
             tmpparamstr = urllib.urlencode({tmpkey: value})
         if paramstr is None:
             paramstr = "?"
         else:
             paramstr += "&"
         paramstr += tmpparamstr
     if self.MUTLIPLEAUTHENTICATIONCOUNTER not in session or session[self.MUTLIPLEAUTHENTICATIONCOUNTER] is None:
         session[self.MUTLIPLEAUTHENTICATIONCOUNTER] = 0
     authn_method = session[self.MUTLIPLEAUTHENTICATIONCOUNTER]
     #query = Test how the url should be built up. The user should be redirected to this url as long
     #as all method is not tested.
     query = environ['PATH_INFO'] + paramstr
     session[self.MULTIPLEAUTHENTICATIONREDIRECT] = query
     if self.auth_list_lengt <= 0:
         resp = Unauthorized("No authentication method")
         return resp(environ, start_response)
     else:
         return self.auth_list[authn_method].authenticate(environ, start_response, reference, key, redirect_uri)
Exemple #5
0
def application(environ, start_response):
    """
    WSGI application. Handles all requests.
    :param environ: WSGI enviroment.
    :param start_response: WSGI start response.
    :return: Depends on the request. Always a WSGI response where start_response first have to be initialized.
    """
    try:
        start_response = start_response_intercept(start_response)
        session = Session(environ)

        http_helper = HttpHandler(environ, start_response, session, logger)
        path = http_helper.path()

        environ = sphandler.verify_sp_user_validity(session, environ, path)
        http_helper.log_request()
        response = None
        if server_conf.OP_FRONTEND and ophandler.verify_provider_requests(path):
            response = ophandler.handle_provider_requests(environ, start_response, path, session)
        if server_conf.IDP_FRONTEND and idphandler.verify_provider_requests(path, environ):
            response = idphandler.handle_provider_requests(environ, start_response, path)
        elif sphandler.verify_sp_requests(path):
            response = sphandler.handle_sp_requests(environ, start_response, path, session)
        elif http_helper.verify_static(path):
            return http_helper.handle_static(path)

        if response is None:
            response = http_helper.http404()

        http_helper.log_response(response)
        #Catch all unauthorized attempts and present a better web page.
        if start_response.status[0:3] == "401":
            mte = LOOKUP.get_template("unauthorized.mako")
            message = None
            if len(response) == 1:
                message = str(response[0])
            if message is None or len(message.strip()) == 0:
                message = "You are not authorized!"
            argv = {
                "message": message,
            }
            return [mte.render(**argv)]
        return response
    except Exception, excp:
        urn = uuid4().urn
        logger.error("uuid: " + str(urn) + str(exception_trace(excp)))
        argv = {
            "log_id": str(urn),
        }
        mte = LOOKUP.get_template("bad_request.mako")
        resp = BadRequest(mte.render(**argv))
        return resp(environ, start_response)
Exemple #6
0
def handle_path(environ, start_response, response_encoder):
    path = environ.get('PATH_INFO', '').lstrip('/')
    session = environ['beaker.session']
    http_helper = HttpHandler(environ, start_response, session, LOGGER)

    parameters = http_helper.query_dict()
    if path == "favicon.ico":
        return static(environ, start_response, "static/favicon.ico")
    if path.startswith("static/"):
        return static(environ, start_response, path)

    # TODO This is all web frameworks which should be imported via dirg-util
    if path.startswith("_static/"):
        return static(environ, start_response, path)
    if path.startswith("export/"):
        return static(environ, start_response, path)
    if path == "":
        return op_config(environ, start_response, "test_instance_list.mako")
    if path == "config_page":
        return op_config(environ, start_response, "op_config.mako")
    if path == "create_new_config_file":
        return handle_create_new_config_file(response_encoder, session, parameters)
    if path == "get_op_config":
        return handle_get_op_config(session, response_encoder)
    if path == "does_op_config_exist":
        return handle_does_op_config_exist(session, response_encoder)
    if path == "download_config_file":
        return handle_download_config_file(response_encoder, parameters)
    if path == "upload_config_file":
        return handle_upload_config_file(parameters, session, response_encoder)
    if path == "start_op_tester":
        return handle_start_test_instance(session, response_encoder, parameters)
    if path == "get_redirect_url":
        return handle_get_redirect_url(session, response_encoder, parameters)
    if path == "request_instance_ids":
        return handle_request_instance_ids(response_encoder, parameters)
    if path == "submit_contact_info":
        return handle_submit_contact_info(response_encoder, parameters)
    if path == "load_existing_config":
        return handle_load_existing_config(response_encoder, session, parameters)
    if path == "load_existing_contact_info":
        return handle_load_existing_contact_info(response_encoder, parameters)
    if path == "restart_test_instance":
        return handle_restart_test_instance(response_encoder, parameters)
    return http_helper.http404()
Exemple #7
0
    def verify_bool(self, environ, start_response):
        query = HttpHandler.query_dictionary(environ)
        valid = False
        try:
            valid, uid, parameters = self.auth_helper.verify(query)
        except (AssertionError, KeyError):
            return valid

        return valid
Exemple #8
0
 def verify_bool(self, environ, start_response):
     query = HttpHandler.query_dictionary(environ)
     cookie = environ.get('HTTP_COOKIE')
     valid = False
     try:
         valid, uid, return_to_query = self.auth_helper.verify(query, cookie)
     except (AssertionError, KeyError):
         return valid
     return valid
Exemple #9
0
    def verify_bool(self, environ, start_response):
        query = HttpHandler.query_dictionary(environ)
        valid = False
        try:
            valid, uid, parameters = self.auth_helper.verify(query)
        except (AssertionError, KeyError):
            return valid

        return valid
Exemple #10
0
def application(environ, start_response):
    """
    WSGI application. Handles all requests.
    :param environ: WSGI enviroment.
    :param start_response: WSGI start response.
    :return: Depends on the request. Always a WSGI response where start_response first have to be initialized.
    """
    global username_password
    verification = False
    response = None

    session = SecureSession(environ, username_password)

    http_helper = HttpHandler(environ, start_response, session, logger)

    parameters = http_helper.query_dict()

    information = Information(environ, start_response, session, logger, parameters, LOOKUP, CACHE,
                              config.AUTHENTICATION_LIST , config.SQLITE_DB, config.EMAIL_CONFIG, sphandler,
                              config.ISSUER, config.IMAGE_FOLDER_PATH)

    path = http_helper.path()

    http_helper.log_request()

    if path=="refresh":
        username_password = open("auth/user_pass.json").read()
        username_password = json.loads(username_password)
        return Response("You have performed a refresh.")(environ, start_response)

    if http_helper.verify_static(path) or path.startswith(config.IMAGE_FOLDER_PATH):
        return http_helper.handle_static(path)
    elif information.verify(path):
        return information.handle(path)
    elif sphandler.verify_sp_requests(path):
        response = sphandler.handle_sp_requests(environ, start_response, path, session, parameters, information)
        verification = session.is_verification()

    if response is None:
        response = http_helper.http404()

    http_helper.log_response(response)
    session.verification(verification)
    return response
Exemple #11
0
    def do_verify(self, environ, start_response, _):
        query = HttpHandler.query_dictionary(environ)
        authn_ref = self.authn_broker.pick()[0][0].get_authn_reference(query)
        if authn_ref is not None:
            authn = self.authn_broker[authn_ref]
            if authn:
                return authn["method"].verify(environ, start_response)

        resp = Unauthorized("")
        return resp(environ, start_response)
Exemple #12
0
    def do_verify(self, environ, start_response, _):
        query = HttpHandler.query_dictionary(environ)
        authn_ref = self.authn_broker.pick()[0][0].get_authn_reference(query)
        if authn_ref is not None:
            authn = self.authn_broker[authn_ref]
            if authn:
                return authn["method"].verify(environ, start_response)

        resp = Unauthorized("")
        return resp(environ, start_response)
Exemple #13
0
 def verify_bool(self, environ, start_response):
     query = HttpHandler.query_dictionary(environ)
     cookie = environ.get('HTTP_COOKIE')
     valid = False
     try:
         valid, uid, return_to_query = self.auth_helper.verify(
             query, cookie)
     except (AssertionError, KeyError):
         return valid
     return valid
Exemple #14
0
 def verify(self, environ, start_response):
     _ok = self.verify_bool(environ, start_response)
     if not _ok:
         resp = Unauthorized("Unknown user or wrong password")
     else:
         session = Session(environ)
         user = session[SpHandler.SPHANDLERFORUID]
         query = HttpHandler.query_dictionary(environ)
         query = self.decrypt_dict(query["query"])
         resp = self.setup_idp(user, query["authn_reference"], query["redirect_uri"], query["key"])
     return resp(environ, start_response)
Exemple #15
0
 def verify(self, environ, start_response):
     _ok = self.verify_bool(environ, start_response)
     if not _ok:
         resp = Unauthorized("Unknown user or wrong password")
     else:
         session = Session(environ)
         user = session[SpHandler.SPHANDLERFORUID]
         query = HttpHandler.query_dictionary(environ)
         query = self.decrypt_dict(query["query"])
         resp = self.setup_idp(user, query["authn_reference"],
                               query["redirect_uri"], query["key"])
     return resp(environ, start_response)
Exemple #16
0
    def verify_bool(self, environ, start_response):
        session = Session(environ)
        user = session[SpHandler.SPHANDLERFORUID]

        query = HttpHandler.query_dictionary(environ)
        logger.debug("do_verify: %s" % query)

        sp_handler_cache = self.sphandler.get_sp_handler_cache(user)

        if sp_handler_cache is None or not sp_handler_cache.auth or sp_handler_cache.uid is None:
            return False
        return True
Exemple #17
0
    def verify_bool(self, environ, start_response):
        session = Session(environ)
        user = session[SpHandler.SPHANDLERFORUID]

        query = HttpHandler.query_dictionary(environ)
        logger.debug("do_verify: %s" % query)

        sp_handler_cache = self.sphandler.get_sp_handler_cache(user)

        if sp_handler_cache is None or not sp_handler_cache.auth or sp_handler_cache.uid is None:
            return False
        return True
Exemple #18
0
def application(environ, start_response):
    """
    WSGI application. Handles all requests.
    :param environ: WSGI enviroment.
    :param start_response: WSGI start response.
    :return: Depends on the request. Always a WSGI response where start_response first have to be initialized.
    """
    try:
        session = Session(environ)

        http_helper = HttpHandler(environ, start_response, session, logger)
        path = http_helper.path()

        environ = sphandler.verify_sp_user_validity(session, environ, path)
        http_helper.log_request()
        response = None
        if server_conf.OP_FRONTEND and ophandler.verify_provider_requests(path):
            response = ophandler.handle_provider_requests(environ, start_response, path, session)
        if server_conf.IDP_FRONTEND and idphandler.verify_provider_requests(path, environ):
            response = idphandler.handle_provider_requests(environ, start_response, path)
        elif sphandler.verify_sp_requests(path):
            response = sphandler.handle_sp_requests(environ, start_response, path, session)
        elif http_helper.verify_static(path):
            return http_helper.handle_static(path)

        if response is None:
            response = http_helper.http404()

        http_helper.log_response(response)
        return response
    except Exception, excp:
        urn = uuid4().urn
        logger.error("uuid: " + str(urn) + str(exception_trace(excp)))
        argv = {
            "log_id": str(urn),
        }
        mte = LOOKUP.get_template("bad_request.mako")
        resp = BadRequest(mte.render(**argv))
        return resp(environ, start_response)
Exemple #19
0
 def verify(self, environ, start_response):
     request = HttpHandler.query_dictionary(environ)
     cookie = environ.get('HTTP_COOKIE')
     user = None
     valid = False
     query = {}
     try:
         valid, user, return_to_query = self.auth_helper.verify(request, cookie)
         query = dict((k, v if len(v) > 1 else v[0]) for k, v in parse_qs(return_to_query).iteritems())
     except KeyError:
         pass
     if not valid:
         resp = Unauthorized("Unknown user or wrong password")
     else:
         if len(query) != 3 and "authn_reference" not in query or "redirect_uri" not in query or "key" not in query:
             resp = Unauthorized("Unknown user or wrong password")
         else:
             resp = self.setup_idp(user, query["authn_reference"], query["redirect_uri"], query["key"])
     return resp(environ, start_response)
Exemple #20
0
 def verify(self, environ, start_response):
     request = HttpHandler.query_dictionary(environ)
     user = None
     valid = False
     query = {}
     try:
         valid, user, parameters = self.auth_helper.verify(request)
         query = self.decrypt_dict(parameters[self.QUERY_PARAM])
     except KeyError:
         pass
     if not valid:
         resp = Unauthorized("Unknown user or wrong password")
     else:
         if len(query) != 3 and self.AUTHN_REFERENCE_PARAM not in query or "redirect_uri" not in query or \
            "key" not in query:
             resp = Unauthorized("Unknown user or wrong password")
         else:
             resp = self.setup_idp(user, query[self.AUTHN_REFERENCE_PARAM], query["redirect_uri"], query["key"])
     return resp(environ, start_response)
Exemple #21
0
 def verify(self, environ, start_response):
     request = HttpHandler.query_dictionary(environ)
     user = None
     valid = False
     query = {}
     try:
         valid, user, parameters = self.auth_helper.verify(request)
         query = self.decrypt_dict(parameters[self.QUERY_PARAM])
     except KeyError:
         pass
     if not valid:
         resp = Unauthorized("Unknown user or wrong password")
     else:
         if len(query) != 3 and self.AUTHN_REFERENCE_PARAM not in query or "redirect_uri" not in query or \
            "key" not in query:
             resp = Unauthorized("Unknown user or wrong password")
         else:
             resp = self.setup_idp(user, query[self.AUTHN_REFERENCE_PARAM],
                                   query["redirect_uri"], query["key"])
     return resp(environ, start_response)
Exemple #22
0
 def verify(self, environ, start_response):
     request = HttpHandler.query_dictionary(environ)
     cookie = environ.get('HTTP_COOKIE')
     user = None
     valid = False
     query = {}
     try:
         valid, user, return_to_query = self.auth_helper.verify(
             request, cookie)
         query = dict((k, v if len(v) > 1 else v[0])
                      for k, v in parse_qs(return_to_query).iteritems())
     except KeyError:
         pass
     if not valid:
         resp = Unauthorized("Unknown user or wrong password")
     else:
         if len(
                 query
         ) != 3 and "authn_reference" not in query or "redirect_uri" not in query or "key" not in query:
             resp = Unauthorized("Unknown user or wrong password")
         else:
             resp = self.setup_idp(user, query["authn_reference"],
                                   query["redirect_uri"], query["key"])
     return resp(environ, start_response)
Exemple #23
0
def application(environ, start_response):
    """
    WSGI application. Handles all requests.
    :param environ: WSGI enviroment.
    :param start_response: WSGI start response.
    :return: Depends on the request. Always a WSGI response where start_response first have to be initialized.
    """
    session = Session(environ)

    http_helper = HttpHandler(environ, start_response, session, logger)

    parameters = http_helper.query_dict()

    test = Test(environ, start_response, session, logger, LOOKUP, config,
                parameters, CACHE)
    path = http_helper.path()

    http_helper.log_request()
    response = None
    if http_helper.verify_static(path):
        return http_helper.handle_static(path)

    if test.verify(path):
        return test.handle(path)

    if response is None:
        response = http_helper.http404()

    http_helper.log_response(response)
    return response
Exemple #24
0
    def handle_sp_requests(self, environ, start_response, path, session):
        """
        Handles all url:s that are intended for the sp.
        :param environ: WSGI enviroment.
        :param start_response: WSGI start response.
        :return: The response created by underlying methods. For example;
                 Redirect to a discovery server.
                 Redirect to a SAML Idp.
                 URL to the authorization endpoint.
                 400 bad request.
        """
        if path == "sp_metadata":
            start_response('200 OK', [('Content-Type', "text/xml")])
            return self.sp_metadata

        if self.SPHANDLERSSOCACHE not in session or session[self.SPHANDLERSSOCACHE] is None:
            session[self.SPHANDLERSSOCACHE] = Cache()
        if re.search(self.sp_conf.SPVERIFYBASE, path) or re.search(self.sp_conf.SPVERIFYBASEIDP, path):
            if self.sp_conf.SPVERIFYBASE == path:
                session[self.SPHANDLERVERIFYTYPE] = "OP"
            else:
                session[self.SPHANDLERVERIFYTYPE] = "IDP"
            _sso = SSO(self.sp, environ, start_response, self.logger, session[self.SPHANDLERSSOCACHE], **self.args)
            return _sso.do(self.sp_authentication.sp_certificate(environ),
                           self.sp_authentication.sp_encrypt_certificate(environ))
        for regex in self.sp_conf.ASCVERIFYPOSTLIST:
            match = re.search(regex, path)
            if match is not None:
                acs = ACS(self.sp, self.authnmethod, environ, start_response, self.logger,
                          session[self.SPHANDLERSSOCACHE])
                if session[self.SPHANDLERVERIFYTYPE] == "OP":
                    resp = self.handle_response_to_op_handler(acs.post(), environ["HTTP_COOKIE"], session)
                else:
                    if self.sp_conf.COPY_ASSERTION:
                        try:

                            kwargs = {
                                "outstanding_queries": session[self.SPHANDLERSSOCACHE].outstanding_queries,
                                "allow_unsolicited": self.sp.allow_unsolicited,
                                "want_assertions_signed": False,
                                "want_response_signed": self.sp.want_response_signed,
                                "return_addrs": self.sp.service_urls(),
                                "entity_id": self.sp.config.entityid,
                                "attribute_converters": self.sp.config.attribute_converters,
                                "allow_unknown_attributes": self.sp.config.allow_unknown_attributes,
                            }
                            authn_response = AuthnResponse(self.sp.sec, **kwargs)

                            _dict = HttpHandler.query_dictionary(environ)
                            saml_response = _dict["SAMLResponse"]

                            if isinstance(saml_response, list):
                                saml_response = saml_response[0]
                            xmlstr = self.sp.unravel(saml_response, BINDING_HTTP_POST, AuthnResponse.msgtype)

                            authn_response.loads(xmlstr, False)

                            namespace_dict = {}
                            response_search = xmlstr.split(">")
                            for item_resp in response_search:
                                if item_resp.find(":Response") >= 0:
                                    str_split = item_resp.split(" ")
                                    for item in str_split:
                                        if item.find("xmlns:") >= 0:
                                            try:
                                                tmp_namespace = item.split("=")
                                                namespace_dict[tmp_namespace[0].split(":")[1]] = \
                                                    (tmp_namespace[1], item)
                                            except Exception:
                                                pass
                                    break


                            split_name = "EncryptedAssertion"
                            if xmlstr.find(split_name) < 0:
                                split_name = "Assertion"
                            xmlstr_list = xmlstr.split(split_name)

                            start_index = (xmlstr_list[0][::-1].find("<") + 1) * -1
                            str_assertion = xmlstr_list[0][start_index:] + split_name + xmlstr_list[
                                1] + split_name + ">"

                            str_encrypted_assertion = None
                            if split_name == "EncryptedAssertion":
                                str_encrypted_assertion = str_assertion
                                str_assertion = None

                            """
                            authn_response = authn_response.loads(xmlstr, False)
                            assertion = authn_response.response.assertion[0]
                            if len(authn_response.response.encrypted_assertion) == 1:
                                assertion = authn_response.response.encrypted_assertion[0]

                            str_assertion = str(assertion)
                            """

                            uid = hashlib.sha256(Random.new().read(24)).hexdigest()
                            sp_handler_cache = self.get_sp_handler_cache(uid)
                            if sp_handler_cache is None:
                                sp_handler_cache = SpHandlerCache()
                            sp_handler_cache.uid = uid
                            sp_handler_cache.timeout = authn_response.not_on_or_after
                            sp_handler_cache.attributes = {
                                'eduPersonPrincipalName': [hashlib.sha256(Random.new().read(24)).hexdigest()]
                            }
                            sp_handler_cache.assertion = str_assertion
                            sp_handler_cache.encrypted_assertion = str_encrypted_assertion
                            sp_handler_cache.authnresponse = xmlstr
                            sp_handler_cache.namespace_dict = namespace_dict

                            sp_handler_cache.auth = True
                            self.set_sp_handler_cache(uid, sp_handler_cache)

                            session[SpHandler.SPHANDLERFORUID] = uid
                            resp = self.sp_authentication.authn_redirect(environ)
                            return resp(environ, start_response)
                            #resp = self.sp._parse_response(_dict["SAMLResponse"], AuthnResponse,
                            #   "assertion_consumer_service",BINDING_HTTP_POST, **kwargs)
                        except Exception, exc:
                            logger.info("%s" % exc)
                            raise
                    else:
                        resp = self.handle_response_to_idp_handler(acs.post(), environ["HTTP_COOKIE"], session, environ)
                return resp(environ, start_response)
Exemple #25
0
    def handle_acs(self, acs, session, environ, start_response, post):
        if session[self.SPHANDLERVERIFYTYPE] == "OP":
            if post:
                acs = acs.post()
            else:
                acs = acs.redirect()
            resp = self.handle_response_to_op_handler(acs,
                                                      environ["HTTP_COOKIE"],
                                                      session)
        else:
            if self.sp_conf.COPY_ASSERTION:
                try:

                    kwargs = {
                        "outstanding_queries":
                        session[self.SPHANDLERSSOCACHE].outstanding_queries,
                        "allow_unsolicited":
                        self.sp.allow_unsolicited,
                        "want_assertions_signed":
                        False,
                        "want_response_signed":
                        self.sp.want_response_signed,
                        "return_addrs":
                        self.sp.service_urls(),
                        "entity_id":
                        self.sp.config.entityid,
                        "attribute_converters":
                        self.sp.config.attribute_converters,
                        "allow_unknown_attributes":
                        self.sp.config.allow_unknown_attributes,
                    }
                    authn_response = AuthnResponse(self.sp.sec, **kwargs)

                    _dict = HttpHandler.query_dictionary(environ)
                    saml_response = _dict["SAMLResponse"]

                    if isinstance(saml_response, list):
                        saml_response = saml_response[0]
                    xmlstr = self.sp.unravel(saml_response, BINDING_HTTP_POST,
                                             AuthnResponse.msgtype)

                    authn_response.loads(xmlstr, False)

                    namespace_dict = {}
                    response_search = xmlstr.split(">")
                    for item_resp in response_search:
                        if item_resp.find(":Response") >= 0:
                            str_split = item_resp.split(" ")
                            for item in str_split:
                                if item.find("xmlns:") >= 0:
                                    try:
                                        tmp_namespace = item.split("=")
                                        namespace_dict[tmp_namespace[0].split(":")[1]] = \
                                            (tmp_namespace[1], item)
                                    except Exception:
                                        pass
                            break

                    split_name = "EncryptedAssertion"
                    if xmlstr.find(split_name) < 0:
                        split_name = "Assertion"
                    xmlstr_list = xmlstr.split(split_name)

                    start_index = (xmlstr_list[0][::-1].find("<") + 1) * -1
                    str_assertion = xmlstr_list[0][
                        start_index:] + split_name + xmlstr_list[
                            1] + split_name + ">"

                    str_encrypted_assertion = None
                    if split_name == "EncryptedAssertion":
                        str_encrypted_assertion = str_assertion
                        str_assertion = None
                    """
                    authn_response = authn_response.loads(xmlstr, False)
                    assertion = authn_response.response.assertion[0]
                    if len(authn_response.response.encrypted_assertion) == 1:
                        assertion = authn_response.response.encrypted_assertion[0]

                    str_assertion = str(assertion)
                    """

                    uid = hashlib.sha256(Random.new().read(24)).hexdigest()
                    sp_handler_cache = self.get_sp_handler_cache(uid)
                    if sp_handler_cache is None:
                        sp_handler_cache = SpHandlerCache()
                    sp_handler_cache.uid = uid
                    sp_handler_cache.timeout = authn_response.not_on_or_after
                    sp_handler_cache.attributes = {
                        'eduPersonPrincipalName':
                        [hashlib.sha256(Random.new().read(24)).hexdigest()]
                    }
                    sp_handler_cache.assertion = str_assertion
                    sp_handler_cache.encrypted_assertion = str_encrypted_assertion
                    sp_handler_cache.authnresponse = xmlstr
                    sp_handler_cache.namespace_dict = namespace_dict

                    sp_handler_cache.auth = True
                    self.set_sp_handler_cache(uid, sp_handler_cache)

                    session[SpHandler.SPHANDLERFORUID] = uid
                    resp = self.sp_authentication.authn_redirect(environ)
                    return resp(environ, start_response)
                    #resp = self.sp._parse_response(_dict["SAMLResponse"], AuthnResponse,
                    #   "assertion_consumer_service",BINDING_HTTP_POST, **kwargs)
                except Exception, exc:
                    logger.info("%s" % exc)
                    raise
            else:
Exemple #26
0
    def handle_acs(self, acs, session, environ, start_response, post):
        if session[self.SPHANDLERVERIFYTYPE] == "OP":
            if post:
                acs = acs.post()
            else:
                acs = acs.redirect()
            resp = self.handle_response_to_op_handler(acs, environ["HTTP_COOKIE"], session)
        else:
            if self.sp_conf.COPY_ASSERTION:
                try:

                    kwargs = {
                        "outstanding_queries": session[self.SPHANDLERSSOCACHE].outstanding_queries,
                        "allow_unsolicited": self.sp.allow_unsolicited,
                        "want_assertions_signed": False,
                        "want_response_signed": self.sp.want_response_signed,
                        "return_addrs": self.sp.service_urls(),
                        "entity_id": self.sp.config.entityid,
                        "attribute_converters": self.sp.config.attribute_converters,
                        "allow_unknown_attributes": self.sp.config.allow_unknown_attributes,
                    }
                    authn_response = AuthnResponse(self.sp.sec, **kwargs)

                    _dict = HttpHandler.query_dictionary(environ)
                    saml_response = _dict["SAMLResponse"]

                    if isinstance(saml_response, list):
                        saml_response = saml_response[0]
                    xmlstr = self.sp.unravel(saml_response, BINDING_HTTP_POST, AuthnResponse.msgtype)

                    authn_response.loads(xmlstr, False)

                    namespace_dict = {}
                    response_search = xmlstr.split(">")
                    for item_resp in response_search:
                        if item_resp.find(":Response") >= 0:
                            str_split = item_resp.split(" ")
                            for item in str_split:
                                if item.find("xmlns:") >= 0:
                                    try:
                                        tmp_namespace = item.split("=")
                                        namespace_dict[tmp_namespace[0].split(":")[1]] = \
                                            (tmp_namespace[1], item)
                                    except Exception:
                                        pass
                            break


                    split_name = "EncryptedAssertion"
                    if xmlstr.find(split_name) < 0:
                        split_name = "Assertion"
                    xmlstr_list = xmlstr.split(split_name)

                    start_index = (xmlstr_list[0][::-1].find("<") + 1) * -1
                    str_assertion = xmlstr_list[0][start_index:] + split_name + xmlstr_list[
                        1] + split_name + ">"

                    str_encrypted_assertion = None
                    if split_name == "EncryptedAssertion":
                        str_encrypted_assertion = str_assertion
                        str_assertion = None

                    """
                    authn_response = authn_response.loads(xmlstr, False)
                    assertion = authn_response.response.assertion[0]
                    if len(authn_response.response.encrypted_assertion) == 1:
                        assertion = authn_response.response.encrypted_assertion[0]

                    str_assertion = str(assertion)
                    """

                    uid = hashlib.sha256(Random.new().read(24)).hexdigest()
                    sp_handler_cache = self.get_sp_handler_cache(uid)
                    if sp_handler_cache is None:
                        sp_handler_cache = SpHandlerCache()
                    sp_handler_cache.uid = uid
                    sp_handler_cache.timeout = authn_response.not_on_or_after
                    sp_handler_cache.attributes = {
                        'eduPersonPrincipalName': [hashlib.sha256(Random.new().read(24)).hexdigest()]
                    }
                    sp_handler_cache.assertion = str_assertion
                    sp_handler_cache.encrypted_assertion = str_encrypted_assertion
                    sp_handler_cache.authnresponse = xmlstr
                    sp_handler_cache.namespace_dict = namespace_dict

                    sp_handler_cache.auth = True
                    self.set_sp_handler_cache(uid, sp_handler_cache)

                    session[SpHandler.SPHANDLERFORUID] = uid
                    resp = self.sp_authentication.authn_redirect(environ)
                    return resp(environ, start_response)
                    #resp = self.sp._parse_response(_dict["SAMLResponse"], AuthnResponse,
                    #   "assertion_consumer_service",BINDING_HTTP_POST, **kwargs)
                except Exception, exc:
                    logger.info("%s" % exc)
                    raise
            else: