def get_basic_auth_credentials(self, request): basic_auth = request.requestHeaders.getRawHeaders('Authorization', [None])[0] if basic_auth: bc = BasicCredentialFactory(self.realm) try: return bc.decode(basic_auth.split(' ')[1], None) except: raise BadRequest("The Authorization header was not parsable")
def get_basic_auth_credentials(self, request): basic_auth = request.requestHeaders.getRawHeaders( 'Authorization', [None])[0] if basic_auth: bc = BasicCredentialFactory(self.realm) try: return bc.decode(basic_auth.split(' ')[1], None) except: raise BadRequest("The Authorization header was not parsable")
def run(self): task.LoopingCall(self.status_check).start(0.5) root = File('www') root.putChild('st', StatusHandler(self)) root.putChild('upd', self.updateHandler) root.putChild('cfg', ConfigHandler(self)) root.putChild('upt', UptimeHandler(self)) if self.config['config']['use_auth']: clk = ClickHandler(self) args = { self.config['site']['username']: self.config['site']['password'] } checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(**args) realm = HttpPasswordRealm(clk) p = portal.Portal(realm, [checker]) credentialFactory = BasicCredentialFactory( "Garage Door Controller") protected_resource = HTTPAuthSessionWrapper(p, [credentialFactory]) root.putChild('clk', protected_resource) cla = CloseHandler(self) cla_args = { self.config['site']['username']: self.config['site']['password'] } cla_checker = checkers.InMemoryUsernamePasswordDatabaseDontUse( **cla_args) cla_realm = HttpPasswordRealm(cla) cla_p = portal.Portal(cla_realm, [cla_checker]) credentialFactory = BasicCredentialFactory( "Garage Door Controller") cla_protected_resource = HTTPAuthSessionWrapper( cla_p, [credentialFactory]) root.putChild('cla', cla_protected_resource) else: root.putChild('clk', ClickHandler(self)) root.putChild('cla', CloseHandler(self)) if self.config['config']['allow_api']: root.putChild('api', APIHandler(self)) site = server.Site(root) if not self.get_config_with_default(self.config['config'], 'use_https', False): reactor.listenTCP(self.config['site']['port'], site) # @UndefinedVariable reactor.run() # @UndefinedVariable else: sslContext = ssl.DefaultOpenSSLContextFactory( self.config['site']['ssl_key'], self.config['site']['ssl_cert']) reactor.listenSSL(self.config['site']['port_secure'], site, sslContext) # @UndefinedVariable reactor.run() # @UndefinedVariable
def resource(): """Initialize the HTTP Authentication.""" resthandle = RestIntf() realm = CheckRealm(resource=resthandle.app.resource()) portal = Portal(realm, [FilePasswordDB('./server-auth.db')]) credential_factory = BasicCredentialFactory(b"http auth realm") return HTTPAuthSessionWrapper(portal, [credential_factory])
def getAuthResource(in_resource, sname, config, password_checker=AnchorePasswordChecker()): if not password_checker: # explicitly passed in null password checker obj return (in_resource) if sname in config['services']: localconfig = config['services'][sname] else: # no auth required return in_resource do_auth = True if localconfig and 'require_auth' in localconfig and not localconfig[ 'require_auth']: do_auth = False if do_auth: # if localconfig and 'require_auth' in localconfig and localconfig['require_auth']: # if 'require_auth_file' not in localconfig or not os.path.exists(localconfig['require_auth_file']): # raise Exception("require_auth is set for service, but require_auth_file is not set/invalid") realm = HTTPAuthRealm(resource=in_resource) portal = Portal(realm, [password_checker]) credential_factory = BasicCredentialFactory(b'Authentication required') resource = HTTPAuthSessionWrapper(portal, [credential_factory]) else: resource = in_resource return resource
def require_basic_auth(resource): p = portal.Portal(TestAuthRealm()) c = checkers.InMemoryUsernamePasswordDatabaseDontUse() c.addUser("john", "john") p.registerChecker(c) cred_factory = BasicCredentialFactory("Basic Auth protected area") return HTTPAuthSessionWrapper(p, [cred_factory])
def _setup_twisted(self): root = resource.Resource() checker = _PasswordChecker() cf = BasicCredentialFactory(SERVER_NAME) # eggs eggs_path = pkg_resources.resource_filename( 'stoqserver', 'data/eggs') root.putChild( 'eggs', self._get_resource_wrapper(static.File(eggs_path), checker, cf)) # conf root.putChild( 'login', self._get_resource_wrapper(static.File(APP_CONF_FILE), checker, cf)) # md5sum with tempfile.NamedTemporaryFile(delete=False) as f: for egg in SERVER_EGGS: egg_path = os.path.join(eggs_path, egg) if not os.path.exists(eggs_path): continue f.write('%s:%s\n' % (egg, md5sum_for_filename(egg_path))) root.putChild('md5sum', static.File(f.name)) site = server.Site(root) site.protocol = HTTPChannel reactor.listenTCP(SERVER_AVAHI_PORT, site)
def run(self): """ Start the server and listen on host:port """ f = None unix_prefix = 'unix://' if self.http_enabled: rpc = JsonRpcHttpResource() rpc.rpcprocessor = self.rpcprocessor rpc.tls_client_auth_enabled = self.tls_client_auth_enabled if self.http_basic_auth_enabled: checker = PasswordChecker(self.passwdCheckFunction) realm = HttpPasswordRealm(rpc) p = portal.Portal(realm, [checker]) realm_name = 'Reflect RPC' if sys.version_info.major == 2: realm_name = realm_name.encode('utf-8') credentialFactory = BasicCredentialFactory(realm_name) rpc = HTTPAuthSessionWrapper(p, [credentialFactory]) root = RootResource(rpc) f = server.Site(root) else: f = JsonRpcProtocolFactory(self.rpcprocessor, self.tls_client_auth_enabled) if self.tls_enabled: if not self.tls_client_auth_enabled: reactor.listenSSL(self.port, f, self.cert.options(), interface=self.host) else: reactor.listenSSL(self.port, f, self.cert.options(self.client_auth_ca), interface=self.host) else: if self.host.startswith(unix_prefix): path = self.host[len(unix_prefix):] reactor.listenUNIX(path, f, backlog=self.unix_socket_backlog, mode=self.unix_socket_mode, wantPID=self.unix_socket_want_pid) else: reactor.listenTCP(self.port, f, interface=self.host) if self.host.startswith(unix_prefix): print("Listening on %s" % (self.host)) else: print("Listening on %s:%d" % (self.host, self.port)) reactor.run()
def test_getLoginResource(self): self.auth = auth.TwistedICredAuthBase( credentialFactories=[BasicCredentialFactory("buildbot")], checkers=[InMemoryUsernamePasswordDatabaseDontUse(good=b'guy')]) self.auth.master = self.make_master(url='h:/a/b/') rsrc = self.auth.getLoginResource() self.assertIsInstance(rsrc, HTTPAuthSessionWrapper)
def __init__(self, users, **kwargs): TwistedICredAuthBase.__init__( self, [DigestCredentialFactory("md5", "buildbot"), BasicCredentialFactory("buildbot")], [InMemoryUsernamePasswordDatabaseDontUse(**dict(users))], **kwargs)
def addBasicAuth(resource, desc, **users): """Add basic auth for a resource. Twisteds modulation of everything makes this quite.. messy.""" realm = SimpleResourceRealm(resource) portal = Portal(realm, [InMemoryUsernamePasswordDatabaseDontUse(**users)]) credentialFactory = BasicCredentialFactory(desc) return HTTPAuthSessionWrapper(portal, [credentialFactory])
def getChild(self, path, request): if isinstance(self.session, UnauthorizedLogin): factories = [ BasicCredentialFactory('fluidinfo.com'), OAuthCredentialFactory('fluidinfo.com'), OAuth2CredentialFactory('fluidinfo.com') ] return WSFEUnauthorizedResource(factories) # Add a unique id to the request so we can more easily trace its # progress in our log files. Note that we need to put an id on the # request even in the case that we're going to return NoResource, # as it's all logged. request._fluidDB_reqid = self.session.id self.session.http.trace(request) if path == 'oauthecho': return OAuthEchoResource(self.session) elif path == 'renew-oauth-token': return RenewOAuthTokenResource(self.session) try: resource = self._resources[path] except KeyError: return NoResource() else: return resource(self.facadeClient, self.session)
def get_protected_resource(self, resource): checker = RapidSMSRelayAccessChecker(self.get_avatar_id) realm = RapidSMSRelayRealm(resource) p = portal.Portal(realm, [checker]) factory = BasicCredentialFactory("RapidSMS Relay") protected_resource = HTTPAuthSessionWrapper(p, [factory]) return protected_resource
def setupRootResource(facade, development=None): """Get the root resource to use for the API service. @param facade: A L{Facade} instance. @return: An C{HTTPAuthSessionWrapper} instance. """ from fluiddb.web.root import WSFERealm, IFacadeRealm from fluiddb.web.checkers import (AnonymousChecker, FacadeChecker, FacadeOAuthChecker, FacadeOAuth2Checker, IFacadeChecker) portal = Portal(WSFERealm(), [ FacadeChecker(), FacadeOAuthChecker(), FacadeOAuth2Checker(), AnonymousChecker() ]) realm = IFacadeRealm(portal.realm) realm.facadeClient = facade for checker in portal.checkers.values(): if IFacadeChecker.providedBy(checker): checker.facadeClient = facade factories = [ BasicCredentialFactory('fluidinfo.com'), OAuthCredentialFactory('fluidinfo.com'), OAuth2CredentialFactory('fluidinfo.com', development) ] return HTTPAuthSessionWrapper(portal, factories)
def __init__(self, passwdFile, **kwargs): TwistedICredAuthBase.__init__( self, [DigestCredentialFactory("md5", "buildbot"), BasicCredentialFactory("buildbot")], [FilePasswordDB(passwdFile)], **kwargs)
def authed_resource(self, resource): """ See HTTPInterface.register_resource() """ return HTTPAuthSessionWrapper( Portal(EnDroidRealm(resource), self._creds), [BasicCredentialFactory("EnDroid")])
def build_sharing_resource(): passwd_file = os.path.join(os.path.dirname(__file__), "httpd.password") root = build_shared_folder_resource() portal = Portal(PublicHTMLRealm(root), [FilePasswordDB(passwd_file)]) credentialFactory = BasicCredentialFactory("Realm Description....") return HTTPAuthSessionWrapper(portal, [credentialFactory])
def __init__(self, realm, vumi_api): checkers = [ GoUserSessionAccessChecker(vumi_api.session_manager), ] p = portal.Portal(realm, checkers) factory = BasicCredentialFactory("Vumi Go API") super(GoUserAuthSessionWrapper, self).__init__(p, [factory])
def run(self): task.LoopingCall(self.status_check).start(0.5) root = File('www') root.putChild('upd', self.updateHandler) root.putChild('cfg', ConfigHandler(self)) if self.config['config']['use_auth']: clk = ClickHandler(self) args = { self.config['site']['username']: self.config['site']['password'] } checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(**args) realm = HttpPasswordRealm(clk) p = portal.Portal(realm, [checker]) credentialFactory = BasicCredentialFactory( "Garage Door Controller") protected_resource = HTTPAuthSessionWrapper(p, [credentialFactory]) root.putChild('clk', protected_resource) else: root.putChild('clk', ClickHandler(self)) site = server.Site(root) reactor.listenTCP(self.config['site']['port'], site) # @UndefinedVariable reactor.run() # @UndefinedVariable
def getResource(app, sname, config): if sname in config['services']: localconfig = config['services'][sname] else: # no auth required return(app.resource()) if localconfig and 'require_auth' in localconfig and localconfig['require_auth']: #if 'require_auth_file' not in localconfig or not os.path.exists(localconfig['require_auth_file']): # raise Exception("require_auth is set for service, but require_auth_file is not set/invalid") realm = HTTPAuthRealm(resource=app.resource()) portal = Portal(realm, [AnchorePasswordChecker()]) #portal = Portal(realm, [FilePasswordDB(localconfig['require_auth_file'])]) #portal = Portal(realm, [FilePasswordDB(localconfig['require_auth_file'], hash=hellothere)]) # # for route-based auth, need anon and auth # #from twisted.cred.checkers import AllowAnonymousAccess #portal = Portal( # realm, [ # FilePasswordDB('./configs/server-auth.db'), # AllowAnonymousAccess(), # ], #) credential_factory = BasicCredentialFactory('Authentication required') #credential_factory = DigestCredentialFactory('md5', 'anchore') resource = HTTPAuthSessionWrapper(portal, [credential_factory]) else: resource = app.resource() return (resource)
def wrap_with_auth(resource, passwdF, realm="Auth"): """ @param resource: resource to protect """ checkers = [PasswordDictCredentialChecker(passwdF)] return HTTPAuthSessionWrapper(Portal(PublicHTMLRealm(resource), checkers), [BasicCredentialFactory(realm)])
def __init__(self, users, **kwargs): if isinstance(users, dict): users = {user: unicode2bytes(pw) for user, pw in users.items()} elif isinstance(users, list): users = [(user, unicode2bytes(pw)) for user, pw in users] super().__init__([ DigestCredentialFactory(b"MD5", b"buildbot"), BasicCredentialFactory(b"buildbot") ], [InMemoryUsernamePasswordDatabaseDontUse(**dict(users))], **kwargs)
def wrap_with_auth(resource, passwords, realm="Auth"): """ @param resource: resource to protect @param passwords: a dict-like object mapping usernames to passwords """ portal = Portal(PublicHTMLRealm(resource), [PasswordDictCredentialChecker(passwords)]) credentialFactory = BasicCredentialFactory(realm) return HTTPAuthSessionWrapper(portal, [credentialFactory])
def __init__(self, users, **kwargs): for user, password in users.items(): users[user] = unicode2bytes(password) TwistedICredAuthBase.__init__( self, [DigestCredentialFactory(b"md5", b"buildbot"), BasicCredentialFactory(b"buildbot")], [InMemoryUsernamePasswordDatabaseDontUse(**dict(users))], **kwargs)
def setUp(self): checker = InMemoryUsernamePasswordDatabaseDontUse(user='******') portal = Portal(AuthDummyServer(), [checker]) credentialFactory = BasicCredentialFactory('localhost') resource = HTTPAuthSessionWrapper(portal, [credentialFactory]) site = Site(resource) self.port = reactor.listenTCP(0, site) self.portNumber = self.port._realPortNumber
def run_server(project): portal = Portal(ProjectRealm(project), [DatabaseAuth(project.userbase)]) credentialFactory = BasicCredentialFactory(project.description()) resource = HTTPAuthSessionWrapper(portal, [credentialFactory]) factory = Site(resource) reactor.listenTCP(8880, factory) reactor.run()
def boot(listen_addr='127.0.0.1', port=8080, session_bus=False, sage_www_root=DEFAULT_SAGE_ROOT, auth_realm=None, auth_passwd=None, allow_ga=None, deny_ga=None, no_www=False): assert not ( allow_ga and deny_ga ), 'Must not specify both deny and allow rules for group addresses' global api global factory DBusGMainLoop(set_as_default=True) if session_bus: bus = dbus.SessionBus() else: bus = dbus.SystemBus() obj = bus.get_object(DBUS_SERVICE, DBUS_PATH) api = dbus.Interface(obj, DBUS_INTERFACE) uri = createWsUrl(listen_addr, port) factory = SageProtocolFactory(uri, debug=False, api=api, allow_ga=allow_ga, deny_ga=deny_ga) factory.setProtocolOptions(allowHixie76=True, webStatus=False) factory.protocol = SageProtocol factory.clients = [] resource = WebSocketResource(factory) if no_www: root = resource else: root = File(sage_www_root) root.putChild('saged', resource) if auth_realm != None and auth_passwd != None: portal = Portal(SageRealm(root), [ApachePasswordDB(auth_passwd)]) credentialFactories = [ BasicCredentialFactory(auth_realm), ] root = HTTPAuthSessionWrapper(portal, credentialFactories) site = Site(root) site.protocol = HTTPChannelHixie76Aware reactor.listenTCP(port, site, interface=listen_addr) reactor.run()
def main(): readIniFile() LOGGING['handlers']['file']['filename'] = logpath + '/mpexagent.log' logging.config.dictConfig(LOGGING) observer = twlog.PythonLoggingObserver() observer.start() args = parse_args() try: if args.mpex_url: mpexagent = MPExAgent(replaycheck=True, mpexurl=args.mpex_url) else: mpexagent = MPExAgent(replaycheck=True) mpexagent.passphrase = getpass("Enter your GPG passphrase: ") root = JSON_RPC().customize(RPCServer) root.eventhandler.agent = mpexagent if (mode != 'noweb'): webroot = static.File(webpath) webroot.putChild('jsonrpc', root) root = webroot if (auth != 'noauth'): if (auth == 'md5'): hashfunc = hashmd5 if (auth == 'sha1'): hashfunc = hashsha1 if (auth == 'plain'): hashfunc = hashplain realm = HttpPasswordRealm(root) p = portal.Portal(realm, [ checkers.FilePasswordDB(passpath, delim=":", hash=hashfunc) ]) credentialFactory = BasicCredentialFactory("MpexAgent") protected_resource = HTTPAuthSessionWrapper( p, [credentialFactory]) root = protected_resource site = server.Site(root) bindaddr = '*:' if args.listen_addr == '' else args.listen_addr + ':' log.info('Listening on %s%d...', bindaddr, args.port) if (mode != 'https'): reactor.listenTCP(args.port, site, interface=args.listen_addr) else: reactor.listenSSL( args.port, site, ssl.DefaultOpenSSLContextFactory(keypath, certpath)) reactor.run() except KeyboardInterrupt: print '^C received, shutting down server' server.socket.close()
def get_authenticated_resource(self, resource): if not self.web_username: return resource realm = HttpRpcRealm(resource) checkers = [ StaticAuthChecker(self.web_username, self.web_password), ] portal = Portal(realm, checkers) cred_factories = [ BasicCredentialFactory(self.web_auth_domain), ] return HTTPAuthSessionWrapper(portal, cred_factories)
def getChild(self, conversation_key, request): if conversation_key: res = self.resource_class(self.worker, conversation_key) checker = ConversationAccessChecker(self.worker, conversation_key) realm = ConversationRealm(res) p = portal.Portal(realm, [checker]) factory = BasicCredentialFactory("Conversation Realm") protected_resource = HTTPAuthSessionWrapper(p, [factory]) return protected_resource else: return resource.NoResource()
def start_rest_api(self): root_page = resource.Resource() root_page.putChild('api', make_rest_api()) site = AuthenticatedSite(root_page) site.credentialFactories = [ BasicCredentialFactory("CloudMailing API"), DigestCredentialFactory("md5", "CloudMailing API") ] site.credentialsCheckers = [AdminChecker()] site.sessionFactory = UTSession self.p = reactor.listenTCP(0, site, interface="127.0.0.1") self.port = self.p.getHost().port self.api_base_url = 'http://127.0.0.1:%d/api/' % self.port self.agent = None