def verify(self, areq, **kwargs): xmlstr = base64.urlsafe_b64decode(areq["client_assertion"]) try: assertion = assertion_from_string(xmlstr) except: return False return self._verify_saml2_assertion(assertion)
def test_xbox_non_ascii_ava(): conf = config.SPConfig() conf.load_file("server_conf") md = MetadataStore([saml, samlp], None, conf) md.load("local", IDP_EXAMPLE) conf.metadata = md conf.only_use_keys_in_metadata = False sec = sigver.security_context(conf) assertion = factory( saml.Assertion, version="2.0", id="id-11111", issue_instant="2009-10-30T13:20:28Z", signature=sigver.pre_signature_part("id-11111", sec.my_cert, 1), attribute_statement=do_attribute_statement( { ("", "", "surName"): ("Föö", ""), ("", "", "givenName"): ("Bär", ""), } ) ) sigass = sec.sign_statement( assertion, class_name(assertion), key_file=PRIV_KEY, node_id=assertion.id, ) _ass0 = saml.assertion_from_string(sigass) encrypted_assertion = EncryptedAssertion() encrypted_assertion.add_extension_element(_ass0) tmp = make_temp( str(pre_encryption_part()).encode('utf-8'), decode=False ) enctext = sec.crypto.encrypt( str(encrypted_assertion), conf.cert_file, tmp.name, "des-192", '/*[local-name()="EncryptedAssertion"]/*[local-name()="Assertion"]', ) decr_text = sec.decrypt(enctext, key_file=PRIV_KEY) _seass = saml.encrypted_assertion_from_string(decr_text) assertions = [] assers = extension_elements_to_elements( _seass.extension_elements, [saml, samlp] ) for ass in assers: _txt = sec.verify_signature( str(ass), PUB_KEY, node_name=class_name(assertion) ) if _txt: assertions.append(ass) assert assertions print(assertions)
def test_SAML_sign_with_pkcs11(self): """ Test signing a SAML assertion using PKCS#11 and then verifying it. """ os.environ['SOFTHSM_CONF'] = self.softhsm_conf ass = self._assertion print(ass) sign_ass = self.sec.sign_assertion("%s" % ass, node_id=ass.id) #print(sign_ass) sass = saml.assertion_from_string(sign_ass) #print(sass) assert _eq(sass.keyswv(), [ 'attribute_statement', 'issue_instant', 'version', 'signature', 'id' ]) assert sass.version == "2.0" assert sass.id == "11111" assert time_util.str_to_time(sass.issue_instant) print("Crypto version : %s" % (self.sec.crypto.version())) item = self.sec.check_signature(sass, class_name(sass), sign_ass) assert isinstance(item, saml.Assertion) print("Test PASSED")
def test_SAML_sign_with_pkcs11(self): """ Test signing a SAML assertion using PKCS#11 and then verifying it. """ os.environ['SOFTHSM_CONF'] = self.softhsm_conf ass = self._assertion print ass sign_ass = self.sec.sign_assertion("%s" % ass, node_id=ass.id) #print sign_ass sass = saml.assertion_from_string(sign_ass) #print sass assert _eq(sass.keyswv(), ['attribute_statement', 'issue_instant', 'version', 'signature', 'id']) assert sass.version == "2.0" assert sass.id == "11111" assert time_util.str_to_time(sass.issue_instant) print "Crypto version : %s" % (self.sec.crypto.version()) item = self.sec.check_signature(sass, class_name(sass), sign_ass) assert isinstance(item, saml.Assertion) print "Test PASSED"
def test_xbox_non_ascii_ava(): conf = config.SPConfig() conf.load_file("server_conf") md = MetadataStore([saml, samlp], None, conf) md.load("local", IDP_EXAMPLE) conf.metadata = md conf.only_use_keys_in_metadata = False sec = sigver.security_context(conf) assertion = factory( saml.Assertion, version="2.0", id="11111", issue_instant="2009-10-30T13:20:28Z", signature=sigver.pre_signature_part("11111", sec.my_cert, 1), attribute_statement=do_attribute_statement( { ("", "", "surName"): ("Föö", ""), ("", "", "givenName"): ("Bär", ""), } ) ) sigass = sec.sign_statement( assertion, class_name(assertion), key_file=PRIV_KEY, node_id=assertion.id, ) _ass0 = saml.assertion_from_string(sigass) encrypted_assertion = EncryptedAssertion() encrypted_assertion.add_extension_element(_ass0) _, pre = make_temp( str(pre_encryption_part()).encode('utf-8'), decode=False ) enctext = sec.crypto.encrypt( str(encrypted_assertion), conf.cert_file, pre, "des-192", '/*[local-name()="EncryptedAssertion"]/*[local-name()="Assertion"]', ) decr_text = sec.decrypt(enctext, key_file=PRIV_KEY) _seass = saml.encrypted_assertion_from_string(decr_text) assertions = [] assers = extension_elements_to_elements( _seass.extension_elements, [saml, samlp] ) for ass in assers: _txt = sec.verify_signature( str(ass), PUB_KEY, node_name=class_name(assertion) ) if _txt: assertions.append(ass) assert assertions print(assertions)
def testAccessors(self): """Test for Assertion accessors""" self.assertion.id = "assertion id" self.assertion.version = saml2.VERSION self.assertion.issue_instant = "2007-08-31T01:05:02Z" self.assertion.issuer = saml.issuer_from_string(saml2_data.TEST_ISSUER) self.assertion.signature = ds.signature_from_string(ds_data.TEST_SIGNATURE) self.assertion.subject = saml.subject_from_string(saml2_data.TEST_SUBJECT) self.assertion.conditions = saml.conditions_from_string(saml2_data.TEST_CONDITIONS) self.assertion.advice = saml.Advice() self.assertion.statement.append(saml.Statement()) self.assertion.authn_statement.append(saml.authn_statement_from_string(saml2_data.TEST_AUTHN_STATEMENT)) self.assertion.authz_decision_statement.append(saml.AuthzDecisionStatement()) self.assertion.attribute_statement.append( saml.attribute_statement_from_string(saml2_data.TEST_ATTRIBUTE_STATEMENT) ) new_assertion = saml.assertion_from_string(self.assertion.to_string()) assert new_assertion.id == "assertion id" assert new_assertion.version == saml2.VERSION assert new_assertion.issue_instant == "2007-08-31T01:05:02Z" assert isinstance(new_assertion.issuer, saml.Issuer) assert isinstance(new_assertion.signature, ds.Signature) assert isinstance(new_assertion.subject, saml.Subject) assert isinstance(new_assertion.conditions, saml.Conditions) assert isinstance(new_assertion.advice, saml.Advice) assert isinstance(new_assertion.statement[0], saml.Statement) assert isinstance(new_assertion.authn_statement[0], saml.AuthnStatement) assert isinstance(new_assertion.authz_decision_statement[0], saml.AuthzDecisionStatement) assert isinstance(new_assertion.attribute_statement[0], saml.AttributeStatement)
def test_sign_verify_assertion_with_cert_from_instance(self): assertion = factory(saml.Assertion, version="2.0", id="11100", issue_instant="2009-10-30T13:20:28Z", signature=sigver.pre_signature_part("11100", self.sec .my_cert), attribute_statement=do_attribute_statement({ ("", "", "surName"): ("Fox", ""), ("", "", "givenName"): ("Bear", ""), }) ) to_sign = [(class_name(assertion), assertion.id)] s_assertion = sigver.signed_instance_factory(assertion, self.sec, to_sign) print(s_assertion) ass = assertion_from_string(s_assertion) ci = "".join(sigver.cert_from_instance(ass)[0].split()) assert ci == self.sec.my_cert res = self.sec.verify_signature(s_assertion, node_name=class_name(ass)) assert res res = self.sec._check_signature(s_assertion, ass, class_name(ass)) assert res
def verify(self, areq, **kwargs): xmlstr = base64.urlsafe_b64decode(areq["client_assertion"]) try: assertion = assertion_from_string(xmlstr) except Exception: # FIXME: This should catch specific exceptions thrown by `assertion_from_string` return False return self._verify_saml2_assertion(assertion)
def test_xbox(): conf = config.SPConfig() conf.load_file("server_conf") md = MetadataStore([saml, samlp], None, conf) md.load("local", full_path("idp_example.xml")) conf.metadata = md conf.only_use_keys_in_metadata = False sec = sigver.security_context(conf) assertion = factory(saml.Assertion, version="2.0", id="11111", issue_instant="2009-10-30T13:20:28Z", signature=sigver.pre_signature_part( "11111", sec.my_cert, 1), attribute_statement=do_attribute_statement({ ("", "", "surName"): ("Foo", ""), ("", "", "givenName"): ("Bar", ""), })) sigass = sec.sign_statement(assertion, class_name(assertion), key_file=full_path("test.key"), node_id=assertion.id) _ass0 = saml.assertion_from_string(sigass) encrypted_assertion = EncryptedAssertion() encrypted_assertion.add_extension_element(_ass0) _, pre = make_temp(str(pre_encryption_part()).encode('utf-8'), decode=False) enctext = sec.crypto.encrypt( str(encrypted_assertion), conf.cert_file, pre, "des-192", '/*[local-name()="EncryptedAssertion"]/*[local-name()="Assertion"]') decr_text = sec.decrypt(enctext) _seass = saml.encrypted_assertion_from_string(decr_text) assertions = [] assers = extension_elements_to_elements(_seass.extension_elements, [saml, samlp]) sign_cert_file = full_path("test.pem") for ass in assers: _ass = "%s" % ass #_ass = _ass.replace('xsi:nil="true" ', '') #assert sigass == _ass _txt = sec.verify_signature(_ass, sign_cert_file, node_name=class_name(assertion)) if _txt: assertions.append(ass) print(assertions)
def test_xbox(): conf = config.SPConfig() conf.load_file("server_conf") md = MetadataStore([saml, samlp], None, conf) md.load("local", full_path("idp_example.xml")) conf.metadata = md conf.only_use_keys_in_metadata = False sec = sigver.security_context(conf) assertion = factory( saml.Assertion, version="2.0", id="11111", issue_instant="2009-10-30T13:20:28Z", signature=sigver.pre_signature_part("11111", sec.my_cert, 1), attribute_statement=do_attribute_statement( {("", "", "surName"): ("Foo", ""), ("", "", "givenName"): ("Bar", "")} ), ) sigass = sec.sign_statement(assertion, class_name(assertion), key_file=full_path("test.key"), node_id=assertion.id) _ass0 = saml.assertion_from_string(sigass) encrypted_assertion = EncryptedAssertion() encrypted_assertion.add_extension_element(_ass0) _, pre = make_temp(str(pre_encryption_part()).encode("utf-8"), decode=False) enctext = sec.crypto.encrypt( str(encrypted_assertion), conf.cert_file, pre, "des-192", '/*[local-name()="EncryptedAssertion"]/*[local-name()="Assertion"]', ) decr_text = sec.decrypt(enctext) _seass = saml.encrypted_assertion_from_string(decr_text) assertions = [] assers = extension_elements_to_elements(_seass.extension_elements, [saml, samlp]) sign_cert_file = full_path("test.pem") for ass in assers: _ass = "%s" % ass # _ass = _ass.replace('xsi:nil="true" ', '') # assert sigass == _ass _txt = sec.verify_signature(_ass, sign_cert_file, node_name=class_name(assertion)) if _txt: assertions.append(ass) print(assertions)
def test_sign_then_encrypt_assertion2(self): # Begin with the IdPs side _sec = self.server.sec nameid_policy = samlp.NameIDPolicy( allow_create="false", format=saml.NAMEID_FORMAT_PERSISTENT) asser = Assertion({"givenName": "Derek", "surName": "Jeter"}) assertion = asser.construct( self.client.config.entityid, "_012345", "http://lingon.catalogix.se:8087/", factory(saml.NameID, format=saml.NAMEID_FORMAT_TRANSIENT), policy=self.server.config.getattr("policy", "idp"), issuer=self.server._issuer(), attrconvs=self.server.config.attribute_converters, authn_class=INTERNETPROTOCOLPASSWORD, authn_auth="http://www.example.com/login") assertion.signature = sigver.pre_signature_part( assertion.id, _sec.my_cert, 1) sigass = _sec.sign_statement( assertion, class_name(assertion), #key_file="pki/mykey.pem", key_file="test.key", node_id=assertion.id) # Create an Assertion instance from the signed assertion _ass = saml.assertion_from_string(sigass) response = sigver.response_factory( in_response_to="_012345", destination="https://www.example.com", status=s_utils.success_status_factory(), issuer=self.server._issuer(), assertion=_ass) enctext = _sec.crypto.encrypt_assertion(response, _sec.cert_file, pre_encryption_part()) #seresp = samlp.response_from_string(enctext) resp_str = base64.encodestring(enctext) # Now over to the client side resp = self.client.parse_authn_request_response( resp_str, BINDING_HTTP_POST, {"_012345": "http://foo.example.com/service"}) #assert resp.encrypted_assertion == [] assert resp.assertion assert resp.ava == {'givenName': ['Derek'], 'sn': ['Jeter']}
def test_sign_then_encrypt_assertion2(self): # Begin with the IdPs side _sec = self.server.sec nameid_policy = samlp.NameIDPolicy(allow_create="false", format=saml.NAMEID_FORMAT_PERSISTENT) asser = Assertion({"givenName": "Derek", "surName": "Jeter"}) assertion = asser.construct( self.client.config.entityid, "_012345", "http://lingon.catalogix.se:8087/", factory(saml.NameID, format=saml.NAMEID_FORMAT_TRANSIENT), policy=self.server.config.getattr("policy", "idp"), issuer=self.server._issuer(), attrconvs=self.server.config.attribute_converters, authn_class=INTERNETPROTOCOLPASSWORD, authn_auth="http://www.example.com/login") assertion.signature = sigver.pre_signature_part( assertion.id, _sec.my_cert, 1) sigass = _sec.sign_statement(assertion, class_name(assertion), #key_file="pki/mykey.pem", key_file="test.key", node_id=assertion.id) # Create an Assertion instance from the signed assertion _ass = saml.assertion_from_string(sigass) response = sigver.response_factory( in_response_to="_012345", destination="https://www.example.com", status=s_utils.success_status_factory(), issuer=self.server._issuer(), assertion=_ass ) enctext = _sec.crypto.encrypt_assertion(response, _sec.cert_file, pre_encryption_part()) #seresp = samlp.response_from_string(enctext) resp_str = base64.encodestring(enctext) # Now over to the client side resp = self.client.parse_authn_request_response( resp_str, BINDING_HTTP_POST, {"_012345": "http://foo.example.com/service"}) #assert resp.encrypted_assertion == [] assert resp.assertion assert resp.ava == {'givenName': ['Derek'], 'sn': ['Jeter']}
def test_multiple_signatures_assertion(self): ass = self._assertion # basic test with two of the same to_sign = [(ass, ass.id, ""), (ass, ass.id, "")] sign_ass = self.sec.multiple_signatures("%s" % ass, to_sign) sass = saml.assertion_from_string(sign_ass) assert _eq(sass.keyswv(), ["attribute_statement", "issue_instant", "version", "signature", "id"]) assert sass.version == "2.0" assert sass.id == "11111" assert time_util.str_to_time(sass.issue_instant) print("Crypto version : %s" % (self.sec.crypto.version())) item = self.sec.check_signature(sass, class_name(sass), sign_ass, must=True) assert isinstance(item, saml.Assertion)
def test_sign_assertion(self): ass = self._assertion print(ass) sign_ass = self.sec.sign_assertion("%s" % ass, node_id=ass.id) # print(sign_ass) sass = saml.assertion_from_string(sign_ass) # print(sass) assert _eq(sass.keyswv(), ["attribute_statement", "issue_instant", "version", "signature", "id"]) assert sass.version == "2.0" assert sass.id == "11111" assert time_util.str_to_time(sass.issue_instant) print("Crypto version : %s" % (self.sec.crypto.version())) item = self.sec.check_signature(sass, class_name(sass), sign_ass) assert isinstance(item, saml.Assertion)
def test_sign_assertion(self): ass = self._assertion print(ass) sign_ass = self.sec.sign_assertion("%s" % ass, node_id=ass.id) #print(sign_ass) sass = saml.assertion_from_string(sign_ass) #print(sass) assert _eq(sass.keyswv(), ['attribute_statement', 'issue_instant', 'version', 'signature', 'id']) assert sass.version == "2.0" assert sass.id == "11111" assert time_util.str_to_time(sass.issue_instant) print("Crypto version : %s" % (self.sec.crypto.version())) item = self.sec.check_signature(sass, class_name(sass), sign_ass) assert isinstance(item, saml.Assertion)
def test_multiple_signatures_assertion(self): ass = self._assertion # basic test with two of the same to_sign = [(ass, ass.id), (ass, ass.id)] sign_ass = self.sec.multiple_signatures(str(ass), to_sign) sass = saml.assertion_from_string(sign_ass) assert _eq(sass.keyswv(), ['issuer', 'attribute_statement', 'issue_instant', 'version', 'signature', 'id']) assert sass.version == "2.0" assert sass.id == "id-11111" assert time_util.str_to_time(sass.issue_instant) print("Crypto version : %s" % (self.sec.crypto.version())) item = self.sec.check_signature(sass, class_name(sass), sign_ass, must=True) assert isinstance(item, saml.Assertion)
def _encrypted_assertion(self, xmlstr): if xmlstr.encrypted_data: assertion_str = self.sec.decrypt(xmlstr.encrypted_data.to_string()) assertion = saml.assertion_from_string(assertion_str) else: decrypt_xml = self.sec.decrypt(xmlstr) logger.debug("Decryption successfull") self.response = samlp.response_from_string(decrypt_xml) logger.debug("Parsed decrypted assertion successfull") enc = self.response.encrypted_assertion[0].extension_elements[0] assertion = extension_element_to_element( enc, saml.ELEMENT_FROM_STRING, namespace=saml.NAMESPACE) logger.debug("Decrypted Assertion: %s" % assertion) return self._assertion(assertion)
def test_sign_assertion(self): ass = self._assertion print ass sign_ass = self.sec.sign_assertion_using_xmlsec("%s" % ass, nodeid=ass.id) #print sign_ass sass = saml.assertion_from_string(sign_ass) #print sass assert _eq(sass.keyswv(), ['attribute_statement', 'issue_instant', 'version', 'signature', 'id']) assert sass.version == "2.0" assert sass.id == "11111" assert time_util.str_to_time(sass.issue_instant) print xmlsec_version(get_xmlsec_binary()) item = self.sec.check_signature(sass, class_name(sass), sign_ass) assert isinstance(item, saml.Assertion)
def _encrypted_assertion(self, xmlstr): if xmlstr.encrypted_data: assertion_str = self.sec.decrypt(xmlstr.encrypted_data) assertion = saml.assertion_from_string(assertion_str) else: decrypt_xml = self.sec.decrypt(xmlstr) logger.debug("Decryption successfull") self.response = samlp.response_from_string(decrypt_xml) logger.debug("Parsed decrypted assertion successfull") enc = self.response.encrypted_assertion[0].extension_elements[0] assertion = extension_element_to_element(enc, saml.ELEMENT_FROM_STRING, namespace=saml.NAMESPACE) logger.debug("Decrypted Assertion: %s" % assertion) return self._assertion(assertion)
def test_multiple_signatures_assertion(self): ass = self._assertion # basic test with two of the same to_sign = [(ass, ass.id, ''), (ass, ass.id, '') ] sign_ass = self.sec.multiple_signatures("%s" % ass, to_sign) sass = saml.assertion_from_string(sign_ass) assert _eq(sass.keyswv(), ['attribute_statement', 'issue_instant', 'version', 'signature', 'id']) assert sass.version == "2.0" assert sass.id == "11111" assert time_util.str_to_time(sass.issue_instant) print xmlsec_version(get_xmlsec_binary()) item = self.sec.check_signature(sass, class_name(sass), sign_ass, must=True) assert isinstance(item, saml.Assertion)
def correctly_signed_response(self, decoded_xml, must=False, origdoc=None): """ Check if a instance is correctly signed, if we have metadata for the IdP that sent the info use that, if not use the key that are in the message if any. :param decoded_xml: The SAML message as a XML string :param must: Whether there must be a signature :param origdoc: :return: None if the signature can not be verified otherwise an instance """ response = samlp.any_response_from_string(decoded_xml) if not response: raise TypeError("Not a Response") if response.signature: self._check_signature(decoded_xml, response, class_name(response), origdoc) if isinstance(response, Response) and (response.assertion or response.encrypted_assertion): # Try to find the signing cert in the assertion for assertion in (response.assertion or response.encrypted_assertion): if response.encrypted_assertion: decoded_xml = self.decrypt(assertion.encrypted_data.to_string()) assertion = saml.assertion_from_string(decoded_xml) if not assertion.signature: logger.debug("unsigned") if must: raise SignatureError("Signature missing") continue else: logger.debug("signed") try: self._check_signature(decoded_xml, assertion, class_name(assertion), origdoc) except Exception, exc: logger.error("correctly_signed_response: %s" % exc) raise
def test_sign_assertion(self): ass = self._assertion print ass sign_ass = self.sec.sign_assertion_using_xmlsec("%s" % ass, nodeid=ass.id) #print sign_ass sass = saml.assertion_from_string(sign_ass) #print sass assert _eq(sass.keyswv(), [ 'attribute_statement', 'issue_instant', 'version', 'signature', 'id' ]) assert sass.version == "2.0" assert sass.id == "11111" assert time_util.str_to_time(sass.issue_instant) print xmlsec_version(get_xmlsec_binary()) item = self.sec.check_signature(sass, class_name(sass), sign_ass) assert isinstance(item, saml.Assertion)
def test_okta(): conf = config.Config() conf.load_file("server_conf") conf.id_attr_name = 'Id' md = MetadataStore([saml, samlp], None, conf) md.load("local", IDP_EXAMPLE) conf.metadata = md conf.only_use_keys_in_metadata = False sec = sigver.security_context(conf) with open(OKTA_RESPONSE) as f: enctext = f.read() decr_text = sec.decrypt(enctext) _seass = saml.encrypted_assertion_from_string(decr_text) assers = extension_elements_to_elements(_seass.extension_elements, [saml, samlp]) with open(OKTA_ASSERTION) as f: okta_assertion = f.read() expected_assert = assertion_from_string(okta_assertion) assert len(assers) == 1 assert assers[0] == expected_assert
def test_sign_then_encrypt_assertion(self): # Begin with the IdPs side _sec = self.server.sec assertion = s_utils.assertion_factory( subject=factory(saml.Subject, text="_aaa", name_id=factory( saml.NameID, format=saml.NAMEID_FORMAT_TRANSIENT)), attribute_statement=do_attribute_statement( { ("", "", "surName"): ("Jeter", ""), ("", "", "givenName"): ("Derek", ""), } ), issuer=self.server._issuer(), ) assertion.signature = sigver.pre_signature_part( assertion.id, _sec.my_cert, 1) sigass = _sec.sign_statement(assertion, class_name(assertion), key_file="pki/mykey.pem", node_id=assertion.id) # Create an Assertion instance from the signed assertion _ass = saml.assertion_from_string(sigass) response = sigver.response_factory( in_response_to="_012345", destination="https:#www.example.com", status=s_utils.success_status_factory(), issuer=self.server._issuer(), assertion=_ass ) enctext = _sec.crypto.encrypt_assertion(response, _sec.cert_file, pre_encryption_part()) seresp = samlp.response_from_string(enctext) # Now over to the client side _csec = self.client.sec if seresp.encrypted_assertion: decr_text = _csec.decrypt(enctext) seresp = samlp.response_from_string(decr_text) resp_ass = [] sign_cert_file = "pki/mycert.pem" for enc_ass in seresp.encrypted_assertion: assers = extension_elements_to_elements( enc_ass.extension_elements, [saml, samlp]) for ass in assers: if ass.signature: if not _csec.verify_signature("%s" % ass, sign_cert_file, node_name=class_name(ass)): continue resp_ass.append(ass) seresp.assertion = resp_ass seresp.encrypted_assertion = None #print _sresp assert seresp.assertion
def _parse_response(self, xmlstr, response_cls, service, binding, outstanding_certs=None, **kwargs): """ Deal with a Response :param xmlstr: The response as a xml string :param response_cls: What type of response it is :param binding: What type of binding this message came through. :param kwargs: Extra key word arguments :return: None if the reply doesn't contain a valid SAML Response, otherwise the response. """ response = None if self.config.accepted_time_diff: kwargs["timeslack"] = self.config.accepted_time_diff if "asynchop" not in kwargs: if binding in [BINDING_SOAP, BINDING_PAOS]: kwargs["asynchop"] = False else: kwargs["asynchop"] = True if xmlstr: if "return_addrs" not in kwargs: if binding in [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST]: try: # expected return address kwargs["return_addrs"] = self.config.endpoint( service, binding=binding) except Exception: logger.info("Not supposed to handle this!") return None try: response = response_cls(self.sec, **kwargs) except Exception as exc: logger.info("%s" % exc) raise xmlstr = self.unravel(xmlstr, binding, response_cls.msgtype) origxml = xmlstr if outstanding_certs is not None: _response = samlp.any_response_from_string(xmlstr) if len(_response.encrypted_assertion) > 0: _, cert_file = make_temp( "%s" % outstanding_certs[_response.in_response_to][ "key"], decode=False) cbxs = CryptoBackendXmlSec1(self.config.xmlsec_binary) xmlstr = cbxs.decrypt(xmlstr, cert_file) if not xmlstr: # Not a valid reponse return None try: response = response.loads(xmlstr, False, origxml=origxml) except SigverError as err: logger.error("Signature Error: %s" % err) raise except UnsolicitedResponse: logger.error("Unsolicited response") raise except Exception as err: if "not well-formed" in "%s" % err: logger.error("Not well-formed XML") raise logger.debug("XMLSTR: %s" % xmlstr) if hasattr(response.response, 'encrypted_assertion'): for encrypted_assertion in response.response\ .encrypted_assertion: if encrypted_assertion.extension_elements is not None: assertion_list = extension_elements_to_elements( encrypted_assertion.extension_elements, [saml]) for assertion in assertion_list: _assertion = saml.assertion_from_string( str(assertion)) response.response.assertion.append(_assertion) if response: response = response.verify() if not response: return None #logger.debug(response) return response
def test_sign_then_encrypt_assertion(self): # Begin with the IdPs side _sec = self.server.sec assertion = s_utils.assertion_factory( subject=factory(saml.Subject, text="_aaa", name_id=factory( saml.NameID, format=saml.NAMEID_FORMAT_TRANSIENT)), attribute_statement=do_attribute_statement({ ("", "", "surName"): ("Jeter", ""), ("", "", "givenName"): ("Derek", ""), }), issuer=self.server._issuer(), ) assertion.signature = sigver.pre_signature_part( assertion.id, _sec.my_cert, 1) sigass = _sec.sign_statement(assertion, class_name(assertion), key_file=full_path("test.key"), node_id=assertion.id) # Create an Assertion instance from the signed assertion _ass = saml.assertion_from_string(sigass) response = sigver.response_factory( in_response_to="_012345", destination="https:#www.example.com", status=s_utils.success_status_factory(), issuer=self.server._issuer(), assertion=_ass) enctext = _sec.crypto.encrypt_assertion(response, _sec.cert_file, pre_encryption_part()) seresp = samlp.response_from_string(enctext) # Now over to the client side _csec = self.client.sec if seresp.encrypted_assertion: decr_text = _csec.decrypt(enctext) seresp = samlp.response_from_string(decr_text) resp_ass = [] sign_cert_file = full_path("test.pem") for enc_ass in seresp.encrypted_assertion: assers = extension_elements_to_elements( enc_ass.extension_elements, [saml, samlp]) for ass in assers: if ass.signature: if not _csec.verify_signature( "%s" % ass, sign_cert_file, node_name=class_name(ass)): continue resp_ass.append(ass) seresp.assertion = resp_ass seresp.encrypted_assertion = None #print _sresp assert seresp.assertion
except UnsolicitedResponse: logger.error("Unsolicited response") raise except Exception, err: if "not well-formed" in "%s" % err: logger.error("Not well-formed XML") raise logger.debug("XMLSTR: %s" % xmlstr) if hasattr(response.response, 'encrypted_assertion'): for encrypted_assertion in response.response.encrypted_assertion: if encrypted_assertion.extension_elements is not None: assertion_list = extension_elements_to_elements(encrypted_assertion.extension_elements, [saml]) for assertion in assertion_list: _assertion = saml.assertion_from_string(str(assertion)) response.response.assertion.append(_assertion) if response: response = response.verify() if not response: return None #logger.debug(response) return response # ------------------------------------------------------------------------ def parse_logout_request_response(self, xmlstr, binding=BINDING_SOAP):
def _parse_response(self, xmlstr, response_cls, service, binding, outstanding_certs=None, **kwargs): """ Deal with a Response :param xmlstr: The response as a xml string :param response_cls: What type of response it is :param binding: What type of binding this message came through. :param kwargs: Extra key word arguments :return: None if the reply doesn't contain a valid SAML Response, otherwise the response. """ response = None if self.config.accepted_time_diff: kwargs["timeslack"] = self.config.accepted_time_diff if "asynchop" not in kwargs: if binding in [BINDING_SOAP, BINDING_PAOS]: kwargs["asynchop"] = False else: kwargs["asynchop"] = True if xmlstr: if "return_addrs" not in kwargs: if binding in [BINDING_HTTP_REDIRECT, BINDING_HTTP_POST]: try: # expected return address kwargs["return_addrs"] = self.config.endpoint( service, binding=binding) except Exception: logger.info("Not supposed to handle this!") return None try: response = response_cls(self.sec, **kwargs) except Exception as exc: logger.info("%s" % exc) raise xmlstr = self.unravel(xmlstr, binding, response_cls.msgtype) origxml = xmlstr if outstanding_certs is not None: _response = samlp.any_response_from_string(xmlstr) if len(_response.encrypted_assertion) > 0: _, cert_file = make_temp( "%s" % outstanding_certs[_response.in_response_to]["key"], decode=False) cbxs = CryptoBackendXmlSec1(self.config.xmlsec_binary) xmlstr = cbxs.decrypt(xmlstr, cert_file) if not xmlstr: # Not a valid reponse return None try: response = response.loads(xmlstr, False, origxml=origxml) except SigverError as err: logger.error("Signature Error: %s" % err) raise except UnsolicitedResponse: logger.error("Unsolicited response") raise except Exception as err: if "not well-formed" in "%s" % err: logger.error("Not well-formed XML") raise logger.debug("XMLSTR: %s" % xmlstr) if hasattr(response.response, 'encrypted_assertion'): for encrypted_assertion in response.response\ .encrypted_assertion: if encrypted_assertion.extension_elements is not None: assertion_list = extension_elements_to_elements( encrypted_assertion.extension_elements, [saml]) for assertion in assertion_list: _assertion = saml.assertion_from_string( str(assertion)) response.response.assertion.append(_assertion) if response: response = response.verify() if not response: return None #logger.debug(response) return response