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
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
Exemple #3
0
def multi_keys(com_args, key_conf):
    # 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, key_conf, "m%d")

    return {"jwks": jwks, "keys": key_conf}
Exemple #4
0
def multi_keys(com_args, key_conf):
    # 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, key_conf, "m%d")

    return {"jwks": jwks, "keys": key_conf}
Exemple #5
0
def main(base_url, cookie_handler):
    config = {
        "registration_info": {
            "token_endpoint_auth_method": "client_secret_basic",
            "application_type": "web",
            "redirect_uris": ["%s/uma" % base_url],
            "grant_types": ["authorization_code", "implicit"],
            "scope": [PAT],
            "response_types": ["code", "token"]
        },
        "client_authn_method": {
            "client_secret_basic": ClientSecretBasic,
            "bearer_header": BearerHeader
        },
        "flow_type": "code",
        "symkey": "abcdefghijklmnop",
        "baseurl": base_url,
        "scope": PAT
    }

    dataset = RESTIDMWrap(USERDB, baseurl=config["baseurl"])
    res_srv = ResourceServer1C(dataset, **config)

    jwks = keyjar_init(res_srv, KEYS, "a%d")

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

    cookie_handler.init_srv(res_srv)

    return res_srv
Exemple #6
0
def main(base_url, cookie_handler):
    config = {
        "registration_info": {
            "token_endpoint_auth_method": "client_secret_basic",
            "application_type": "web",
            "redirect_uris": ["%s/uma" % base_url],
            "grant_types": ["authorization_code", "implicit"],
            "scope": [PAT],
            "response_types": ["code", "token"]
        },
        "client_authn_method": {
            "client_secret_basic": ClientSecretBasic,
            "bearer_header": BearerHeader
        },
        "flow_type": "code",
        "symkey": "abcdefghijklmnop",
        "baseurl": base_url,
        "scope": PAT
    }

    dataset = RESTIDMWrap(USERDB, baseurl=config["baseurl"])
    res_srv = ResourceServer1C(dataset, **config)

    jwks = keyjar_init(res_srv, KEYS, "a%d")

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

    cookie_handler.init_srv(res_srv)

    return res_srv
Exemple #7
0
    def dynamic_client(self, userid):
        client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD,
                                 verify_ssl=self.config.VERIFY_SSL)
        keyjar_init(client, self.config.POP_KEYS)
        issuer = client.wf.discovery_query(userid)
        if issuer in self.client:
            return self.client[issuer]
        else:
            # Gather OP information
            _pcr = client.provider_config(issuer)
            # register the client
            _ = client.register(_pcr["registration_endpoint"],
                                **self.config.CLIENTS[""]["client_info"])
            try:
                client.behaviour.update(**self.config.CLIENTS[""]["behaviour"])
            except KeyError:
                pass

            self.client[issuer] = client
            return client
Exemple #8
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)

    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
Exemple #9
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
Exemple #10
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
Exemple #11
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
Exemple #12
0
def multi_keys(as_args, key_conf):
    # a throw-away OP used to do the initial key setup
    _op = Provider(**as_args)
    jwks = keyjar_init(_op, key_conf, "m%d")

    return {"jwks": jwks, "keys": key_conf}
Exemple #13
0
 def __setattr__(self, key, value):
     if key == "keys":
         # Update the keyjar instead of just storing the keys description
         keyjar_init(self, value)
     else:
         super(provider.Provider, self).__setattr__(key, value)
Exemple #14
0
    client_db = {}
    provider = Provider(issuer, SessionDB(issuer), client_db, authn_broker,
                        userinfo, AuthzHandling(), verify_client, None)
    provider.baseurl = issuer
    provider.symkey = rndstr(16)

    # Setup keys
    path = os.path.join(os.path.dirname(__file__), "static")
    try:
        os.makedirs(path)
    except OSError, e:
        if e.errno != errno.EEXIST:
            raise e
        pass
    jwks = keyjar_init(provider, settings["provider"]["keys"])
    name = "jwks.json"
    with open(os.path.join(path, name), "w") as f:
        f.write(json.dumps(jwks))

    provider.jwks_uri.append(
        "{}/static/{}".format(provider.baseurl, name))

    # Mount the WSGI callable object (app) on the root directory
    app_routing = setup_endpoints(provider)
    app_routing["/.well-known/openid-configuration"] = pyoidcMiddleware(
        provider.providerinfo_endpoint)
    app_routing["/.well-known/webfinger"] = pyoidcMiddleware(
        partial(_webfinger, provider))
    routing = dict(auth_routing.items() + app_routing.items())
    routing["/static"] = make_static_handler(path)
Exemple #15
0
 def __setattr__(self, key, value):
     if key == "keys":
         # Update the keyjar instead of just storing the keys description
         keyjar_init(self, value)
     else:
         super(provider.Provider, self).__setattr__(key, value)
Exemple #16
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
Exemple #17
0
    def create_client(self, **kwargs):
        """
        Instantiate a client instance

        :param: Keyword arguments
            Keys are ["srv_discovery_url", "client_info", "client_registration",
            "provider_info". "keys]
        :return: client instance
        """

        _key_set = set(kwargs.keys())
        args = {}

        client = self.client_cls(client_authn_methods=CLIENT_AUTHN_METHOD,
                                 behaviour=kwargs["behaviour"],
                                 verify_ssl=self.config.VERIFY_SSL, **args)

        # The behaviour parameter is not significant for the election process
        _key_set.discard("behaviour")
        try:
            setattr(client, "allow", kwargs["allow"])
        except KeyError:
            pass
        else:
            _key_set.discard("allow")

        try:
            jwks = keyjar_init(client, kwargs["keys"])
        except KeyError:
            pass
        else:
            # export JWKS
            p = urlparse(self.config.CLIENT["key_export_url"] % self._port)
            f = open("."+p.path, "w")
            f.write(json.dumps(jwks))
            f.close()
            client.jwks_uri = p.geturl()

        self.test_features = _key_set

        try:
            client.client_prefs = copy.copy(kwargs["preferences"])
        except KeyError:
            pass
        else:
            _key_set.discard("preferences")

        if "client_info" in _key_set:
            client.redirect_uris = self.config.CLIENT[
                "client_info"]["redirect_uris"]
        elif "client_registration" in _key_set:
            reg_info = self.config.CLIENT["client_registration"]
            client.redirect_uris = reg_info["redirect_uris"]
            client.client_id = reg_info["client_id"]
            try:
                client.client_secret = reg_info["client_secret"]
            except KeyError:
                pass

        if "provider_info" in _key_set:
            client.provider_info = ProviderConfigurationResponse(
                **self.config.CLIENT["provider_info"])

            for key, val in self.config.CLIENT["provider_info"].items():
                if key.endswith("_endpoint"):
                    setattr(client, key, val)
                elif key == "jwks_uri":
                    client.keyjar.load_keys(client.provider_info,
                                            client.provider_info["issuer"])

        return client
Exemple #18
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
Exemple #19
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
Exemple #20
0
    provider.cookie_ttl = config.COOKIETTL
    provider.cookie_name = config.COOKIENAME

    if args.debug:
        provider.debug = True

    try:
        # JWK: JSON Web Key
        # JWKS: is a dictionary of JWK
        # __________ NOTE __________
        # JWKS contains private key information.
        #
        # keyjar_init configures cryptographic key
        # based on the provided configuration "keys".
        jwks = keyjar_init(
            provider,             # server/client instance
            config.keys,          # key configuration
            kid_template="op%d")  # template by which to build the kids (key ID parameter)
    except Exception as err:
        # LOGGER.error("Key setup failed: %s" % err)
        provider.key_setup("static", sig={"format": "jwk", "alg": "rsa"})
    else:
        for key in jwks["keys"]:
            for k in key.keys():
                key[k] = as_unicode(key[k])

        f = open(jwksFileName, "w")
        f.write(json.dumps(jwks))
        f.close()
        provider.jwks_uri = "%s%s" % (provider.baseurl, jwksFileName)

    # for b in OAS.keyjar[""]:
Exemple #21
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
Exemple #22
0
def multi_keys(as_args, key_conf):
    # a throw-away OP used to do the initial key setup
    _op = Provider(**as_args)
    jwks = keyjar_init(_op, key_conf, "m%d")

    return {"jwks": jwks, "keys": key_conf}
Exemple #23
0
    client_db = {}
    provider = Provider(issuer, SessionDB(issuer), client_db, authn_broker,
                        userinfo, AuthzHandling(), verify_client, None)
    provider.baseurl = issuer
    provider.symkey = rndstr(16)

    # Setup keys
    path = os.path.join(os.path.dirname(__file__), "static")
    try:
        os.makedirs(path)
    except OSError, e:
        if e.errno != errno.EEXIST:
            raise e
        pass
    jwks = keyjar_init(provider, settings["provider"]["keys"])
    name = "jwks.json"
    with open(os.path.join(path, name), "w") as f:
        f.write(json.dumps(jwks))

    provider.jwks_uri.append("{}/static/{}".format(provider.baseurl, name))

    # Mount the WSGI callable object (app) on the root directory
    app_routing = setup_endpoints(provider)
    app_routing["/.well-known/openid-configuration"] = pyoidcMiddleware(
        provider.providerinfo_endpoint)
    app_routing["/.well-known/webfinger"] = pyoidcMiddleware(
        partial(_webfinger, provider))
    routing = dict(auth_routing.items() + app_routing.items())
    routing["/static"] = make_static_handler(path)
    dispatcher = WSGIPathInfoDispatcher(routing)
Exemple #24
0
def op_setup(args, config, provider_cls):
    # Client data base
    cdb = shelve_wrapper.open("client_db")

    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)

    auth_setup = AuthSetup(config, _issuer)
    auth_setup()

    # dealing with authorization
    authz = AuthzHandling()

    auth_setup.init_mako()

    kwargs = {
        "template_lookup": auth_setup.lookup,
        "template": {"form_post": "form_response.mako"},
        # "template_args": {"form_post": {"action": "form_post"}}
    }

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

    if args.capabilities:
        kwargs["capabilities"] = json.loads(open(args.capabilities).read())
    else:
        pass

    _sdb = create_session_db(_issuer, 'automover', '430X', {})
    _op = provider_cls(_issuer, _sdb, cdb, auth_setup.ac, None,
                       authz, verify_client, config.SYM_KEY, **kwargs)
    _op.baseurl = _issuer

    for authn in auth_setup.ac:
        authn.srv = _op

    if config.USERINFO == "SIMPLE":
        # User info is a simple dictionary in this case statically defined in
        # the configuration file
        _op.userinfo = UserInfo(config.USERDB)
    elif config.USERINFO == "SAML":
        _op.userinfo = UserInfo(config.SAML)
    elif config.USERINFO == "AA":
        _op.userinfo = AaUserInfo(config.SP_CONFIG, _issuer, config.SAML)
    else:
        raise Exception("Unsupported userinfo source")

    try:
        _op.cookie_ttl = config.COOKIETTL
    except AttributeError:
        pass

    try:
        _op.cookie_name = config.COOKIENAME
    except AttributeError:
        pass

    # print URLS
    if args.debug:
        _op.debug = True

    try:
        jwks = keyjar_init(_op, config.keys, kid_template="op%d")
    except Exception as err:
        logger.error("Key setup failed: %s" % err)
        _op.key_setup("static", sig={"format": "jwk", "alg": "rsa"})
    else:
        f = open(config.JWKS_FILE_NAME, "w")
        f.write(json.dumps(jwks))
        f.close()

        _op.jwks_uri = "%s%s" % (_op.baseurl, config.JWKS_FILE_NAME)

        try:
            _op.signed_jwks_uri = "%s%s" % (_op.baseurl,
                                            config.SIGNED_JWKS_PATH)
        except AttributeError:
            pass

        _op.keyjar.verify_ssl = kwargs["verify_ssl"]

    for b in _op.keyjar[""]:
        logger.info("OC3 server keys: %s" % b)

    return _op
Exemple #25
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
Exemple #26
0
    try:
        OAS.cookie_name = config.COOKIENAME
    except AttributeError:
        pass

    #print URLS
    if args.debug:
        OAS.debug = True

    # All endpoints the OpenID Connect Provider should answer on
    add_endpoints(ENDPOINTS)
    OAS.endpoints = ENDPOINTS

    try:
        jwks = keyjar_init(OAS, config.keys, kid_template="op%d")
    except Exception as err:
        LOGGER.error("Key setup failed: %s" % err)
        OAS.key_setup("static", sig={"format": "jwk", "alg": "rsa"})
    else:
        jwks_file_name = JWKS_FILE_NAME
        f = open(jwks_file_name, "w")

        for key in jwks["keys"]:
            for k in key.keys():
                key[k] = as_unicode(key[k])

        f.write(json.dumps(jwks))
        f.close()
        OAS.jwks_uri = "%s%s" % (OAS.baseurl, jwks_file_name)
Exemple #27
0
def multi_keys(com_args, key_conf):
    # a throw-away OP used to do the initial key setup
    _op = Provider(sdb=SessionDB(com_args["baseurl"]), **com_args)
    jwks = keyjar_init(_op, key_conf, "m%d")

    return {"jwks": jwks, "keys": key_conf}
Exemple #28
0
def multi_keys(com_args, key_conf):
    # a throw-away OP used to do the initial key setup
    _op = Provider(sdb=SessionDB(com_args["baseurl"]), **com_args)
    jwks = keyjar_init(_op, key_conf, "m%d")

    return {"jwks": jwks, "keys": key_conf}
Exemple #29
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
Exemple #30
0
def main():
    parser = argparse.ArgumentParser(description='Example OIDC Provider.')
    parser.add_argument("-p", "--port", default=80, type=int)
    parser.add_argument("-b", "--base", default="https://localhost", type=str)
    parser.add_argument("-d", "--debug", action="store_true")
    parser.add_argument("settings")
    args = parser.parse_args()

    # Load configuration
    with open(args.settings, "r") as f:
        settings = yaml.load(f)

    issuer = args.base.rstrip("/")

    template_dirs = settings["server"].get("template_dirs", "templates")
    jinja_env = Environment(loader=FileSystemLoader(template_dirs))
    authn_broker, auth_routing = setup_authentication_methods(settings["authn"],
                                                              jinja_env)

    # Setup userinfo
    userinfo_conf = settings["userinfo"]
    cls = make_cls_from_name(userinfo_conf["class"])
    i = cls(**userinfo_conf["kwargs"])
    userinfo = UserInfo(i)

    client_db = {}
    session_db = create_session_db(issuer,
                                   secret=rndstr(32), password=rndstr(32))
    provider = Provider(issuer, session_db, client_db, authn_broker,
                        userinfo, AuthzHandling(), verify_client, None)
    provider.baseurl = issuer
    provider.symkey = rndstr(16)

    # Setup keys
    path = os.path.join(os.path.dirname(__file__), "static")
    try:
        os.makedirs(path)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise e
        pass
    jwks = keyjar_init(provider, settings["provider"]["keys"])
    name = "jwks.json"
    with open(os.path.join(path, name), "w") as f:
        f.write(json.dumps(jwks))

    #TODO: I take this out and it still works, what was this for?
    #provider.jwks_uri.append(
    #    "{}/static/{}".format(provider.baseurl, name))

    # Mount the WSGI callable object (app) on the root directory
    app_routing = setup_endpoints(provider)
    app_routing["/.well-known/openid-configuration"] = pyoidcMiddleware(
        provider.providerinfo_endpoint)
    app_routing["/.well-known/webfinger"] = pyoidcMiddleware(
        partial(_webfinger, provider))
    routing = dict(list(auth_routing.items()) + list(app_routing.items()))
    routing["/static"] = make_static_handler(path)
    dispatcher = WSGIPathInfoDispatcher(routing)
    server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', args.port), dispatcher)

    # Setup SSL
    if provider.baseurl.startswith("https://"):
        server.ssl_adapter = BuiltinSSLAdapter(
        settings["server"]["cert"], settings["server"]["key"],
        settings["server"]["cert_chain"])

    # Start the CherryPy WSGI web server
    try:
        print("Server started: {}".format(issuer))
        server.start()
    except KeyboardInterrupt:
        server.stop()
Exemple #31
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
Exemple #32
0
    add_endpoints(endpoints)
    OAS.endpoints = endpoints

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

    if not OAS.baseurl.endswith("/"):
        OAS.baseurl += "/"

    try:
        jwks = keyjar_init(OAS, config.keys)
    except Exception, err:
        LOGGER.error("Key setup failed: %s" % err)
        OAS.key_setup("static", sig={"format": "jwk", "alg": "rsa"})
    else:
        new_name = "static/jwks.json"
        f = open(new_name, "w")
        f.write(json.dumps(jwks))
        f.close()
        OAS.jwks_uri.append("%s%s" % (OAS.baseurl, new_name))

    for b in OAS.keyjar[""]:
        LOGGER.info("OC3 server keys: %s" % b)

    if config.USERINFO == "LDAP":
        from oic.utils.userinfo.ldap_info import UserInfoLDAP
Exemple #33
0
    provider.cookie_name = config.COOKIENAME

    if args.debug:
        provider.debug = True

    try:
        # JWK: JSON Web Key
        # JWKS: is a dictionary of JWK
        # __________ NOTE __________
        # JWKS contains private key information.
        #
        # keyjar_init configures cryptographic key
        # based on the provided configuration "keys".
        jwks = keyjar_init(
            provider,  # server/client instance
            config.keys,  # key configuration
            kid_template="op%d"
        )  # template by which to build the kids (key ID parameter)
    except Exception as err:
        # LOGGER.error("Key setup failed: %s" % err)
        provider.key_setup("static", sig={"format": "jwk", "alg": "rsa"})
    else:
        for key in jwks["keys"]:
            for k in key.keys():
                key[k] = as_unicode(key[k])

        f = open(jwksFileName, "w")
        f.write(json.dumps(jwks))
        f.close()
        provider.jwks_uri = "%s%s" % (provider.baseurl, jwksFileName)
Exemple #34
0
    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:
        OAS = Provider(**COM_ARGS)
        jwks = keyjar_init(OAS, config.keys)
    except KeyError:
        pass
    else:
        # export JWKS
        p = urlparse(config.KEY_EXPORT_URL % args.port)
        f = open("."+p.path, "w")
        f.write(json.dumps(jwks))
        f.close()
        OP_ARG["keyjar"] = OAS.keyjar
        OP_ARG["jwks_uri"] = p.geturl()

    # Setup the web server
    SRV = wsgiserver.CherryPyWSGIServer(('0.0.0.0', args.port),
                                        SessionMiddleware(application,
                                                          session_opts))
    try:
        OAS.cookie_ttl = CONFIG.COOKIETTL
    except AttributeError:
        pass

    try:
        OAS.cookie_name = CONFIG.COOKIENAME
    except AttributeError:
        pass

    if ARGS.debug:
        OAS.debug = True

    try:
        JWKS = keyjar_init(OAS, CONFIG.keys, kid_template="op%d")
    except Exception as err:
        LOGGER.error("Key setup failed: %s" % err)
        OAS.key_setup("static", sig={"format": "jwk", "alg": "rsa"})
    else:
        NEW_NAME = "static/jwks.json"
        f = open(NEW_NAME, "w")

        for key in JWKS["keys"]:
            for k in key.keys():
                key[k] = as_unicode(key[k])

        f.write(json.dumps(JWKS))
        f.close()
        OAS.jwks_uri.append("%s%s" % (OAS.baseurl, NEW_NAME))
Exemple #36
0
def main():
    parser = argparse.ArgumentParser(description='Example OIDC Provider.')
    parser.add_argument("-p", "--port", default=80, type=int)
    parser.add_argument("-b", "--base", default="https://localhost", type=str)
    parser.add_argument("-d", "--debug", action="store_true")
    parser.add_argument("settings")
    args = parser.parse_args()

    # Load configuration
    with open(args.settings, "r") as f:
        settings = yaml.load(f)

    issuer = args.base.rstrip("/")

    template_dirs = settings["server"].get("template_dirs", "templates")
    jinja_env = Environment(loader=FileSystemLoader(template_dirs))
    authn_broker, auth_routing = setup_authentication_methods(
        settings["authn"], jinja_env)

    # Setup userinfo
    userinfo_conf = settings["userinfo"]
    cls = make_cls_from_name(userinfo_conf["class"])
    i = cls(**userinfo_conf["kwargs"])
    userinfo = UserInfo(i)

    client_db = {}
    provider = Provider(issuer, SessionDB(issuer), client_db, authn_broker,
                        userinfo, AuthzHandling(), verify_client, None)
    provider.baseurl = issuer
    provider.symkey = rndstr(16)

    # Setup keys
    path = os.path.join(os.path.dirname(__file__), "static")
    try:
        os.makedirs(path)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise e
        pass
    jwks = keyjar_init(provider, settings["provider"]["keys"])
    name = "jwks.json"
    with open(os.path.join(path, name), "w") as f:
        f.write(json.dumps(jwks))

    provider.jwks_uri.append("{}/static/{}".format(provider.baseurl, name))

    # Mount the WSGI callable object (app) on the root directory
    app_routing = setup_endpoints(provider)
    app_routing["/.well-known/openid-configuration"] = pyoidcMiddleware(
        provider.providerinfo_endpoint)
    app_routing["/.well-known/webfinger"] = pyoidcMiddleware(
        partial(_webfinger, provider))
    routing = dict(list(auth_routing.items()) + list(app_routing.items()))
    routing["/static"] = make_static_handler(path)
    dispatcher = WSGIPathInfoDispatcher(routing)
    server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', args.port), dispatcher)

    # Setup SSL
    if provider.baseurl.startswith("https://"):
        server.ssl_adapter = BuiltinSSLAdapter(
            settings["server"]["cert"], settings["server"]["key"],
            settings["server"]["cert_chain"])

    # Start the CherryPy WSGI web server
    try:
        print("Server started: {}".format(issuer))
        server.start()
    except KeyboardInterrupt:
        server.stop()
Exemple #37
0
    def create_client(self, userid="", **kwargs):
        """
        Do an instantiation of a client instance

        :param userid: An identifier of the user
        :param: Keyword arguments
            Keys are ["srv_discovery_url", "client_info", "client_registration",
            "provider_info"]
        :return: client instance
        """

        _key_set = set(list(kwargs.keys()))
        args = {}
        for param in ["verify_ssl"]:
            try:
                args[param] = kwargs[param]
            except KeyError:
                pass
            else:
                _key_set.discard(param)

        client = self.client_cls(client_authn_method=CLIENT_AUTHN_METHOD,
                                 behaviour=kwargs["behaviour"], verify_ssl=self.config.VERIFY_SSL,
                                 **args)

        keyjar_init(client, self.config.POP_KEYS)

        try:
            client.userinfo_request_method = kwargs["userinfo_request_method"]
        except KeyError:
            pass
        else:
            _key_set.discard("userinfo_request_method")

        # The behaviour parameter is not significant for the election process
        _key_set.discard("behaviour")
        for param in ["allow"]:
            try:
                setattr(client, param, kwargs[param])
            except KeyError:
                pass
            else:
                _key_set.discard(param)

        if _key_set == set(["client_info"]):  # Everything dynamic
            # There has to be a userid
            if not userid:
                raise MissingAttribute("Missing userid specification")

            # Find the service that provides information about the OP
            issuer = client.wf.discovery_query(userid)
            # Gather OP information
            _ = client.provider_config(issuer)
            # register the client
            _ = client.register(client.provider_info["registration_endpoint"],
                                **kwargs["client_info"])
        elif _key_set == set(["client_info", "srv_discovery_url"]):
            # Ship the webfinger part
            # Gather OP information
            _ = client.provider_config(kwargs["srv_discovery_url"])
            # register the client
            _ = client.register(client.provider_info["registration_endpoint"],
                                **kwargs["client_info"])
        elif _key_set == set(["provider_info", "client_info"]):
            client.handle_provider_config(
                ProviderConfigurationResponse(**kwargs["provider_info"]),
                kwargs["provider_info"]["issuer"])
            _ = client.register(client.provider_info["registration_endpoint"],
                                **kwargs["client_info"])
        elif _key_set == set(["provider_info", "client_registration"]):
            client.handle_provider_config(
                ProviderConfigurationResponse(**kwargs["provider_info"]),
                kwargs["provider_info"]["issuer"])
            client.store_registration_info(RegistrationResponse(
                **kwargs["client_registration"]))
        elif _key_set == set(["srv_discovery_url", "client_registration"]):
            _ = client.provider_config(kwargs["srv_discovery_url"])
            client.store_registration_info(RegistrationResponse(
                **kwargs["client_registration"]))
        else:
            raise Exception("Configuration error ?")

        return client
    authz = Implicit()

    try:
        capabilities = config.CAPABILITIES
    except AttributeError:
        capabilities = None

    # Initiate the Provider
    OAS = Custom_POP_Provider(config.issuer, None, cdb, broker, authz,
                   baseurl=config.issuer, client_authn=verify_client,
                   symkey=config.SYM_KEY, hostname=config.HOST,
                   capabilities=capabilities,
                   behavior=config.BEHAVIOR)

    try:
        jwks = keyjar_init(OAS, config.keys, kid_template="op%d")

    except Exception as err:
        LOGGER.error("Key setup failed: {}".format(err))
        print("Key setup failed: {}".format(err))
        exit()
        #OAS.key_setup("static", sig={"format": "jwk", "alg": "rsa"})
    else:
        jwks_file_name = JWKS_FILE_NAME
        f = open(jwks_file_name, "w")

        for key in jwks["keys"]:
            for k in key.keys():
                key[k] = as_unicode(key[k])

        f.write(json.dumps(jwks))
Exemple #39
0
    def create_client(self, **kwargs):
        """
        Instantiate a client instance

        :param: Keyword arguments
            Keys are ["srv_discovery_url", "client_info", "client_registration",
            "provider_info". "keys]
        :return: client instance
        """

        _key_set = set(kwargs.keys())
        args = {}

        client = self.client_cls(client_authn_methods=CLIENT_AUTHN_METHOD,
                                 behaviour=kwargs["behaviour"],
                                 verify_ssl=self.config.VERIFY_SSL,
                                 **args)

        # The behaviour parameter is not significant for the election process
        _key_set.discard("behaviour")
        try:
            setattr(client, "allow", kwargs["allow"])
        except KeyError:
            pass
        else:
            _key_set.discard("allow")

        try:
            jwks = keyjar_init(client, kwargs["keys"])
        except KeyError:
            pass
        else:
            # export JWKS
            p = urlparse(self.config.CLIENT["key_export_url"] % self._port)
            f = open("." + p.path, "w")
            f.write(json.dumps(jwks))
            f.close()
            client.jwks_uri = p.geturl()

        self.test_features = _key_set

        try:
            client.client_prefs = copy.copy(kwargs["preferences"])
        except KeyError:
            pass
        else:
            _key_set.discard("preferences")

        if "client_info" in _key_set:
            client.redirect_uris = self.config.CLIENT["client_info"][
                "redirect_uris"]
        elif "client_registration" in _key_set:
            reg_info = self.config.CLIENT["client_registration"]
            client.redirect_uris = reg_info["redirect_uris"]
            client.client_id = reg_info["client_id"]
            try:
                client.client_secret = reg_info["client_secret"]
            except KeyError:
                pass

        if "provider_info" in _key_set:
            client.provider_info = ProviderConfigurationResponse(
                **self.config.CLIENT["provider_info"])

            for key, val in self.config.CLIENT["provider_info"].items():
                if key.endswith("_endpoint"):
                    setattr(client, key, val)
                elif key == "jwks_uri":
                    client.keyjar.load_keys(client.provider_info,
                                            client.provider_info["issuer"])

        return client