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)
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
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
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)
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
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)
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
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)
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)
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)
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)
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:
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: