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 _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 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 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 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 setUp(self): if not ssh: raise unittest.SkipTest("Crypto requirements missing, can't run historic recvline tests over ssh") u, p = "testuser", "testpass" rlm = TerminalRealm() rlm.userFactory = TestUser rlm.chainedProtocolFactory = lambda: insultsServer ptl = portal.Portal(rlm, [checkers.InMemoryUsernamePasswordDatabaseDontUse(**{u: p})]) sshFactory = ConchFactory(ptl) sshFactory.serverProtocol = self.serverProtocol sshFactory.startFactory() recvlineServer = self.serverProtocol() insultsServer = insults.ServerProtocol(lambda: recvlineServer) sshServer = sshFactory.buildProtocol(None) clientTransport = LoopbackRelay(sshServer) recvlineClient = NotifyingExpectableBuffer() insultsClient = insults.ClientProtocol(lambda: recvlineClient) sshClient = TestTransport(lambda: insultsClient, (), {}, u, p, self.WIDTH, self.HEIGHT) serverTransport = LoopbackRelay(sshClient) sshClient.makeConnection(clientTransport) sshServer.makeConnection(serverTransport) self.recvlineClient = recvlineClient self.sshClient = sshClient self.sshServer = sshServer self.clientTransport = clientTransport self.serverTransport = serverTransport return recvlineClient.onConnection
def __init__(self, namespace = None): """Generates the manhole, contstrained to the namespace...""" realm = TerminalRealm() realm.chainedProtocolFactory = \ lambda: insults.ServerProtocol(ColoredManhole, namespace) xportal = portal.Portal(realm) xportal.registerChecker(SSHRestrictedPKDB([getpass.getuser(),])) ConchFactory.__init__(self, xportal)
def makeFactory(namespace): checker = checkers.InMemoryUsernamePasswordDatabaseDontUse( username='******') def chainProtocolFactory(): return insults.ServerProtocol(ColoredManhole, namespace) rlm = TerminalRealm() rlm.chainedProtocolFactory = chainProtocolFactory ptl = portal.Portal(rlm, [checker]) return ConchFactory(ptl)
def makeManholeService(ns, options): from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse checker = InMemoryUsernamePasswordDatabaseDontUse(admin="admin") def chainProtocolFactory(): return insults.ServerProtocol(ColoredManhole, namespace=ns) rlm = TerminalRealm() rlm.chainedProtocolFactory = chainProtocolFactory ptl = portal.Portal(rlm, [checker]) f = ConchFactory(ptl) return internet.TCPServer(options['manhole-port'], f)
def make_service(args): checker = DjangoSuperuserCredChecker() def chainProtocolFactory(): return insults.ServerProtocol( args["protocol_factory"], *args.get("protocol_args", ()), **args.get("protocol_kwargs", {}) ) realm = TerminalRealm() realm.chainedProtocolFactory = chainProtocolFactory ptl = portal.Portal(realm, [checker]) f = ConchFactory(ptl) return internet.TCPServer(args["ssh_port"], f)
def make_service(args): checker = DjangoSuperuserCredChecker() def chainProtocolFactory(): return insults.ServerProtocol(args['protocol_factory'], *args.get('protocol_args', ()), **args.get('protocol_kwargs', {})) realm = TerminalRealm() realm.chainedProtocolFactory = chainProtocolFactory ptl = portal.Portal(realm, [checker]) f = ConchFactory(ptl) return internet.TCPServer(args['ssh_port'], f)
def make_manhole_server(self, port, username, password): from twisted.application.internet import TCPServer from twisted.cred.portal import Portal from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse from twisted.conch.manhole import ColoredManhole from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm from twisted.conch.insults.insults import ServerProtocol rlm = TerminalRealm() rlm.chainedProtocolFactory = lambda: ServerProtocol(ColoredManhole, None) auth_checker = InMemoryUsernamePasswordDatabaseDontUse(**{username: password}) return TCPServer(port, ConchFactory(Portal(rlm, [auth_checker])))
def startService(self): def chainedProtocolFactory(): def getManhole(): return Manhole({"store": self.store}) protocol = insults.ServerProtocol(ColoredManhole) protocol.protocolFactory = getManhole return protocol checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(**{str(self.username): self.password}) realm = TerminalRealm() realm.chainedProtocolFactory = chainedProtocolFactory p = portal.Portal(realm, [checker]) strports.service(self.listen, ConchFactory(p)).setServiceParent(self.parent)
def __init__(self): TerminalRealm.__init__(self) def userFactory(original, avatarId): user = OmsTerminalUser(original, avatarId) auth = getUtility(IAuthentication, context=None) user.principal = auth.getPrincipal(avatarId) return user self.chainedProtocolFactory = lambda: insults.ServerProtocol(OmsShellProtocol) self.sessionFactory = OmsTerminalSession self.userFactory = userFactory self.transportFactory = OmsTerminalSessionTransport
def make_manhole (self, xmpp_message, room, nick, message): """ Open up a manhole and announce our currentl ip. """ # control args. args = \ { 'protocolFactory' : ColoredManhole, 'protocolArgs' : (None,), 'telnet' : 6023, 'ssh' : 6022, } # protocol factory. def chainProtocolFactory(): return insults.ServerProtocol( args['protocolFactory'], *args.get('protocolArgs', ()), **args.get('protocolKwArgs', {})) # server factory. f = protocol.ServerFactory() f.protocol = lambda: TelnetTransport(TelnetBootstrapProtocol, insults.ServerProtocol, args['protocolFactory'], *args.get('protocolArgs', ()), **args.get('protocolKwArgs', {})) # checker, realms. checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(pedram="iampedram") tsvc = internet.TCPServer(args['telnet'], f) rlm = TerminalRealm() rlm.chainedProtocolFactory = chainProtocolFactory ptl = portal.Portal(rlm, [checker]) f = ConchFactory(ptl) csvc = internet.TCPServer(args['ssh'], f) m = service.MultiService() application = service.Application("Interactive Python Interpreter") # scaffold. tsvc.setServiceParent(m) csvc.setServiceParent(m) m.setServiceParent(application) # determine IP address and announce. ipaddr = requests.get("http://ifconfig.me/all.json").json()['ip_addr'] return "(successful) manhole opened @ %s" % ipaddr
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 make_manhole_server(self, port, username, password): from twisted.application.internet import TCPServer from twisted.cred.portal import Portal from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse from twisted.conch.manhole import ColoredManhole from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm from twisted.conch.insults.insults import ServerProtocol rlm = TerminalRealm() rlm.chainedProtocolFactory = lambda: ServerProtocol( ColoredManhole, None) auth_checker = InMemoryUsernamePasswordDatabaseDontUse( **{username: password}) return TCPServer(port, ConchFactory(Portal(rlm, [auth_checker])))
def setupManhole(application, config): """Setup an SSH manhole for the API service. The manhole port is taken from the C{manhole-port} option in the config file. If this option is not provided the api port plus 100 is used. @param application: The fluidinfo API L{Application} object. @param config: The configuration object. """ servicePort = config.getint('service', 'port') if config.has_option('service', 'manhole-port'): manholePort = config.getint('service', 'manhole-port') else: manholePort = servicePort + 100 def getManhole(_): manhole = Manhole(globals()) ps1 = 'fluidinfo-api [%d] > ' % servicePort ps2 = '... '.rjust(len(ps1)) manhole.ps = (ps1, ps2) return manhole realm = TerminalRealm() realm.chainedProtocolFactory.protocolFactory = getManhole portal = Portal(realm) portal.registerChecker(SSHPublicKeyDatabase()) factory = ConchFactory(portal) manholeService = TCPServer(manholePort, factory, interface='127.0.0.1') manholeService.setServiceParent(application)
def setUp(self): if not ssh: raise unittest.SkipTest( "cryptography requirements missing, can't run historic " "recvline tests over ssh") u, p = b'testuser', b'testpass' rlm = TerminalRealm() rlm.userFactory = TestUser rlm.chainedProtocolFactory = lambda: insultsServer checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() checker.addUser(u, p) ptl = portal.Portal(rlm) ptl.registerChecker(checker) sshFactory = ConchFactory(ptl) sshKey = keys._getPersistentRSAKey(filepath.FilePath(self.mktemp()), keySize=512) sshFactory.publicKeys[b"ssh-rsa"] = sshKey sshFactory.privateKeys[b"ssh-rsa"] = sshKey sshFactory.serverProtocol = self.serverProtocol sshFactory.startFactory() recvlineServer = self.serverProtocol() insultsServer = insults.ServerProtocol(lambda: recvlineServer) sshServer = sshFactory.buildProtocol(None) clientTransport = LoopbackRelay(sshServer) recvlineClient = NotifyingExpectableBuffer() insultsClient = insults.ClientProtocol(lambda: recvlineClient) sshClient = TestTransport(lambda: insultsClient, (), {}, u, p, self.WIDTH, self.HEIGHT) serverTransport = LoopbackRelay(sshClient) sshClient.makeConnection(clientTransport) sshServer.makeConnection(serverTransport) self.recvlineClient = recvlineClient self.sshClient = sshClient self.sshServer = sshServer self.clientTransport = clientTransport self.serverTransport = serverTransport return recvlineClient.onConnection
def makeService(port, namespace): namespace.update({ 'refund_kick': refund_kick, 'filter_tables': filter_tables, 'filter_games': filter_games, 'pp': pp, 'namespace': namespace }) global poker_service poker_service = namespace['poker_service'] def chainProtocolFactory(): return insults.ServerProtocol(ColoredManhole, namespace) realm = TerminalRealm() realm.chainedProtocolFactory = chainProtocolFactory manhole_portal = portal.Portal(realm, [AllowAnyAccess()]) factory = ConchFactory(manhole_portal) return internet.TCPServer(port, factory, interface="127.0.0.1")
def genSSHProtocol(args): checker = Auth.LDAPChecker(Settings.LDAPServer, Settings.LDAPManager, Settings.LDAPPass, Settings.LDAPBase) 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) return f
def makeService(self, options): settings.loadConfig(options["file"]) svc = service.MultiService() checker = PublicKeyCredentialsChecker(pubAuthKeys) namespace = {"host": "67.23.43.147", "user": "******", "pw": "pkxmen0w", "provision": provision} sshRealm = TerminalRealm() sshRealm.chainedProtocolFactory = chainedProtocolFactory(namespace) sshPortal = portal.Portal(sshRealm, [checker]) sshFactory = ConchFactory(sshPortal) sshService = strports.service(str(settings.config["ssh"]["port"]), sshFactory) sshService.setServiceParent(svc) site = server.Site(web.getRoot(), logPath=settings.config["web"]["log"]) if int(settings.config["web"]["port"]) != 0: siteService = strports.service(settings.config["web"]["port"], site) siteService.setServiceParent(svc) if int(settings.config["web"]["sslport"]) != 0: key = settings.config["web"]["key"] cert = settings.config["web"]["cert"] port = int(settings.config["web"]["sslport"]) sslFactory = ChainedOpenSSLContextFactory(key, cert) sslServer = internet.SSLServer(port, site, sslFactory) sslServer.setServiceParent(svc) return svc
def makeService(port, namespace): namespace.update({ 'refund_kick': refund_kick, 'filter_tables': filter_tables, 'filter_games': filter_games, 'pp': pp, 'namespace': namespace }) global poker_service poker_service = namespace['poker_service'] def chainProtocolFactory(): return insults.ServerProtocol( ColoredManhole, namespace ) realm = TerminalRealm() realm.chainedProtocolFactory = chainProtocolFactory manhole_portal = portal.Portal(realm, [AllowAnyAccess()]) factory = ConchFactory(manhole_portal) return internet.TCPServer(port, factory, interface="127.0.0.1")
def setUp(self): if not ssh: raise unittest.SkipTest( "Crypto requirements missing, can't run historic recvline tests over ssh" ) u, p = 'testuser', 'testpass' rlm = TerminalRealm() rlm.userFactory = TestUser rlm.chainedProtocolFactory = lambda: insultsServer ptl = portal.Portal( rlm, [checkers.InMemoryUsernamePasswordDatabaseDontUse(**{u: p})]) sshFactory = ConchFactory(ptl) sshFactory.serverProtocol = self.serverProtocol sshFactory.startFactory() recvlineServer = self.serverProtocol() insultsServer = insults.ServerProtocol(lambda: recvlineServer) sshServer = sshFactory.buildProtocol(None) clientTransport = LoopbackRelay(sshServer) recvlineClient = NotifyingExpectableBuffer() insultsClient = insults.ClientProtocol(lambda: recvlineClient) sshClient = TestTransport(lambda: insultsClient, (), {}, u, p, self.WIDTH, self.HEIGHT) serverTransport = LoopbackRelay(sshClient) sshClient.makeConnection(clientTransport) sshServer.makeConnection(serverTransport) self.recvlineClient = recvlineClient self.sshClient = sshClient self.sshServer = sshServer self.clientTransport = clientTransport self.serverTransport = serverTransport return recvlineClient.onConnection
def makeService(self, options): settings.loadConfig(options["file"]) svc = service.MultiService() checker = PublicKeyCredentialsChecker(pubAuthKeys) from shaft import supervisor s = supervisor.get() # We don't start by default since this will be triggered by web #s.startMinecraft(jar=settings.config["minecraft"]["jar"], # path=settings.config["minecraft"]["home"]) s.setServiceParent(svc) namespace = {"s": s, "log": log, "p": s.protocols} sshRealm = TerminalRealm() sshRealm.chainedProtocolFactory = chainedProtocolFactory(namespace) sshPortal = portal.Portal(sshRealm, [checker]) sshFactory = ConchFactory(sshPortal) sshService = strports.service(str(settings.config["ssh"]["port"]), sshFactory) sshService.setServiceParent(svc) site = server.Site(web.getRoot(), logPath=settings.config["web"]["log"]) if int(settings.config["web"]["port"]) != 0: siteService = strports.service(settings.config["web"]["port"], site) siteService.setServiceParent(svc) return svc
def createManholeListener(): sshRealm = TerminalRealm() sshRealm.chainedProtocolFactory.protocolFactory = lambda _: Manhole(namespace) if settings.MANHOLE_PUBLIC_KEY == 'None': credChecker = checkers.InMemoryUsernamePasswordDatabaseDontUse() credChecker.addUser(settings.MANHOLE_USER, '') else: userKeys = { settings.MANHOLE_USER : settings.MANHOLE_PUBLIC_KEY, } credChecker = PublicKeyChecker(userKeys) sshPortal = portal.Portal(sshRealm) sshPortal.registerChecker(credChecker) sessionFactory = ConchFactory(sshPortal) return sessionFactory
def createManholeListener(): sshRealm = TerminalRealm() sshRealm.chainedProtocolFactory.protocolFactory = lambda _: Manhole( namespace) # You can uncomment this if you're lazy and want insecure authentication instead # of setting up keys. #credChecker = checkers.InMemoryUsernamePasswordDatabaseDontUse(carbon='') userKeys = { settings.MANHOLE_USER: settings.MANHOLE_PUBLIC_KEY, } credChecker = PublicKeyChecker(userKeys) sshPortal = portal.Portal(sshRealm) sshPortal.registerChecker(credChecker) sessionFactory = ConchFactory(sshPortal) return sessionFactory
def start_manhole(self, config, details=None): """ Start a Manhole service within this process. **Usage:** This procedure is registered under * ``crossbar.node.<node_id>.worker.<worker_id>.start_manhole`` - for native workers * ``crossbar.node.<node_id>.controller.start_manhole`` - for node controllers The procedure takes a Manhole service configuration which defines a listening endpoint for the service and a list of users including passwords, e.g. .. code-block:: javascript { "endpoint": { "type": "tcp", "port": 6022 }, "users": [ { "user": "******", "password": "******" } ] } **Errors:** The procedure may raise the following errors: * ``crossbar.error.invalid_configuration`` - the provided configuration is invalid * ``crossbar.error.already_started`` - the Manhole service is already running (or starting) * ``crossbar.error.feature_unavailable`` - the required support packages are not installed **Events:** The procedure will publish an event when the service **is starting** to * ``crossbar.node.<node_id>.worker.<worker_id>.on_manhole_starting`` - for native workers * ``crossbar.node.<node_id>.controller.on_manhole_starting`` - for node controllers and publish an event when the service **has started** to * ``crossbar.node.<node_id>.worker.<worker_id>.on_manhole_started`` - for native workers * ``crossbar.node.<node_id>.controller.on_manhole_started`` - for node controllers :param config: Manhole service configuration. :type config: dict """ self.log.debug("{cls}.start_manhole(config = {config})", cls=self.__class__.__name__, config=config) if not _HAS_MANHOLE: emsg = "Could not start manhole: required packages are missing ({})".format( _MANHOLE_MISSING_REASON) self.log.error(emsg) raise ApplicationError(u"crossbar.error.feature_unavailable", emsg) if self._manhole_service: emsg = "Could not start manhole - already running (or starting)" self.log.warn(emsg) raise ApplicationError(u"crossbar.error.already_started", emsg) try: checkconfig.check_manhole(config) except Exception as e: emsg = "Could not start manhole: invalid configuration ({})".format( e) self.log.error(emsg) raise ApplicationError(u'crossbar.error.invalid_configuration', emsg) # setup user authentication # checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() for user in config['users']: checker.addUser(user['user'], user['password']) # setup manhole namespace # namespace = {'session': self} from twisted.conch.manhole_ssh import (ConchFactory, TerminalRealm, TerminalSession) from twisted.conch.manhole import ColoredManhole class PatchedTerminalSession(TerminalSession): # get rid of # exceptions.AttributeError: TerminalSession instance has no attribute 'windowChanged' def windowChanged(self, winSize): pass rlm = TerminalRealm() rlm.sessionFactory = PatchedTerminalSession # monkey patch rlm.chainedProtocolFactory.protocolFactory = lambda _: ColoredManhole( namespace) ptl = portal.Portal(rlm, [checker]) factory = ConchFactory(ptl) factory.noisy = False self._manhole_service = ManholeService(config, details.caller) starting_topic = '{}.on_manhole_starting'.format(self._uri_prefix) starting_info = self._manhole_service.marshal() # the caller gets a progressive result .. if details.progress: details.progress(starting_info) # .. while all others get an event self.publish(starting_topic, starting_info, options=PublishOptions(exclude=details.caller)) try: self._manhole_service.port = yield create_listening_port_from_config( config['endpoint'], self.cbdir, factory, self._reactor, self.log) except Exception as e: self._manhole_service = None emsg = "Manhole service endpoint cannot listen: {}".format(e) self.log.error(emsg) raise ApplicationError(u"crossbar.error.cannot_listen", emsg) # alright, manhole has started self._manhole_service.started = datetime.utcnow() self._manhole_service.status = 'started' started_topic = '{}.on_manhole_started'.format(self._uri_prefix) started_info = self._manhole_service.marshal() self.publish(started_topic, started_info, options=PublishOptions(exclude=details.caller)) returnValue(started_info)
def start_manhole(self, config, details=None): """ Start a Manhole service within this process. **Usage:** This procedure is registered under * ``crossbar.node.<node_id>.worker.<worker_id>.start_manhole`` - for native workers * ``crossbar.node.<node_id>.controller.start_manhole`` - for node controllers The procedure takes a Manhole service configuration which defines a listening endpoint for the service and a list of users including passwords, e.g. .. code-block:: javascript { "endpoint": { "type": "tcp", "port": 6022 }, "users": [ { "user": "******", "password": "******" } ] } **Errors:** The procedure may raise the following errors: * ``crossbar.error.invalid_configuration`` - the provided configuration is invalid * ``crossbar.error.already_started`` - the Manhole service is already running (or starting) * ``crossbar.error.feature_unavailable`` - the required support packages are not installed **Events:** The procedure will publish an event when the service **is starting** to * ``crossbar.node.<node_id>.worker.<worker_id>.on_manhole_starting`` - for native workers * ``crossbar.node.<node_id>.controller.on_manhole_starting`` - for node controllers and publish an event when the service **has started** to * ``crossbar.node.<node_id>.worker.<worker_id>.on_manhole_started`` - for native workers * ``crossbar.node.<node_id>.controller.on_manhole_started`` - for node controllers :param config: Manhole service configuration. :type config: dict """ self.log.debug("{cls}.start_manhole(config = {config})", cls=self.__class__.__name__, config=config) if not _HAS_MANHOLE: emsg = "Could not start manhole: required packages are missing ({})".format(_MANHOLE_MISSING_REASON) self.log.error(emsg) raise ApplicationError(u"crossbar.error.feature_unavailable", emsg) if self._manhole_service: emsg = "Could not start manhole - already running (or starting)" self.log.warn(emsg) raise ApplicationError(u"crossbar.error.already_started", emsg) try: checkconfig.check_manhole(config) except Exception as e: emsg = "Could not start manhole: invalid configuration ({})".format(e) self.log.error(emsg) raise ApplicationError(u'crossbar.error.invalid_configuration', emsg) # setup user authentication # checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() for user in config['users']: checker.addUser(user['user'], user['password']) # setup manhole namespace # namespace = {'session': self} class PatchedTerminalSession(TerminalSession): # get rid of # exceptions.AttributeError: TerminalSession instance has no attribute 'windowChanged' def windowChanged(self, winSize): pass rlm = TerminalRealm() rlm.sessionFactory = PatchedTerminalSession # monkey patch rlm.chainedProtocolFactory.protocolFactory = lambda _: ColoredManhole(namespace) ptl = portal.Portal(rlm, [checker]) factory = ConchFactory(ptl) factory.noisy = False self._manhole_service = ManholeService(config, details.caller) starting_topic = '{}.on_manhole_starting'.format(self._uri_prefix) starting_info = self._manhole_service.marshal() # the caller gets a progressive result .. if details.progress: details.progress(starting_info) # .. while all others get an event self.publish(starting_topic, starting_info, options=PublishOptions(exclude=details.caller)) try: self._manhole_service.port = yield create_listening_port_from_config(config['endpoint'], self.cbdir, factory, self._reactor, self.log) except Exception as e: self._manhole_service = None emsg = "Manhole service endpoint cannot listen: {}".format(e) self.log.error(emsg) raise ApplicationError(u"crossbar.error.cannot_listen", emsg) # alright, manhole has started self._manhole_service.started = datetime.utcnow() self._manhole_service.status = 'started' started_topic = '{}.on_manhole_started'.format(self._uri_prefix) started_info = self._manhole_service.marshal() self.publish(started_topic, started_info, options=PublishOptions(exclude=details.caller)) returnValue(started_info)
from twisted.internet import reactor from twisted.internet.endpoints import serverFromString from twisted.cred import checkers, portal from twisted.conch.manhole import ColoredManhole from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm if __name__ == '__main__': log.startLogging(sys.stdout) checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() checker.addUser('oberstet', 'secret') namespace = {'foo': 23} rlm = TerminalRealm() rlm.chainedProtocolFactory.protocolFactory = lambda _: ColoredManhole( namespace) ptl = portal.Portal(rlm, [checker]) factory = ConchFactory(ptl) server = serverFromString(reactor, "tcp:6022") server.listen(factory) reactor.run()
def start_manhole(self, config, details = None): """ Start a manhole (SSH) within this worker. :param config: Manhole configuration. :type config: obj """ if self.debug: log.msg("{}.start_manhole".format(self.__class__.__name__), config) if not _HAS_MANHOLE: emsg = "ERROR: could not start manhole - required packages are missing ({})".format(_MANHOLE_MISSING_REASON) log.msg(emsg) raise ApplicationError("crossbar.error.feature_unavailable", emsg) if self._manhole_service: emsg = "ERROR: could not start manhole - already running (or starting)" log.msg(emsg) raise ApplicationError("crossbar.error.already_started", emsg) try: checkconfig.check_manhole(config) except Exception as e: emsg = "ERROR: could not start manhole - invalid configuration ({})".format(e) log.msg(emsg) raise ApplicationError('crossbar.error.invalid_configuration', emsg) ## setup user authentication ## checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() for user in config['users']: checker.addUser(user['user'], user['password']) ## setup manhole namespace ## namespace = {'session': self} class PatchedTerminalSession(TerminalSession): ## get rid of ## exceptions.AttributeError: TerminalSession instance has no attribute 'windowChanged' def windowChanged(self, winSize): pass rlm = TerminalRealm() rlm.sessionFactory = PatchedTerminalSession # monkey patch rlm.chainedProtocolFactory.protocolFactory = lambda _: ColoredManhole(namespace) ptl = portal.Portal(rlm, [checker]) factory = ConchFactory(ptl) factory.noisy = False self._manhole_service = ManholeService(config, details.authid) starting_topic = '{}.on_manhole_starting'.format(self._uri_prefix) starting_info = self._manhole_service.marshal() ## the caller gets a progressive result .. if details.progress: details.progress(starting_info) ## .. while all others get an event self.publish(starting_topic, starting_info, options = PublishOptions(exclude = [details.caller])) try: self._manhole_service.port = yield create_listening_port_from_config(config['endpoint'], factory, self.cbdir, reactor) except Exception as e: self._manhole_service = None emsg = "ERROR: manhole service endpoint cannot listen - {}".format(e) log.msg(emsg) raise ApplicationError("crossbar.error.cannot_listen", emsg) ## alright, manhole has started self._manhole_service.started = datetime.utcnow() self._manhole_service.status = 'started' started_topic = '{}.on_manhole_started'.format(self._uri_prefix) started_info = self._manhole_service.marshal() self.publish(started_topic, started_info, options = PublishOptions(exclude = [details.caller])) returnValue(started_info)
def start_manhole(self, config, details=None): """ Start a manhole (SSH) within this worker. :param config: Manhole configuration. :type config: obj """ if self.debug: log.msg("{}.start_manhole".format(self.__class__.__name__), config) if not _HAS_MANHOLE: emsg = "ERROR: could not start manhole - required packages are missing ({})".format( _MANHOLE_MISSING_REASON) log.msg(emsg) raise ApplicationError("crossbar.error.feature_unavailable", emsg) if self._manhole_service: emsg = "ERROR: could not start manhole - already running (or starting)" log.msg(emsg) raise ApplicationError("crossbar.error.already_started", emsg) try: checkconfig.check_manhole(config) except Exception as e: emsg = "ERROR: could not start manhole - invalid configuration ({})".format( e) log.msg(emsg) raise ApplicationError('crossbar.error.invalid_configuration', emsg) # setup user authentication # checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() for user in config['users']: checker.addUser(user['user'], user['password']) # setup manhole namespace # namespace = {'session': self} class PatchedTerminalSession(TerminalSession): # get rid of # exceptions.AttributeError: TerminalSession instance has no attribute 'windowChanged' def windowChanged(self, winSize): pass rlm = TerminalRealm() rlm.sessionFactory = PatchedTerminalSession # monkey patch rlm.chainedProtocolFactory.protocolFactory = lambda _: ColoredManhole( namespace) ptl = portal.Portal(rlm, [checker]) factory = ConchFactory(ptl) factory.noisy = False self._manhole_service = ManholeService(config, details.caller) starting_topic = '{}.on_manhole_starting'.format(self._uri_prefix) starting_info = self._manhole_service.marshal() # the caller gets a progressive result .. if details.progress: details.progress(starting_info) # .. while all others get an event self.publish(starting_topic, starting_info, options=PublishOptions(exclude=[details.caller])) try: self._manhole_service.port = yield create_listening_port_from_config( config['endpoint'], factory, self.cbdir, reactor) except Exception as e: self._manhole_service = None emsg = "ERROR: manhole service endpoint cannot listen - {}".format( e) log.msg(emsg) raise ApplicationError("crossbar.error.cannot_listen", emsg) # alright, manhole has started self._manhole_service.started = datetime.utcnow() self._manhole_service.status = 'started' started_topic = '{}.on_manhole_started'.format(self._uri_prefix) started_info = self._manhole_service.marshal() self.publish(started_topic, started_info, options=PublishOptions(exclude=[details.caller])) returnValue(started_info)
def start_manhole(self, config, details=None): """ Start a Manhole service within this process. **Usage:** This procedure is registered under * ``crossbar.node.<node_id>.worker.<worker_id>.start_manhole`` - for native workers * ``crossbar.node.<node_id>.controller.start_manhole`` - for node controllers The procedure takes a Manhole service configuration which defines a listening endpoint for the service and a list of users including passwords, e.g. .. code-block:: javascript { "endpoint": { "type": "tcp", "port": 6022 }, "users": [ { "user": "******", "password": "******" } ] } **Errors:** The procedure may raise the following errors: * ``crossbar.error.invalid_configuration`` - the provided configuration is invalid * ``crossbar.error.already_started`` - the Manhole service is already running (or starting) * ``crossbar.error.feature_unavailable`` - the required support packages are not installed **Events:** The procedure will publish an event when the service **is starting** to * ``crossbar.node.<node_id>.worker.<worker_id>.on_manhole_starting`` - for native workers * ``crossbar.node.<node_id>.controller.on_manhole_starting`` - for node controllers and publish an event when the service **has started** to * ``crossbar.node.<node_id>.worker.<worker_id>.on_manhole_started`` - for native workers * ``crossbar.node.<node_id>.controller.on_manhole_started`` - for node controllers :param config: Manhole service configuration. :type config: dict """ self.log.debug("{cls}.start_manhole(config = {config})", cls=self.__class__.__name__, config=config) if not _HAS_MANHOLE: emsg = "Could not start manhole: required packages are missing ({})".format(_MANHOLE_MISSING_REASON) self.log.error(emsg) raise ApplicationError(u"crossbar.error.feature_unavailable", emsg) if self._manhole_service: emsg = "Could not start manhole - already running (or starting)" self.log.warn(emsg) raise ApplicationError(u"crossbar.error.already_started", emsg) try: self.personality.check_manhole(self.personality, config) except Exception as e: emsg = "Could not start manhole: invalid configuration ({})".format(e) self.log.error(emsg) raise ApplicationError(u'crossbar.error.invalid_configuration', emsg) from twisted.conch.ssh import keys from twisted.conch.manhole_ssh import ( ConchFactory, TerminalRealm, TerminalSession) from twisted.conch.manhole import ColoredManhole from twisted.conch.checkers import SSHPublicKeyDatabase class PublicKeyChecker(SSHPublicKeyDatabase): def __init__(self, userKeys): self.userKeys = {} for username, keyData in userKeys.items(): self.userKeys[username] = keys.Key.fromString(data=keyData).blob() def checkKey(self, credentials): username = credentials.username.decode('utf8') if username in self.userKeys: keyBlob = self.userKeys[username] return keyBlob == credentials.blob # setup user authentication # authorized_keys = { 'oberstet': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCz7K1QwDhaq/Bi8o0uqiJQuVFCDQL5rbRvMClLHRx9KE3xP2Fh2eapzXuYGSgtG9Fyz1UQd+1oNM3wuNnT/DsBUBQrECP4bpFIHcJkMaFTARlCagkXosWsadzNnkW0osUCuHYMrzBJuXWF2GH+0OFCtVu+8E+4Mhvchu9xsHG8PM92SpI6aP0TtmT9D/0Bsm9JniRj8kndeS+iWG4s/pEGj7Rg7eGnbyQJt/9Jc1nWl6PngGbwp63dMVmh+8LP49PtfnxY8m9fdwpL4oW9U8beYqm8hyfBPN2yDXaehg6RILjIa7LU2/6bu96ZgnIz26zi/X9XlnJQt2aahWJs1+GR oberstet@thinkpad-t430s' } checker = PublicKeyChecker(authorized_keys) # setup manhole namespace # namespace = {'session': self} class PatchedTerminalSession(TerminalSession): # get rid of # exceptions.AttributeError: TerminalSession instance has no attribute 'windowChanged' def windowChanged(self, winSize): pass rlm = TerminalRealm() rlm.sessionFactory = PatchedTerminalSession # monkey patch rlm.chainedProtocolFactory.protocolFactory = lambda _: ColoredManhole(namespace) ptl = portal.Portal(rlm) ptl.registerChecker(checker) factory = ConchFactory(ptl) factory.noisy = False private_key = keys.Key.fromFile(os.path.join(self.cbdir, 'ssh_host_rsa_key')) public_key = private_key.public() publicKeys = { b'ssh-rsa': public_key } privateKeys = { b'ssh-rsa': private_key } factory.publicKeys = publicKeys factory.privateKeys = privateKeys self._manhole_service = ManholeService(config, details.caller) starting_topic = '{}.on_manhole_starting'.format(self._uri_prefix) starting_info = self._manhole_service.marshal() # the caller gets a progressive result .. if details.progress: details.progress(starting_info) # .. while all others get an event self.publish(starting_topic, starting_info, options=PublishOptions(exclude=details.caller)) try: self._manhole_service.port = yield create_listening_port_from_config(config['endpoint'], self.cbdir, factory, self._reactor, self.log) except Exception as e: self._manhole_service = None emsg = "Manhole service endpoint cannot listen: {}".format(e) self.log.error(emsg) raise ApplicationError(u"crossbar.error.cannot_listen", emsg) # alright, manhole has started self._manhole_service.started = datetime.utcnow() self._manhole_service.status = 'started' started_topic = '{}.on_manhole_started'.format(self._uri_prefix) started_info = self._manhole_service.marshal() self.publish(started_topic, started_info, options=PublishOptions(exclude=details.caller)) returnValue(started_info)
def start_manhole(self, config, details=None): """ Start a Manhole service within this process. **Usage:** This procedure is registered under * ``crossbar.node.<node_id>.worker.<worker_id>.start_manhole`` - for native workers * ``crossbar.node.<node_id>.controller.start_manhole`` - for node controllers The procedure takes a Manhole service configuration which defines a listening endpoint for the service and a list of users including passwords, e.g. .. code-block:: javascript { "endpoint": { "type": "tcp", "port": 6022 }, "users": [ { "user": "******", "password": "******" } ] } **Errors:** The procedure may raise the following errors: * ``crossbar.error.invalid_configuration`` - the provided configuration is invalid * ``crossbar.error.already_started`` - the Manhole service is already running (or starting) * ``crossbar.error.feature_unavailable`` - the required support packages are not installed **Events:** The procedure will publish an event when the service **is starting** to * ``crossbar.node.<node_id>.worker.<worker_id>.on_manhole_starting`` - for native workers * ``crossbar.node.<node_id>.controller.on_manhole_starting`` - for node controllers and publish an event when the service **has started** to * ``crossbar.node.<node_id>.worker.<worker_id>.on_manhole_started`` - for native workers * ``crossbar.node.<node_id>.controller.on_manhole_started`` - for node controllers :param config: Manhole service configuration. :type config: dict """ self.log.debug("{cls}.start_manhole(config = {config})", cls=self.__class__.__name__, config=config) if not _HAS_MANHOLE: emsg = "Could not start manhole: required packages are missing ({})".format( _MANHOLE_MISSING_REASON) self.log.error(emsg) raise ApplicationError(u"crossbar.error.feature_unavailable", emsg) if self._manhole_service: emsg = "Could not start manhole - already running (or starting)" self.log.warn(emsg) raise ApplicationError(u"crossbar.error.already_started", emsg) try: self.personality.check_manhole(self.personality, config) except Exception as e: emsg = "Could not start manhole: invalid configuration ({})".format( e) self.log.error(emsg) raise ApplicationError(u'crossbar.error.invalid_configuration', emsg) from twisted.conch.ssh import keys from twisted.conch.manhole_ssh import (ConchFactory, TerminalRealm, TerminalSession) from twisted.conch.manhole import ColoredManhole from twisted.conch.checkers import SSHPublicKeyDatabase class PublicKeyChecker(SSHPublicKeyDatabase): def __init__(self, userKeys): self.userKeys = {} for username, keyData in userKeys.items(): self.userKeys[username] = keys.Key.fromString( data=keyData).blob() def checkKey(self, credentials): username = credentials.username.decode('utf8') if username in self.userKeys: keyBlob = self.userKeys[username] return keyBlob == credentials.blob # setup user authentication # authorized_keys = { 'oberstet': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCz7K1QwDhaq/Bi8o0uqiJQuVFCDQL5rbRvMClLHRx9KE3xP2Fh2eapzXuYGSgtG9Fyz1UQd+1oNM3wuNnT/DsBUBQrECP4bpFIHcJkMaFTARlCagkXosWsadzNnkW0osUCuHYMrzBJuXWF2GH+0OFCtVu+8E+4Mhvchu9xsHG8PM92SpI6aP0TtmT9D/0Bsm9JniRj8kndeS+iWG4s/pEGj7Rg7eGnbyQJt/9Jc1nWl6PngGbwp63dMVmh+8LP49PtfnxY8m9fdwpL4oW9U8beYqm8hyfBPN2yDXaehg6RILjIa7LU2/6bu96ZgnIz26zi/X9XlnJQt2aahWJs1+GR oberstet@thinkpad-t430s' } checker = PublicKeyChecker(authorized_keys) # setup manhole namespace # namespace = {'session': self} class PatchedTerminalSession(TerminalSession): # get rid of # exceptions.AttributeError: TerminalSession instance has no attribute 'windowChanged' def windowChanged(self, winSize): pass rlm = TerminalRealm() rlm.sessionFactory = PatchedTerminalSession # monkey patch rlm.chainedProtocolFactory.protocolFactory = lambda _: ColoredManhole( namespace) ptl = portal.Portal(rlm) ptl.registerChecker(checker) factory = ConchFactory(ptl) factory.noisy = False private_key = keys.Key.fromFile( os.path.join(self.cbdir, 'ssh_host_rsa_key')) public_key = private_key.public() publicKeys = {b'ssh-rsa': public_key} privateKeys = {b'ssh-rsa': private_key} factory.publicKeys = publicKeys factory.privateKeys = privateKeys self._manhole_service = ManholeService(config, details.caller) starting_topic = '{}.on_manhole_starting'.format(self._uri_prefix) starting_info = self._manhole_service.marshal() # the caller gets a progressive result .. if details.progress: details.progress(starting_info) # .. while all others get an event self.publish(starting_topic, starting_info, options=PublishOptions(exclude=details.caller)) try: self._manhole_service.port = yield create_listening_port_from_config( config['endpoint'], self.cbdir, factory, self._reactor, self.log) except Exception as e: self._manhole_service = None emsg = "Manhole service endpoint cannot listen: {}".format(e) self.log.error(emsg) raise ApplicationError(u"crossbar.error.cannot_listen", emsg) # alright, manhole has started self._manhole_service.started = datetime.utcnow() self._manhole_service.status = 'started' started_topic = '{}.on_manhole_started'.format(self._uri_prefix) started_info = self._manhole_service.marshal() self.publish(started_topic, started_info, options=PublishOptions(exclude=details.caller)) returnValue(started_info)