def test_crypto_backend(): idpc = IdPConfig() idpc.load(IDP_XMLSECURITY) assert idpc.crypto_backend == 'XMLSecurity' sec = security_context(idpc) assert isinstance(sec.crypto, CryptoBackendXMLSecurity)
def __init__(self, attrc, config, ca_certs=None, check_validity=True, disable_ssl_certificate_validation=False, filter=None): """ :params attrc: :params config: Config() :params ca_certs: :params disable_ssl_certificate_validation: """ MetaData.__init__(self, attrc, check_validity=check_validity) if disable_ssl_certificate_validation: self.http = HTTPBase(verify=False, ca_bundle=ca_certs) else: self.http = HTTPBase(verify=True, ca_bundle=ca_certs) self.security = security_context(config) self.ii = 0 self.metadata = {} self.check_validity = check_validity self.filter = filter self.to_old = {}
def test_xmlsec_err_non_ascii_ava(): 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"): ("Föö", ""), ("", "", "givenName"): ("Bär", ""), }) ) try: sec.sign_statement(assertion, class_name(assertion), key_file=full_path("tes.key"), node_id=assertion.id) except (XmlsecError, SigverError) as err: # should throw an exception pass else: assert False
def create_metadata_string(configfile, config=None, valid=None, cert=None, keyfile=None, mid=None, name=None, sign=None): valid_for = 0 nspair = {"xs": "http://www.w3.org/2001/XMLSchema"} # paths = [".", "/opt/local/bin"] if valid: valid_for = int(valid) # Hours eds = [] if config is None: if configfile.endswith(".py"): configfile = configfile[:-3] config = Config().load_file(configfile, metadata_construction=True) eds.append(entity_descriptor(config)) conf = Config() conf.key_file = config.key_file or keyfile conf.cert_file = config.cert_file or cert conf.debug = 1 conf.xmlsec_binary = config.xmlsec_binary secc = security_context(conf) if mid: eid, xmldoc = entities_descriptor(eds, valid_for, name, mid, sign, secc) else: eid = eds[0] if sign: eid, xmldoc = sign_entity_descriptor(eid, mid, secc) else: xmldoc = None valid_instance(eid) return metadata_tostring_fix(eid, nspair, xmldoc)
def setup_class(self): # This would be one way to initialize the security context : # # conf = config.SPConfig() # conf.load_file("server_conf") # conf.only_use_keys_in_metadata = False # # but instead, FakeConfig() is used to really only use the minimal # set of parameters needed for these test cases. Other test cases # (TestSecurityMetadata below) excersise the SPConfig() mechanism. # conf = FakeConfig() self.sec = sigver.security_context(conf) self._assertion = factory( saml.Assertion, version="2.0", id="11111", issue_instant="2009-10-30T13:20:28Z", signature=sigver.pre_signature_part("11111", self.sec.my_cert, 1), attribute_statement=do_attribute_statement({ ("", "", "surName"): ("Föö", ""), ("", "", "givenName"): ("Bär", ""), }) )
def attribute_response(conf, return_addrs, timeslack=0, asynchop=False, test=False, conv_info=None): sec = security_context(conf) if not timeslack: try: timeslack = int(conf.accepted_time_diff) except TypeError: timeslack = 0 return AttributeResponse(sec, conf.attribute_converters, conf.entityid, return_addrs, timeslack, asynchop=asynchop, test=test, conv_info=conv_info)
def test_xbox_non_ascii_ava(): 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"): ("Föö", ""), ("", "", "givenName"): ("Bär", ""), }) ) 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 authn_response(conf, return_addrs, outstanding_queries=None, timeslack=0, asynchop=True, allow_unsolicited=False, want_assertions_signed=False, conv_info=None): sec = security_context(conf) if not timeslack: try: timeslack = int(conf.accepted_time_diff) except TypeError: timeslack = 0 return AuthnResponse(sec, conf.attribute_converters, conf.entityid, return_addrs, outstanding_queries, timeslack, asynchop=asynchop, allow_unsolicited=allow_unsolicited, want_assertions_signed=want_assertions_signed, conv_info=conv_info)
def setup_class(self): conf = config.SPConfig() conf.load_file("server_conf") md = MetadataStore([saml, samlp], None, conf) md.load("local", full_path("metadata_cert.xml")) conf.metadata = md conf.only_use_keys_in_metadata = False self.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", self.sec.my_cert, 1), attribute_statement=do_attribute_statement( {("", "", "surName"): ("Föö", ""), ("", "", "givenName"): ("Bär", ""), }) )
def create_metadata_string(configfile, config=None, valid=None, cert=None, keyfile=None, mid=None, name=None, sign=None): valid_for = 0 nspair = {"xs": "http://www.w3.org/2001/XMLSchema"} # paths = [".", "/opt/local/bin"] if valid: valid_for = int(valid) # Hours eds = [] if config is None: if configfile.endswith(".py"): configfile = configfile[:-3] config = Config().load_file(configfile, metadata_construction=True) eds.append(entity_descriptor(config)) conf = Config() conf.key_file = config.key_file or keyfile conf.cert_file = config.cert_file or cert conf.debug = 1 conf.xmlsec_binary = config.xmlsec_binary secc = security_context(conf) if mid: eid, xmldoc = entities_descriptor(eds, valid_for, name, mid, sign, secc) else: eid = eds[0] if sign: eid, xmldoc = sign_entity_descriptor(eid, mid, secc) else: xmldoc = None valid_instance(eid) return metadata_tostring_fix(eid, nspair, xmldoc)
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", full_path("idp_example.xml")) 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 __init__(self, attrc, config, ca_certs=None, check_validity=True, disable_ssl_certificate_validation=False, filter=None): """ :params attrc: :params config: Config() :params ca_certs: :params disable_ssl_certificate_validation: """ MetaData.__init__(self, attrc, check_validity=check_validity) if disable_ssl_certificate_validation: self.http = HTTPBase(verify=False, ca_bundle=ca_certs) else: self.http = HTTPBase(verify=True, ca_bundle=ca_certs) self.security = security_context(config) self.ii = 0 self.metadata = {} self.check_validity = check_validity self.filter = filter self.to_old = {}
def response_factory(xmlstr, conf, return_addrs=None, outstanding_queries=None, timeslack=0, decode=True, request_id=0, origxml=None, asynchop=True, allow_unsolicited=False, want_assertions_signed=False, conv_info=None): sec_context = security_context(conf) if not timeslack: try: timeslack = int(conf.accepted_time_diff) except TypeError: timeslack = 0 attribute_converters = conf.attribute_converters entity_id = conf.entityid extension_schema = conf.extension_schema response = StatusResponse(sec_context, return_addrs, timeslack, request_id, asynchop, conv_info=conv_info) try: response.loads(xmlstr, decode, origxml) if response.response.assertion or response.response.encrypted_assertion: authnresp = AuthnResponse( sec_context, attribute_converters, entity_id, return_addrs, outstanding_queries, timeslack, asynchop, allow_unsolicited, extension_schema=extension_schema, want_assertions_signed=want_assertions_signed, conv_info=conv_info) authnresp.update(response) return authnresp except TypeError: response.signature_check = sec_context.correctly_signed_logout_response response.loads(xmlstr, decode, origxml) logoutresp = LogoutResponse(sec_context, return_addrs, timeslack, asynchop=asynchop, conv_info=conv_info) logoutresp.update(response) return logoutresp return response
def test_sha256_signing_non_ascii_ava(): 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, sign_alg=SIG_RSA_SHA256), attribute_statement=do_attribute_statement( {("", "", "surName"): ("Föö", ""), ("", "", "givenName"): ("Bär", ""), }) ) s = sec.sign_statement(assertion, class_name(assertion), key_file=full_path("test.key"), node_id=assertion.id) assert s
def setup_class(self): logging.debug("Creating test pkcs11 token using softhsm") try: self.softhsm_db = self._tf() self.softhsm_conf = self._tf() self.signer_cert_pem = self._tf() self.openssl_conf = self._tf() self.signer_cert_der = self._tf() logging.debug("Generating softhsm.conf") with open(self.softhsm_conf, "w") as f: f.write("#Generated by pysaml2 cryptobackend test\n0:%s\n" % self.softhsm_db) logging.debug("Initializing the token") self._p([ 'softhsm', '--slot', '0', '--label', 'test', '--init-token', '--pin', 'secret1', '--so-pin', 'secret2' ]) logging.debug( "Importing test key {!r} into SoftHSM".format(PRIV_KEY)) self._p([ 'softhsm', '--slot', '0', '--label', 'test', '--import', PRIV_KEY, '--id', 'a1b2', '--pin', 'secret1', '--so-pin', 'secret2' ]) logging.debug("Transforming PEM certificate to DER") self._p([ 'openssl', 'x509', '-inform', 'PEM', '-outform', 'DER', '-in', PUB_KEY, '-out', self.signer_cert_der ]) logging.debug("Importing certificate into token") self._p([ 'pkcs11-tool', '--module', P11_MODULE, '-l', '--slot', '0', '--id', 'a1b2', '--label', 'test', '-y', 'cert', '-w', self.signer_cert_der, '--pin', 'secret1' ]) # list contents of SoftHSM self._p([ 'pkcs11-tool', '--module', P11_MODULE, '-l', '--pin', 'secret1', '-O' ]) self._p([ 'pkcs11-tool', '--module', P11_MODULE, '-l', '--pin', 'secret1', '-T' ]) self._p([ 'pkcs11-tool', '--module', P11_MODULE, '-l', '--pin', 'secret1', '-L' ]) self.sec = sigver.security_context(FakeConfig(pub_key=PUB_KEY)) self._assertion = factory( saml.Assertion, version="2.0", id="11111", issue_instant="2009-10-30T13:20:28Z", signature=sigver.pre_signature_part("11111", self.sec.my_cert, 1), attribute_statement=do_attribute_statement({ ("", "", "surName"): ("Foo", ""), ("", "", "givenName"): ("Bar", ""), })) self.configured = True except Exception as ex: print("-" * 64) traceback.print_exc() print("-" * 64) logging.warning( "PKCS11 tests disabled: unable to initialize test token: %s" % ex) raise
def setup_class(self): logging.debug("Creating test pkcs11 token using softhsm") try: self.softhsm_db = self._tf() self.softhsm_conf = self._tf() self.signer_cert_pem = self._tf() self.openssl_conf = self._tf() self.signer_cert_der = self._tf() logging.debug("Generating softhsm.conf") with open(self.softhsm_conf, "w") as f: f.write("#Generated by pysaml2 cryptobackend test\n0:%s\n" % self.softhsm_db) logging.debug("Initializing the token") self._p(['softhsm', '--slot', '0', '--label', 'test', '--init-token', '--pin', 'secret1', '--so-pin', 'secret2']) logging.debug("Importing test key {!r} into SoftHSM".format(PRIV_KEY)) self._p(['softhsm', '--slot', '0', '--label', 'test', '--import', PRIV_KEY, '--id', 'a1b2', '--pin', 'secret1', '--so-pin', 'secret2']) logging.debug("Transforming PEM certificate to DER") self._p(['openssl', 'x509', '-inform', 'PEM', '-outform', 'DER', '-in', PUB_KEY, '-out', self.signer_cert_der]) logging.debug("Importing certificate into token") self._p(['pkcs11-tool', '--module', P11_MODULE, '-l', '--slot', '0', '--id', 'a1b2', '--label', 'test', '-y', 'cert', '-w', self.signer_cert_der, '--pin', 'secret1']) # list contents of SoftHSM self._p(['pkcs11-tool', '--module', P11_MODULE, '-l', '--pin', 'secret1', '-O']) self._p(['pkcs11-tool', '--module', P11_MODULE, '-l', '--pin', 'secret1', '-T']) self._p(['pkcs11-tool', '--module', P11_MODULE, '-l', '--pin', 'secret1', '-L']) self.sec = sigver.security_context(FakeConfig(pub_key = PUB_KEY)) self._assertion = factory(saml.Assertion, version="2.0", id="11111", issue_instant="2009-10-30T13:20:28Z", signature=sigver.pre_signature_part("11111", self.sec.my_cert, 1), attribute_statement=do_attribute_statement( {("", "", "surName"): ("Foo", ""), ("", "", "givenName"): ("Bar", ""), }) ) self.configured = True except Exception as ex: print("-" * 64) traceback.print_exc() print("-" * 64) logging.warning("PKCS11 tests disabled: unable to initialize test token: %s" % ex) raise
bas, fil = os.path.split(filespec) if bas != "": sys.path.insert(0, bas) if fil.endswith(".py"): fil = fil[:-3] cnf = Config().load_file(fil, metadata_construction=True) if valid_for: cnf.valid_for = valid_for eds.append(entity_descriptor(cnf)) conf = Config() conf.key_file = args.keyfile conf.cert_file = args.cert conf.debug = 1 conf.xmlsec_binary = args.xmlsec secc = security_context(conf) if args.id: desc, xmldoc = entities_descriptor(eds, valid_for, args.name, args.id, args.sign, secc) valid_instance(desc) xmldoc = metadata_tostring_fix(desc, nspair, xmldoc) print(xmldoc.decode("utf-8")) else: for eid in eds: if args.sign: assert conf.key_file assert conf.cert_file eid, xmldoc = sign_entity_descriptor(eid, args.id, secc) else: xmldoc = None
bas, fil = os.path.split(filespec) if bas != "": sys.path.insert(0, bas) if fil.endswith(".py"): fil = fil[:-3] cnf = Config().load_file(fil, metadata_construction=True) if valid_for: cnf.valid_for = valid_for eds.append(entity_descriptor(cnf)) conf = Config() conf.key_file = args.keyfile conf.cert_file = args.cert conf.debug = 1 conf.xmlsec_binary = args.xmlsec secc = security_context(conf) if args.id: desc, xmldoc = entities_descriptor(eds, valid_for, args.name, args.id, args.sign, secc) valid_instance(desc) xmldoc = metadata_tostring_fix(desc, nspair, xmldoc) print(xmldoc.decode("utf-8")) else: for eid in eds: if args.sign: assert conf.key_file assert conf.cert_file eid, xmldoc = sign_entity_descriptor(eid, args.id, secc) else: xmldoc = None