Exemplo n.º 1
0
    def load_complex(self, cnf, typ="", metadata_construction=False):
        try:
            self.setattr(typ, "policy", Policy(cnf["policy"]))
        except KeyError:
            pass

        try:
            try:
                acs = ac_factory(cnf["attribute_map_dir"])
            except KeyError:
                acs = ac_factory()

            if not acs:
                raise Exception("No attribute converters, something is wrong!!")

            _acs = self.getattr("attribute_converters", typ)
            if _acs:
                _acs.extend(acs)
            else:
                self.setattr(typ, "attribute_converters", acs)

        except KeyError:
            pass

        if not metadata_construction:
            try:
                self.setattr(typ, "metadata",
                             self.load_metadata(cnf["metadata"]))
            except KeyError:
                pass
Exemplo n.º 2
0
    def load_complex(self, cnf, typ="", metadata_construction=False):
        _attr_typ = self._attr[typ]
        try:
            _attr_typ["policy"] = Policy(cnf["policy"])
        except KeyError:
            pass

        try:
            try:
                acs = ac_factory(cnf["attribute_map_dir"])
            except KeyError:
                acs = ac_factory()

            if not acs:
                raise Exception(
                    ("No attribute converters, ", "something is wrong!!"))
            try:
                _attr_typ["attribute_converters"].extend(acs)
            except KeyError:
                _attr_typ["attribute_converters"] = acs
        except KeyError:
            pass

        if not metadata_construction:
            try:
                _attr_typ["metadata"] = self.load_metadata(cnf["metadata"])
            except KeyError:
                pass
Exemplo n.º 3
0
    def load_complex(self, cnf, typ="", metadata_construction=False):
        try:
            self.setattr(typ, "policy", Policy(cnf["policy"]))
        except KeyError:
            pass

        try:
            try:
                acs = ac_factory(cnf["attribute_map_dir"])
            except KeyError:
                acs = ac_factory()

            if not acs:
                raise Exception(
                    ("No attribute converters, ", "something is wrong!!"))

            _acs = self.getattr("attribute_converters", typ)
            if _acs:
                _acs.extend(acs)
            else:
                self.setattr(typ, "attribute_converters", acs)

        except KeyError:
            pass

        if not metadata_construction:
            try:
                self.setattr(typ, "metadata",
                             self.load_metadata(cnf["metadata"]))
            except KeyError:
                pass
Exemplo n.º 4
0
    def load_complex(self, cnf, typ="", metadata_construction=False):
        _attr_typ = self._attr[typ]
        try:
            _attr_typ["policy"] = Policy(cnf["policy"])
        except KeyError:
            pass

        try:
            try:
                acs = ac_factory(cnf["attribute_map_dir"])
            except KeyError:
                acs = ac_factory()

            if not acs:
                raise Exception(("No attribute converters, ",
                                    "something is wrong!!"))
            try:
                _attr_typ["attribute_converters"].extend(acs)
            except KeyError:
                _attr_typ["attribute_converters"] = acs
        except KeyError:
            pass

        if not metadata_construction:
            try:
                _attr_typ["metadata"] = self.load_metadata(cnf["metadata"])
            except KeyError:
                pass
Exemplo n.º 5
0
def test_filter_on_wire_representation_2():
    r = [
        Attribute(
            friendly_name="surName",
            name="urn:oid:2.5.4.4",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri",
        ),
        Attribute(
            friendly_name="givenName",
            name="urn:oid:2.5.4.42",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri",
        ),
    ]
    o = [
        Attribute(
            friendly_name="title",
            name="urn:oid:2.5.4.12",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri",
        )
    ]

    acs = attribute_converter.ac_factory(full_path("attributemaps"))

    ava = {"sn": ["Hedberg"], "givenname": ["Roland"], "title": ["Master"], "uid": ["rohe0002"]}

    ava = assertion.filter_on_wire_representation(ava, acs, r, o)
    assert _eq(ava.keys(), ["sn", "givenname", "title"])
Exemplo n.º 6
0
def load_providers():
    metadata = {}
    for filename in settings.WALDUR_AUTH_SAML2['IDP_METADATA_LOCAL']:
        mdf = MetaDataFile(ac_factory(), filename)
        mdf.load()
        metadata.update(mdf.items())
    return metadata
Exemplo n.º 7
0
def test_filter_values_req_opt_2():
    r = [
        to_dict(
            Attribute(
                friendly_name="surName",
                name="urn:oid:2.5.4.4",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
            ONTS),
        to_dict(
            Attribute(
                friendly_name="givenName",
                name="urn:oid:2.5.4.42",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
            ONTS),
        to_dict(
            Attribute(
                friendly_name="mail",
                name="urn:oid:0.9.2342.19200300.100.1.3",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
            ONTS)]
    o = [
        to_dict(
            Attribute(
                friendly_name="title",
                name="urn:oid:2.5.4.12",
                name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
            ONTS)]

    ava = {"surname": ["Hedberg"], "givenName": ["Roland"],
           "eduPersonAffiliation": ["staff"], "uid": ["rohe0002"]}

    with raises(MissingValue):
        filter_on_attributes(ava, r, o, acs=ac_factory())
Exemplo n.º 8
0
def test_filter_on_attributes_with_missing_optional_attribute():
    ava = {"extra": "foo"}
    eptid = to_dict(Attribute(
        friendly_name="eduPersonTargetedID",
        name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10",
        name_format=NAME_FORMAT_URI), ONTS)
    assert filter_on_attributes(ava, optional=[eptid], acs=ac_factory()) == {}
Exemplo n.º 9
0
def test_filter_values_req_opt_4():
    r = [
        Attribute(
            friendly_name="surName",
            name="urn:oid:2.5.4.4",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
        Attribute(
            friendly_name="givenName",
            name="urn:oid:2.5.4.42",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")
    ]
    o = [
        Attribute(
            friendly_name="title",
            name="urn:oid:2.5.4.12",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")
    ]

    acs = attribute_converter.ac_factory(full_path("attributemaps"))

    rava = attribute_converter.list_to_local(acs, r)
    oava = attribute_converter.list_to_local(acs, o)

    ava = {
        "sn": ["Hedberg"],
        "givenName": ["Roland"],
        "eduPersonAffiliation": ["staff"],
        "uid": ["rohe0002"]
    }

    ava = assertion.filter_on_demands(ava, rava, oava)
    print(ava)
    assert _eq(sorted(list(ava.keys())), ['givenName', 'sn'])
    assert ava == {'givenName': ['Roland'], 'sn': ['Hedberg']}
Exemplo n.º 10
0
def test_filter_values_req_opt_4():
    r = [
        Attribute(
            friendly_name="surName",
            name="urn:oid:2.5.4.4",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
        Attribute(
            friendly_name="givenName",
            name="urn:oid:2.5.4.42",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]
    o = [
        Attribute(
            friendly_name="title",
            name="urn:oid:2.5.4.12",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")]

    acs = attribute_converter.ac_factory(full_path("attributemaps"))

    rava = attribute_converter.list_to_local(acs, r)
    oava = attribute_converter.list_to_local(acs, o)

    ava = {"sn": ["Hedberg"], "givenName": ["Roland"],
           "eduPersonAffiliation": ["staff"], "uid": ["rohe0002"]}

    ava = assertion.filter_on_demands(ava, rava, oava)
    print ava
    assert _eq(ava.keys(), ['givenName', 'sn'])
    assert ava == {'givenName': ['Roland'], 'sn': ['Hedberg']}
Exemplo n.º 11
0
def test_filter_on_wire_representation_2():
    r = [
        Attribute(
            friendly_name="surName",
            name="urn:oid:2.5.4.4",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri"),
        Attribute(
            friendly_name="givenName",
            name="urn:oid:2.5.4.42",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")
    ]
    o = [
        Attribute(
            friendly_name="title",
            name="urn:oid:2.5.4.12",
            name_format="urn:oasis:names:tc:SAML:2.0:attrname-format:uri")
    ]

    acs = attribute_converter.ac_factory(full_path("attributemaps"))

    ava = {
        "sn": ["Hedberg"],
        "givenname": ["Roland"],
        "title": ["Master"],
        "uid": ["rohe0002"]
    }

    ava = assertion.filter_on_wire_representation(ava, acs, r, o)
    assert _eq(sorted(list(ava.keys())), ["givenname", "sn", "title"])
Exemplo n.º 12
0
def test_assertion_2():
    AVA = {'mail': '*****@*****.**',
           'eduPersonTargetedID': 'http://lingon.ladok.umu.se:8090/idp!http://lingon.ladok.umu.se:8088/sp!95e9ae91dbe62d35198fbbd5e1fb0976',
           'displayName': 'Roland Hedberg',
           'uid': 'http://roland.hedberg.myopenid.com/'}

    ava = Assertion(AVA)

    policy = Policy({
        "default": {
            "lifetime": {"minutes": 240},
            "attribute_restrictions": None,  # means all I have
            "name_form": NAME_FORMAT_URI
        },
    })

    ava = ava.apply_policy("", policy)
    acs = ac_factory(full_path("attributemaps"))
    attribute = from_local(acs, ava, policy.get_name_form(""))

    assert len(attribute) == 4
    names = [attr.name for attr in attribute]
    assert _eq(names, ['urn:oid:0.9.2342.19200300.100.1.3',
                       'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
                       'urn:oid:2.16.840.1.113730.3.1.241',
                       'urn:oid:0.9.2342.19200300.100.1.1'])
Exemplo n.º 13
0
def load_providers():
    metadata = {}
    for filename in settings.WALDUR_AUTH_SAML2['idp_metadata_local']:
        mdf = MetaDataFile(ac_factory(), filename)
        mdf.load()
        metadata.update(mdf.items())
    return metadata
Exemplo n.º 14
0
def test_filter_on_attributes_with_missing_optional_attribute():
    ava = {"extra": "foo"}
    eptid = to_dict(
        Attribute(friendly_name="eduPersonTargetedID",
                  name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10",
                  name_format=NAME_FORMAT_URI), ONTS)
    assert filter_on_attributes(ava, optional=[eptid], acs=ac_factory()) == {}
Exemplo n.º 15
0
def test_assertion_2():
    AVA = {'mail': u'*****@*****.**',
           'eduPersonTargetedID': 'http://lingon.ladok.umu.se:8090/idp!http://lingon.ladok.umu.se:8088/sp!95e9ae91dbe62d35198fbbd5e1fb0976',
           'displayName': u'Roland Hedberg',
           'uid': 'http://roland.hedberg.myopenid.com/'}

    ava = Assertion(AVA)

    policy = Policy( {
        "default": {
            "lifetime": {"minutes": 240},
            "attribute_restrictions": None, # means all I have
            "name_form": NAME_FORMAT_URI
        },
    })

    ava = ava.apply_policy( "", policy )
    acs = ac_factory("attributemaps")
    attribute=from_local(acs, ava, policy.get_name_form(""))

    assert len(attribute) == 4
    names = [attr.name for attr in attribute]
    assert _eq(names, ['urn:oid:0.9.2342.19200300.100.1.3',
                       'urn:oid:1.3.6.1.4.1.5923.1.1.1.10',
                       'urn:oid:2.16.840.1.113730.3.1.241',
                       'urn:oid:0.9.2342.19200300.100.1.1'])
Exemplo n.º 16
0
def test_filter_on_attributes_with_missing_required_attribute():
    ava = {"extra": "foo"}
    eptid = to_dict(
        Attribute(friendly_name="eduPersonTargetedID",
                  name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10",
                  name_format=NAME_FORMAT_URI), ONTS)
    with raises(MissingValue):
        filter_on_attributes(ava, required=[eptid], acs=ac_factory())
Exemplo n.º 17
0
def test_filter_on_attributes_with_missing_required_attribute():
    ava = {"extra": "foo"}
    eptid = to_dict(Attribute(
        friendly_name="eduPersonTargetedID",
        name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10",
        name_format=NAME_FORMAT_URI), ONTS)
    with pytest.raises(MissingValue):
        filter_on_attributes(ava, required=[eptid], acs=ac_factory())
Exemplo n.º 18
0
def test_filter_on_attributes_with_missing_name_format():
    ava = {"eduPersonTargetedID": "*****@*****.**",
           "eduPersonAffiliation": "test",
           "extra": "foo"}
    eptid = to_dict(Attribute(friendly_name="eduPersonTargetedID",
                              name="urn:myown:eptid",
                              name_format=''), ONTS)
    ava = filter_on_attributes(ava, optional=[eptid], acs=ac_factory())
    assert ava['eduPersonTargetedID'] == "*****@*****.**"
Exemplo n.º 19
0
def test_schac():
    attr = attribute_from_string(ava)
    acs = attribute_converter.ac_factory()
    for ac in acs:
        try:
            res = ac.ava_from(attr)
            assert res[0] == "schacHomeOrganization"
        except KeyError:
            pass
Exemplo n.º 20
0
def test_optional_attributes():
    attrconverters = ac_factory("../tests/attributemaps")
    ras = metadata.do_requested_attribute(
        SP["service"]["sp"]["optional_attributes"], attrconverters)
    assert len(ras) == len(SP["service"]["sp"]["optional_attributes"])
    print(ras[0])
    assert ras[0].name == 'urn:oid:2.5.4.12'
    assert ras[0].name_format == NAME_FORMAT_URI
    assert ras[0].is_required == "false"
Exemplo n.º 21
0
def test_schac():
    attr = attribute_from_string(ava)
    acs = attribute_converter.ac_factory()
    for ac in acs:
        try:
            res = ac.ava_from(attr)
            assert res[0] == "schacHomeOrganization"
        except KeyError:
            pass
Exemplo n.º 22
0
    def filter(self,
               ava,
               sp_entity_id,
               mdstore=None,
               required=None,
               optional=None):
        """ What attribute and attribute values returns depends on what
        the SP or the registration authority has said it wants in the request
        or in the metadata file and what the IdP/AA wants to release.
        An assumption is that what the SP or the registration authority
        asks for overrides whatever is in the metadata. But of course the
        IdP never releases anything it doesn't want to.

        :param ava: The information about the subject as a dictionary
        :param sp_entity_id: The entity ID of the SP
        :param required: Attributes that the SP requires in the assertion
        :param optional: Attributes that the SP regards as optional
        :return: A possibly modified AVA
        """

        if mdstore is not None:
            warn_msg = (
                "The mdstore parameter for saml2.assertion.Policy.filter "
                "is deprecated; "
                "instead, initialize the Policy object setting the mds param.")
            logger.warning(warn_msg)
            _warn(warn_msg, DeprecationWarning)

        # acs MUST have a value, fall back to default.
        if not self.acs:
            self.acs = ac_factory()

        subject_ava = ava.copy()

        # entity category restrictions
        _ent_rest = self.get_entity_categories(sp_entity_id,
                                               mds=mdstore,
                                               required=required)
        if _ent_rest:
            subject_ava = filter_attribute_value_assertions(
                subject_ava, _ent_rest)
        elif required or optional:
            logger.debug("required: %s, optional: %s", required, optional)
            subject_ava = filter_on_attributes(
                subject_ava,
                required,
                optional,
                self.acs,
                self.get_fail_on_missing_requested(sp_entity_id),
            )

        # attribute restrictions
        _attr_rest = self.get_attribute_restrictions(sp_entity_id)
        subject_ava = filter_attribute_value_assertions(
            subject_ava, _attr_rest)

        return subject_ava or {}
Exemplo n.º 23
0
def test_filter_on_attributes_with_missing_name_format():
    ava = {"eduPersonTargetedID": "*****@*****.**",
           "eduPersonAffiliation": "test",
           "extra": "foo"}
    eptid = to_dict(Attribute(friendly_name="eduPersonTargetedID",
                              name="urn:myown:eptid",
                              name_format=''), ONTS)
    ava = filter_on_attributes(ava, optional=[eptid], acs=ac_factory())
    assert ava['eduPersonTargetedID'] == "*****@*****.**"
Exemplo n.º 24
0
def test_required_attributes():
    attrconverters = ac_factory("../tests/attributemaps")
    ras = metadata.do_requested_attribute(
                                SP["service"]["sp"]["required_attributes"],
                                attrconverters, is_required="true")
    assert len(ras) == len(SP["service"]["sp"]["required_attributes"])
    print((ras[0]))
    assert ras[0].name == 'urn:oid:2.5.4.4'
    assert ras[0].name_format == NAME_FORMAT_URI
    assert ras[0].is_required == "true"
Exemplo n.º 25
0
def test_filter_on_attributes_1():
    a = to_dict(Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                          friendly_name="serialNumber"), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345"], "givenName": ["Lars"]}

    ava = filter_on_attributes(ava, required, acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert ava["serialNumber"] == ["12345"]
Exemplo n.º 26
0
def test_filter_on_attributes_2():

    a = to_dict(Attribute(friendly_name="surName",name="urn:oid:2.5.4.4",
                          name_format=NAME_FORMAT_URI), ONTS)
    required = [a]
    ava = {"sn":["kakavas"]}

    ava = filter_on_attributes(ava,required,acs=ac_factory())
    assert list(ava.keys()) == ['sn']
    assert ava["sn"] == ["kakavas"]
Exemplo n.º 27
0
def test_filter_values_req_4():
    a = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345"]}

    raises(MissingValue, filter_on_attributes, ava, required, acs=ac_factory())
Exemplo n.º 28
0
def test_filter_on_attributes_1():
    a = to_dict(Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                          friendly_name="serialNumber"), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345"], "givenName": ["Lars"]}

    ava = filter_on_attributes(ava, required, acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert ava["serialNumber"] == ["12345"]
Exemplo n.º 29
0
def test_optional_attributes():
    attrconverters = ac_factory("../tests/attributemaps")
    ras = metadata.do_requested_attribute(
                                SP["service"]["sp"]["optional_attributes"],
                                attrconverters)
    assert len(ras) == len(SP["service"]["sp"]["optional_attributes"])
    print ras[0]
    assert ras[0].name == 'urn:oid:2.5.4.12'
    assert ras[0].name_format == NAME_FORMAT_URI
    assert ras[0].is_required == "false"
Exemplo n.º 30
0
def test_filter_on_attributes_2():
    
    a = to_dict(Attribute(friendly_name="surName",name="urn:oid:2.5.4.4",
                          name_format=NAME_FORMAT_URI), ONTS)
    required = [a]
    ava = {"sn":["kakavas"]}

    ava = filter_on_attributes(ava,required,acs=ac_factory())
    assert list(ava.keys()) == ['sn']
    assert ava["sn"] == ["kakavas"]
Exemplo n.º 31
0
def test_filter_values_req_2():
    a1 = to_dict(Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                           friendly_name="serialNumber"), ONTS)
    a2 = to_dict(Attribute(name="urn:oid:2.5.4.4", name_format=NAME_FORMAT_URI,
                           friendly_name="surName"), ONTS)

    required = [a1, a2]
    ava = {"serialNumber": ["12345"], "givenName": ["Lars"]}

    raises(MissingValue, filter_on_attributes, ava, required, acs=ac_factory())
Exemplo n.º 32
0
def test_filter_values_req_4():
    a = to_dict(
        Attribute(name="urn:oid:2.5.4.5",
                  name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345"]}

    raises(MissingValue, filter_on_attributes, ava, required, acs=ac_factory())
Exemplo n.º 33
0
def test_filter_values_req_2():
    a1 = to_dict(Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                           friendly_name="serialNumber"), ONTS)
    a2 = to_dict(Attribute(name="urn:oid:2.5.4.4", name_format=NAME_FORMAT_URI,
                           friendly_name="surName"), ONTS)

    required = [a1, a2]
    ava = {"serialNumber": ["12345"], "givenName": ["Lars"]}

    with raises(MissingValue):
        filter_on_attributes(ava, required, acs=ac_factory())
Exemplo n.º 34
0
def test_filter_values_req_6():
    a = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345", "54321"]}

    ava = filter_on_attributes(ava, required, acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert ava["serialNumber"] == ["54321"]
Exemplo n.º 35
0
def test_filter_on_attributes_without_friendly_name():
    ava = {"eduPersonTargetedID": "*****@*****.**", "eduPersonAffiliation": "test",
           "extra": "foo"}
    eptid = to_dict(
            Attribute(name="urn:oid:1.3.6.1.4.1.5923.1.1.1.10", name_format=NAME_FORMAT_URI), ONTS)
    ep_affiliation = to_dict(
            Attribute(name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1", name_format=NAME_FORMAT_URI), ONTS)

    restricted_ava = filter_on_attributes(ava, required=[eptid], optional=[ep_affiliation],
                                          acs=ac_factory())
    assert restricted_ava == {"eduPersonTargetedID": "*****@*****.**",
                              "eduPersonAffiliation": "test"}
Exemplo n.º 36
0
def test_filter_values_req_6():
    a = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)

    required = [a]
    ava = {"serialNumber": ["12345", "54321"]}

    ava = filter_on_attributes(ava, required, acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert ava["serialNumber"] == ["54321"]
Exemplo n.º 37
0
    def load_complex(self, cnf, typ="", metadata_construction=False):
        try:
            self.setattr(typ, "policy", Policy(cnf["policy"]))
        except KeyError:
            pass

        # for srv, spec in cnf["service"].items():
        #     try:
        #         self.setattr(srv, "policy",
        #                      Policy(cnf["service"][srv]["policy"]))
        #     except KeyError:
        #         pass

        try:
            try:
                acs = ac_factory(cnf["attribute_map_dir"])
            except KeyError:
                acs = ac_factory()

            if not acs:
                raise ConfigurationError(
                    "No attribute converters, something is wrong!!")

            _acs = self.getattr("attribute_converters", typ)
            if _acs:
                _acs.extend(acs)
            else:
                self.setattr(typ, "attribute_converters", acs)

        except KeyError:
            pass

        if not metadata_construction:
            try:
                self.setattr(typ, "metadata",
                             self.load_metadata(cnf["metadata"]))
            except KeyError:
                pass
Exemplo n.º 38
0
    def load_complex(self, cnf, typ="", metadata_construction=False):
        try:
            self.setattr(typ, "policy", Policy(cnf["policy"]))
        except KeyError:
            pass

        # for srv, spec in cnf["service"].items():
        #     try:
        #         self.setattr(srv, "policy",
        #                      Policy(cnf["service"][srv]["policy"]))
        #     except KeyError:
        #         pass

        try:
            try:
                acs = ac_factory(cnf["attribute_map_dir"])
            except KeyError:
                acs = ac_factory()

            if not acs:
                raise ConfigurationError(
                    "No attribute converters, something is wrong!!")

            _acs = self.getattr("attribute_converters", typ)
            if _acs:
                _acs.extend(acs)
            else:
                self.setattr(typ, "attribute_converters", acs)

        except KeyError:
            pass

        if not metadata_construction:
            try:
                self.setattr(typ, "metadata",
                             self.load_metadata(cnf["metadata"]))
            except KeyError:
                pass
Exemplo n.º 39
0
def test_filter_values_req_opt_0():
    r = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)
    o = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="12345")]), ONTS)

    ava = {"serialNumber": ["12345", "54321"]}

    ava = filter_on_attributes(ava, [r], [o], acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert _eq(ava["serialNumber"], ["12345", "54321"])
Exemplo n.º 40
0
    def load_complex(self, cnf):
        acs = ac_factory(cnf.get("attribute_map_dir"))
        if not acs:
            raise ConfigurationError(
                "No attribute converters, something is wrong!!")
        self.setattr("", "attribute_converters", acs)

        try:
            self.setattr("", "metadata", self.load_metadata(cnf["metadata"]))
        except KeyError:
            pass

        for srv, spec in cnf.get("service", {}).items():
            policy_conf = spec.get("policy")
            self.setattr(srv, "policy", Policy(policy_conf, self.metadata))
Exemplo n.º 41
0
def test_filter_values_req_opt_0():
    r = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="54321")]), ONTS)
    o = to_dict(
        Attribute(name="urn:oid:2.5.4.5", name_format=NAME_FORMAT_URI,
                  friendly_name="serialNumber",
                  attribute_value=[AttributeValue(text="12345")]), ONTS)

    ava = {"serialNumber": ["12345", "54321"]}

    ava = filter_on_attributes(ava, [r], [o], acs=ac_factory())
    assert list(ava.keys()) == ["serialNumber"]
    assert _eq(ava["serialNumber"], ["12345", "54321"])
Exemplo n.º 42
0
def test_filter_on_attributes_without_friendly_name():
    ava = {"eduPersonTargetedID": "*****@*****.**",
           "eduPersonAffiliation": "test",
           "extra": "foo"}
    eptid = to_dict(
        Attribute(name="urn:oid:1.3.6.1.4.1.5923.1.1.1.11",
                  name_format=NAME_FORMAT_URI), ONTS)
    ep_affiliation = to_dict(
        Attribute(name="urn:oid:1.3.6.1.4.1.5923.1.1.1.1",
                  name_format=NAME_FORMAT_URI), ONTS)

    restricted_ava = filter_on_attributes(ava, required=[eptid],
                                          optional=[ep_affiliation],
                                          acs=ac_factory())
    assert restricted_ava == {"eduPersonTargetedID": "*****@*****.**",
                              "eduPersonAffiliation": "test"}
    def test(self):
        failures = 0
        friendly_name = "schacHomeOrganization"
        ava_schac = BuilderAVA("urn:oid:1.3.6.1.4.1.25178.1.2.9",
                               friendly_name, saml_map.MAP['identifier'])

        attr = attribute_from_string(ava_schac.ava)
        acs = attribute_converter.ac_factory()

        for ac in acs:
            try:
                res = ac.ava_from(attr)
            except KeyError:
                failures += 1
            else:
                assert res[0] == "schacHomeOrganization"

        assert failures != len(acs)
    def test(self):
        failures = 0
        friendly_name = 'PersonIdentifier'
        ava_eidas = BuilderAVA(saml_map.EIDAS_NATURALPERSON + friendly_name,
                               friendly_name, saml_map.MAP['identifier'])

        attr = attribute_from_string(ava_eidas.ava)
        acs = attribute_converter.ac_factory()

        for ac in acs:
            try:
                res = ac.ava_from(attr)
            except KeyError:
                failures += 1
            else:
                assert res[0] == friendly_name

        assert failures != len(acs)
Exemplo n.º 45
0
    def test(self):
        failures = 0
        friendly_name = 'PersonIdentifier'
        ava_eidas = BuilderAVA(
            saml_map.EIDAS_NATURALPERSON + friendly_name,
            friendly_name,
            saml_map.MAP['identifier'])

        attr = attribute_from_string(ava_eidas.ava)
        acs = attribute_converter.ac_factory()

        for ac in acs:
            try:
                res = ac.ava_from(attr)
            except KeyError:
                failures += 1
            else:
                assert res[0] == friendly_name

        assert failures != len(acs)
Exemplo n.º 46
0
    def test(self):
        failures = 0
        friendly_name = "schacHomeOrganization"
        ava_schac = BuilderAVA(
            "urn:oid:1.3.6.1.4.1.25178.1.2.9",
            friendly_name,
            saml_map.MAP['identifier'])

        attr = attribute_from_string(ava_schac.ava)
        acs = attribute_converter.ac_factory()

        for ac in acs:
            try:
                res = ac.ava_from(attr)
            except KeyError:
                failures += 1
            else:
                assert res[0] == "schacHomeOrganization"

        assert failures != len(acs)
Exemplo n.º 47
0
    def filter(self, ava, sp_entity_id, mdstore, required=None, optional=None):
        """ What attribute and attribute values returns depends on what
        the SP has said it wants in the request or in the metadata file and
        what the IdP/AA wants to release. An assumption is that what the SP
        asks for overrides whatever is in the metadata. But of course the
        IdP never releases anything it doesn't want to.

        :param ava: The information about the subject as a dictionary
        :param sp_entity_id: The entity ID of the SP
        :param mdstore: A Metadata store
        :param required: Attributes that the SP requires in the assertion
        :param optional: Attributes that the SP regards as optional
        :return: A possibly modified AVA
        """

        _ava = None

        if not self.acs:  # acs MUST have a value, fall back to default.
            self.acs = ac_factory()

        _rest = self.get_entity_categories(sp_entity_id, mdstore, required)
        if _rest:
            _ava = filter_attribute_value_assertions(ava.copy(), _rest)
        elif required or optional:
            logger.debug("required: %s, optional: %s", required, optional)
            _ava = filter_on_attributes(
                ava.copy(), required, optional, self.acs,
                self.get_fail_on_missing_requested(sp_entity_id))

        _rest = self.get_attribute_restrictions(sp_entity_id)
        if _rest:
            if _ava is None:
                _ava = ava.copy()
            _ava = filter_attribute_value_assertions(_ava, _rest)
        elif _ava is None:
            _ava = ava.copy()

        if _ava is None:
            return {}
        else:
            return _ava
Exemplo n.º 48
0
    def filter(self, ava, sp_entity_id, mdstore, required=None, optional=None):
        """ What attribute and attribute values returns depends on what
        the SP has said it wants in the request or in the metadata file and
        what the IdP/AA wants to release. An assumption is that what the SP
        asks for overrides whatever is in the metadata. But of course the
        IdP never releases anything it doesn't want to.

        :param ava: The information about the subject as a dictionary
        :param sp_entity_id: The entity ID of the SP
        :param mdstore: A Metadata store
        :param required: Attributes that the SP requires in the assertion
        :param optional: Attributes that the SP regards as optional
        :return: A possibly modified AVA
        """

        _ava = None

        if not self.acs:  # acs MUST have a value, fall back to default.
            self.acs = ac_factory()

        _rest = self.get_entity_categories(sp_entity_id, mdstore, required)
        if _rest:
            _ava = filter_attribute_value_assertions(ava.copy(), _rest)
        elif required or optional:
            logger.debug("required: %s, optional: %s", required, optional)
            _ava = filter_on_attributes(
                ava.copy(), required, optional, self.acs,
                self.get_fail_on_missing_requested(sp_entity_id))

        _rest = self.get_attribute_restrictions(sp_entity_id)
        if _rest:
            if _ava is None:
                _ava = ava.copy()
            _ava = filter_attribute_value_assertions(_ava, _rest)
        elif _ava is None:
            _ava = ava.copy()

        if _ava is None:
            return {}
        else:
            return _ava
Exemplo n.º 49
0
    def __init__(self, config):
        baseurl = config['protocol'] + "://" + config['url']
        log.info("Application baseurl: " + baseurl)

        # Update URLs with base
        for pro in SSIXASAMLProvider_SERVICE_EP:
            for serv in SSIXASAMLProvider_SERVICE_EP[pro]['endpoints']:
                if 'service' in serv:
                    for ep in SSIXASAMLProvider_SERVICE_EP[pro]['endpoints'][
                            serv]:
                        SSIXASAMLProvider_SERVICE_EP[pro]['endpoints'][serv][
                            0] = baseurl + ep[0]

        # Update SAML config
        config['saml_config'].update({'service': SSIXASAMLProvider_SERVICE_EP})
        cfg = SAMLIdpConfig(config['saml_config'])

        # Create SAML IdP server - Init super class after config preparation
        super(SSIXASAMLProvider, self).__init__(config=cfg, cache=Cache())

        # Add authn broker
        self.authn_broker = AuthnBroker()
        self.userinfodb = SAMLUserInfoDB()
        i = BlockchainAuthMethod(baseurl + "/saml", config['proxymode'],
                                 config, self.userinfodb, config['trustmodel'])
        self.authn_broker.add(authn_context_class_ref(UNSPECIFIED), i, 3,
                              {i.acr})

        # Add attribute converters
        self.config.attribute_converters = ac_factory()

        # Add metadata
        self.metadata = self.create_metadata(config['saml_config']['metadata'])

        # Response bindings that are offered
        self.response_bindings = [BINDING_HTTP_POST, BINDING_HTTP_REDIRECT]

        # Default claims
        self.defaul_claims = copy.deepcopy(
            config['saml_config']['default_claims'])
Exemplo n.º 50
0
def test_assertion_2():
    AVA = {
        "mail": u"*****@*****.**",
        "eduPersonTargetedID": "http://lingon.ladok.umu"
        ".se:8090/idp!http://lingon.ladok.umu"
        ".se:8088/sp!95e9ae91dbe62d35198fbbd5e1fb0976",
        "displayName": u"Roland Hedberg",
        "uid": "http://roland.hedberg.myopenid.com/",
    }

    ava = Assertion(AVA)

    policy = Policy(
        {
            "default": {
                "lifetime": {"minutes": 240},
                "attribute_restrictions": None,  # means all I have
                "name_form": NAME_FORMAT_URI,
            }
        }
    )

    ava = ava.apply_policy("", policy)
    acs = ac_factory(full_path("attributemaps"))
    attribute = from_local(acs, ava, policy.get_name_form(""))

    assert len(attribute) == 4
    names = [attr.name for attr in attribute]
    assert _eq(
        names,
        [
            "urn:oid:0.9.2342.19200300.100.1.3",
            "urn:oid:1.3.6.1.4.1.5923.1.1.1.10",
            "urn:oid:2.16.840.1.113730.3.1.241",
            "urn:oid:0.9.2342.19200300.100.1.1",
        ],
    )
Exemplo n.º 51
0
    <EmailAddress>[email protected]</EmailAddress>
  </ContactPerson>
</EntityDescriptor>
</EntitiesDescriptor>
""".format(cert_data=TEST_CERT)

ONTS = {
    saml.NAMESPACE: saml,
    md.NAMESPACE: md,
    xmldsig.NAMESPACE: xmldsig,
    xmlenc.NAMESPACE: xmlenc
}

ONTS.update(load_extensions())

ATTRCONV = ac_factory(full_path("attributemaps"))

METADATACONF = {
    "1": [{
        "class": "saml2.mdstore.MetaDataFile",
        "metadata": [(full_path("swamid-1.0.xml"),)],
    }],
    "2": [{
        "class": "saml2.mdstore.MetaDataFile",
        "metadata": [(full_path("InCommon-metadata.xml"),)],
    }],
    "3": [{
        "class": "saml2.mdstore.MetaDataFile",
        "metadata": [(full_path("extended.xml"),)],
    }],
    # "7": [{
Exemplo n.º 52
0
ONTS = {
    dri.NAMESPACE: dri,
    idpdisc.NAMESPACE: idpdisc,
    md.NAMESPACE: md,
    mdattr.NAMESPACE: mdattr,
    mdui.NAMESPACE: mdui,
    saml.NAMESPACE: saml,
    ui.NAMESPACE: ui,
    xmlenc.NAMESPACE: xmlenc,
    xmldsig.NAMESPACE: xmldsig,
}

start = time.time()
for i in range(1, 10):
    mdmd = MetaDataMD(ONTS, ac_factory("../tests/attributemaps"), "swamid2.md")
    mdmd.load()

    _ = mdmd.keys()

print time.time() - start

start = time.time()
for i in range(1, 10):
    mdf = MetaDataFile(ONTS.values(), ac_factory("../tests/attributemaps"),
                      "../tests/swamid-2.0.xml")
    mdf.load()
    _ = mdf.keys()

print time.time() - start
Exemplo n.º 53
0
metad = None

# config file format
#
# local <local file name>
# remote <url> <local file name for certificate use to verify signature>
#
# for instance
#
#local metadata_sp_1.xml
#local InCommon-metadata.xml
#remote https://kalmar2.org/simplesaml/module.php/aggregator/?id=kalmarcentral2&set=saml2 kalmar2.pem
#

ATTRCONV = ac_factory(args.attrsmap)

mds = MetadataStore(ONTS.values(), None, None)

for line in open(args.conf).readlines():
    line = line.strip()
    if len(line) == 0:
        continue
    elif line[0] == "#":
        continue
    spec = line.split(" ")

    if args.ignore_valid:
        kwargs = {"check_validity": False}
    else:
        kwargs = {}
 def setup_class(self):
     self.acs = attribute_converter.ac_factory("attributemaps")
Exemplo n.º 55
0
parser = argparse.ArgumentParser()
parser.add_argument('-t', dest='type')
parser.add_argument('-u', dest='url')
parser.add_argument('-c', dest='cert')
parser.add_argument('-a', dest='attrsmap')
parser.add_argument('-o', dest='output')
parser.add_argument('-x', dest='xmlsec')
parser.add_argument(dest="item")
args = parser.parse_args()

metad = None

if args.type == "local":
    metad = MetaDataFile(list(ONTS.values()), args.item, args.item)
elif args.type == "external":
    ATTRCONV = ac_factory(args.attrsmap)
    httpc = HTTPBase()
    crypto = _get_xmlsec_cryptobackend(args.xmlsec)
    sc = SecurityContext(crypto)
    metad = MetaDataExtern(list(ONTS.values()),
                           ATTRCONV,
                           args.url,
                           sc,
                           cert=args.cert,
                           http=httpc)

if metad:
    try:
        metad.load()
    except:
        raise
def test_default():
    acs = attribute_converter.ac_factory()
    assert acs
Exemplo n.º 57
0
CONST_UNKNOWERROR = CONST_STATIC_FILE + "unknownError.html"

#Needed for reading metadatafiles.
CONST_ONTS = {
    saml.NAMESPACE: saml,
    mdui.NAMESPACE: mdui,
    mdattr.NAMESPACE: mdattr,
    dri.NAMESPACE: dri,
    ui.NAMESPACE: ui,
    idpdisc.NAMESPACE: idpdisc,
    md.NAMESPACE: md,
    xmldsig.NAMESPACE: xmldsig,
    xmlenc.NAMESPACE: xmlenc
}
#Needed for reading metadatafiles.
CONST_ATTRCONV = attribute_converter.ac_factory("attributemaps")


class MetadataGeneration(object):

    def __init__(self, conf, key, idp_conf, xmlsec_path):
        """
        Constructor.
        Initiates the class.
        :param conf: Specific metadata conf
        :param key: A RSA key to be used for encryption.
        :param idp_conf: idp_conf see IdpProxy/idp_conf.example.py
        :param xmlsec_path:
        :raise:
        """
        if (conf is None) or (key is None):
Exemplo n.º 58
0
    xmlsec_path = '/usr/bin/xmlsec1'


ONTS = {
    saml.NAMESPACE: saml,
    mdui.NAMESPACE: mdui,
    mdattr.NAMESPACE: mdattr,
    dri.NAMESPACE: dri,
    ui.NAMESPACE: ui,
    idpdisc.NAMESPACE: idpdisc,
    md.NAMESPACE: md,
    xmldsig.NAMESPACE: xmldsig,
    xmlenc.NAMESPACE: xmlenc
}

ATTRCONV = ac_factory("attributemaps")

METADATACONF = {
    "1": {
        "local": ["swamid-1.0.xml"]
    },
    "2": {
        "local": ["InCommon-metadata.xml"]
    },
    "3": {
        "local": ["extended.xml"]
    },
    "7": {
        "local": ["metadata_sp_1.xml", "InCommon-metadata.xml"],
        "remote": [{"url": "https://kalmar2.org/simplesaml/module.php/aggregator/?id=kalmarcentral2&set=saml2",
                    "cert": "kalmar2.pem"}]
Exemplo n.º 59
0
"""
A script that imports and verifies metadata and stores it in a pysaml2 format
"""

MDIMPORT = {
    "swamid": {
        "url": "https://kalmar2.org/simplesaml/module.php/aggregator/?id=kalmarcentral2&set=saml2",
        "cert":"kalmar2.pem"
    },
#    "incommon": {
#        "url": "file://InCommon-metadata.xml"
#    }
}

ATTRCONV = ac_factory("attributemaps")

def _eval(val):
    if isinstance(val, basestring):
        val = val.strip()
        if not val:
            return None
        else:
            return val
    elif isinstance(val, dict) or isinstance(val, SamlBase):
        return to_dict(val)
    elif isinstance(val, list):
        lv = []
        for v in val:
            if isinstance(v, dict) or isinstance(v, SamlBase):
                lv.append(to_dict(v))
Exemplo n.º 60
0
from saml2.attribute_converter import ac_factory, AttributeConverterNOOP

from pytest import raises

from saml2.extension import mdui
from saml2.extension import idpdisc
from saml2.extension import dri
from saml2.extension import mdattr
from saml2 import saml
from saml2 import xmldsig
from saml2 import xmlenc

from pathutils import full_path

ONTS = [saml, mdui, mdattr, dri, idpdisc, md, xmldsig, xmlenc]
ATTRCONV = ac_factory(full_path("attributemaps"))
sec_config = config.Config()

METADATACONF = {
    "1": [{
        "class": "saml2.mdstore.MetaDataFile",
        "metadata": [(full_path("swamid-2.0.xml"), )],
    }],
}


def _eq(l1, l2):
    return set(l1) == set(l2)


gn = to_dict(