def getTelnetFactory(commands, prompt, **users): if not users: raise SSHServerError("You must provide at least one " "username/password combination " "to run this Telnet server.") cmds = {} for command in commands: cmds[command.name] = command commands = cmds for exit_cmd in ['_exit', 'exit']: if exit_cmd not in commands: commands[exit_cmd] = MockSSH.command_exit telnetRealm = TelnetRealm(prompt, commands) telnetPortal = portal.Portal( telnetRealm, (checkers.InMemoryUsernamePasswordDatabaseDontUse(**users), )) telnetPortal.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(**users)) telnetFactory = ServerFactory() telnetFactory.protocol = makeTelnetProtocol(telnetPortal, telnetRealm, users) return telnetFactory
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 main(): """Start a Cournal server""" locale_dir = os.path.join(sys.prefix, "local", "share", "locale") #locale_dir = os.path.realpath(os.path.dirname(sys.argv[0])) gettext.install("cournal") #, locale_dir) args = CmdlineParser().parse() port = args.port realm = CournalRealm() realm.server = CournalServer(args.autosave_directory, args.autosave_interval, args.save_hook) atexit.register(realm.server.exit) checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() checker.addUser(USERNAME, PASSWORD) p = portal.Portal(realm, [checker]) try: reactor.listenTCP(port, pb.PBServerFactory(p)) except CannotListenError as err: debug(0, _("ERROR: Failed to listen on port {}").format(err.port)) return 1 debug(2, _("Listening on port {}").format(port)) reactor.run()
def startSSHManhole(self): namespace = self.getConsoleLocals() realm = manhole_ssh.TerminalRealm() # If we don't do this, the server will generate an exception when # you resize the SSH window realm.sessionFactory.windowChanged = lambda *args, **kwargs: None def getManhole(_): return Manhole(namespace) realm.chainedProtocolFactory.protocolFactory = getManhole p = portal.Portal(realm) # Username/Password authentication passwordDB = checkers.InMemoryUsernamePasswordDatabaseDontUse() passwordDB.addUser('trosnoth', '') p.registerChecker(passwordDB) factory = manhole_ssh.ConchFactory(p) manholePort = 6799 try: reactor.listenTCP(manholePort, factory) except CannotListenError: log.error('Error starting manhole on port %d', manholePort) except ConchError as e: log.error('Error starting manhole on port %d: %s', manholePort, e.value) else: log.warning('SSH manhole started on port %d with password ""', manholePort)
def __init__(self, window_agents): Thread.__init__(self) # Make sure this thread is a daemon not to prevent program exit. self.daemon = True realm = manhole_ssh.TerminalRealm() namespace = { 'Gtk': Gtk, 'walk': walk, 'widgets': lambda: walk(iter(window_agents).next()), 'window_agents': window_agents, 'window': lambda: iter(window_agents).next() } realm.chainedProtocolFactory.protocolFactory = \ lambda _: manhole.Manhole(namespace) p = portal.Portal(realm) p.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(nemo='nemo')) reactor.listenTCP(2222, manhole_ssh.ConchFactory(p)) # Starting the thread is not enough because the Python interpreter # is no running all the time and therefore the thread will not run # too. Workaround this by using a timer to run the interpreter # periodically. def timer(): time.sleep(0.001) # Yield to other threads. return True GObject.timeout_add(10, timer)
def __init__(self, port, user="******", passwd="clientpw", denotesPassSchedulerGroups=None): ''' port : port for PBListener to listen on user : PBListener username passwd : PBListener password denotesPassSchedulerGroups : list of scheduler group(s) that when all builders pass indicates a passing build ''' base.StatusReceiverMultiService.__init__(self) if type(port) is int: port = "tcp:%d" % port self.port = port self.cred = (user, passwd) p = portal.Portal(self) c = checkers.InMemoryUsernamePasswordDatabaseDontUse() c.addUser(user, passwd) p.registerChecker(c) f = pb.PBServerFactory(p) #TODO: not sure if i need this: f.unsafeTracebacks = True self.passBuilderGroups = [] if denotesPassSchedulerGroups: self.setupDenotesPassSchedulerGroup(denotesPassSchedulerGroups) s = strports.service(port, f) s.setServiceParent(self)
def make_service(args): def chain_protocol_factory(): return insults.ServerProtocol(args['protocolFactory'], *args.get('protocolArgs', ()), **args.get('protocolKwArgs', {})) m = service.MultiService() # Telnet manhole if True: f = protocol.ServerFactory() f.protocol = lambda: TelnetTransport( TelnetBootstrapProtocol, insults.ServerProtocol, args[ 'protocolFactory'], *args.get('protocolArgs', ()), **args.get('protocolKwArgs', {})) tsvc = internet.TCPServer(args['telnet'], f) # @UndefinedVariable tsvc.setServiceParent(m) # SSH manhole if False: checker = checkers.InMemoryUsernamePasswordDatabaseDontUse( user="******") rlm = TerminalRealm() rlm.chainedProtocolFactory = chain_protocol_factory ptl = portal.Portal(rlm, [checker]) f = ConchFactory(ptl) csvc = internet.TCPServer(args['ssh'], f) # @UndefinedVariable csvc.setServiceParent(m) return m
def require_digest_auth(resource): p = portal.Portal(TestAuthRealm(DIGEST_AUTH_PAGE)) c = checkers.InMemoryUsernamePasswordDatabaseDontUse() c.addUser("digestuser", "digestuser") p.registerChecker(c) cred_factory = DigestCredentialFactory("md5", "Digest Auth protected area") return HTTPAuthSessionWrapper(p, [cred_factory])
def getSSHFactory(commands, prompt, keypath, **users): if not users: raise SSHServerError("You must provide at least one " "username/password combination " "to run this SSH server.") cmds = {} for command in commands: cmds[command.name] = command commands = cmds for exit_cmd in ['_exit', 'exit']: if exit_cmd not in commands: commands[exit_cmd] = command_exit # sshFactory = factory.SSHFactory() sshFactory = SSHFactory() sshFactory.portal = portal.Portal( SSHRealm(prompt=prompt, commands=commands)) sshFactory.portal.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(**users)) pubKeyString, privKeyString = getRSAKeys(keypath) sshFactory.publicKeys = {'ssh-rsa': keys.Key.fromString(data=pubKeyString)} sshFactory.privateKeys = { 'ssh-rsa': keys.Key.fromString(data=privKeyString) } sshFactory.services = { 'ssh-userauth': userauth.SSHUserAuthServer, 'ssh-connection': connection.SSHConnection } return sshFactory
def test_badUsernamePasswordLogin(self): """ Test that a login attempt with an invalid user or invalid password fails in the appropriate way. """ self.portal.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(user='******')) factory = pb.PBClientFactory() firstLogin = factory.login( credentials.UsernamePassword('nosuchuser', 'pass')) secondLogin = factory.login( credentials.UsernamePassword('user', 'wrongpass')) self.assertFailure(firstLogin, UnauthorizedLogin) self.assertFailure(secondLogin, UnauthorizedLogin) d = gatherResults([firstLogin, secondLogin]) def cleanup(passthrough): self.flushLoggedErrors(UnauthorizedLogin) factory.disconnect() return passthrough d.addBoth(cleanup) reactor.connectTCP("127.0.0.1", self.portno, factory) return d
def makeService(config): port, user, password = config['port'], config['user'], config['password'] p = portal.Portal( service.Realm( service.Service(config["tracebacks"], config.get('namespace'))), [checkers.InMemoryUsernamePasswordDatabaseDontUse(**{user: password})]) return strports.service(port, pb.PBServerFactory(p, config["tracebacks"]))
def _makeService(args): checker = checkers.InMemoryUsernamePasswordDatabaseDontUse( admin="password") f = protocol.ServerFactory() f.protocol = lambda: TelnetTransport( TelnetBootstrapProtocol, insults.ServerProtocol, args[ 'protocolFactory'], *args.get('protocolArgs', ()), **args.get('protocolKwArgs', {})) tsvc = internet.TCPServer(args['telnet'], f) def chainProtocolFactory(): return insults.ServerProtocol(args['protocolFactory'], *args.get('protocolArgs', ()), **args.get('protocolKwArgs', {})) rlm = TerminalRealm() rlm.chainedProtocolFactory = chainProtocolFactory ptl = portal.Portal(rlm, [checker]) f = ConchFactory(ptl) #csvc = internet.TCPServer(args['ssh'], f) m = service.MultiService() tsvc.setServiceParent(m) #csvc.setServiceParent(m) return m
def buildGuardedResource(): return simpleguard.guardResource( Authenticated(), [checkers.InMemoryUsernamePasswordDatabaseDontUse(bob="12345")], nonauthenticated=LoginPage(), callback=callback, errback=LoginPage)
def create_remote_factory(namespace, users): realm = manhole_ssh.TerminalRealm() def create_remote_protocol(_): return manhole.ColoredManhole(namespace) realm.chainedProtocolFactory.protocolFactory = create_remote_protocol p = portal.Portal(realm) users = {key: value.encode() for key, value in users.items()} p.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(**users)) f = manhole_ssh.ConchFactory(p) ssh_key_base_path = path.join(config.config_dir, "ssh-keys") ssh_pubkey_path = path.join(ssh_key_base_path, "ssh_host_rsa_key.pub") ssh_privkey_path = path.join(ssh_key_base_path, "ssh_host_rsa_key") try: f.publicKeys[b"ssh-rsa"] = keys.Key.fromFile(ssh_pubkey_path) f.privateKeys[b"ssh-rsa"] = keys.Key.fromFile(ssh_privkey_path) except FileNotFoundError: print("ERROR: You don't have any keys in the host key location") print("Generate one with:") print(" mkdir {}".format(ssh_key_base_path)) print(" ssh-keygen -f {} -t rsa".format(ssh_privkey_path)) print("make sure to specify no password") sys.exit(1) return f
def __init__(self, port, username, password, ssh_hostkey_dir): """ @type port: string or int @param port: what port should the Manhole listen on? This is a strports specification string, like 'tcp:12345' or 'tcp:12345:interface=127.0.0.1'. Bare integers are treated as a simple tcp port. @param username: @param password: username= and password= form a pair of strings to use when authenticating the remote user. @type ssh_hostkey_dir: str @param ssh_hostkey_dir: directory which contains ssh host keys for this server """ if not manhole_ssh: config.error("cryptography required for ssh mahole.") self.username = username self.password = password self.ssh_hostkey_dir = ssh_hostkey_dir c = checkers.InMemoryUsernamePasswordDatabaseDontUse() c.addUser(unicode2bytes(username), unicode2bytes(password)) _BaseManhole.__init__(self, port, c, ssh_hostkey_dir)
def _get_checker(): ''' creates login:password based on config ''' checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() checker.addUser(CONFIG['username'], CONFIG['password']) return checker
def getManholeFactory(namespace, password): realm = manhole_ssh.TerminalRealm() # If we don't do this, the server will generate an exception when # you resize the SSH window def windowChanged(self, size): pass realm.sessionFactory.windowChanged = windowChanged def getManhole(_): return Manhole(namespace) realm.chainedProtocolFactory.protocolFactory = getManhole p = portal.Portal(realm) # Username/Password authentication passwordDB = checkers.InMemoryUsernamePasswordDatabaseDontUse() passwordDB.addUser('trosnoth', password) p.registerChecker(passwordDB) factory = manhole_ssh.ConchFactory(p) privatePath = getPath(user, 'authserver', 'manhole_rsa') if not os.path.isfile(privatePath): generateKeys(privatePath) if os.path.isfile(privatePath): factory.privateKeys[b'ssh-rsa'] = k = keys.Key.fromFile(privatePath) if not hasattr(k._keyObject, 'sign'): log.warn('SSH manhole may require newer version of cryptography!') publicPath = privatePath + '.pub' if os.path.isfile(publicPath): factory.publicKeys[b'ssh-rsa'] = keys.Key.fromFile(publicPath) return factory
def test_view(self): """ Verify that a viewpoint can be retrieved after authenticating with cred. """ self.portal.registerChecker( checkers.InMemoryUsernamePasswordDatabaseDontUse(user='******')) factory = pb.PBClientFactory() d = factory.login(credentials.UsernamePassword("user", "pass"), "BRAINS!") def cbLogin(perspective): return perspective.callRemote("getViewPoint") d.addCallback(cbLogin) def cbView(viewpoint): return viewpoint.callRemote("check") d.addCallback(cbView) d.addCallback(self.failUnless) 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): from twisted.protocols.ftp import FTPRealm, FTPFactory from scrapy.core.downloader.handlers.ftp import FTPDownloadHandler # setup dirs and test file self.directory = self.mktemp() os.mkdir(self.directory) userdir = os.path.join(self.directory, self.username) os.mkdir(userdir) fp = FilePath(userdir) fp.child('file.txt').setContent(b"I have the power!") fp.child('file with spaces.txt').setContent(b"Moooooooooo power!") # setup server realm = FTPRealm(anonymousRoot=self.directory, userHome=self.directory) p = portal.Portal(realm) users_checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() users_checker.addUser(self.username, self.password) p.registerChecker(users_checker, credentials.IUsernamePassword) self.factory = FTPFactory(portal=p) 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 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 MakeFactory(allowedIP, username, password): namespace = {} namespace["Account"] = Account namespace["RemoveAccount"] = RemoveAccount namespace["QueueProduct"] = QueueProduct namespace["SetUserBanLevel"] = SetUserBanLevel namespace["NukeUser"] = NukeUser namespace["UnbanSubnet"] = UnbanSubnet telnetRealm = _StupidRealm(telnet.TelnetBootstrapProtocol, insults.ServerProtocol, manhole.ColoredManhole, namespace) checker = checkers.InMemoryUsernamePasswordDatabaseDontUse( **{username: password}) telnetPortal = portal.Portal(telnetRealm, [checker]) telnetFactory = MyFactory() telnetFactory.allowedIP = allowedIP telnetFactory.protocol = makeTelnetProtocol(telnetPortal) #telnetService = strports.service(port,telnetFactory) #telnetService.setServiceParent(svc) #strports.service(port, telnetFactory).setServiceParent(application) return telnetFactory
def createManholeListener(): sshRealm = TerminalRealm() sshRealm.chainedProtocolFactory.protocolFactory = lambda _: Manhole( namespace) if settings.MANHOLE_PUBLIC_KEY == 'None': credChecker = checkers.InMemoryUsernamePasswordDatabaseDontUse() credChecker.addUser(settings.MANHOLE_USER.encode('utf-8'), ''.encode('utf-8')) else: userKeys = { settings.MANHOLE_USER.encode('utf-8'): settings.MANHOLE_PUBLIC_KEY.encode('utf-8'), } credChecker = PublicKeyChecker(userKeys) sshPortal = portal.Portal(sshRealm) sshPortal.registerChecker(credChecker) sessionFactory = ConchFactory(sshPortal) # set ssh host keys if settings.MANHOLE_HOST_KEY_DIR == "": raise CarbonConfigException("MANHOLE_HOST_KEY_DIR not defined") openSSHFactory = OpenSSHFactory() openSSHFactory.dataRoot = settings.MANHOLE_HOST_KEY_DIR sessionFactory.publicKeys = openSSHFactory.getPublicKeys() sessionFactory.privateKeys = openSSHFactory.getPrivateKeys() return sessionFactory
def addPortal(self): r = TestRealm() p = portal.Portal(r) c = checkers.InMemoryUsernamePasswordDatabaseDontUse() c.addUser('[email protected]', 'passXword') p.registerChecker(c) self.proxy.portal = p
def makeConsoleServerFactory(): from twisted.conch.insults import insults from twisted.conch.manhole import ColoredManhole from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm from twisted.conch.ssh import keys from twisted.cred import checkers, portal shell_password = str(uuid.uuid1()).split("-")[0] # Note - using unsafe credentials checker. checker = checkers.InMemoryUsernamePasswordDatabaseDontUse( octopus=shell_password) def chainProtocolFactory(): return insults.ServerProtocol( ColoredManhole, dict(sketches=loaded_sketches, experiments=running_experiments)) rlm = TerminalRealm() rlm.chainedProtocolFactory = chainProtocolFactory ptl = portal.Portal(rlm, [checker]) factory = ConchFactory(ptl) factory.publicKeys[b"ssh-rsa"] = keys.Key.fromFile( os.path.join(data_path, "ssh-keys", "ssh_host_rsa_key.pub")) factory.privateKeys[b"ssh-rsa"] = keys.Key.fromFile( os.path.join(data_path, "ssh-keys", "ssh_host_rsa_key")) print("Octopus SSH access credentials are octopus:%s\n\n" % shell_password) return factory
def manhole(username, password, globals): """Starts a ssh listener with password authentication using the given username and password. Clients connecting to the ssh listener will find themselves in a colored python shell with the supplied globals. Args: username(str): The username ssh clients should auth with. password(str): The password ssh clients should auth with. globals(dict): The variables to expose in the shell. Returns: twisted.internet.protocol.Factory: A factory to pass to ``listenTCP`` """ checker = checkers.InMemoryUsernamePasswordDatabaseDontUse( **{username: password}) rlm = manhole_ssh.TerminalRealm() rlm.chainedProtocolFactory = lambda: insults.ServerProtocol( ColoredManhole, dict(globals, __name__="__console__")) factory = manhole_ssh.ConchFactory(portal.Portal(rlm, [checker])) factory.publicKeys['ssh-rsa'] = Key.fromString(PUBLIC_KEY) factory.privateKeys['ssh-rsa'] = Key.fromString(PRIVATE_KEY) return 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 start_listening(self): config = self.get_config() for listener in config.listeners: if listener["type"] == "http": self._listener_http(config, listener) elif listener["type"] == "manhole": checker = checkers.InMemoryUsernamePasswordDatabaseDontUse( matrix="rabbithole") rlm = manhole_ssh.TerminalRealm() rlm.chainedProtocolFactory = lambda: insults.ServerProtocol( ColoredManhole, { "__name__": "__console__", "hs": self, }) f = manhole_ssh.ConchFactory(portal.Portal(rlm, [checker])) reactor.listenTCP(listener["port"], f, interface=listener.get( "bind_address", '127.0.0.1')) else: logger.warn("Unrecognized listener type: %s", listener["type"])
def __init__(self, port, username, password): self.username = username self.password = password c = checkers.InMemoryUsernamePasswordDatabaseDontUse() c.addUser(username, password) _BaseManhole.__init__(self, port, c, using_ssh=False)