def test_anonymousLogin(self): """ Verify that a PB server using a portal configured with an checker which allows IAnonymous credentials can be logged into using IAnonymous credentials. """ self.portal.registerChecker(checkers.AllowAnonymousAccess()) factory = pb.PBClientFactory() d = factory.login(credentials.Anonymous(), "BRAINS!") def cbLoggedIn(perspective): return perspective.callRemote('echo', 123) d.addCallback(cbLoggedIn) d.addCallback(self.assertEqual, 123) def cleanup(passthrough): factory.disconnect() d = Deferred() reactor.callLater(1.0, d.callback, None) return d d.addBoth(cleanup) reactor.connectTCP("127.0.0.1", self.portno, factory) return d
def setUp(self): # Create a directory self.directory = self.mktemp() os.mkdir(self.directory) # Start the server p = portal.Portal(ftp.FTPRealm(self.directory)) p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) self.factory = ftp.FTPFactory(portal=p) self.port = reactor.listenTCP(0, self.factory, interface="127.0.0.1") # Hook the server's buildProtocol to make the protocol instance # accessible to tests. buildProtocol = self.factory.buildProtocol def _rememberProtocolInstance(addr): protocol = buildProtocol(addr) self.serverProtocol = protocol.wrappedProtocol return protocol self.factory.buildProtocol = _rememberProtocolInstance # Connect a client to it portNum = self.port.getHost().port clientCreator = protocol.ClientCreator(reactor, ftp.FTPClientBasic) self.client = wait(clientCreator.connectTCP("127.0.0.1", portNum))
def setUp(self): self.filename = self.mktemp() file(self.filename, 'w').write('admin:asdf\nalice:foo\n') self.goodChecker = checkers.FilePasswordDB(self.filename) self.badChecker = checkers.FilePasswordDB(self.filename, hash=self._hash) self.anonChecker = checkers.AllowAnonymousAccess()
def test_forceAuthentication(self): """ Test that if an HTTPError with an Unauthorized status code is raised from within our protected resource, we add the WWW-Authenticate headers if they do not already exist. """ self.portal.registerChecker(checkers.AllowAnonymousAccess()) nonAnonResource = NonAnonymousResource() nonAnonResource.responseText = "We don't like anonymous users" root = wrapper.HTTPAuthResource(nonAnonResource, [self.credFactory], self.portal, interfaces=(IHTTPUser, )) def _tryAuthenticate(result): credentials = base64.encodestring('username:password') d2 = self.assertResponse((root, 'http://localhost/', { 'authorization': ('basic', credentials) }), (200, {}, "We don't like anonymous users")) return d2 d = self.assertResponse((root, 'http://localhost/', {}), (401, { 'WWW-Authenticate': [('basic', { 'realm': "test realm" })] }, None)) d.addCallback(_tryAuthenticate) return d
def postOptions(self): from twisted.internet import reactor if self['pop3s']: if not self['certificate']: raise usage.UsageError("Cannot specify --pop3s without " "--certificate") elif not os.path.exists(self['certificate']): raise usage.UsageError("Certificate file %r does not exist." % self['certificate']) else: self.addEndpoint('pop3', self['pop3s'], certificate=self['certificate']) if not self['disable-anonymous']: self.service.smtpPortal.registerChecker( checkers.AllowAnonymousAccess()) anything = False for service in self._protoDefaults: self[service] = self._getEndpoints(reactor, service) if self[service]: anything = True if not anything: raise usage.UsageError("You cannot disable all protocols")
def test_anonymousAuthentication(self): """ If our portal has a credentials checker for IAnonymous credentials authentication succeeds if no Authorization header is present """ self.portal.registerChecker(checkers.AllowAnonymousAccess()) self.protectedResource.responseText = "Anonymous access allowed" root = wrapper.HTTPAuthResource(self.protectedResource, [self.credFactory], self.portal, interfaces=(IHTTPUser,)) def _checkRequest(ign): self.assertEquals( self.protectedResource.request.avatar.username, 'anonymous') d = self.assertResponse((root, 'http://localhost/', {}), (200, {}, "Anonymous access allowed")) d.addCallback(_checkRequest) return d
def test_responseFilterDoesntClobberHeaders(self): """ Test that if an UNAUTHORIZED response is returned and already has 'WWW-Authenticate' headers we don't add them. """ self.portal.registerChecker(checkers.AllowAnonymousAccess()) nonAnonResource = NonAnonymousResource() nonAnonResource.responseText = "We don't like anonymous users" nonAnonResource.sendOwnHeaders = True root = wrapper.HTTPAuthResource(nonAnonResource, [self.credFactory], self.portal, interfaces=(IHTTPUser,)) d = self.assertResponse( (root, 'http://localhost/', {}), (401, {'WWW-Authenticate': [('basic', {'realm': "foo"})]}, None)) return d
def postOptions(self): """ Check the validity of the specified set of options and configure authentication. @raise UsageError: When the set of options is invalid. """ from twisted.internet import reactor if self['esmtp'] and self['hostname'] is None: raise usage.UsageError("--esmtp requires --hostname") # If the --auth option was passed, this will be present -- otherwise, # it won't be, which is also a perfectly valid state. if 'credCheckers' in self: for ch in self['credCheckers']: self.service.smtpPortal.registerChecker(ch) if not self['disable-anonymous']: self.service.smtpPortal.registerChecker( checkers.AllowAnonymousAccess()) anything = False for service in self._protoDefaults: self[service] = self._getEndpoints(reactor, service) if self[service]: anything = True if not anything: raise usage.UsageError("You cannot disable all protocols")
def setUp(self): from twisted.protocols.ftp import FTPRealm, FTPFactory from scrapy.core.downloader.handlers.ftp import FTPDownloadHandler # setup dir and test file self.directory = self.mktemp() os.mkdir(self.directory) fp = FilePath(self.directory) fp.child('file.txt').setContent(b"I have the power!") fp.child('file with spaces.txt').setContent(b"Moooooooooo power!") # setup server for anonymous access realm = FTPRealm(anonymousRoot=self.directory) p = portal.Portal(realm) p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) self.factory = FTPFactory(portal=p, userAnonymous=self.username) self.port = reactor.listenTCP(0, self.factory, interface="127.0.0.1") self.portNum = self.port.getHost().port crawler = get_crawler() self.download_handler = create_instance(FTPDownloadHandler, crawler.settings, crawler) self.addCleanup(self.port.stopListening)
def test_anonymousLoginWithMultipleCheckers(self): """ Like L{test_anonymousLogin} but against a portal with a checker for both IAnonymous and IUsernamePassword. """ self.portal.registerChecker(checkers.AllowAnonymousAccess()) self.portal.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(user='******')) factory = pb.PBClientFactory() d = factory.login(credentials.Anonymous(), "BRAINS!") def cbLogin(perspective): return perspective.callRemote('echo', 123) d.addCallback(cbLogin) d.addCallback(self.assertEqual, 123) def cleanup(passthrough): factory.disconnect() return passthrough d.addBoth(cleanup) reactor.connectTCP('127.0.0.1', self.portno, factory) return d
def test_authenticatedLoginWithMultipleCheckers(self): """ Like L{test_anonymousLoginWithMultipleCheckers} but check that username/password authentication works. """ self.portal.registerChecker(checkers.AllowAnonymousAccess()) self.portal.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(user='******')) factory = pb.PBClientFactory() d = factory.login(credentials.UsernamePassword('user', 'pass'), "BRAINS!") def cbLogin(perspective): return perspective.callRemote('add', 100, 23) d.addCallback(cbLogin) d.addCallback(self.assertEqual, 123) def cleanup(passthrough): factory.disconnect() return passthrough d.addBoth(cleanup) reactor.connectTCP('127.0.0.1', self.portno, factory) return d
def setUp(self): self.filename = self.mktemp() with open(self.filename, "wb") as f: f.write(b"admin:asdf\nalice:foo\n") self.goodChecker = checkers.FilePasswordDB(self.filename) self.badChecker = checkers.FilePasswordDB(self.filename, hash=self._hash) self.anonChecker = checkers.AllowAnonymousAccess()
def getSite(config): form = AddressBookResource() form.remember(config, ILDAPConfig) realm = AddressBookRealm(form) site = appserver.NevowSite( guard.SessionWrapper( portal.Portal(realm, [checkers.AllowAnonymousAccess()]))) return site
def guardResource(resource, checkers, callback=parentRedirect, errback=None, nonauthenticated=None): myPortal = portal.Portal(MarkingRealm(resource, nonauthenticated)) for checker in checkers+[checkerslib.AllowAnonymousAccess()]: myPortal.registerChecker(checker) un = guard.UsernamePasswordWrapper(myPortal, callback=callback, errback=errback) return guard.SessionWrapper(un)
def createRealm(klass, master): realm = klass(master) p = portal.Portal(realm) p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) p.registerChecker(WebUiCredentialChecker(require_admin=False)) s = guard.SessionWrapper(p, mindFactory=klass.mind) s.useCookies = False # XXX: False is good for debugging, URIs show session info return s
def guardedRoot(db): realm = VellumRealm() port = portal.Portal(realm) myChecker = AxiomEmailChecker() port.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) port.registerChecker(myChecker) res = websession.PersistentSessionWrapper(db, port) return res
def createResource(): realm = MyRealm() porta = portal.Portal(realm) myChecker = checkers.InMemoryUsernamePasswordDatabaseDontUse() myChecker.addUser("user","password") myChecker.addUser("fred", "flintstone") porta.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) porta.registerChecker(myChecker) res = guard.SessionWrapper(porta) return res
def createPortal(enamel): """ createPortal Constructs our guarded realm and portal @param enamel: C{Enamel} instance """ realm = Realm(enamel) porta = portal.Portal(realm) porta.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) porta.registerChecker(enamel.authenticator(enamel)) return porta
def postOptions(self): if self['pop3s']: if not self['certificate']: raise usage.UsageError("Cannot specify --pop3s without " "--certificate") elif not os.path.exists(self['certificate']): raise usage.UsageError("Certificate file %r does not exist." % self['certificate']) if not self['disable-anonymous']: self.service.smtpPortal.registerChecker( checkers.AllowAnonymousAccess()) if not (self['pop3'] or self['smtp'] or self['pop3s']): raise usage.UsageError("You cannot disable all protocols")
def main(): r = Realm() p = portal.Portal(r) c = checkers.InMemoryUsernamePasswordDatabaseDontUse() c.addUser("auser", "thepass") c.addUser("SECONDUSER", "secret") p.registerChecker(c) p.registerChecker(checkers.AllowAnonymousAccess()) f = ServerFactory(p) log.startLogging(sys.stdout) from twisted.internet import reactor reactor.listenTCP(4738, f) reactor.run()
def wrapAuthorized(site): # force site to be nevow-compatible, using adapter for # twisted.web sites... site = inevow.IResource(site) realmObject = realm.CinemonRealm(site) portalObject = portal.Portal(realmObject) myChecker = checkers.InMemoryUsernamePasswordDatabaseDontUse() myChecker.addUser("user", "password") myChecker.addUser("fred", "flintstone") # Allow anonymous access. Needed for access to loginform portalObject.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) # Allow users registered in the password file. portalObject.registerChecker(myChecker) site = appserver.NevowSite(resource=guard.SessionWrapper(portalObject)) return site
def createPortal(db, root): """ createPortal Constructs our guarded realm and portal @param db: C{AccessBroker} instance """ realm = Realm(db, root) porta = portal.Portal(realm) porta.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) checker = Auth.LDAPChecker( Settings.LDAPServer, Settings.LDAPManager, Settings.LDAPPass, Settings.LDAPBase) # construct our database cred checker #checker = Auth.PlainChecker() porta.registerChecker(checker) return porta
def getResource(cfg=None, skinFactory=None): """Get a resource for the Ldaptor-webui app.""" if cfg is None: cfg = LDAPConfig() checker = LDAPBindingChecker(cfg) realm = TODOGetRidOfMeRealm(config=cfg) porta = portal.Portal(realm) porta.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) porta.registerChecker(checker) mainResource = guard.SessionWrapper(porta) if skinFactory is None: skinFactory = defskin.DefaultSkin return skin.Skinner(skinFactory, mainResource)
def makeService(config): f = ftp.FTPFactory() r = ftp.FTPRealm(config['root']) p = portal.Portal(r) p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) if config['password-file'] is not None: p.registerChecker(checkers.FilePasswordDB(config['password-file'], cache=True)) f.tld = config['root'] f.userAnonymous = config['userAnonymous'] f.portal = p f.protocol = ftp.FTP try: portno = int(config['port']) except KeyError: portno = 2121 return internet.TCPServer(portno, f)
def postOptions(self): for f in ('pop3', 'smtp', 'pop3s'): try: self[f] = int(self[f]) if not (0 <= self[f] < 2 ** 16): raise ValueError except ValueError: raise usage.UsageError( 'Invalid port specified to --%s: %s' % (f, self[f]) ) if self['pop3s']: if not self['certificate']: raise usage.UsageError("Cannot specify --pop3s without " "--certificate") elif not os.path.exists(self['certificate']): raise usage.UsageError("Certificate file %r does not exist." % self['certificate']) if not self['disable-anonymous']: self.service.smtpPortal.registerChecker(checkers.AllowAnonymousAccess()) if not (self['pop3'] or self['smtp'] or self['pop3s']): raise usage.UsageError("You cannot disable all protocols")
def createVFSApplication(vfsRoot): application = service.Application('FAKESFTP') p = portal.Portal(Realm(vfsRoot)) p.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(admin='admin')) p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) # sftp # http://igloo.its.unimelb.edu.au/Webmail/tips/msg00495.html # ssh-keygen -q -b 1024 -t dsa -f ssh_host_dsa_key pubkey = keys.getPublicKeyString( '../sshkeys/ssh_host_dsa_key.pub') privkey = keys.getPrivateKeyObject( '../sshkeys/ssh_host_dsa_key') class SSHFactory(factory.SSHFactory): publicKeys = {common.getNS(pubkey)[0]: pubkey} privateKeys = {keys.objectType(privkey): privkey} sftpf = SSHFactory() sftpf.portal = p internet.TCPServer( int( 2222 ), sftpf, ).setServiceParent(application) # ftp f = twisted.protocols.ftp.FTPFactory() f.portal = p f.protocol = twisted.protocols.ftp.FTP internet.TCPServer( 2221, f ).setServiceParent(application) return application
def getFactory(self): if self.factory is None: if self.certificateFile is not None: cert = PrivateCertificate.loadPEM( file(self.certificateFile).read()) certOpts = CertificateOptions(cert.privateKey.original, cert.original, requireCertificate=False, method=SSL.SSLv23_METHOD) else: certOpts = None self.portal = portal.Portal( self.userbase, [self.userbase, checkers.AllowAnonymousAccess()]) self.factory = ESMTPFactory( self.portal, self.domain, { 'CRAM-MD5': credentials.CramMD5Credentials, 'LOGIN': imap4.LOGINCredentials, }, certOpts) if self.debug: self.factory = policies.TrafficLoggingFactory( self.factory, 'smtp') return self.factory
def postOptions(self): from twisted.internet import reactor if self['pop3s']: if not self['certificate']: raise usage.UsageError("Cannot specify --pop3s without " "--certificate") elif not os.path.exists(self['certificate']): raise usage.UsageError("Certificate file %r does not exist." % self['certificate']) else: self.addEndpoint('pop3', self['pop3s'], certificate=self['certificate']) if self['esmtp'] and self['hostname'] is None: raise usage.UsageError("--esmtp requires --hostname") # If the --auth option was passed, this will be present -- otherwise, # it won't be, which is also a perfectly valid state. if 'credCheckers' in self: for ch in self['credCheckers']: self.service.smtpPortal.registerChecker(ch) if not self['disable-anonymous']: self.service.smtpPortal.registerChecker( checkers.AllowAnonymousAccess()) anything = False for service in self._protoDefaults: self[service] = self._getEndpoints(reactor, service) if self[service]: anything = True if not anything: raise usage.UsageError("You cannot disable all protocols")
def __init__(self, *a, **kw): usage.Options.__init__(self, *a, **kw) self.addChecker(checkers.AllowAnonymousAccess())
class FTPRealm: implements(portal.IRealm) def __init__(self, anonymousRoot): self.anonymousRoot = filepath.FilePath(anonymousRoot) self.dir = {'ljd': "/tmp", 'root': '/'} def requestAvatar(self, avatarId, mind, *interfaces): for iface in interfaces: if iface is ftp.IFTPShell: if avatarId is checkers.ANONYMOUS: avatar = ftp.FTPAnonymousShell(self.anonymousRoot) else: user_dir = self.dir[avatarId] avatar = ftp.FTPShell(filepath.FilePath(user_dir)) return ftp.IFTPShell, avatar, getattr(avatar, 'logout', lambda: None) raise NotImplementedError( "Only IFTPShell interface is supported by this realm") portal = portal.Portal(FTPRealm('/data')) portal.registerChecker(checkers.AllowAnonymousAccess()) portal.registerChecker(checkers.FilePasswordDB("pwd.txt")) f = ftp.FTPFactory(portal) from twisted.internet import reactor reactor.listenTCP(1234, f) reactor.run()