Example #1
0
    def _create_op(self, issuer, endpoint_baseurl, jwks_uri):
        """
        Create the necessary Provider instance.
        :type issuer: str
        :type endpoint_baseurl: str
        :type jwks_uri: str
        :param issuer: issuer URL for the OP
        :param endpoint_baseurl: baseurl to build endpoint URL from
        :param jwks_uri: URL to where the JWKS will be published
        """
        kj = KeyJar()
        signing_key = KeyBundle(source="file://{}".format(self.conf["signing_key_path"]),
                                fileformat="der", keyusage=["sig"])
        kj.add_kb("", signing_key)
        capabilities = {
            "response_types_supported": ["id_token"],
            "id_token_signing_alg_values_supported": [self.sign_alg],
            "response_modes_supported": ["fragment", "query"],
            "subject_types_supported": ["public", "pairwise"],
            "grant_types_supported": ["implicit"],
            "claim_types_supported": ["normal"],
            "claims_parameter_supported": True,
            "request_parameter_supported": False,
            "request_uri_parameter_supported": False,
        }

        if "client_db_path" in self.conf:
            cdb = shelve_wrapper.open(self.conf["client_db_path"])
        else:
            cdb = {}  # client db in memory only

        self.provider = Provider(issuer, None, cdb, None, None, None, None, None, keyjar=kj,
                                 capabilities=capabilities, jwks_uri=jwks_uri)
        self.provider.baseurl = endpoint_baseurl
        self.provider.endp = [RegistrationEndpoint, AuthorizationEndpoint]
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
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
Example #6
0
    def _create_op(self, issuer, endpoint_baseurl, jwks_uri):
        """
        Create the necessary Provider instance.
        :type issuer: str
        :type endpoint_baseurl: str
        :type jwks_uri: str
        :param issuer: issuer URL for the OP
        :param endpoint_baseurl: baseurl to build endpoint URL from
        :param jwks_uri: URL to where the JWKS will be published
        """
        kj = KeyJar()
        signing_key = KeyBundle(source="file://{}".format(
            self.conf["signing_key_path"]),
                                fileformat="der",
                                keyusage=["sig"])
        kj.add_kb("", signing_key)
        capabilities = {
            "response_types_supported": ["id_token"],
            "id_token_signing_alg_values_supported": [self.sign_alg],
            "response_modes_supported": ["fragment", "query"],
            "subject_types_supported": ["public", "pairwise"],
            "grant_types_supported": ["implicit"],
            "claim_types_supported": ["normal"],
            "claims_parameter_supported": True,
            "request_parameter_supported": False,
            "request_uri_parameter_supported": False,
        }

        if "client_db_path" in self.conf:
            cdb = shelve_wrapper.open(self.conf["client_db_path"])
        else:
            cdb = {}  # client db in memory only

        self.provider = Provider(issuer,
                                 None,
                                 cdb,
                                 None,
                                 None,
                                 None,
                                 None,
                                 None,
                                 keyjar=kj,
                                 capabilities=capabilities,
                                 jwks_uri=jwks_uri)
        self.provider.baseurl = endpoint_baseurl
        self.provider.endp = [RegistrationEndpoint, AuthorizationEndpoint]
Example #7
0
def print_client(cdb, cid):
    print(json.dumps(cdb[cid]))


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('-l', dest='list', action='store_true')
    parser.add_argument('-c', dest='clear', action='store_true')
    parser.add_argument('-p', dest='print')
    parser.add_argument('-n', dest='new')
    parser.add_argument('-d', dest='delete')
    args = parser.parse_args()

    cdb = shelve_wrapper.open("client_db")

    if args.clear:
        remove_old(cdb)

    if args.delete:
        del cdb[args.delete]

    if args.list:
        list_clients(cdb)

    if args.print:
        print_client(cdb, args.print)

    if args.new:
        _info = json.loads(args.new)
Example #8
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
Example #9
0
    parser = argparse.ArgumentParser()
    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('-t', dest='tls', action='store_true')
    parser.add_argument('-k', dest='insecure', action='store_true')
    parser.add_argument(
        '-c', dest='capabilities',
        help="A file containing a JSON representation of the capabilities")
    parser.add_argument('-i', dest='issuer', help="issuer id of the OP",
                        nargs=1)
    parser.add_argument(dest="config")
    args = parser.parse_args()

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

    logger.info("Known client_ids: {}".format([k for k in cdb.keys()]))
    sys.path.insert(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 += '/'
Example #10
0
    from oic.utils.sdb import SessionDB

    parser = argparse.ArgumentParser()
    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(
        '-c',
        dest='capabilities',
        help="A file containing a JSON representation of the capabilities")
    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)
    config.issuer = config.issuer % args.port
    config.SERVICE_URL = config.SERVICE_URL % args.port

    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, "%s/authorization" % config.issuer,
        None, full_end_point_paths)
Example #11
0
        None,  # templ_arg_func ??!!
        fullEndPointsPath)  # verification endpoints

    # AuthnIndexedEndpointWrapper is a wrapper class for using an authentication module with multiple endpoints.
    authnIndexedEndPointWrapper = AuthnIndexedEndpointWrapper(
        usernamePasswordAuthn, passwordEndPointIndex)

    authnBroker.add(
        config.AUTHENTICATION["UserPassword"]["ACR"],  # (?!)
        authnIndexedEndPointWrapper,  # (?!) method: an identifier of the authentication method.
        config.AUTHENTICATION["UserPassword"]["WEIGHT"],  # security level
        "")  # (?!) authentication authority

    # ?!
    authz = AuthzHandling()
    clientDB = shelve_wrapper.open(config.CLIENTDB)

    # In-Memory non-persistent SessionDB issuing DefaultTokens
    sessionDB = create_session_db(config.ISSUER,
                                  secret=rndstr(32),
                                  password=rndstr(32))

    provider = Provider(
        name=config.ISSUER,  # name
        sdb=sessionDB,  # session database.
        cdb=clientDB,  # client database
        authn_broker=authnBroker,  # authn broker
        userinfo=None,  # user information
        authz=authz,  # authz
        client_authn=verify_client,  # client authentication
        symkey=config.SYM_KEY,  # Used for Symmetric key authentication
Example #12
0
def db(tmpdir):
    return shelve_wrapper.open(
        os.path.join(tmpdir.strpath, "test_db_shelve_wrapper"))
Example #13
0
    from oic.utils.sdb import SessionDB

    PARSER = argparse.ArgumentParser()
    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(
        '-c', dest='capabilities',
        help="A file containing a JSON representation of the capabilities")
    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]
Example #14
0
        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)

    authnBroker.add(config.AUTHENTICATION["UserPassword"]["ACR"],  # (?!)
           authnIndexedEndPointWrapper,                      # (?!) method: an identifier of the authentication method.
           config.AUTHENTICATION["UserPassword"]["WEIGHT"],  # security level
           "")                                               # (?!) authentication authority

    # ?!
    authz = AuthzHandling()
    clientDB = shelve_wrapper.open(config.CLIENTDB)

    # In-Memory non-persistent SessionDB issuing DefaultTokens
    sessionDB = create_session_db(config.ISSUER,
                                  secret=rndstr(32),
                                  password=rndstr(32))

    provider = Provider(
        name=config.ISSUER,                            # name
        sdb=sessionDB,                                 # session database.
        cdb=clientDB,                                  # client database
        authn_broker=authnBroker,                      # authn broker
        userinfo=None,                                 # user information
        authz=authz,                                   # authz
        client_authn=verify_client,                    # client authentication
        symkey=config.SYM_KEY,                         # Used for Symmetric key authentication