Esempio n. 1
0
def as_setup(jconf):

    _module = importlib.import_module('oic.utils.authn.user')
    ab = AuthnBroker()
    for _id, authn in jconf["authn"].items():
        cls = getattr(_module, authn["class"])
        if "template_lookup" in authn["kwargs"]:
            authn["kwargs"]["template_lookup"] = lookup(jconf["template_root"])

        ci = cls(None, **authn["kwargs"])
        ab.add(_id, ci, authn["level"], authn["authn_authority"])

    _base = jconf["configuration"]["issuer"]
    cauth = dict([(x, CLIENT_AUTHN_METHOD[x]) for x in jconf["client_auth_methods"]])

    return {
        "name": _base,
        "sdb": {},
        "cdb": {},
        "authn_broker": ab,
        "authz": Implicit("PERMISSION"),
        "client_authn": verify_client,
        "symkey": "1234567890123456",
        "client_authn_methods": cauth,
        "client_info_url": jconf["client_info_url"],
        "default_acr": jconf["default_acr"],
        "keyjar": None
        }
Esempio n. 2
0
def as_setup(jconf):

    _module = importlib.import_module('oic.utils.authn.user')
    ab = AuthnBroker()
    for _id, authn in jconf["authn"].items():
        cls = getattr(_module, authn["class"])
        if "template_lookup" in authn["kwargs"]:
            authn["kwargs"]["template_lookup"] = lookup(jconf["template_root"])

        ci = cls(None, **authn["kwargs"])
        ab.add(_id, ci, authn["level"], authn["authn_authority"])

    _base = jconf["configuration"]["issuer"]
    cauth = dict([(x, CLIENT_AUTHN_METHOD[x])
                  for x in jconf["client_auth_methods"]])

    return {
        "name": _base,
        "sdb": {},
        "cdb": {},
        "authn_broker": ab,
        "authz": Implicit("PERMISSION"),
        "client_authn": verify_client,
        "symkey": "1234567890123456",
        "client_authn_methods": cauth,
        "client_info_url": jconf["client_info_url"],
        "default_acr": jconf["default_acr"],
        "keyjar": None
    }
Esempio n. 3
0
def create_authn_broker(config, lookup, password):
    ac = AuthnBroker()
    end_points = config.AUTHENTICATION["UserPassword"]["END_POINTS"]
    full_end_point_paths = ["%s%s" % (config.issuer, ep) for ep in end_points]
    username_password_authn = UsernamePasswordMako(
        None, "login.mako", lookup, password, "%sauthorization" % config.issuer,
        None, full_end_point_paths)

    for authkey, value in config.AUTHENTICATION.items():
        authn = None

        if "UserPassword" == authkey:
            PASSWORD_END_POINT_INDEX = 0
            end_point = config.AUTHENTICATION[authkey]["END_POINTS"][
                PASSWORD_END_POINT_INDEX]
            authn = AuthnIndexedEndpointWrapper(username_password_authn,
                                                PASSWORD_END_POINT_INDEX)
            APP.add_url_rule("/{}".format(end_point), end_point, make_auth_verify(authn.verify),
                             methods=['GET', 'POST'])

        if "JavascriptLogin" == authkey:
            pass
        if "SAML" == authkey:
            pass
        if "SamlPass" == authkey:
            pass
        if "JavascriptPass" == authkey:
            pass

        if authn is not None:
            ac.add(config.AUTHENTICATION[authkey]["ACR"], authn,
                   config.AUTHENTICATION[authkey]["WEIGHT"],
                   "")
    return ac
Esempio n. 4
0
    def test_pkce_verify_256(self, session_db_factory):
        _cli = Client(
            config={"code_challenge": {
                "method": "S256",
                "length": 64
            }})
        args, cv = _cli.add_code_challenge()

        authn_broker = AuthnBroker()
        authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
        _prov = Provider(
            "as",
            session_db_factory("https://connect-op.heroku.com"),
            {},
            authn_broker,
            Implicit(),
            verify_client,
        )

        assert _prov.verify_code_challenge(cv, args["code_challenge"]) is True
        assert _prov.verify_code_challenge(cv, args["code_challenge"],
                                           "S256") is True
        resp = _prov.verify_code_challenge("XXX", args["code_challenge"])
        assert isinstance(resp, Response)
        assert resp.info()["status_code"] == 401
Esempio n. 5
0
def test_pkce_verify_512():
    _cli = Client(config={'code_challenge': {'method': 'S512', 'length': 96}})
    args, cv = _cli.add_code_challenge()

    authn_broker = AuthnBroker()
    authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
    _prov = Provider("as", sdb.SessionDB(SERVER_INFO["issuer"]), CDB,
                     authn_broker, Implicit(), verify_client)

    assert _prov.verify_code_challenge(cv, args['code_challenge'],
                                       'S512') is True
Esempio n. 6
0
def setup_authentication_methods(authn_config, template_env):
    """Add all authentication methods specified in the configuration."""
    routing = {}
    ac = AuthnBroker()
    for authn_method in authn_config:
        cls = make_cls_from_name(authn_method["class"])
        instance = cls(template_env=template_env, **authn_method["kwargs"])
        ac.add(authn_method["acr"], instance)
        routing[instance.url_endpoint] = VerifierMiddleware(instance)

    return ac, routing
Esempio n. 7
0
def test_pkce_verify_512():
    _cli = Client(config={'code_challenge': {'method': 'S512', 'length': 96}})
    args, cv = _cli.add_code_challenge()

    authn_broker = AuthnBroker()
    authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
    _prov = Provider("as",
                     sdb.SessionDB(SERVER_INFO["issuer"]), CDB,
                     authn_broker, Implicit(), verify_client)

    assert _prov.verify_code_challenge(cv, args['code_challenge'],'S512') is True
Esempio n. 8
0
def setup_authentication_methods(authn_config, template_env):
    """Add all authentication methods specified in the configuration."""
    routing = {}
    ac = AuthnBroker()
    for authn_method in authn_config:
        cls = make_cls_from_name(authn_method["class"])
        instance = cls(template_env=template_env, **authn_method["kwargs"])
        ac.add(authn_method["acr"], instance)
        routing[instance.url_endpoint] = VerifierMiddleware(instance)

    return ac, routing
def provider(tmpdir):
    client_db_path = os.path.join(tmpdir.strpath, "client_db")
    cdb = shelve_wrapper.open(client_db_path)

    ab = AuthnBroker()
    ab.add("dummy", DummyAuthn())

    sdb = SessionDB("https://testprovider.com")

    provider = CourseProvider("https://testprovider.com", sdb, cdb, ab, UserInfo({"user": {}}),
                              AuthzHandling(), None, None)
    return provider
def provider(tmpdir):
    client_db_path = os.path.join(tmpdir.strpath, "client_db")
    cdb = shelve_wrapper.open(client_db_path)

    ab = AuthnBroker()
    ab.add("dummy", DummyAuthn())

    sdb = SessionDB("https://testprovider.com")

    provider = CourseProvider("https://testprovider.com", sdb, cdb, ab,
                              UserInfo({"user": {}}), AuthzHandling(), None,
                              None)
    return provider
def setup():
    with open("config.yaml", 'r') as f:
        config = yaml.load(f)

    issuer = config["baseurl"]

    ac = AuthnBroker()

    authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD,
                                 "{}/authorization".format(issuer))
    ac.add("password", authn)
    URLS.append((r'^verify', make_auth_verify(authn.verify)))

    authz = AuthzHandling()
    client_db_path = os.environ.get("OIDC_CLIENT_DB", "client_db")
    LOGGER.info("Using db: {}".format(client_db_path))
    cdb = shelve_wrapper.open(client_db_path)
    global OAS
    OAS = CourseProvider(issuer, SessionDB(issuer), cdb, ac, None, authz,
                         verify_client, rndstr(16))
    OAS.baseurl = issuer
    OAS.userinfo = UserInfo(config["userdb"])
    # Additional endpoints the OpenID Connect Provider should answer on
    add_endpoints(ENDPOINTS, ENDPOINT_FUNCS)
    OAS.endpoints = ENDPOINTS

    authn.srv = OAS

    try:
        OAS.cookie_ttl = config["cookie_ttl"]
    except KeyError:
        pass

    try:
        OAS.cookie_name = config["cookie_name"]
    except KeyError:
        pass

    keyjar_init(OAS, config["keys"])
    public_keys = []
    for keybundle in OAS.keyjar[""]:
        for key in keybundle.keys():
            public_keys.append(key.serialize())
    public_jwks = {"keys": public_keys}
    filename = "static/jwks.json"
    with open(filename, "w") as f:
        f.write(json.dumps(public_jwks))
    OAS.jwks_uri = "{}/{}".format(OAS.baseurl, filename)

    return config
Esempio n. 12
0
def authn_setup(config):
    broker = AuthnBroker()

    # Which methods to use is defined in the configuration file
    for authkey, method_conf in config.AUTHN_METHOD.items():
        try:
            func = AUTH_METHOD[authkey]
        except KeyError:
            pass
        else:
            broker.add(method_conf["ACR"], func(method_conf),
                       method_conf["WEIGHT"], method_conf["URL"])

    return broker
def setup():
    with open("config.yaml", 'r') as f:
        config = yaml.load(f)

    issuer = config["baseurl"]

    ac = AuthnBroker()

    authn = UsernamePasswordMako(
            None, "login.mako", LOOKUP, PASSWD, "{}/authorization".format(issuer))
    ac.add("password", authn)
    URLS.append((r'^verify', make_auth_verify(authn.verify)))

    authz = AuthzHandling()
    client_db_path = os.environ.get("OIDC_CLIENT_DB", "client_db")
    LOGGER.info("Using db: {}".format(client_db_path))
    cdb = shelve_wrapper.open(client_db_path)
    global OAS
    OAS = CourseProvider(issuer, SessionDB(issuer), cdb, ac, None,
                         authz, verify_client, rndstr(16))
    OAS.baseurl = issuer
    OAS.userinfo = UserInfo(config["userdb"])
    # Additional endpoints the OpenID Connect Provider should answer on
    add_endpoints(ENDPOINTS, ENDPOINT_FUNCS)
    OAS.endpoints = ENDPOINTS

    authn.srv = OAS

    try:
        OAS.cookie_ttl = config["cookie_ttl"]
    except KeyError:
        pass

    try:
        OAS.cookie_name = config["cookie_name"]
    except KeyError:
        pass

    keyjar_init(OAS, config["keys"])
    public_keys = []
    for keybundle in OAS.keyjar[""]:
        for key in keybundle.keys():
            public_keys.append(key.serialize())
    public_jwks = {"keys": public_keys}
    filename = "static/jwks.json"
    with open(filename, "w") as f:
        f.write(json.dumps(public_jwks))
    OAS.jwks_uri = "{}/{}".format(OAS.baseurl, filename)

    return config
Esempio n. 14
0
    def test_pkce_verify_512(self, session_db_factory):
        _cli = Client(config={'code_challenge': {'method': 'S512', 'length': 96}})
        args, cv = _cli.add_code_challenge()

        authn_broker = AuthnBroker()
        authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
        _prov = Provider("as",
                         session_db_factory('https://connect-op.heroku.com'), {},
                         authn_broker, Implicit(), verify_client)

        assert _prov.verify_code_challenge(cv, args['code_challenge'], 'S512') is True
        resp = _prov.verify_code_challenge('XXX', args['code_challenge'])
        assert isinstance(resp, Response)
        assert resp.info()['status_code'] == 401
Esempio n. 15
0
def authn_setup(config):
    broker = AuthnBroker()

    # Which methods to use is defined in the configuration file
    for authkey, method_conf in config.AUTHN_METHOD.items():
        try:
            func = AUTH_METHOD[authkey]
        except KeyError:
            pass
        else:
            broker.add(method_conf["ACR"], func(method_conf),
                       method_conf["WEIGHT"], method_conf["URL"])

    return broker
Esempio n. 16
0
    def test_pkce_verify_512(self, session_db_factory):
        _cli = Client(config={'code_challenge': {'method': 'S512', 'length': 96}})
        args, cv = _cli.add_code_challenge()

        authn_broker = AuthnBroker()
        authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
        _prov = Provider("as",
                         session_db_factory('https://connect-op.heroku.com'), {},
                         authn_broker, Implicit(), verify_client)

        assert _prov.verify_code_challenge(cv, args['code_challenge'], 'S512') is True
        resp = _prov.verify_code_challenge('XXX', args['code_challenge'])
        assert isinstance(resp, Response)
        assert resp.info()['status_code'] == 401
Esempio n. 17
0
def test_pkce_verify_256(session_db_factory):
    _cli = Client(config={'code_challenge': {'method': 'S256', 'length': 64}})
    args, cv = _cli.add_code_challenge()

    authn_broker = AuthnBroker()
    authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
    _prov = Provider("as", session_db_factory(SERVER_INFO["issuer"]), CDB,
                     authn_broker, Implicit(), verify_client)

    assert _prov.verify_code_challenge(cv, args['code_challenge']) is True
    assert _prov.verify_code_challenge(cv, args['code_challenge'],
                                       'S256') is True
    resp = _prov.verify_code_challenge('XXX', args['code_challenge'])
    assert isinstance(resp, Response)
    assert resp.info()['status_code'] == 401
Esempio n. 18
0
    def create_provider(self):
        authn_broker = AuthnBroker()
        authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))

        self.provider = Provider("pyoicserv",
                                 sdb.SessionDB(
                                     TestProvider.SERVER_INFO["issuer"]),
                                 TestProvider.CDB,
                                 authn_broker, Implicit(),
                                 verify_client,
                                 client_info_url="https://example.com/as",
                                 client_authn_methods={
                                     "client_secret_post": ClientSecretPost,
                                     "client_secret_basic": ClientSecretBasic,
                                     "bearer_header": BearerHeader})
Esempio n. 19
0
def test_pkce_verify_256(session_db_factory):
    _cli = Client(config={'code_challenge': {'method': 'S256', 'length': 64}})
    args, cv = _cli.add_code_challenge()

    authn_broker = AuthnBroker()
    authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
    _prov = Provider("as",
                     session_db_factory(SERVER_INFO["issuer"]), CDB,
                     authn_broker, Implicit(), verify_client)

    assert _prov.verify_code_challenge(cv, args['code_challenge']) is True
    assert _prov.verify_code_challenge(cv, args['code_challenge'], 'S256') is True
    resp = _prov.verify_code_challenge('XXX', args['code_challenge'])
    assert isinstance(resp, Response)
    assert resp.info()['status_code'] == 401
Esempio n. 20
0
def init_fed_op(cnf):
    with open(cnf["PROVIDER_CONFIG"]) as f:
        provider_config = yaml.safe_load(f)

    root_key = keyrep(provider_config["root_key_jwk"])
    federation_keys = [keyrep(jwk) for jwk in provider_config["federations_jwk"]]

    authn_broker = AuthnBroker()

    name = "https://" + cnf["SERVER_NAME"]
    user = "******"
    authn_broker.add("password", NoAuthn(None, user))
    provider = Provider(name, SessionDB(name), {}, authn_broker, None, AuthzHandling(), verify_client, None)

    return OP(name, root_key, provider_config["software_statements"], federation_keys, name + "/signed_jwks",
              provider, name + "/jwks")
Esempio n. 21
0
    def test_password_grant_type_no_authn(self):
        # Set a blank AuthnBroker
        self.provider.authn_broker = AuthnBroker()
        self.provider.set_token_policy('client1', {'grant_type': ['password']})
        areq = ROPCAccessTokenRequest(grant_type='password', username='******', password='******')
        areq['client_id'] = 'client1'  # Token endpoint would fill that in based on client_authn
        resp = self.provider.password_grant_type(areq)

        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert atr['error'] == 'invalid_grant'
Esempio n. 22
0
def main(base, cookie_handler):
    as_conf = {
        "version": "1.0",
        "issuer": base,
        "pat_profiles_supported": ["bearer"],
        "aat_profiles_supported": ["bearer"],
        "rpt_profiles_supported": ["bearer"],
        "pat_grant_types_supported": ["authorization_code"],
        "aat_grant_types_supported": ["authorization_code"],
        "claim_profiles_supported": ["openid"],
        #"dynamic_client_endpoint": "%s/dynamic_client_endpoint" % BASE,
        #"token_endpoint": "%s/token_endpoint" % BASE,
        #"user_endpoint": "%s/user_endpoint" % BASE,
        #"resource_set_registration_endpoint": "%s/rsr_endpoint" % BASE,
        #"introspection_endpoint": "%s/introspection_endpoint" % BASE,
        #"permission_registration_endpoint": "%s/pr_endpoint" % BASE,
        #"rpt_endpoint": "%s/rpt_endpoint" % BASE,
        #"authorization_request_endpoint": "%s/ar_endpoint" % BASE,
        #"userinfo_endpoint": "%s/user_info_endpoint" % BASE
        # ------------ The OIDC provider config -----------------------
    }

    base_url = "http://%s" % socket.gethostname()
    ab = AuthnBroker()
    ab.add("linda", DummyAuthn(None, "linda"))
    #AB.add("hans", DummyAuthn(None, "*****@*****.**"))
    ab.add(
        "UserPwd",
        UsernamePasswordMako(None, "login2.mako", LOOKUP, PASSWD,
                             "%s/authorization" % base), 10, base_url)
    ab.add("BasicAuthn", BasicAuthnExtra(None, PASSWD), 10, base_url)

    AUTHZSRV = authzsrv.OidcDynRegUmaAS(base,
                                        SessionDB(base_url),
                                        CDB,
                                        ab,
                                        USERINFO,
                                        AUTHZ,
                                        verify_client,
                                        "1234567890",
                                        keyjar=None,
                                        configuration=as_conf,
                                        base_url=base)

    cookie_handler.init_srv(AUTHZSRV)
    jwks = keyjar_init(AUTHZSRV, KEYS, "a%d")

    fp = open("static/jwk_as.json", "w")
    fp.write(json.dumps(jwks))
    fp.close()

    return AUTHZSRV
Esempio n. 23
0
def test_pkce_verify_512(session_db_factory):
    _cli = Client(config={"code_challenge": {"method": "S512", "length": 96}})
    args, cv = _cli.add_code_challenge()

    authn_broker = AuthnBroker()
    authn_broker.add("UNDEFINED", DummyAuthn(None, "username"))
    _prov = Provider(
        "as",
        session_db_factory(SERVER_INFO["issuer"]),
        CDB,
        authn_broker,
        Implicit(),
        verify_client,
    )

    assert _prov.verify_code_challenge(cv, args["code_challenge"],
                                       "S512") is True
    resp = _prov.verify_code_challenge("XXX", args["code_challenge"])
    assert isinstance(resp, Response)
    assert resp.info()["status_code"] == 401
Esempio n. 24
0
def main(base, cookie_handler):
    as_conf = {
        "version": "1.0",
        "issuer": base,
        "pat_profiles_supported": ["bearer"],
        "aat_profiles_supported": ["bearer"],
        "rpt_profiles_supported": ["bearer"],
        "pat_grant_types_supported": ["authorization_code"],
        "aat_grant_types_supported": ["authorization_code"],
        "claim_profiles_supported": ["openid"],
        #"dynamic_client_endpoint": "%s/dynamic_client_endpoint" % BASE,
        #"token_endpoint": "%s/token_endpoint" % BASE,
        #"user_endpoint": "%s/user_endpoint" % BASE,
        #"resource_set_registration_endpoint": "%s/rsr_endpoint" % BASE,
        #"introspection_endpoint": "%s/introspection_endpoint" % BASE,
        #"permission_registration_endpoint": "%s/pr_endpoint" % BASE,
        #"rpt_endpoint": "%s/rpt_endpoint" % BASE,
        #"authorization_request_endpoint": "%s/ar_endpoint" % BASE,
        #"userinfo_endpoint": "%s/user_info_endpoint" % BASE
        # ------------ The OIDC provider config -----------------------

    }

    base_url = "http://%s" % socket.gethostname()
    ab = AuthnBroker()
    ab.add("linda", DummyAuthn(None, "linda"))
    ab.add("hans", DummyAuthn(None, "hans"))

    AUTHZSRV = FakeUmaAs(
        base, SessionDB(base_url), CDB, ab, USERINFO, AUTHZ,
        verify_client, "1234567890", keyjar=None, configuration=as_conf,
        base_url=base)

    cookie_handler.init_srv(AUTHZSRV)
    jwks = keyjar_init(AUTHZSRV, KEYS, "a%d")

    fp = open("static/jwk_as.json", "w")
    fp.write(json.dumps(jwks))
    fp.close()

    return AUTHZSRV
Esempio n. 25
0
    def test_password_grant_type_no_authn(self):
        # Set a blank AuthnBroker
        self.provider.authn_broker = AuthnBroker()
        self.provider.set_token_policy("client1", {"grant_type": ["password"]})
        areq = ROPCAccessTokenRequest(grant_type="password",
                                      username="******",
                                      password="******")
        areq[
            "client_id"] = "client1"  # Token endpoint would fill that in based on client_authn
        resp = self.provider.password_grant_type(areq)

        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert atr["error"] == "invalid_grant"
Esempio n. 26
0
    def test(self):
        ac = AuthnBroker()
        issuer = "https://example.com/op"
        CAS_SERVER = ""
        SERVICE_URL = ""

        LDAP = {
            "uri": "ldaps://ldap.umu.se",
            "base": "dc=umu, dc=se",
            "filter_pattern": "(uid=%s)",
            "user": "",
            "passwd": "",
            "attr": ["eduPersonScopedAffiliation", "eduPersonAffiliation"],
        }

        LDAP_EXTRAVALIDATION = {
            "verify_attr": "eduPersonAffiliation",
            "verify_attr_valid": ["employee", "staff", "student"],
        }
        LDAP_EXTRAVALIDATION.update(LDAP)

        ac.add(
            PASSWORD,
            UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD,
                                 "%s/authorization" % issuer),
            10,
            "http://%s" % socket.gethostname(),
        )

        try:
            ac.add(
                PASSWORD,
                CasAuthnMethod(
                    None,
                    CAS_SERVER,
                    SERVICE_URL,
                    "%s/authorization" % issuer,
                    UserLDAPMemberValidation(**LDAP_EXTRAVALIDATION),
                ),
                20,
                "http://%s" % socket.gethostname(),
            )
        except Exception:
            assert len(ac) == 1
        else:
            assert len(ac) == 2

            res = ac.pick(PASSWORD)

            assert res
            # list of two 2-tuples
            assert len(res) == 2
            assert res[0][0].__class__.__name__ == "CasAuthnMethod"
            assert res[1][0].__class__.__name__ == "UsernamePasswordMako"
Esempio n. 27
0
File: uma_as.py Progetto: rohe/pyuma
def main(base, cookie_handler):
    as_conf = {
        "version": "1.0",
        "issuer": base,
        "pat_profiles_supported": ["bearer"],
        "aat_profiles_supported": ["bearer"],
        "rpt_profiles_supported": ["bearer"],
        "pat_grant_types_supported": ["authorization_code"],
        "aat_grant_types_supported": ["authorization_code"],
        "claim_profiles_supported": ["openid"],
        # "dynamic_client_endpoint": "%s/dynamic_client_endpoint" % BASE,
        # "token_endpoint": "%s/token_endpoint" % BASE,
        # "user_endpoint": "%s/user_endpoint" % BASE,
        # "resource_set_registration_endpoint": "%s/rsr_endpoint" % BASE,
        # "introspection_endpoint": "%s/introspection_endpoint" % BASE,
        # "permission_registration_endpoint": "%s/pr_endpoint" % BASE,
        # "rpt_endpoint": "%s/rpt_endpoint" % BASE,
        # "authorization_request_endpoint": "%s/ar_endpoint" % BASE,
        # "userinfo_endpoint": "%s/user_info_endpoint" % BASE
        # ------------ The OIDC provider config -----------------------
    }

    base_url = "http://%s" % socket.gethostname()
    ab = AuthnBroker()
    ab.add("linda", DummyAuthn(None, "linda"))
    # AB.add("hans", DummyAuthn(None, "*****@*****.**"))
    ab.add(
        "UserPwd", UsernamePasswordMako(None, "login2.mako", LOOKUP, PASSWD, "%s/authorization" % base), 10, base_url
    )
    ab.add("BasicAuthn", BasicAuthnExtra(None, PASSWD), 10, base_url)

    AS = authz_srv.OidcDynRegUmaAS(
        base,
        SessionDB(base_url),
        CDB,
        ab,
        USERINFO,
        AUTHZ,
        verify_client,
        "1234567890",
        keyjar=None,
        configuration=as_conf,
        base_url=base,
    )

    cookie_handler.init_srv(AS)
    jwks = keyjar_init(AS, KEYS, "a%d")

    fp = open("static/jwk_as.json", "w")
    fp.write(json.dumps(jwks))
    fp.close()

    return AUTHZSRV
Esempio n. 28
0
    def __init__(self, config, issuer):
        self.config = config
        self.issuer = issuer
        self.root = None
        self.lookup = None
        self.username_password_authn = None
        self.saml_authn = None
        self.javascript_login_authn = None
        self.urls = []
        self.ac = AuthnBroker()
        self.authn = False

        end_points = config.AUTHENTICATION["UserPassword"]["END_POINTS"]
        self.full_end_point_paths = [
            "{}{}".format(self.issuer, ep) for ep in end_points]

        self.auth_methods = {
            "UserPassword": self.user_password,
            # "JavascriptLogin": self.javascript_login,
            # "SAML": self.saml_login,
            # "SamlPass": self.saml_pass_login,
            # "JavascriptPass": self.javascript_passw_login
        }
Esempio n. 29
0
def main(base, cookie_handler):
    as_conf = {
        "version": "1.0",
        "issuer": base,
        "pat_profiles_supported": ["bearer"],
        "aat_profiles_supported": ["bearer"],
        "rpt_profiles_supported": ["bearer"],
        "pat_grant_types_supported": ["authorization_code"],
        "aat_grant_types_supported": ["authorization_code"],
        "claim_profiles_supported": ["openid"],
        #"dynamic_client_endpoint": "%s/dynamic_client_endpoint" % BASE,
        #"token_endpoint": "%s/token_endpoint" % BASE,
        #"user_endpoint": "%s/user_endpoint" % BASE,
        #"resource_set_registration_endpoint": "%s/rsr_endpoint" % BASE,
        #"introspection_endpoint": "%s/introspection_endpoint" % BASE,
        #"permission_registration_endpoint": "%s/pr_endpoint" % BASE,
        #"rpt_endpoint": "%s/rpt_endpoint" % BASE,
        #"authorization_request_endpoint": "%s/ar_endpoint" % BASE,
        #"userinfo_endpoint": "%s/user_info_endpoint" % BASE
        # ------------ The OIDC provider config -----------------------

    }

    ab = AuthnBroker()
    ab.add("alice", DummyAuthn(None, "alice"))
    ab.add("roger", DummyAuthn(None, "roger"))
    ab.add("UserPwd",
           UsernamePasswordMako(None, "login_as.mako", LOOKUP, PASSWD,
                                "%s/authorization" % base),
           10, "http://%s" % socket.gethostname())
    ab.add("BasicAuthn", BasicAuthnExtra(None, PASSWD), 10,
           "http://%s" % socket.gethostname())

    AUTHZSRV = authzsrv.OAuth2UmaAS(base, SessionDB(), CDB, ab, AUTHZ,
                                    verify_client, "1234567890123456",
                                    keyjar=None,
                                    configuration=as_conf,
                                    base_url=base,
                                    client_info_url="%s/" % base,
                                    client_authn_methods={
                                        "client_secret_post": ClientSecretPost,
                                        "client_secret_basic": ClientSecretBasic,
                                        "bearer_header": BearerHeader})

    cookie_handler.init_srv(AUTHZSRV)
    init_keyjar(AUTHZSRV, KEYS, "static/jwk_as.json")

    return AUTHZSRV
Esempio n. 30
0
def main(base, cookie_handler):
    as_conf = {
        "version": "1.0",
        "issuer": base,
        "pat_profiles_supported": ["bearer"],
        "aat_profiles_supported": ["bearer"],
        "rpt_profiles_supported": ["bearer"],
        "pat_grant_types_supported": ["authorization_code"],
        "aat_grant_types_supported": ["authorization_code"],
        "claim_profiles_supported": ["openid"],
        #"dynamic_client_endpoint": "%s/dynamic_client_endpoint" % BASE,
        #"token_endpoint": "%s/token_endpoint" % BASE,
        #"user_endpoint": "%s/user_endpoint" % BASE,
        #"resource_set_registration_endpoint": "%s/rsr_endpoint" % BASE,
        #"introspection_endpoint": "%s/introspection_endpoint" % BASE,
        #"permission_registration_endpoint": "%s/pr_endpoint" % BASE,
        #"rpt_endpoint": "%s/rpt_endpoint" % BASE,
        #"authorization_request_endpoint": "%s/ar_endpoint" % BASE,
        #"userinfo_endpoint": "%s/user_info_endpoint" % BASE
        # ------------ The OIDC provider config -----------------------
    }

    base_url = "http://%s" % socket.gethostname()
    ab = AuthnBroker()
    ab.add("linda", DummyAuthn(None, "linda"))
    ab.add("hans", DummyAuthn(None, "hans"))

    AUTHZSRV = FakeUmaAs(base,
                         SessionDB(base_url),
                         CDB,
                         ab,
                         USERINFO,
                         AUTHZ,
                         verify_client,
                         "1234567890",
                         keyjar=None,
                         configuration=as_conf,
                         base_url=base)

    cookie_handler.init_srv(AUTHZSRV)
    jwks = keyjar_init(AUTHZSRV, KEYS, "a%d")

    fp = open("static/jwk_as.json", "w")
    fp.write(json.dumps(jwks))
    fp.close()

    return AUTHZSRV
Esempio n. 31
0
    def test(self):
        ac = AuthnBroker()
        issuer = "https://example.com/op"
        CAS_SERVER = ""
        SERVICE_URL = ""

        LDAP = {
            "uri": "ldaps://ldap.umu.se",
            "base": "dc=umu, dc=se",
            "filter_pattern": "(uid=%s)",
            "user": "",
            "passwd": "",
            "attr": ["eduPersonScopedAffiliation", "eduPersonAffiliation"],
        }

        LDAP_EXTRAVALIDATION = {
            "verify_attr": "eduPersonAffiliation",
            "verify_attr_valid": ['employee', 'staff', 'student']
        }
        LDAP_EXTRAVALIDATION.update(LDAP)

        ac.add(PASSWORD,
               UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD,
                                    "%s/authorization" % issuer),
               10, "http://%s" % socket.gethostname())

        try:
            ac.add(PASSWORD,
                   CasAuthnMethod(
                       None, CAS_SERVER, SERVICE_URL,
                       "%s/authorization" % issuer,
                       UserLDAPMemberValidation(**LDAP_EXTRAVALIDATION)),
                   20, "http://%s" % socket.gethostname())
        except Exception:
            assert len(ac) == 1
        else:
            assert len(ac) == 2

            res = ac.pick(PASSWORD)

            assert res
            # list of two 2-tuples
            assert len(res) == 2
            assert res[0][0].__class__.__name__ == "CasAuthnMethod"
            assert res[1][0].__class__.__name__ == "UsernamePasswordMako"
Esempio n. 32
0
def main_setup(args, lookup=None):
    sys.path.insert(0, ".")
    config = importlib.import_module(args.config)
    config.issuer = config.issuer % args.port
    config.SERVICE_URL = config.SERVICE_URL % args.port

    # Client data base
    cdb = shelve.open(config.CLIENT_DB, writeback=True)

    ac = AuthnBroker()

    for authkey, value in list(config.AUTHENTICATION.items()):
        authn = None
        # if "UserPassword" == authkey:
        #     from oic.utils.authn.user import UsernamePasswordMako
        #     authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD,
        #                                  "authorization")

        if "NoAuthn" == authkey:
            from oic.utils.authn.user import NoAuthn

            authn = NoAuthn(None, user=config.AUTHENTICATION[authkey]["user"])

        if authn is not None:
            ac.add(config.AUTHENTICATION[authkey]["ACR"], authn,
                   config.AUTHENTICATION[authkey]["WEIGHT"])

    # dealing with authorization
    authz = AuthzHandling()

    if config.USERINFO == "SIMPLE":
        # User info is a simple dictionary in this case statically defined in
        # the configuration file
        userinfo = UserInfo(config.USERDB)
    else:
        userinfo = None

    com_args = {
        "name": config.issuer,
        "baseurl": config.baseurl,
        "cdb": cdb,
        "authn_broker": ac,
        "userinfo": userinfo,
        "authz": authz,
        "client_authn": verify_client,
        "symkey": config.SYM_KEY,
        "template_lookup": lookup,
        "template": {
            "form_post": "form_response.mako"
        },
        "jwks_name": "./static/jwks_{}.json"
    }

    # Should I care about verifying the certificates used by other entities
    if args.insecure:
        com_args["verify_ssl"] = False
    else:
        com_args["verify_ssl"] = True

    try:
        assert os.path.isfile(config.SERVER_CERT)
        assert os.path.isfile(config.SERVER_KEY)
        com_args['client_cert'] = (config.SERVER_CERT, config.SERVER_KEY)
    except AttributeError:
        pass
    except AssertionError:
        print("Can't access client certificate and/or client secret")
        exit(-1)

    op_arg = {}

    try:
        op_arg["cookie_ttl"] = config.COOKIETTL
    except AttributeError:
        pass

    try:
        op_arg["cookie_name"] = config.COOKIENAME
    except AttributeError:
        pass

    # print URLS
    if args.debug:
        op_arg["debug"] = True

    # All endpoints the OpenID Connect Provider should answer on
    add_endpoints(ENDPOINTS)
    op_arg["endpoints"] = ENDPOINTS

    if args.port == 80:
        _baseurl = config.baseurl
    else:
        if config.baseurl.endswith("/"):
            config.baseurl = config.baseurl[:-1]
        _baseurl = "%s:%d" % (config.baseurl, args.port)

    if not _baseurl.endswith("/"):
        _baseurl += "/"

    op_arg["baseurl"] = _baseurl

    # Add own keys for signing/encrypting JWTs
    try:
        # a throw-away OP used to do the initial key setup
        _op = Provider(sdb=SessionDB(com_args["baseurl"]), **com_args)
        jwks = keyjar_init(_op, config.keys)
    except KeyError:
        pass
    else:
        op_arg["jwks"] = jwks
        op_arg['keyjar'] = _op.keyjar
        #op_arg["keys"] = config.keys

    try:
        op_arg["marg"] = multi_keys(com_args, config.multi_keys)
    except AttributeError as err:
        pass

    return com_args, op_arg, config
Esempio n. 33
0
def main_setup(args, lookup=None):
    sys.path.insert(0, ".")
    config = importlib.import_module(args.config)
    config.issuer = config.issuer % args.port
    config.SERVICE_URL = config.SERVICE_URL % args.port

    # Client data base
    cdb = shelve.open(config.CLIENT_DB, writeback=True)

    ac = AuthnBroker()

    for authkey, value in list(config.AUTHENTICATION.items()):
        authn = None
        # if "UserPassword" == authkey:
        #     from oic.utils.authn.user import UsernamePasswordMako
        #     authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD,
        #                                  "authorization")

        if "NoAuthn" == authkey:
            from oic.utils.authn.user import NoAuthn

            authn = NoAuthn(None, user=config.AUTHENTICATION[authkey]["user"])

        if authn is not None:
            ac.add(config.AUTHENTICATION[authkey]["ACR"], authn,
                   config.AUTHENTICATION[authkey]["WEIGHT"])

    # dealing with authorization
    authz = AuthzHandling()

    if config.USERINFO == "SIMPLE":
        # User info is a simple dictionary in this case statically defined in
        # the configuration file
        userinfo = UserInfo(config.USERDB)
    else:
        userinfo = None

    com_args = {
        "name": config.issuer,
        "baseurl": config.baseurl,
        "cdb": cdb,
        "authn_broker": ac,
        "userinfo": userinfo,
        "authz": authz,
        "client_authn": verify_client,
        "symkey": config.SYM_KEY,
        "template_lookup": lookup,
        "template": {"form_post": "form_response.mako"},
        "jwks_name": "./static/jwks_{}.json"
    }

    # Should I care about verifying the certificates used by other entities
    if args.insecure:
        com_args["verify_ssl"] = False
    else:
        com_args["verify_ssl"] = True

    try:
        assert os.path.isfile(config.SERVER_CERT)
        assert os.path.isfile(config.SERVER_KEY)
        com_args['client_cert'] = (config.SERVER_CERT, config.SERVER_KEY)
    except AttributeError:
        pass
    except AssertionError:
        print("Can't access client certificate and/or client secret")
        exit(-1)

    op_arg = {}

    try:
        op_arg["cookie_ttl"] = config.COOKIETTL
    except AttributeError:
        pass

    try:
        op_arg["cookie_name"] = config.COOKIENAME
    except AttributeError:
        pass

    # print URLS
    if args.debug:
        op_arg["debug"] = True

    # All endpoints the OpenID Connect Provider should answer on
    add_endpoints(ENDPOINTS)
    op_arg["endpoints"] = ENDPOINTS

    if args.port == 80:
        _baseurl = config.baseurl
    else:
        if config.baseurl.endswith("/"):
            config.baseurl = config.baseurl[:-1]
        _baseurl = "%s:%d" % (config.baseurl, args.port)

    if not _baseurl.endswith("/"):
        _baseurl += "/"

    op_arg["baseurl"] = _baseurl

    # Add own keys for signing/encrypting JWTs
    try:
        # a throw-away OP used to do the initial key setup
        _op = Provider(sdb=SessionDB(com_args["baseurl"]), **com_args)
        jwks = keyjar_init(_op, config.keys)
    except KeyError:
        pass
    else:
        op_arg["jwks"] = jwks
        op_arg['keyjar'] = _op.keyjar
        #op_arg["keys"] = config.keys

    try:
        op_arg["marg"] = multi_keys(com_args, config.multi_keys)
    except AttributeError as err:
        pass

    return com_args, op_arg, config
Esempio n. 34
0
}

USERNAME = "******"
USERDB = {
    USERNAME: {
        "name": "Linda Lindgren",
        "nickname": "Linda",
        "email": "*****@*****.**",
        "verified": True,
        "sub": "username"
    }
}

USERINFO = UserInfo(USERDB)

AUTHN_BROKER = AuthnBroker()
AUTHN_BROKER.add("UNDEFINED", DummyAuthn(None, USERNAME))

AUTHZ = AuthzHandling()
SYMKEY = rndstr(16)  # symmetric key used to encrypt cookie info


class FakeOP:
    STATE = "12345678"

    def __init__(self):
        op_base_url = TestConfiguration.get_instance().rp_config.OP_URL
        self.provider = Provider(
            "https://op.tester.se/",
            SessionDB(op_base_url),
            CDB,
Esempio n. 35
0
    parser.add_argument('-b', dest='baseurl', help="base url of the OP")
    parser.add_argument(dest="config")
    args = parser.parse_args()

    # Client data base
    cdb = shelve_wrapper.open("client_db")

    sys.path.insert(0, ".")
    config = importlib.import_module(args.config)
    if args.baseurl:
        config.baseurl = args.baseurl

    config.issuer = config.issuer.format(base=config.baseurl, port=args.port)
    config.SERVICE_URL = config.SERVICE_URL.format(issuer=config.issuer)

    ac = AuthnBroker()

    saml_authn = None

    end_points = config.AUTHENTICATION["UserPassword"]["END_POINTS"]
    full_end_point_paths = ["%s%s" % (config.issuer, ep) for ep in end_points]
    username_password_authn = UsernamePasswordMako(
        None, "login.mako", LOOKUP, PASSWD, "%sauthorization" % config.issuer,
        None, full_end_point_paths)

    for authkey, value in config.AUTHENTICATION.items():
        authn = None

        if "UserPassword" == authkey:
            PASSWORD_END_POINT_INDEX = 0
            end_point = config.AUTHENTICATION[authkey]["END_POINTS"][
Esempio n. 36
0

class DummyAuthn(UserAuthnMethod):
    def __init__(self, srv, user):
        UserAuthnMethod.__init__(self, srv)
        self.user = user

    def authenticated_as(self, cookie=None, **kwargs):
        if cookie == "FAIL":
            return None, 0
        else:
            return {"uid": self.user}, time()


# AUTHN = UsernamePasswordMako(None, "login.mako", tl, PASSWD, "authenticated")
AUTHN_BROKER = AuthnBroker()
AUTHN_BROKER.add("UNDEFINED", DummyAuthn(None, "username"))

# dealing with authorization
AUTHZ = AuthzHandling()
SYMKEY = rndstr(16)  # symmetric key used to encrypt cookie info
USERINFO = UserInfo(USERDB)

KEYS = {}
ISSUER = {}
OPERATOR = {}

for entity in ['fo', 'fo1', 'org', 'inter', 'admin', 'ligo', 'op']:
    fname = os.path.join(BASE_PATH, "{}.key".format(entity))
    _keydef = KEYDEFS[:]
    _keydef[0]['key'] = fname
Esempio n. 37
0
    BASE = "http://localhost:%s/" % PORT
    RESOURCE_SERVER = "https://localhost:8089"

    # The UMA AS=C combo
    as_conf = {
        "version": "1.0",
        "issuer": BASE,
        "pat_profiles_supported": ["bearer"],
        "aat_profiles_supported": ["bearer"],
        "rpt_profiles_supported": ["bearer"],
        "pat_grant_types_supported": ["authorization_code"],
        "aat_grant_types_supported": ["authorization_code"],
        "claim_profiles_supported": ["openid"],
    }

    ab = AuthnBroker()
    ab.add("alice", DummyAuthn(None, "alice"))
    ab.add(
        "UserPwd",
        UsernamePasswordMako(None, "login2.mako", LOOKUP, PASSWD,
                             "%s/authorization" % BASE), 10,
        "http://%s" % socket.gethostname())
    ab.add("BasicAuthn", BasicAuthnExtra(None, PASSWD), 10,
           "http://%s" % socket.gethostname())

    AUTHZSRV = AuthorizationServer(BASE,
                                   SessionDB(),
                                   CDB,
                                   ab,
                                   AUTHZ,
                                   verify_client,
Esempio n. 38
0
def as_arg_setup(args, lookup, config):
    if args.port:
        _port = args.port
    else:
        if args.tls:
            _port = 443
        else:
            _port = 80

    if args.path2port:
        # means there is a reverse proxy in front translating
        # path -> port
        p2p_map = read_path2port_map(args.path2port)
        _path = p2p_map[_port]
        if args.xport:
            _issuer = "{base}:{port}/{path}".format(base=config.baseurl,
                                                    port=args.xport,
                                                    path=_path)
            _port = args.xport
        else:
            _issuer = "{base}/{path}".format(base=config.baseurl, path=_path)
    else:  # the old port based
        _path = ''
        _issuer = "{base}:{port}".format(base=config.baseurl, port=_port)
        if args.tls and _issuer.startswith('http://'):
            _issuer = _issuer.replace('http://', 'https://')

    cdb = {}

    ac = AuthnBroker()

    for authkey, value in list(config.AUTHENTICATION.items()):
        authn = None
        # if "UserPassword" == authkey:
        #     from oic.utils.authn.user import UsernamePasswordMako
        #     authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD,
        #                                  "authorization")

        if "NoAuthn" == authkey:
            from oic.utils.authn.user import NoAuthn

            authn = NoAuthn(None, user=config.AUTHENTICATION[authkey]["user"])

        if authn is not None:
            ac.add(config.AUTHENTICATION[authkey]["ACR"], authn,
                   config.AUTHENTICATION[authkey]["WEIGHT"])

    # dealing with authorization
    authz = AuthzHandling()

    if config.USERINFO == "SIMPLE":
        # User info is a simple dictionary in this case statically defined in
        # the configuration file
        userinfo = UserInfo(config.USERDB)
    else:
        userinfo = None

    as_args = {
        "name": _issuer,
        'instance_path': _path,
        'instance_port': _port,
        "cdb": cdb,
        "authn_broker": ac,
        "userinfo": userinfo,
        "authz": authz,
        "client_authn": verify_client,
        "symkey": config.SYM_KEY,
        "template_lookup": lookup,
        "template": {
            "form_post": "form_response.mako"
        },
        "jwks_name": "./static/jwks_{}.json",
        'event_db': Events(),
    }

    try:
        as_args['behavior'] = config.BEHAVIOR
    except AttributeError:
        pass

    com_args = {
        "baseurl": config.baseurl,
    }

    for arg in [
            'name', 'cdb', 'authn_broker', 'userinfo', 'authz', 'template',
            'jwks_name', 'client_authn', 'symkey', 'template_lookup'
    ]:
        com_args[arg] = as_args[arg]

    # Add own keys for signing/encrypting JWTs
    try:
        # a throw-away OP used to do the initial key setup
        _op = Provider(sdb=SessionDB(com_args["baseurl"]), **com_args)
        jwks = keyjar_init(_op, config.keys)
    except KeyError:
        key_arg = {}
    else:
        key_arg = {"jwks": jwks, "keys": config.keys}
        as_args['jwks_name'] = 'static/jwks.json'
        f = open('static/jwks.json', 'w')
        f.write(json.dumps(jwks))
        f.close()

        if args.insecure:
            _op.keyjar.verify_ssl = False
        else:
            _op.keyjar.verify_ssl = True

        as_args['keyjar'] = _op.keyjar
        as_args['sdb'] = SessionDB(
            com_args["baseurl"],
            token_factory=JWTToken('T',
                                   keyjar=_op.keyjar,
                                   lt_pattern={
                                       'code': 3600,
                                       'token': 900
                                   },
                                   iss=com_args['baseurl'],
                                   sign_alg='RS256'),
            refresh_token_factory=JWTToken('R',
                                           keyjar=_op.keyjar,
                                           lt_pattern={'': 24 * 3600},
                                           iss=com_args['baseurl']))

    return as_args, key_arg
Esempio n. 39
0
def main_setup(args, lookup=None):
    sys.path.insert(0, ".")
    config = importlib.import_module(args.config)
    if args.path:
        if config.baseurl.endswith('/'):
            config.issuer = '{}{}/'.format(config.baseurl, args.path)
        else:
            config.issuer = '{}/{}/'.format(config.baseurl, args.path)
    elif args.port and args.port not in [80, 443]:
        if config.baseurl.endswith('/'):
            config.issuer = '{}:{}/'.format(config.baseurl[:-1], args.port)
        else:
            config.issuer = '{}:{}/'.format(config.baseurl, args.port)

    _baseurl = config.issuer

    if not _baseurl.endswith("/"):
        _baseurl += "/"

    com_args = {
        "name": config.issuer,
        "baseurl": _baseurl,
        "client_authn": verify_client,
        "symkey": config.SYM_KEY,
        "template_lookup": lookup,
        "template": {"form_post": "form_response.mako"},
        "jwks_name": "./static/jwks_{}.json"
    }

    # Client data base
    try:
        com_args['cdb'] = InMemoryBCD()
        #com_args['cdb'] = shelve.open(config.CLIENT_DB, writeback=True)
    except AttributeError:
        pass

    try:
        _auth = config.AUTHENTICATION
    except AttributeError:
        pass
    else:
        ab = AuthnBroker()

        for authkey, value in list(_auth.items()):
            authn = None

            if "NoAuthn" == authkey:
                from oic.utils.authn.user import NoAuthn

                authn = NoAuthn(None, user=_auth[authkey]["user"])

            if authn is not None:
                ab.add(_auth[authkey]["ACR"], authn, _auth[authkey]["WEIGHT"])

        com_args['authn_broker'] = ab

        # dealing with authorization
        com_args['authz'] = AuthzHandling()

    try:
        if config.USERINFO == "SIMPLE":
            # User info is a simple dictionary in this case statically defined in
            # the configuration file
            com_args['userinfo'] = UserInfo(config.USERDB)
        else:
            com_args['userinfo'] = None
    except AttributeError:
        pass

    # Should I care about verifying the certificates used by other entities
    if args.insecure:
        com_args["verify_ssl"] = False
    else:
        com_args["verify_ssl"] = True

    try:
        assert os.path.isfile(config.SERVER_CERT)
        assert os.path.isfile(config.SERVER_KEY)
        com_args['client_cert'] = (config.SERVER_CERT, config.SERVER_KEY)
    except AttributeError:
        pass
    except AssertionError:
        print("Can't access client certificate and/or client secret")
        exit(-1)

    op_arg = {}

    try:
        op_arg["cookie_ttl"] = config.COOKIETTL
    except AttributeError:
        pass

    try:
        op_arg["cookie_name"] = config.COOKIENAME
    except AttributeError:
        pass

    # print URLS
    if args.debug:
        op_arg["debug"] = True

    # All endpoints the OpenID Connect Provider should answer on
    add_endpoints(ENDPOINTS)
    op_arg["endpoints"] = ENDPOINTS

    op_arg["baseurl"] = _baseurl

    # Add own keys for signing/encrypting JWTs
    try:
        # a throw-away OP used to do the initial key setup
        _sdb = create_session_db(com_args["baseurl"], 'automover', '430X', {})
        _op = Provider(sdb=_sdb, **com_args)
        jwks = keyjar_init(_op, config.keys)
    except KeyError:
        pass
    else:
        op_arg["jwks"] = jwks
        op_arg['keyjar'] = _op.keyjar
        #op_arg["keys"] = config.keys

    try:
        op_arg["marg"] = multi_keys(com_args, config.multi_keys)
    except AttributeError as err:
        pass

    return com_args, op_arg, config
Esempio n. 40
0
def main_setup(args, lookup=None):
    sys.path.insert(0, ".")
    config = importlib.import_module(args.config)
    if args.path:
        if config.baseurl.endswith('/'):
            config.issuer = '{}{}/'.format(config.baseurl, args.path)
        else:
            config.issuer = '{}/{}/'.format(config.baseurl, args.path)
    elif args.port and args.port not in [80, 443]:
        if config.baseurl.endswith('/'):
            config.issuer = '{}:{}/'.format(config.baseurl[:-1], args.port)
        else:
            config.issuer = '{}:{}/'.format(config.baseurl, args.port)

    _baseurl = config.issuer

    if not _baseurl.endswith("/"):
        _baseurl += "/"

    com_args = {
        "name": config.issuer,
        "baseurl": _baseurl,
        "client_authn": verify_client,
        "symkey": config.SYM_KEY,
        "template_lookup": lookup,
        "template": {
            "form_post": "form_response.mako"
        },
        "jwks_name": "./static/jwks_{}.json"
    }

    # Client data base
    try:
        com_args['cdb'] = shelve.open(config.CLIENT_DB, writeback=True)
    except AttributeError:
        pass

    try:
        _auth = config.AUTHENTICATION
    except AttributeError:
        pass
    else:
        ab = AuthnBroker()

        for authkey, value in list(_auth.items()):
            authn = None

            if "NoAuthn" == authkey:
                from oic.utils.authn.user import NoAuthn

                authn = NoAuthn(None, user=_auth[authkey]["user"])

            if authn is not None:
                ab.add(_auth[authkey]["ACR"], authn, _auth[authkey]["WEIGHT"])

        com_args['authn_broker'] = ab

        # dealing with authorization
        com_args['authz'] = AuthzHandling()

    try:
        if config.USERINFO == "SIMPLE":
            # User info is a simple dictionary in this case statically defined in
            # the configuration file
            com_args['userinfo'] = UserInfo(config.USERDB)
        else:
            com_args['userinfo'] = None
    except AttributeError:
        pass

    # Should I care about verifying the certificates used by other entities
    if args.insecure:
        com_args["verify_ssl"] = False
    else:
        com_args["verify_ssl"] = True

    try:
        assert os.path.isfile(config.SERVER_CERT)
        assert os.path.isfile(config.SERVER_KEY)
        com_args['client_cert'] = (config.SERVER_CERT, config.SERVER_KEY)
    except AttributeError:
        pass
    except AssertionError:
        print("Can't access client certificate and/or client secret")
        exit(-1)

    op_arg = {}

    try:
        op_arg["cookie_ttl"] = config.COOKIETTL
    except AttributeError:
        pass

    try:
        op_arg["cookie_name"] = config.COOKIENAME
    except AttributeError:
        pass

    # print URLS
    if args.debug:
        op_arg["debug"] = True

    # All endpoints the OpenID Connect Provider should answer on
    add_endpoints(ENDPOINTS)
    op_arg["endpoints"] = ENDPOINTS

    op_arg["baseurl"] = _baseurl

    # Add own keys for signing/encrypting JWTs
    try:
        # a throw-away OP used to do the initial key setup
        _sdb = create_session_db(com_args["baseurl"], 'automover', '430X', {})
        _op = Provider(sdb=_sdb, **com_args)
        jwks = keyjar_init(_op, config.keys)
    except KeyError:
        pass
    else:
        op_arg["jwks"] = jwks
        op_arg['keyjar'] = _op.keyjar
        #op_arg["keys"] = config.keys

    try:
        op_arg["marg"] = multi_keys(com_args, config.multi_keys)
    except AttributeError as err:
        pass

    return com_args, op_arg, config
Esempio n. 41
0
        "name": "Hans Granberg",
        "nickname": "Hasse",
        "email": "*****@*****.**",
        "verified": False,
        "sub": "user"
    }
}

URLMAP = {CLIENT_ID: ["https://example.com/authz"]}

PASSWD = {"user": "******"}

ROOT = '../oc3/'
tl = TemplateLookup(directories=[ROOT + 'templates', ROOT + 'htdocs'],
                    module_directory=ROOT + 'modules',
                    input_encoding='utf-8', output_encoding='utf-8')

AUTHN_BROKER = AuthnBroker()
AUTHN_BROKER.add("1", UsernamePasswordMako(None, "login.mako", tl, PASSWD,
                                           "authenticated"))

# dealing with authorization
AUTHZ = AuthzHandling()
SYMKEY = "symmetric key used to encrypt cookie info"
USERINFO = UserInfo(USERDB)

provider_init = Provider("pyoicserv", SessionDB(SERVER_INFO["issuer"]), CDB,
                         AUTHN_BROKER, USERINFO,
                         AUTHZ, verify_client, SYMKEY, urlmap=URLMAP,
                         keyjar=KEYJAR)
Esempio n. 42
0
    parser.add_argument('-X', dest='XpressConnect', action='store_true')
    parser.add_argument('-A', dest='authn_as', default="")
    parser.add_argument('-P', dest='provider_conf')
    parser.add_argument('-k', dest='insecure', action='store_true')
    parser.add_argument(dest="config")
    args = parser.parse_args()

    # Client data base
    cdb = shelve.open("client_db", writeback=True)

    sys.path.insert(0, ".")
    config = importlib.import_module(args.config)
    config.issuer = config.issuer % args.port
    config.SERVICE_URL = config.SERVICE_URL % args.port

    ac = AuthnBroker()

    for authkey, value in config.AUTHORIZATION.items():
        authn = None
        if "CAS" == authkey:
           from oic.utils.authn.user_cas import CasAuthnMethod
           from oic.utils.authn.ldap_member import UserLDAPMemberValidation
           config.LDAP_EXTRAVALIDATION.update(config.LDAP)
           authn = CasAuthnMethod(None, config.CAS_SERVER, config.SERVICE_URL,"%s/authorization" % config.issuer,
                                  UserLDAPMemberValidation(**config.LDAP_EXTRAVALIDATION))
        if "UserPassword" == authkey:
            from oic.utils.authn.user import UsernamePasswordMako
            authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD,
                                         "%s/authorization" % config.issuer)
        if authn is not None:
            ac.add(config.AUTHORIZATION[authkey]["ACR"],
Esempio n. 43
0
    config = importlib.import_module(args.config)

    if args.issuer:
        _issuer = args.issuer[0]
    else:
        if args.port not in [80, 443]:
            _issuer = config.ISSUER + ':{}'.format(args.port)
        else:
            _issuer = config.ISSUER

    if _issuer[-1] != '/':
        _issuer += '/'

    config.SERVICE_URL = config.SERVICE_URL.format(issuer=_issuer)

    ac = AuthnBroker()

    saml_authn = None

    end_points = config.AUTHENTICATION["UserPassword"]["END_POINTS"]
    full_end_point_paths = ["%s%s" % (_issuer, ep) for ep in end_points]
    username_password_authn = UsernamePasswordMako(
        None, "login.mako", LOOKUP, PASSWD, "%sauthorization" % _issuer,
        None, full_end_point_paths)

    _urls = []
    for authkey, value in config.AUTHENTICATION.items():
        authn = None

        if "UserPassword" == authkey:
            PASSWORD_END_POINT_INDEX = 0
Esempio n. 44
0
def main_setup(args, lookup):
    sys.path.insert(0, ".")
    config = importlib.import_module(args.config)
    config.issuer = config.issuer % args.port
    config.SERVICE_URL = config.SERVICE_URL % args.port

    # Client data base
    # cdb = shelve.open(config.CLIENT_DB, writeback=True)
    cdb = {}

    ac = AuthnBroker()

    for authkey, value in list(config.AUTHENTICATION.items()):
        authn = None
        # if "UserPassword" == authkey:
        #     from oic.utils.authn.user import UsernamePasswordMako
        #     authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD,
        #                                  "authorization")

        if "NoAuthn" == authkey:
            from oic.utils.authn.user import NoAuthn

            authn = NoAuthn(None, user=config.AUTHENTICATION[authkey]["user"])

        if authn is not None:
            ac.add(config.AUTHENTICATION[authkey]["ACR"], authn,
                   config.AUTHENTICATION[authkey]["WEIGHT"])

    # dealing with authorization
    authz = AuthzHandling()

    kwargs = {
        "template_lookup": lookup,
        "template": {"form_post": "form_response.mako"},
    }

    if config.USERINFO == "SIMPLE":
        # User info is a simple dictionary in this case statically defined in
        # the configuration file
        userinfo = UserInfo(config.USERDB)
    else:
        userinfo = None

    # Should I care about verifying the certificates used by other entities
    if args.insecure:
        kwargs["verify_ssl"] = False
    else:
        kwargs["verify_ssl"] = True

    uri_schemes = read_uri_schemes('uri-schemes-1.csv')

    as_args = {
        "name": config.issuer,
        "cdb": cdb,
        "authn_broker": ac,
        "userinfo": userinfo,
        "authz": authz,
        "client_authn": verify_client,
        "symkey": config.SYM_KEY,
        "template_lookup": lookup,
        "template": {"form_post": "form_response.mako"},
        "jwks_name": "./static/jwks_{}.json",
        'event_db': Events(),
    }

    com_args = {
        "name": config.issuer,
        # "sdb": SessionDB(config.baseurl),
        "baseurl": config.baseurl,
        "cdb": cdb,
        "authn_broker": ac,
        "userinfo": userinfo,
        "authz": authz,
        "client_authn": verify_client,
        "symkey": config.SYM_KEY,
        "template_lookup": lookup,
        "template": {"form_post": "form_response.mako"},
        "jwks_name": "./static/jwks_{}.json",
        'uri_schemes': uri_schemes
    }

    op_arg = {}

    try:
        op_arg["cookie_ttl"] = config.COOKIETTL
    except AttributeError:
        pass

    try:
        op_arg["cookie_name"] = config.COOKIENAME
    except AttributeError:
        pass

    try:
        as_args['behavior'] = config.BEHAVIOR
    except AttributeError:
        pass

    # print URLS
    if args.debug:
        op_arg["debug"] = True

    if args.port == 80:
        _baseurl = config.baseurl
    else:
        if config.baseurl.endswith("/"):
            config.baseurl = config.baseurl[:-1]
        _baseurl = "%s:%d" % (config.baseurl, args.port)

    if not _baseurl.endswith("/"):
        _baseurl += "/"

    op_arg["baseurl"] = _baseurl

    # Add own keys for signing/encrypting JWTs
    try:
        # a throw-away OP used to do the initial key setup
        _op = Provider(sdb=SessionDB(com_args["baseurl"]), **com_args)
        jwks = keyjar_init(_op, config.keys)
    except KeyError:
        pass
    else:
        op_arg["jwks"] = jwks
        op_arg["keys"] = config.keys

        as_args['jwks_uri'] = '{}{}/jwks.json'.format(_baseurl, 'static')
        as_args['jwks_name'] = 'static/jwks.json'

        f = open('static/jwks.json', 'w')
        f.write(json.dumps(jwks))
        f.close()

        as_args['keyjar'] = _op.keyjar
        as_args['sdb'] = SessionDB(
            com_args["baseurl"],
            token_factory=JWTToken('T', keyjar=_op.keyjar,
                                   lt_pattern={'code': 3600, 'token': 900},
                                   iss=_baseurl,
                                   sign_alg='RS256'),
            refresh_token_factory=JWTToken(
                'R', keyjar=_op.keyjar, lt_pattern={'': 24 * 3600},
                iss=_baseurl)
        )

    try:
        op_arg["marg"] = multi_keys(as_args, config.multi_keys)
    except AttributeError as err:
        pass

    return as_args, op_arg, config
Esempio n. 45
0
    PARSER.add_argument('-b', dest='baseurl', help="base url of the OP")
    PARSER.add_argument(dest="config")
    ARGS = PARSER.parse_args()

    # Client data base
    CDB = shelve_wrapper.open("client_db", writeback=True)

    sys.path.insert(0, ".")
    CONFIG = importlib.import_module(ARGS.config)
    if ARGS.baseurl:
        CONFIG.BASEURL = ARGS.baseurl

    CONFIG.ISSUER = CONFIG.ISSUER.format(base=CONFIG.BASEURL, port=ARGS.port)
    CONFIG.SERVICE_URL = CONFIG.SERVICE_URL.format(issuer=CONFIG.ISSUER)

    AC = AuthnBroker()

    SAML_AUTHN = None

    END_POINTS = CONFIG.AUTHENTICATION["UserPassword"]["END_POINTS"]
    FULL_END_POINT_PATHS = ["%s%s" % (CONFIG.ISSUER, ep) for ep in END_POINTS]
    USERNAME_PASSWORD_AUTHN = UsernamePasswordMako(
        None, "login.mako", LOOKUP, PASSWD, "%sauthorization" % CONFIG.ISSUER,
        None, FULL_END_POINT_PATHS)

    for authkey, value in CONFIG.AUTHENTICATION.items():
        authn = None

        if "UserPassword" == authkey:
            PASSWORD_END_POINT_INDEX = 0
            end_point = CONFIG.AUTHENTICATION[authkey]["END_POINTS"][
Esempio n. 46
0
class AuthSetup(object):
    def __init__(self, config, issuer):
        self.config = config
        self.issuer = issuer
        self.root = None
        self.lookup = None
        self.username_password_authn = None
        self.saml_authn = None
        self.javascript_login_authn = None
        self.urls = []
        self.ac = AuthnBroker()
        self.authn = False

        end_points = config.AUTHENTICATION["UserPassword"]["END_POINTS"]
        self.full_end_point_paths = [
            "{}{}".format(self.issuer, ep) for ep in end_points]

        self.auth_methods = {
            "UserPassword": self.user_password,
            # "JavascriptLogin": self.javascript_login,
            # "SAML": self.saml_login,
            # "SamlPass": self.saml_pass_login,
            # "JavascriptPass": self.javascript_passw_login
        }

    def init_mako(self):
        if self.root is None:
            self.root = self.config.MAKO_ROOT
        if self.lookup is None:
            from mako.lookup import TemplateLookup

            self.lookup = TemplateLookup(
                directories=[self.root + 'templates', self.root + 'htdocs'],
                module_directory=self.root + 'modules',
                input_encoding='utf-8', output_encoding='utf-8')

    def user_password(self, info):
        self.init_mako()

        self.username_password_authn = UsernamePasswordMako(
            None, "login.mako", self.lookup, self.config.PASSWD,
            "%sauthorization" % self.issuer,
            None, self.full_end_point_paths)

        PASSWORD_END_POINT_INDEX = 0

        end_point = info["END_POINTS"][PASSWORD_END_POINT_INDEX]
        authn = AuthnIndexedEndpointWrapper(self.username_password_authn,
                                            PASSWORD_END_POINT_INDEX)
        self.urls.append((r'^' + end_point, make_auth_verify(authn.verify)))
        return authn

    # def javascript_login(self, info):
    #     if self.javascript_login_authn is None:
    #         self.init_mako()
    #
    #         end_points = self.config.AUTHENTICATION[
    #             "JavascriptLogin"]["END_POINTS"]
    #         full_end_point_paths = [
    #             "{}{}".format(self.issuer, ep) for ep in end_points]
    #
    #         self.javascript_login_authn = JavascriptFormMako(
    #             None, "javascript_login.mako", self.lookup, self.config.PASSWD,
    #             "{}authorization".format(self.issuer), None,
    #             full_end_point_paths)
    #
    #     self.ac.add("", self.javascript_login_authn, "", "")
    #     JAVASCRIPT_END_POINT_INDEX = 0
    #     end_point = info["END_POINTS"][JAVASCRIPT_END_POINT_INDEX]
    #     authn = AuthnIndexedEndpointWrapper(self.javascript_login_authn,
    #                                         JAVASCRIPT_END_POINT_INDEX)
    #     self.urls.append((r'^' + end_point, make_auth_verify(authn.verify)))
    #     return authn
    #
    # def saml_login(self, info):
    #     from saml2 import BINDING_HTTP_REDIRECT, BINDING_HTTP_POST
    #
    #     if self.saml_authn is None:
    #         self.init_mako()
    #
    #         self.saml_authn = SAMLAuthnMethod(
    #             None, self.lookup, self.config.SAML, self.config.SP_CONFIG,
    #             self.issuer, "{}authorization".format(self.issuer),
    #             userinfo=self.config.USERINFO)
    #
    #     self.ac.add("", self.saml_authn, "", "")
    #     SAML_END_POINT_INDEX = 0
    #     end_point = info["END_POINTS"][SAML_END_POINT_INDEX]
    #     end_point_indexes = {BINDING_HTTP_REDIRECT: 0, BINDING_HTTP_POST: 0,
    #                          "disco_end_point_index": 0}
    #     authn = AuthnIndexedEndpointWrapper(self.saml_authn, end_point_indexes)
    #     self.urls.append((r'^' + end_point, make_auth_verify(authn.verify)))
    #     return authn
    #
    # def saml_pass_login(self, info):
    #     from saml2 import BINDING_HTTP_REDIRECT, BINDING_HTTP_POST
    #
    #     if self.saml_authn is None:
    #         self.init_mako()
    #
    #         self.saml_authn = SAMLAuthnMethod(
    #             None, self.lookup, self.config.SAML, self.config.SP_CONFIG,
    #             self.issuer, "{}authorization".format(self.issuer),
    #             userinfo=self.config.USERINFO)
    #
    #     PASSWORD_END_POINT_INDEX = 1
    #     SAML_END_POINT_INDEX = 1
    #     password_end_point = self.config.AUTHENTICATION['UserPassword'][
    #         "END_POINTS"][PASSWORD_END_POINT_INDEX]
    #     saml_endpoint = info["END_POINTS"][SAML_END_POINT_INDEX]
    #
    #     end_point_indexes = {BINDING_HTTP_REDIRECT: 1, BINDING_HTTP_POST: 1,
    #                          "disco_end_point_index": 1}
    #     multi_saml = AuthnIndexedEndpointWrapper(self.saml_authn,
    #                                              end_point_indexes)
    #     multi_password = AuthnIndexedEndpointWrapper(
    #         self.username_password_authn, PASSWORD_END_POINT_INDEX)
    #
    #     auth_modules = [(multi_saml, r'^' + saml_endpoint),
    #                     (multi_password, r'^' + password_end_point)]
    #     return setup_multi_auth(self.ac, self.urls, auth_modules)
    #
    # def javascript_passw_login(self, info):
    #     if self.javascript_login_authn is None:
    #         self.init_mako()
    #
    #         end_points = self.config.AUTHENTICATION[
    #             "JavascriptLogin"]["END_POINTS"]
    #         full_end_point_paths = [
    #             "{}{}".format(self.issuer, ep) for ep in end_points]
    #         self.javascript_login_authn = JavascriptFormMako(
    #             None, "javascript_login.mako", self.lookup, self.config.PASSWD,
    #             "{}authorization".format(self.issuer), None,
    #             full_end_point_paths)
    #
    #     PASSWORD_END_POINT_INDEX = 2
    #     JAVASCRIPT_POINT_INDEX = 1
    #
    #     password_end_point = self.config.AUTHENTICATION["UserPassword"][
    #         "END_POINTS"][PASSWORD_END_POINT_INDEX]
    #     javascript_end_point = info["END_POINTS"][JAVASCRIPT_POINT_INDEX]
    #
    #     multi_password = AuthnIndexedEndpointWrapper(
    #         self.username_password_authn, PASSWORD_END_POINT_INDEX)
    #     multi_javascript = AuthnIndexedEndpointWrapper(
    #         self.javascript_login_authn, JAVASCRIPT_POINT_INDEX)
    #
    #     auth_modules = [(multi_password, r'^' + password_end_point),
    #                     (multi_javascript, r'^' + javascript_end_point)]
    #     return setup_multi_auth(self.ac, self.urls, auth_modules)

    def __call__(self):
        for authkey, value in self.config.AUTHENTICATION.items():
            authn = self.auth_methods[authkey](value)
            if authn is not None:
                self.ac.add(value["ACR"], authn, value["WEIGHT"], "")
Esempio n. 47
0
ressrv = ResourceServer(DataSet(), registration_info=reginfo)

# -------------------- ResourceServer as Client ---------------------

rs_client = Client({}, {"client_authn_method": CLIENT_AUTHN_METHOD})
_me = ressrv.registration_info.copy()
_me["redirect_uris"] = ["https://rs.example.com/"]

# init authsrv

authzsrv = Provider("foo", SessionDB(), CDB, None, AUTHZ,
                    verify_client, "1234567890", keyjar=KeyJar())

authzsrv.baseurl = "https://as.example.com/"

AUTHN_BROKER = AuthnBroker()
AUTHN_BROKER.add(UNSPECIFIED, DummyAuthn(None, user="******"), 0,
                 "http://%s" % socket.gethostname())
# AUTHN_BROKER.add(PASSWORD,
#                  UsernamePasswordMako(
#                      None, "login.mako", LOOKUP, PASSWD,
#                      "%s/authorization" % authzsrv.baseurl),
#                  10, "http://%s" % socket.gethostname())
AUTHN_BROKER.add(PASSWORD,
                 BasicAuthn(None, PASSWD),
                 10, "http://%s" % socket.gethostname())

authzsrv.set_authn_broker(AUTHN_BROKER)

ressrv.set_client(authzsrv.baseurl, rs_client)
Esempio n. 48
0
    config = importlib.import_module(args.config)
    config.ISSUER = config.ISSUER + ':{}/'.format(config.PORT)
    config.SERVICEURL = config.SERVICEURL.format(issuer=config.ISSUER)
    endPoints = config.AUTHENTICATION["UserPassword"]["EndPoints"]
    fullEndPointsPath = ["%s%s" % (config.ISSUER, ep) for ep in endPoints]

# TODO: why this instantiation happens so early? can I move it later?
    # An OIDC Authorization/Authentication server is designed to
    # allow more than one authentication method to be used by the server.
    # And that is what the AuthBroker is for.
    # Given information about the authorisation request, the AuthBroker
    # chooses which method(s) to be used for authenticating the person/entity.
    # According to the OIDC standard a Relaying Party can say
    # 'I want this type of authentication', and the AuthnBroker tries to pick
    # methods from the set it has been supplied, to map that request.
    authnBroker = AuthnBroker()

    # UsernamePasswordMako: authenticas a user using the username/password form in a
    # WSGI environment using Mako as template system
    usernamePasswordAuthn = UsernamePasswordMako(
        None,                               # server instance
        "login.mako",                       # a mako template
        lookup,                             # lookup template
        usernamePasswords,                  # username/password dictionary-like database
        "%sauthorization" % config.ISSUER,  # where to send the user after authentication
        None,                               # templ_arg_func ??!!
        fullEndPointsPath)                  # verification endpoints

    # AuthnIndexedEndpointWrapper is a wrapper class for using an authentication module with multiple endpoints.
    authnIndexedEndPointWrapper = AuthnIndexedEndpointWrapper(usernamePasswordAuthn, passwordEndPointIndex)
Esempio n. 49
0
        "verified": False,
        "sub": "user"
    }
}

URLMAP = {CLIENT_ID: ["https://example.com/authz"]}

PASSWD = {"user": "******"}

ROOT = '../oc3/'
tl = TemplateLookup(directories=[ROOT + 'templates', ROOT + 'htdocs'],
                    module_directory=ROOT + 'modules',
                    input_encoding='utf-8',
                    output_encoding='utf-8')

AUTHN_BROKER = AuthnBroker()
AUTHN_BROKER.add(
    "1", UsernamePasswordMako(None, "login.mako", tl, PASSWD, "authenticated"))

# dealing with authorization
AUTHZ = AuthzHandling()
SYMKEY = "symmetric key used to encrypt cookie info"
USERINFO = UserInfo(USERDB)

provider_init = Provider("pyoicserv",
                         SessionDB(SERVER_INFO["issuer"]),
                         CDB,
                         AUTHN_BROKER,
                         USERINFO,
                         AUTHZ,
                         verify_client,
Esempio n. 50
0
        #'session.data_dir': './data',
        'session.auto': True,
        'session.timeout': 900
    }

    sys.path.insert(0, ".")
    config = importlib.import_module(args.config)
    config.issuer = config.issuer % args.port
    config.SERVICE_URL = config.SERVICE_URL % args.port

    # Client data base
    cdb = shelve.open(config.CLIENT_DB, writeback=True)

    SETUP = {}

    ac = AuthnBroker()

    for authkey, value in config.AUTHENTICATION.items():
        authn = None
        # if "UserPassword" == authkey:
        #     from oic.utils.authn.user import UsernamePasswordMako
        #     authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD,
        #                                  "authorization")

        if "NoAuthn" == authkey:
            from oic.utils.authn.user import NoAuthn

            authn = NoAuthn(None, user=config.AUTHENTICATION[authkey]["user"])

        if authn is not None:
            ac.add(config.AUTHENTICATION[authkey]["ACR"], authn,
Esempio n. 51
0
    parser.add_argument('-v', dest='verbose', action='store_true')
    parser.add_argument('-d', dest='debug', action='store_true')
    parser.add_argument('-p', dest='port', default=80, type=int)
    parser.add_argument('-k', dest='insecure', action='store_true')
    parser.add_argument(dest="config")
    args = parser.parse_args()

    # Client data base
    cdb = shelve.open("client_db", writeback=True)

    sys.path.insert(0, ".")
    config = importlib.import_module(args.config)
    config.issuer = config.issuer % args.port
    config.SERVICE_URL = config.SERVICE_URL % args.port

    ac = AuthnBroker()

    for authkey, value in config.AUTHENTICATION.items():
        authn = None
        if "UserPassword" == authkey:
            from oic.utils.authn.user import UsernamePasswordMako
            authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD,
                                         "%s/authorization" % config.issuer)
        if "SAML" == authkey:
            from oic.utils.authn.saml import SAMLAuthnMethod
            authn = SAMLAuthnMethod(None, LOOKUP, config.SAML,
                                    config.SP_CONFIG, config.issuer,
                                    "%s/authorization" % config.issuer,
                                    config.SERVICE_URL)
        if authn is not None:
            ac.add(config.AUTHENTICATION[authkey]["ACR"], authn,
Esempio n. 52
0
def verify_outcome(msg, prefix, lista):
    """
    Compare message to list of claims: values.

    :param prefix: prefix string
    :param lista: list of claims=value
    :return: list of possible strings
    """
    assert msg.startswith(prefix)
    qsl = ['{}={}'.format(k, v[0]) for k, v in
           parse_qs(msg[len(prefix):]).items()]
    return set(qsl) == set(lista)


AUTHN_BROKER = AuthnBroker()
AUTHN_BROKER.add("UNDEFINED", DummyAuthn(None, "username"))
AUTHN_BROKER2 = AuthnBroker()
AUTHN_BROKER2.add('UNDEFINED', NoCookieAuthn(None, 'username'))
# dealing with authorization
AUTHZ = Implicit()


class TestProvider(object):
    @pytest.fixture(autouse=True)
    def create_provider(self, session_db_factory):
        self.provider = Provider("pyoicserv",
                                 session_db_factory(ISSUER), CDB,
                                 AUTHN_BROKER, AUTHZ, verify_client,
                                 baseurl='https://example.com/as')
Esempio n. 53
0
    BASE = "http://localhost:%s/" % PORT
    RESOURCE_SERVER = "https://localhost:8089"

    # The UMA AS=C combo
    as_conf = {
        "version": "1.0",
        "issuer": BASE,
        "pat_profiles_supported": ["bearer"],
        "aat_profiles_supported": ["bearer"],
        "rpt_profiles_supported": ["bearer"],
        "pat_grant_types_supported": ["authorization_code"],
        "aat_grant_types_supported": ["authorization_code"],
        "claim_profiles_supported": ["openid"],
    }

    ab = AuthnBroker()
    ab.add("alice", DummyAuthn(None, "alice"))
    ab.add("UserPwd",
           UsernamePasswordMako(None, "login2.mako", LOOKUP, PASSWD,
                                "%s/authorization" % BASE),
           10, "http://%s" % socket.gethostname())
    ab.add("BasicAuthn", BasicAuthnExtra(None, PASSWD), 10,
           "http://%s" % socket.gethostname())

    AUTHZSRV = AuthorizationServer(
        BASE, SessionDB(), CDB, ab, AUTHZ, verify_client, "1234567890123456",
        keyjar=None, configuration=as_conf, base_url=BASE,
        client_info_url="%s/" % BASE,
        client_authn_methods={
            "client_secret_post": ClientSecretPost,
            "client_secret_basic": ClientSecretBasic,
Esempio n. 54
0
    config = importlib.import_module(args.config)
    config.ISSUER = config.ISSUER + ':{}/'.format(config.PORT)
    config.SERVICEURL = config.SERVICEURL.format(issuer=config.ISSUER)
    endPoints = config.AUTHENTICATION["UserPassword"]["EndPoints"]
    fullEndPointsPath = ["%s%s" % (config.ISSUER, ep) for ep in endPoints]

    # TODO: why this instantiation happens so early? can I move it later?
    # An OIDC Authorization/Authentication server is designed to
    # allow more than one authentication method to be used by the server.
    # And that is what the AuthBroker is for.
    # Given information about the authorisation request, the AuthBroker
    # chooses which method(s) to be used for authenticating the person/entity.
    # According to the OIDC standard a Relaying Party can say
    # 'I want this type of authentication', and the AuthnBroker tries to pick
    # methods from the set it has been supplied, to map that request.
    authnBroker = AuthnBroker()

    # UsernamePasswordMako: authenticas a user using the username/password form in a
    # WSGI environment using Mako as template system
    usernamePasswordAuthn = UsernamePasswordMako(
        None,  # server instance
        "login.mako",  # a mako template
        lookup,  # lookup template
        usernamePasswords,  # username/password dictionary-like database
        "%sauthorization" %
        config.ISSUER,  # where to send the user after authentication
        None,  # templ_arg_func ??!!
        fullEndPointsPath)  # verification endpoints

    # AuthnIndexedEndpointWrapper is a wrapper class for using an authentication module with multiple endpoints.
    authnIndexedEndPointWrapper = AuthnIndexedEndpointWrapper(
Esempio n. 55
0
def main_setup(args, lookup):
    sys.path.insert(0, ".")
    config = importlib.import_module(args.config)
    config.issuer = config.issuer % args.port
    config.SERVICE_URL = config.SERVICE_URL % args.port

    # Client data base
    # cdb = shelve.open(config.CLIENT_DB, writeback=True)
    cdb = {}

    ac = AuthnBroker()

    for authkey, value in list(config.AUTHENTICATION.items()):
        authn = None
        # if "UserPassword" == authkey:
        #     from oic.utils.authn.user import UsernamePasswordMako
        #     authn = UsernamePasswordMako(None, "login.mako", LOOKUP, PASSWD,
        #                                  "authorization")

        if "NoAuthn" == authkey:
            from oic.utils.authn.user import NoAuthn

            authn = NoAuthn(None, user=config.AUTHENTICATION[authkey]["user"])

        if authn is not None:
            ac.add(config.AUTHENTICATION[authkey]["ACR"], authn,
                   config.AUTHENTICATION[authkey]["WEIGHT"])

    # dealing with authorization
    authz = AuthzHandling()

    kwargs = {
        "template_lookup": lookup,
        "template": {
            "form_post": "form_response.mako"
        },
    }

    if config.USERINFO == "SIMPLE":
        # User info is a simple dictionary in this case statically defined in
        # the configuration file
        userinfo = UserInfo(config.USERDB)
    else:
        userinfo = None

    # Should I care about verifying the certificates used by other entities
    if args.insecure:
        kwargs["verify_ssl"] = False
    else:
        kwargs["verify_ssl"] = True

    uri_schemes = read_uri_schemes('uri-schemes-1.csv')

    as_args = {
        "name": config.issuer,
        "cdb": cdb,
        "authn_broker": ac,
        "userinfo": userinfo,
        "authz": authz,
        "client_authn": verify_client,
        "symkey": config.SYM_KEY,
        "template_lookup": lookup,
        "template": {
            "form_post": "form_response.mako"
        },
        "jwks_name": "./static/jwks_{}.json",
        'event_db': Events(),
    }

    com_args = {
        "name": config.issuer,
        # "sdb": SessionDB(config.baseurl),
        "baseurl": config.baseurl,
        "cdb": cdb,
        "authn_broker": ac,
        "userinfo": userinfo,
        "authz": authz,
        "client_authn": verify_client,
        "symkey": config.SYM_KEY,
        "template_lookup": lookup,
        "template": {
            "form_post": "form_response.mako"
        },
        "jwks_name": "./static/jwks_{}.json",
        'uri_schemes': uri_schemes
    }

    op_arg = {}

    try:
        op_arg["cookie_ttl"] = config.COOKIETTL
    except AttributeError:
        pass

    try:
        op_arg["cookie_name"] = config.COOKIENAME
    except AttributeError:
        pass

    try:
        as_args['behavior'] = config.BEHAVIOR
    except AttributeError:
        pass

    # print URLS
    if args.debug:
        op_arg["debug"] = True

    if args.port == 80:
        _baseurl = config.baseurl
    else:
        if config.baseurl.endswith("/"):
            config.baseurl = config.baseurl[:-1]
        _baseurl = "%s:%d" % (config.baseurl, args.port)

    if not _baseurl.endswith("/"):
        _baseurl += "/"

    op_arg["baseurl"] = _baseurl

    # Add own keys for signing/encrypting JWTs
    try:
        # a throw-away OP used to do the initial key setup
        _op = Provider(sdb=SessionDB(com_args["baseurl"]), **com_args)
        jwks = keyjar_init(_op, config.keys)
    except KeyError:
        pass
    else:
        op_arg["jwks"] = jwks
        op_arg["keys"] = config.keys

        as_args['jwks_uri'] = '{}{}/jwks.json'.format(_baseurl, 'static')
        as_args['jwks_name'] = 'static/jwks.json'

        f = open('static/jwks.json', 'w')
        f.write(json.dumps(jwks))
        f.close()

        as_args['keyjar'] = _op.keyjar
        as_args['sdb'] = SessionDB(com_args["baseurl"],
                                   token_factory=JWTToken('T',
                                                          keyjar=_op.keyjar,
                                                          lt_pattern={
                                                              'code': 3600,
                                                              'token': 900
                                                          },
                                                          iss=_baseurl,
                                                          sign_alg='RS256'),
                                   refresh_token_factory=JWTToken(
                                       'R',
                                       keyjar=_op.keyjar,
                                       lt_pattern={'': 24 * 3600},
                                       iss=_baseurl))

    try:
        op_arg["marg"] = multi_keys(as_args, config.multi_keys)
    except AttributeError as err:
        pass

    return as_args, op_arg, config
Esempio n. 56
0
ROOT = '../oc3/'
tl = TemplateLookup(directories=[ROOT + 'templates', ROOT + 'htdocs'],
                    module_directory=ROOT + 'modules',
                    input_encoding='utf-8', output_encoding='utf-8')


class DummyAuthn(UserAuthnMethod):
    def __init__(self, srv, user):
        UserAuthnMethod.__init__(self, srv)
        self.user = user

    def authenticated_as(self, cookie=None, **kwargs):
        return {"uid": self.user}

AUTHN_BROKER = AuthnBroker()
AUTHN_BROKER.add("UNDEFINED", DummyAuthn(None, "username"))

# dealing with authorization
AUTHZ = Implicit()


def content_type(headers):
    for key, val in headers:
        if key == "Content-type":
            if val == "application/json":
                return "json"


def _eq(l1, l2):
    return set(l1) == set(l2)
Esempio n. 57
0
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', dest='port', default=80, type=int)
    parser.add_argument("-b", required=True, dest="base",
                        help="base url of the provider")
    parser.add_argument(dest="config")
    args = parser.parse_args()

    # Client data base
    cdb = shelve.Shelf({})

    sys.path.insert(0, ".")
    config = importlib.import_module(args.config)
    baseurl = "{base}:{port}".format(base=args.base.rstrip("/"), port=args.port)

    ac = AuthnBroker()
    authn = UsernamePasswordMako(None, "login.mako", LOOKUP, config.PASSWD,
                                 "%s/authorization" % baseurl)
    ac.add("UsernamePassword", authn)

    # dealing with authorization
    authz = AuthzHandling()

    # Consent and list tokens page
    renderer = MakoRenderer(LOOKUP)
    consent_page_handler = partial(renderer, "consent.mako",
                                   form_action="/consent_ok")
    list_tokens_page_handler = partial(renderer, "list_access_tokens.mako")

    OAS = NonWebProvider(baseurl, SessionDB(baseurl), cdb, ac,
                         None, authz, verify_client, config.SYM_KEY,