Beispiel #1
0
    def test_sp_type_false(self):
        fil = "sp_mdext_conf.py"
        cnf = Config().load_file(fil, metadata_construction=True)
        cnf.setattr('sp', 'sp_type_in_metadata', False)
        ed = entity_descriptor(cnf)

        assert all(e.tag is not SPType.c_tag for e in ed.extensions.extension_elements)
Beispiel #2
0
    def __init__(self, cargs, kwargs):
        self.nspair = {"xs": "http://www.w3.org/2001/XMLSchema"}

        _cnf = kwargs['conf']
        res = read_multi_conf(_cnf, True)
        eds = []
        for key, cnf in res.items():
            eds.append(entity_descriptor(cnf))

        valid_for = 0

        """
            Setting things to None here that are now unused, but might be useful someday
        """
        conf = Config()
        conf.key_file = None
        conf.cert_file = None
        conf.debug = 1
        conf.xmlsec_binary = None
        args_name = None
        args_id = None
        args_sign = None
        secc = security_context(conf)

        desc, xmldoc = entities_descriptor(eds, valid_for, args_name, args_id,
                                           args_sign, secc)
        valid_instance(desc)

        self.desc = desc
        self.xmldoc = xmldoc
    def test_sp_attr_policy2(self):
        # create a pysaml SP
        self.sp_conf = SPConfig()
        _sp_conf = copy.deepcopy(SAML_SP_CONFIG)
        _sp_conf['service']['sp']['required_attributes'] = [
            'email', 'givenName', 'eduPersonPrincipalName', 'sn', 'telexNumber'
        ]
        self.sp_conf.load(_sp_conf)
        # put sp metadata into IDP md store
        sp_metadata = entity_descriptor(self.sp_conf)
        with open(IDP_SP_METADATA_PATH + '/sp.xml', 'wb') as fd:
            fd.write(sp_metadata.to_string())

        sp_client = Saml2Client(self.sp_conf)
        session_id, result = sp_client.prepare_for_authenticate(
            entityid=idp_eid, relay_state='/', binding=BINDING_HTTP_POST)
        url, data = extract_saml_authn_data(result)
        response = self.client.post(url, data, follow=True)
        # login again to update existing user on db
        login_response = self.client.post(login_url,
                                          data=self.login_data,
                                          follow=True)
        # is there a SAML response?
        saml_resp = re.findall(samlresponse_form_regexp,
                               login_response.content.decode())
Beispiel #4
0
def metadata(request, config_loader_path=None, valid_for=None):
    """Returns an XML with the SAML 2.0 metadata for this
    SP as configured in the settings.py file.
    """
    conf = get_config(config_loader_path, request)
    metadata = entity_descriptor(conf)
    return HttpResponse(content=str(metadata), content_type="text/xml; charset=utf8")
Beispiel #5
0
    def test_entity_attributes(self):
        fil = "sp_mdext_conf.py"
        cnf = Config().load_file(fil, metadata_construction=True)
        ed = entity_descriptor(cnf)

        entity_attributes = next(
            e
            for e in ed.extensions.extension_elements
            if e.tag == 'EntityAttributes'
        )
        attributes = [
            parse_str_as(Attribute, e.to_string())
            for e in entity_attributes.children
        ]
        assert all(
            a.name in [
                "urn:oasis:names:tc:SAML:profiles:subject-id:req",
                "somename",
            ]
            for a in attributes
        )

        import saml2.attribute_converter
        attrc = saml2.attribute_converter.ac_factory()

        import saml2.mdstore
        mds = saml2.mdstore.MetadataStore(attrc, cnf)

        mds.load("inline", ed.to_string())
        entityid = ed.entity_id
        entity_attributes = mds.entity_attributes(entityid)
        assert entity_attributes == {
            'urn:oasis:names:tc:SAML:profiles:subject-id:req': ['any'],
            'somename': ['x', 'y', 'z'],
        }
 def get_metadata(self):
     """Returns SAML Identity Provider Metadata"""
     edesc = entity_descriptor(self._config, 24)
     if self._config.key_file:
         edesc = sign_entity_descriptor(edesc, 24, None, security_context(self._config))
     response = make_response(str(edesc))
     response.headers['Content-type'] = 'text/xml; charset=utf-8'
     return response
Beispiel #7
0
def metadata(request):
    """Returns an XML with the SAML 2.0 metadata for this
    SP as configured in the settings.py file.
    """
    conf = get_saml2_config(
        request.registry.settings.get('saml2.settings_module'))
    metadata = entity_descriptor(conf)
    return Response(body=str(metadata), content_type="text/xml; charset=utf8")
Beispiel #8
0
def metadata(request):
    """ Returns an XML with the SAML 2.0 metadata for this Idp.
        The metadata is constructed on-the-fly based on the config dict in the django settings.
    """
    conf = IdPConfig()
    conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
    metadata = entity_descriptor(conf)
    return HttpResponse(content=text_type(metadata).encode('utf-8'), content_type="text/xml; charset=utf8")
Beispiel #9
0
def metadata(request, config_loader_path=None, valid_for=None):
    """Returns an XML with the SAML 2.0 metadata for this
    SP as configured in the settings.py file.
    """
    conf = get_config(config_loader_path, request)
    metadata = entity_descriptor(conf)
    return HttpResponse(content=str(metadata),
                        content_type="text/xml; charset=utf8")
def build_metadata() -> Response:
    """Build saml metadata."""
    conf = Saml2Config()
    conf.load(app.config["SAML_CONFIG"])
    metadata = entity_descriptor(conf)
    response = make_response(str(metadata).encode("utf-8"))
    response.headers["content-type"] = "text/xml; charset=utf-8"
    return response
Beispiel #11
0
def metadata():
    """
    Returns an XML with the SAML 2.0 metadata for this
    SP as configured in the saml2_settings.py file.
    """
    metadata = entity_descriptor(current_app.saml2_config)
    response = make_response(metadata.to_string(), 200)
    response.headers['Content-Type'] = "text/xml; charset=utf8"
    return response
 def metadata(cls) -> str:
     conf = IdPConfig()
     try:
         conf.load(cls.construct_metadata())
         metadata = entity_descriptor(conf)
     except:
         pass
     return str(metadata)
             
Beispiel #13
0
 def metadata(cls) -> str:
     """ Get the IDP metadata as a string. """
     conf = IdPConfig()
     try:
         conf.load(cls.construct_metadata())
         metadata = entity_descriptor(conf)
     except Exception as e:
         raise ImproperlyConfigured(_('Could not instantiate IDP metadata based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
     return str(metadata)
Beispiel #14
0
def metadata():
    """
    Returns an XML with the SAML 2.0 metadata for this
    SP as configured in the saml2_settings.py file.
    """
    metadata = entity_descriptor(current_app.saml2_config)
    response = make_response(metadata.to_string(), 200)
    response.headers['Content-Type'] = "text/xml; charset=utf8"
    return response
Beispiel #15
0
def test_requested_attribute_name_format():
    cnf = SPConfig().load(sp_conf, metadata_construction=True)
    ed = entity_descriptor(cnf)

    assert len(ed.spsso_descriptor.attribute_consuming_service) == 1
    acs = ed.spsso_descriptor.attribute_consuming_service[0]
    assert len(acs.requested_attribute) == 4
    for req_attr in acs.requested_attribute:
        assert req_attr.name_format == NAME_FORMAT_URI

    sp2 = copy.copy(sp_conf)
    sp2["service"]["sp"]["requested_attribute_name_format"] = NAME_FORMAT_BASIC

    cnf2 = SPConfig().load(sp2, metadata_construction=True)
    ed = entity_descriptor(cnf2)
    acs = ed.spsso_descriptor.attribute_consuming_service[0]
    assert len(acs.requested_attribute) == 4
    for req_attr in acs.requested_attribute:
        assert req_attr.name_format == NAME_FORMAT_BASIC
Beispiel #16
0
def test_requested_attribute_name_format():
    cnf = SPConfig().load(sp_conf, metadata_construction=True)
    ed = entity_descriptor(cnf)

    assert len(ed.spsso_descriptor.attribute_consuming_service) == 1
    acs = ed.spsso_descriptor.attribute_consuming_service[0]
    assert len(acs.requested_attribute) == 4
    for req_attr in acs.requested_attribute:
        assert req_attr.name_format == NAME_FORMAT_URI

    sp2 = copy.copy(sp_conf)
    sp2["service"]["sp"]["requested_attribute_name_format"] = NAME_FORMAT_BASIC

    cnf2 = SPConfig().load(sp2, metadata_construction=True)
    ed = entity_descriptor(cnf2)
    acs = ed.spsso_descriptor.attribute_consuming_service[0]
    assert len(acs.requested_attribute) == 4
    for req_attr in acs.requested_attribute:
        assert req_attr.name_format == NAME_FORMAT_BASIC
Beispiel #17
0
 def get(self, request, *args, **kwargs):
     conf = self.get_sp_config(request)
     if not conf:
         return HttpResponse(
             content='<msg>unknown service id</msg>'.encode('utf-8'),
             content_type="text/xml; charset=utf-8",
             status=404)
     metadata = entity_descriptor(conf)
     return HttpResponse(content=str(metadata).encode('utf-8'),
                         content_type="text/xml; charset=utf-8")
Beispiel #18
0
    def test_sp_type_true(self):
        fil = "sp_mdext_conf.py"
        cnf = Config().load_file(fil, metadata_construction=True)
        ed = entity_descriptor(cnf)

        assert ed.spsso_descriptor.extensions
        assert len(ed.spsso_descriptor.extensions.extension_elements) == 3
        assert ed.extensions
        assert len(ed.extensions.extension_elements) > 1
        assert any(e.tag is SPType.c_tag for e in ed.extensions.extension_elements)
Beispiel #19
0
    def _metadata_endpoint(self, context):
        """
        Endpoint for retrieving the backend metadata
        :type context: satosa.context.Context
        :rtype: satosa.response.Response

        :param context: The current context
        :return: response with metadata
        """
        logger.debug("Sending metadata response")
        conf = self.sp.config

        metadata = entity_descriptor(conf)
        # creare gli attribute_consuming_service
        cnt = 0
        for (attribute_consuming_service
             ) in metadata.spsso_descriptor.attribute_consuming_service:
            attribute_consuming_service.index = str(cnt)
            cnt += 1

        cnt = 0
        for (assertion_consumer_service
             ) in metadata.spsso_descriptor.assertion_consumer_service:
            assertion_consumer_service.is_default = "true" if not cnt else ""
            assertion_consumer_service.index = str(cnt)
            cnt += 1

        # nameformat patch... tutto questo non rispecchia gli standard OASIS
        for reqattr in metadata.spsso_descriptor.attribute_consuming_service[
                0].requested_attribute:
            reqattr.name_format = None
            reqattr.friendly_name = None

        # attribute consuming service service name patch
        service_name = metadata.spsso_descriptor.attribute_consuming_service[
            0].service_name[0]
        service_name.lang = "it"
        service_name.text = metadata.entity_id

        # remove extension disco and uuinfo (spid-testenv2)
        # metadata.spsso_descriptor.extensions = []

        # load ContactPerson Extensions
        self._metadata_contact_person(metadata, conf)

        # metadata signature
        secc = security_context(conf)
        #
        sign_dig_algs = self.get_kwargs_sign_dig_algs()
        eid, xmldoc = sign_entity_descriptor(metadata, None, secc,
                                             **sign_dig_algs)

        valid_instance(eid)
        return Response(text_type(xmldoc).encode("utf-8"),
                        content="text/xml; charset=utf8")
Beispiel #20
0
def test_entity_description():
    #confd = eval(open("../tests/server.config").read())
    confd = SPConfig().load_file("server_conf")
    print confd.attribute_converters
    entd = metadata.entity_descriptor(confd)
    assert entd is not None
    print entd.keyswv()
    assert _eq(entd.keyswv(), ['valid_until', 'entity_id', 'contact_person',
                                'spsso_descriptor', 'organization'])
    print entd
    assert entd.entity_id == "urn:mace:example.com:saml:roland:sp"
Beispiel #21
0
def test_entity_description():
    #confd = eval(open("../tests/server.config").read())
    confd = SPConfig().load_file("server_conf")
    print confd.attribute_converters
    entd = metadata.entity_descriptor(confd, 1)
    assert entd is not None
    print entd.keyswv()
    assert _eq(entd.keyswv(), [
        'valid_until', 'entity_id', 'contact_person', 'spsso_descriptor',
        'organization'
    ])
    print entd
    assert entd.entity_id == "urn:mace:example.com:saml:roland:sp"
Beispiel #22
0
def run():
    '''配置IdP,生成证书、元数据文件'''
    if not os.path.exists(BASEDIR+'/djangosaml2idp/certificates/mycert.pem') or not \
        os.path.exists(BASEDIR+'/djangosaml2idp/certificates/mykey.pem'):
        create_self_signed_cert()

    conf = IdPConfig()  # pylint: disable=invalid-name
    conf.load(copy.deepcopy(idpsettings.SAML_IDP_CONFIG))
    meta_data = entity_descriptor(conf)  # pylint: disable=invalid-name
    content = text_type(meta_data).encode('utf-8')
    with open(BASEDIR + '/djangosaml2idp/saml2_config/idp_metadata.xml',
              'wb') as f:
        f.write(content)
Beispiel #23
0
    def _add_sp_md(self):
        self._superuser_login()
        # put md store through admin UI
        create_url = reverse('admin:uniauth_saml2_idp_metadatastore_add')
        data = dict(name='sptest',
                    type='local',
                    url=idp_md_path,
                    kwargs='{}',
                    is_active=1)
        response = self.client.post(create_url, data, follow=True)
        assert 'was added successfully' in response.content.decode()

        # put sp metadata into IDP md store
        sp_metadata = entity_descriptor(self.sp_conf)
        with open(IDP_SP_METADATA_PATH + '/sp.xml', 'wb') as fd:
            fd.write(sp_metadata.to_string())
Beispiel #24
0
def metadata(request, config_loader_path=None, valid_for=None):
    """Returns an XML with the SAML 2.0 metadata for this
    SP as configured in the settings.py file.
    """
    conf = get_config(config_loader_path, request)
    valid_for = valid_for or get_custom_setting("SAML_VALID_FOR", 24)
    metadata = entity_descriptor(conf, valid_for)

    saml_token = request.GET.get("saml_token")
    if saml_token:
        # inject the saml token to the sp urls
        for descriptor in metadata.spsso_descriptor.assertion_consumer_service:
            descriptor.location += "?saml_token=%s" % saml_token
        for descriptor in metadata.spsso_descriptor.single_logout_service:
            descriptor.location += "?saml_token=%s" % saml_token

    return HttpResponse(content=str(metadata), content_type="text/xml; charset=utf8")
Beispiel #25
0
def italian_sp_metadata(conf, md_type: str = "spid"):
    metadata = entity_descriptor(conf)

    # this will renumber acs starting from 0 and set index=0 as is_default
    cnt = 0
    for (attribute_consuming_service
         ) in metadata.spsso_descriptor.attribute_consuming_service:
        attribute_consuming_service.index = str(cnt)
        cnt += 1

    cnt = 0
    for (assertion_consumer_service
         ) in metadata.spsso_descriptor.assertion_consumer_service:
        assertion_consumer_service.is_default = "true" if not cnt else ""
        assertion_consumer_service.index = str(cnt)
        cnt += 1

    # nameformat patch
    for reqattr in metadata.spsso_descriptor.attribute_consuming_service[
            0].requested_attribute:
        reqattr.name_format = (
            None  # "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
        )
        reqattr.friendly_name = None

    metadata.extensions = None

    # attribute consuming service service name patch
    service_name = metadata.spsso_descriptor.attribute_consuming_service[
        0].service_name[0]
    service_name.lang = "it"
    service_name.text = conf._sp_name

    if md_type == 'spid':
        spid_contacts_29_v3(metadata)
    elif md_type == 'cie':
        cie_contacts(metadata)

    # metadata signature
    secc = security_context(conf)
    sign_dig_algs = dict(sign_alg=conf._sp_signing_algorithm,
                         digest_alg=conf._sp_digest_algorithm)
    eid, xmldoc = sign_entity_descriptor(metadata, None, secc, **sign_dig_algs)
    return xmldoc
Beispiel #26
0
def metadata_spid(request, config_loader_path=None, valid_for=None):
    """Returns an XML with the SAML 2.0 metadata for this
    SP as configured in the settings.py file.
    """
    conf = get_config(config_loader_path, request)
    metadata = entity_descriptor(conf)

    # this will renumber acs starting from 0 and set index=0 as is_default
    cnt = 0
    for attribute_consuming_service in metadata.spsso_descriptor.attribute_consuming_service:
        attribute_consuming_service.index = str(cnt)
        cnt += 1

    cnt = 0
    for assertion_consumer_service in metadata.spsso_descriptor.assertion_consumer_service:
        assertion_consumer_service.is_default = 'true' if not cnt else ''
        assertion_consumer_service.index = str(cnt)
        cnt += 1

    # nameformat patch... tutto questo non rispecchia gli standard OASIS
    for reqattr in metadata.spsso_descriptor.attribute_consuming_service[0].requested_attribute:
        reqattr.name_format = None #"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
        # reqattr.is_required = None
        reqattr.friendly_name = None

    # remove unecessary encryption and digest algs
    supported_algs = ['http://www.w3.org/2009/xmldsig11#dsa-sha256',
                      'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256']
    new_list = []
    for alg in metadata.extensions.extension_elements:
        # if alg.namespace != 'urn:oasis:names:tc:SAML:metadata:algsupport': continue
        if alg.attributes.get('Algorithm') in supported_algs:
            new_list.append(alg)
    metadata.extensions.extension_elements = new_list
    # ... Piuttosto non devo specificare gli algoritmi di firma/criptazione...
    metadata.extensions = None

    # attribute consuming service service name patch
    service_name = metadata.spsso_descriptor.attribute_consuming_service[0].service_name[0]
    service_name.lang = 'it'
    service_name.text = conf._sp_name

    return HttpResponse(content=text_type(metadata).encode('utf-8'),
                        content_type="text/xml; charset=utf8")
def _make_metadata(config_dict, option):
    """
    Creates metadata from the given idp config

    :type config_dict: dict[str, Any]
    :type option: vopaas.metadata_creation.make_vopaas_metadata.MetadataOption
    :rtype: str

    :param config_dict: config
    :param option: metadata creation settings
    :return: A xml string
    """
    eds = []
    cnf = Config()
    cnf.load(copy.deepcopy(config_dict), metadata_construction=True)

    if option.valid:
        cnf.valid_for = option.valid
    eds.append(entity_descriptor(cnf))

    conf = Config()
    conf.key_file = option.keyfile
    conf.cert_file = option.cert
    conf.debug = 1
    conf.xmlsec_binary = option.xmlsec
    secc = security_context(conf)

    if option.id:
        desc, xmldoc = entities_descriptor(eds, option.valid, option.name, option.id,
                                           option.sign, secc)
        valid_instance(desc)
        print(desc.to_string(NSPAIR))
    else:
        for eid in eds:
            if option.sign:
                assert conf.key_file
                assert conf.cert_file
                eid, xmldoc = sign_entity_descriptor(eid, option.id, secc)
            else:
                xmldoc = None

            valid_instance(eid)
            xmldoc = metadata_tostring_fix(eid, NSPAIR, xmldoc).decode()
            return xmldoc
def create_metadata_string(configfile,
                           config=None,
                           valid=None,
                           cert=None,
                           keyfile=None,
                           mid=None,
                           name=None,
                           sign=None):
    """
    TODO: REMOVE THIS FUNCTION AFTER pysaml2 library is updated. to fix the above metadata_tostring_fix function
    """
    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 _make_metadata(config_dict, option):
    """
    Creates metadata from the given idp config

    :type config_dict: dict[str, Any]
    :type option: vopaas.metadata_creation.make_vopaas_metadata.MetadataOption
    :rtype: str

    :param config_dict: config
    :param option: metadata creation settings
    :return: A xml string
    """
    eds = []
    cnf = Config()
    cnf.load(copy.deepcopy(config_dict), metadata_construction=True)

    if option.valid:
        cnf.valid_for = option.valid
    eds.append(entity_descriptor(cnf))

    conf = Config()
    conf.key_file = option.keyfile
    conf.cert_file = option.cert
    conf.debug = 1
    conf.xmlsec_binary = option.xmlsec
    secc = security_context(conf)

    if option.id:
        desc, xmldoc = entities_descriptor(eds, option.valid, option.name, option.id, option.sign, secc)
        valid_instance(desc)
        print(desc.to_string(NSPAIR))
    else:
        for eid in eds:
            if option.sign:
                assert conf.key_file
                assert conf.cert_file
                eid, xmldoc = sign_entity_descriptor(eid, option.id, secc)
            else:
                xmldoc = None

            valid_instance(eid)
            xmldoc = metadata_tostring_fix(eid, NSPAIR, xmldoc).decode()
            return xmldoc
Beispiel #30
0
def write_metadata(sp_configs):
    """
    Generate SAML XML metadata from the pysaml2 JSON format.
    :param base: base url of the svs node
    :return: dictionary with the config for the two SP's
    """

    for _, config in sp_configs.iteritems():
        cnf = Config().load(config, metadata_construction=True)
        eid = entity_descriptor(cnf)
        valid_instance(eid)
        nspair = {"xs": "http://www.w3.org/2001/XMLSchema"}
        xmldoc = metadata_tostring_fix(eid, nspair, None)

        entity_id = config["entityid"]
        path = urlparse.urlparse(entity_id).path
        filename = os.path.basename(path)
        with open(filename, "w") as output_file:
            output_file.write(xmldoc)
Beispiel #31
0
def metadata(request, config_loader_path=None, valid_for=None):
    """Returns an XML with the SAML 2.0 metadata for this
    SP as configured in the settings.py file.
    """
    conf = get_config(config_loader_path, request)
    metadata = entity_descriptor(conf)
    if conf.extensions:
        if metadata.extensions is None:
            metadata.extensions = md.Extensions()

        for key, val in conf.extensions.items():
            _ext = do_extensions(key, val)
            if _ext:
                for _e in _ext:
                    metadata.extensions.add_extension_element(_e)

    return HttpResponse(
        content=text_type(metadata).encode('utf-8'),
        content_type="text/xml; charset=utf8",
    )
Beispiel #32
0
 def gen_xml(self, filename, entity_id, acs, sls):  # pylint: disable=no-self-use
     '''将SAMLAPP配置写入指定路径xml文件
     '''
     conf = SPConfig()
     endpointconfig = {
         "entityid": entity_id,
         'entity_category': [COC],
         "description": "extra SP setup",
         "service": {
             "sp": {
                 "want_response_signed": False,
                 "authn_requests_signed": True,
                 "logout_requests_signed": True,
                 "endpoints": {
                     "assertion_consumer_service":
                     [(acs, BINDING_HTTP_POST)],
                     "single_logout_service": [
                         (sls, BINDING_HTTP_REDIRECT),
                         (sls.replace('redirect',
                                      'post'), BINDING_HTTP_POST),
                     ],
                 }
             },
         },
         "key_file": BASEDIR +
         "/djangosaml2idp/certificates/mykey.pem",  # 随便放一个私钥,并不知道SP私钥
         "cert_file":
         BASEDIR + '/djangosaml2idp/saml2_config/sp_cert/%s.pem' % filename,
         "xmlsec_binary": xmlsec_path,
         "metadata": {
             "local":
             [BASEDIR + '/djangosaml2idp/saml2_config/idp_metadata.xml']
         },
         "name_form": NAME_FORMAT_URI,
     }
     conf.load(copy.deepcopy(endpointconfig))
     meta_data = entity_descriptor(conf)
     content = text_type(meta_data).encode('utf-8')
     with open(BASEDIR + '/djangosaml2idp/saml2_config/%s.xml' % filename,
               'wb+') as f:
         f.write(content)
Beispiel #33
0
def _parse_metadata_dict_to_inline(metadata):
    """Convert any metadata included as dict to PySAML2's `inline` type.

    Currently PySAML supports remote, local files, and string IdP metadata to
    be included in the SP config dict as XML. It is also possible to pull your
    IdP metadata from local JSON files (the format of the JSON is nearly
    unparsable for any normal human).

    This function adds the ability to include the IdP metadata directly in the
    SP config as a dict of IdP attributes by hacking around this PySAML2
    limitation and converting the dict into XML via PySAML2's IdPConfig class.

    Note: In the process of trying to find an alternative which will allow us
        to NOT be hacking around PySAML so rudely in order to load IdP metadata
        from a Python dict. https://github.com/rohe/pysaml2/issues/172

    Args:
        metadata (dict): The IdP metadata this SP is configured for.

    Returns:
        (dict) config where any metadata `inline_dict` data has been
            converted to `inline` XML.
    """
    if metadata.get('inline_dict', None):
        metadata['inline'] = metadata.get('inline', [])
        for _idp in metadata.get('inline_dict'):
            idp_config = IdPConfig()
            idp_config.load(_idp)
            entity_desc = entity_descriptor(idp_config)
            # Hack for supporting multiple certificates.
            if _idp.get('certs'):
                # `certs` config directive overrides `cert_file`.
                entity_desc.idpsso_descriptor.key_descriptor = \
                    _parse_key_descriptors(_idp['certs'])
            idp_metadata_str = str(entity_desc)
            LOGGER.debug("IdP XML Metadata for %s: %s", _idp['entityid'],
                         idp_metadata_str)
            metadata['inline'].append(idp_metadata_str)
        del metadata['inline_dict']
    return metadata
Beispiel #34
0
def _parse_metadata_dict_to_inline(metadata):
    """Convert any metadata included as dict to PySAML2's `inline` type.

    Currently PySAML supports remote, local files, and string IdP metadata to
    be included in the SP config dict as XML. It is also possible to pull your
    IdP metadata from local JSON files (the format of the JSON is nearly
    unparsable for any normal human).

    This function adds the ability to include the IdP metadata directly in the
    SP config as a dict of IdP attributes by hacking around this PySAML2
    limitation and converting the dict into XML via PySAML2's IdPConfig class.

    Note: In the process of trying to find an alternative which will allow us
        to NOT be hacking around PySAML so rudely in order to load IdP metadata
        from a Python dict. https://github.com/rohe/pysaml2/issues/172

    Args:
        metadata (dict): The IdP metadata this SP is configured for.

    Returns:
        (dict) config where any metadata `inline_dict` data has been
            converted to `inline` XML.
    """
    if metadata.get('inline_dict', None):
        metadata['inline'] = metadata.get('inline', [])
        for _idp in metadata.get('inline_dict'):
            idp_config = IdPConfig()
            idp_config.load(_idp)
            entity_desc = entity_descriptor(idp_config)
            # Hack for supporting multiple certificates.
            if _idp.get('certs'):
                # `certs` config directive overrides `cert_file`.
                entity_desc.idpsso_descriptor.key_descriptor = \
                    _parse_key_descriptors(_idp['certs'])
            idp_metadata_str = str(entity_desc)
            LOGGER.debug("IdP XML Metadata for %s: %s",
                         _idp['entityid'], idp_metadata_str)
            metadata['inline'].append(idp_metadata_str)
        del metadata['inline_dict']
    return metadata
Beispiel #35
0
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"}

    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 __init__(self, config, attribute_map=None):
        """Initialize SAML Service Provider.

        Args:
            config (dict): Service Provider config info in dict form
            attribute_map (dict): Mapping of attribute keys to user data
        """
        self._config = SPConfig()
        self._config.load(config)
        if config['metadata'].get('config'):
            # Hacked in a way to get the IdP metadata from a python dict
            # rather than having to resort to loading XML from file or http.
            idp_config = IdPConfig()
            idp_config.load(config['metadata']['config'][0])
            idp_entityid = config['metadata']['config'][0]['entityid']
            idp_metadata_str = str(entity_descriptor(idp_config, 24))
            LOGGER.debug('IdP XML Metadata for %s: %s' % (
                idp_entityid, idp_metadata_str))
            self._config.metadata.import_metadata(
                idp_metadata_str, idp_entityid)
        self.attribute_map = {}
        if attribute_map is not None:
            self.attribute_map = attribute_map
Beispiel #37
0
def spid_sp_metadata(conf):
    metadata = entity_descriptor(conf)

    # this will renumber acs starting from 0 and set index=0 as is_default
    cnt = 0
    for attribute_consuming_service in metadata.spsso_descriptor.attribute_consuming_service:
        attribute_consuming_service.index = str(cnt)
        cnt += 1

    cnt = 0
    for assertion_consumer_service in metadata.spsso_descriptor.assertion_consumer_service:
        assertion_consumer_service.is_default = 'true' if not cnt else ''
        assertion_consumer_service.index = str(cnt)
        cnt += 1

    # nameformat patch
    for reqattr in metadata.spsso_descriptor.attribute_consuming_service[0].requested_attribute:
        reqattr.name_format = None  # "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
        reqattr.friendly_name = None

    metadata.extensions = None

    # attribute consuming service service name patch
    service_name = metadata.spsso_descriptor.attribute_consuming_service[0].service_name[0]
    service_name.lang = 'it'
    service_name.text = conf._sp_name

    avviso_29_v3(metadata)

    # metadata signature
    secc = security_context(conf)
    sign_dig_algs = dict(
        sign_alg=conf._sp_signing_algorithm,
        digest_alg=conf._sp_digest_algorithm
    )
    eid, xmldoc = sign_entity_descriptor(metadata, None, secc, **sign_dig_algs)
    return xmldoc
Beispiel #38
0
def create_metadata(config):
    return entity_descriptor(config)
Beispiel #39
0
 def make_meta(self):
     self.sp_configure(True)
     print(entity_descriptor(self.sp_config))
Beispiel #40
0
    # translate into hours
    valid_for = int(args.valid) * 24
if args.xmlsec:
    xmlsec = args.xmlsec
else:
    xmlsec = get_xmlsec_binary(paths)

eds = []
for filespec in args.config:
    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)
    eds.append(entity_descriptor(cnf))

secc = SecurityContext(xmlsec, args.keyfile, cert_file=args.cert)
if args.id:
    desc = entities_descriptor(eds, valid_for, args.name, args.id,
                               args.sign, secc)
    valid_instance(desc)
    print desc.to_string(nspair)
else:
    for eid in eds:
        if args.sign:
            desc = sign_entity_descriptor(eid, id, secc)
        else:
            desc = eid
        valid_instance(desc)
        print desc.to_string(nspair)
Beispiel #41
0
def saml_metadata():
    ed = entity_descriptor(sec_config)
    return metadata_tostring_fix(ed,
                                 {"xs": "http://www.w3.org/2001/XMLSchema"},
                                 None)
Beispiel #42
0
def saml_metadata():
    ed = entity_descriptor(sec_config)
    return metadata_tostring_fix(ed, {"xs": "http://www.w3.org/2001/XMLSchema"}, None)
Beispiel #43
0
def create_metadata_from_config_dict(config):
    nspair = {"xs": "http://www.w3.org/2001/XMLSchema"}
    conf = Config().load(config, metadata_construction=True)
    return entity_descriptor(conf).to_string(nspair).decode("utf-8")
Beispiel #44
0
def create_metadata(config):
    return entity_descriptor(config)
Beispiel #45
0
 def get(self, request, *args, **kwargs):
     saml2_config = self.get_saml2_config(request)
     metadata = entity_descriptor(saml2_config)
     return HttpResponse(str(metadata).encode("utf-8"),
                         content_type="text/xml; charset=utf8")
Beispiel #46
0
        print >> sys.stderr, sys.argv[0].split("/")[-1] + ": " + str(err.msg)
        print >> sys.stderr, "\t for help use --help"
        return 2

    if not xmlsec:
        xmlsec = get_xmlsec_binary(path)
        
    eds = []
    for filespec in args:
        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)
        eds.append(entity_descriptor(cnf, valid_for))

    secc = SecurityContext(xmlsec, keyfile, cert_file=pubkeyfile)
    if entitiesid:
        desc = entities_descriptor(eds, valid_for, name, id, sign, secc)
        valid_instance(desc)
        print desc.to_string(nspair)
    else:
        for eid in eds:
            if sign:
                desc = sign_entity_descriptor(eid, valid_for, id, secc)
            else:
                desc = eid
            valid_instance(desc)
            print desc.to_string(nspair)
Beispiel #47
0
 def entity_desc(self, sp_conf):
     return entity_descriptor(SPConfig().load(sp_conf, metadata_construction=True))
Beispiel #48
0
def _create_entity_descriptor(entity_config):
    cnf = Config().load(copy.deepcopy(entity_config), metadata_construction=True)
    return entity_descriptor(cnf)
Beispiel #49
0
if args.valid:
    # translate into hours
    valid_for = int(args.valid) * 24

eds = []
for filespec in args.config:
    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:
from saml2.config import Config
from saml2.metadata import entity_descriptor

__author__ = 'roland'

fil = "sp_mdext_conf.py"

cnf = Config().load_file(fil, metadata_construction=True)
ed = entity_descriptor(cnf)

print(ed)

assert ed.spsso_descriptor.extensions
assert len(ed.spsso_descriptor.extensions.extension_elements) == 3