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}
def test_get_sids_from_uid_distributed(self): db = DictSessionBackend() sdb1 = create_session_db("https://example.com/1", "secret", "password", db=db) sdb2 = create_session_db("https://example.com/2", "secret", "password", db=db) ae = AuthnEvent("sub", "salt", time_stamp=time.time()) sid1 = sdb1.create_authz_session(ae, AREQ) sdb1.do_sub(sid1, "salt") sid2 = sdb2.create_authz_session(ae, AREQ) sdb2.do_sub(sid2, "salt") sdb1sids = sdb1.get_sids_from_uid("sub") sdb2sids = sdb2.get_sids_from_uid("sub") assert sdb1sids == sdb2sids
def setup_op(self, oper_id, test_id, com_args, op_arg, test_conf, events): _sdb = create_session_db(com_args["baseurl"], 'automover', '430X', {}) op = self.provider_cls(sdb=_sdb, **com_args) op.events = events op.oper_id = oper_id op.test_id = test_id for _authn in com_args["authn_broker"]: _authn.srv = op for key, val in list(op_arg.items()): if key == 'keyjar': init_keyjar(op, val, com_args) else: setattr(op, key, val) write_jwks_uri(op, op_arg, self.folder) if op.baseurl.endswith("/"): div = "" else: div = "/" op.name = op.baseurl = "{}{}{}/{}".format(op.baseurl, div, oper_id, test_id) _tc = test_conf[test_id] if not _tc: raise UnknownTestID(test_id) try: _capa = _tc['capabilities'] except KeyError: pass else: op.capabilities.update(_capa) # update jwx for _typ in ["signing_alg", "encryption_alg", "encryption_enc"]: for item in ["id_token", "userinfo"]: cap_param = '{}_{}_values_supported'.format(item, _typ) try: op.jwx_def[_typ][item] = _capa[cap_param][0] except KeyError: pass try: op.claims_type = _tc["claims"] except KeyError: pass try: op.behavior_type = _tc["behavior"] op.server.behavior_type = _tc["behavior"] except KeyError: pass return op
def create_provider(self): sunet_op = 'https://www.sunet.se/op' _kj = build_keyjar(KEYDEFS)[1] fed_ent = FederationEntity(None, keyjar=_kj, iss=sunet_op, signer=signer[OA['sunet']], fo_bundle=keybundle) _sdb = create_session_db(sunet_op, 'hemlighet', 'ordet', {}) self.op = Provider(sunet_op, _sdb, {}, AUTHN_BROKER, USERINFO, AUTHZ, client_authn=verify_client, symkey=SYMKEY, federation_entity=fed_ent) self.op.baseurl = self.op.name self.op.signer = signer[OA['sunet']]
def fac(issuer): return create_session_db(issuer, secret='supersecret', password='******')
# "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 # In-Memory non persistent SessionDB sdb = create_session_db(_issuer, secret=rndstr(32), password=rndstr(32)) OAS = Provider(_issuer, sdb, cdb, ac, None, authz, verify_client, config.SYM_KEY, **kwargs) OAS.baseurl = _issuer for authn in ac: authn.srv = OAS if config.USERINFO == "SIMPLE": # User info is a simple dictionary in this case statically defined in # the configuration file OAS.userinfo = UserInfo(config.USERDB) elif config.USERINFO == "SAML": OAS.userinfo = UserInfo(config.SAML) elif config.USERINFO == "AA":
return None, 0 else: return {"uid": self.user}, time() 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 = {} # ------------------------------------------------------------ _sdb = create_session_db(sunet_op, 'automover', '430X', {}) op = Provider(sunet_op, _sdb, {}, AUTHN_BROKER, USERINFO, AUTHZ, client_authn=verify_client, symkey=SYMKEY, federation_entity=fed_ent) fedpi = op.create_fed_providerinfo() data = urlencode({ 'iss': FO['oidf'], 'ms':
def fac(issuer): return create_session_db(issuer, secret="supersecret", password="******")
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=8093, type=int) parser.add_argument(dest="config") args = parser.parse_args() cdb = json.loads(open("claims_client.json").read()) userinfo = UserInfo(USERDB) # in memory session storage config = json.loads(open(args.config).read()) sdb = create_session_db(config["issuer"], config["SESSION_KEY"], password="******") OAS = ClaimsServer(config["issuer"], sdb, cdb, userinfo, verify_client) if "keys" in config: for typ, info in config["keys"].items(): OAS.keyjar.add_kb("", keybundle_from_local_file(info["key"], "rsa", ["ver", "sig"])) try: OAS.jwks_uri.append(info["jwk"]) except KeyError: pass #print URLS if args.debug:
ac.add(config.AUTHORIZATION[authkey]["ACR"], authn, config.AUTHORIZATION[authkey]["WEIGHT"], config.AUTHORIZATION[authkey]["URL"]) # dealing with authorization authz = AuthzHandling() # authz = UserInfoConsent() # User info database if args.insecure: kwargs = {"verify_ssl": False} else: kwargs = {"verify_ssl": True} # In-Memory SessionDB issuing DefaultTokens sdb = create_session_db(config.baseurl, secret=rndstr(32), password=rndstr(32)) if args.test: URLS.append((r'tracelog', trace_log)) OAS = TestProvider(config.issuer, sdb, cdb, ac, None, authz, config.SYM_KEY) elif args.XpressConnect: from XpressConnect import XpressConnectProvider OAS = XpressConnectProvider(config.issuer, sdb, cdb, ac, None, authz, verify_client, config.SYM_KEY) else: OAS = Provider(config.issuer, sdb, cdb, ac, None, authz, verify_client, config.SYM_KEY, **kwargs)
} # 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 # In-Memory non persistent SessionDB sdb = create_session_db(_issuer, secret=rndstr(32), password=rndstr(32)) OAS = Provider(_issuer, sdb, cdb, ac, None, authz, verify_client, config.SYM_KEY, **kwargs) OAS.baseurl = _issuer for authn in ac: authn.srv = OAS if config.USERINFO == "SIMPLE": # User info is a simple dictionary in this case statically defined in # the configuration file OAS.userinfo = UserInfo(config.USERDB) elif config.USERINFO == "SAML": OAS.userinfo = UserInfo(config.SAML)
# 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 # urlmap = None, # ? # keyjar = None, # ? # hostname = "", # ? template_renderer=mako_renderer, # Rendering custom templates
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=8093, type=int) parser.add_argument(dest="config") args = parser.parse_args() cdb = json.loads(open("claims_client.json").read()) userinfo = UserInfo(USERDB) # in memory session storage config = json.loads(open(args.config).read()) sdb = create_session_db(config["issuer"], config["SESSION_KEY"], password=rndstr(16)) OAS = ClaimsServer(config["issuer"], sdb, cdb, userinfo, verify_client) if "keys" in config: for typ, info in config["keys"].items(): OAS.keyjar.add_kb("", keybundle_from_local_file(info["key"], "rsa", ["ver", "sig"])) try: OAS.jwks_uri.append(info["jwk"]) except KeyError: pass #print URLS if args.debug:
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
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
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
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()
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 # urlmap = None, # ? # keyjar = None, # ? # hostname = "", # ? template_renderer=mako_renderer, # Rendering custom templates
authn, config.AUTHORIZATION[authkey]["WEIGHT"], config.AUTHORIZATION[authkey]["URL"]) # dealing with authorization authz = AuthzHandling() # authz = UserInfoConsent() # User info database if args.insecure: kwargs = {"verify_ssl": False} else: kwargs = {"verify_ssl": True} # In-Memory SessionDB issuing DefaultTokens sdb = create_session_db(config.baseurl, secret=rndstr(32), password=rndstr(32)) if args.test: URLS.append((r'tracelog', trace_log)) OAS = TestProvider(config.issuer, sdb, cdb, ac, None, authz, config.SYM_KEY) elif args.XpressConnect: from XpressConnect import XpressConnectProvider OAS = XpressConnectProvider(config.issuer, sdb, cdb, ac, None, authz, verify_client, config.SYM_KEY) else: OAS = Provider(config.issuer, sdb, cdb, ac, None, authz, verify_client, config.SYM_KEY, **kwargs)