def runServer(prompt="$ ", private_key = 'id_rsa', public_key = 'id_rsa.pub'): if not privateKeyString: raise SSHServerError("Could not load private key file.") if not publicKeyString: raise SSHServerError("Could not load public key file.") log.msg('Initializing Server') sshFactory = SSHFactory() log.msg('loading private key') sshFactory.privateKeys = { 'ssh-rsa': privateKeyString } log.msg('loading public key') sshFactory.publicKeys = { 'ssh-rsa': publicKeyString } sshFactory.portal = portal.Portal(SSHRealm(prompt=prompt)) sshFactory.portal.registerChecker(FilePasswordDB("ssh-passwords")) log.msg('Listening on 2222') reactor.listenTCP(2222, sshFactory) reactor.run()
def main(keys_path, username_get=None, gid=None, port=2022): settings.username_get = username_get settings.gid = gid key_path = keys_path + '/id_rsa' if not os.path.exists(key_path): subprocess.check_call(['ssh-keygen', '-f', key_path, '-t', 'rsa', '-N', '']) with open(key_path) as privateBlobFile: privateBlob = privateBlobFile.read() privateKey = Key.fromString(data=privateBlob) with open(key_path + '.pub') as publicBlobFile: publicBlob = publicBlobFile.read() publicKey = Key.fromString(data=publicBlob) factory = SSHFactory() factory.privateKeys = {'ssh-rsa': privateKey} factory.publicKeys = {'ssh-rsa': publicKey} factory.portal = Portal(KeyRealm()) factory.portal.registerChecker(KeyChecker()) reactor.listenTCP(port, factory) reactor.run()
def makeService(options): """ Construct a Pantheon SSH service. """ from twisted.internet import reactor factory = SSHFactory() key = options["host-key"] factory.privateKeys = {key.sshType(): key} factory.publicKeys = {key.sshType(): key.public()} realm = PantheonRealm( reactor, options['auth-host'], options['auth-port'], options['client-key'].path, options['client-cert'].path) checker = PantheonHTTPChecker( reactor, options['auth-host'], options['auth-port'], options['client-key'].path, options['client-cert'].path) factory.portal = Portal(realm, [checker]) service = MultiService() for endpoint in options["listen"]: child = StreamServerEndpointService(endpoint, factory) child.setServiceParent(service) return service
def run(device): ''' Run a threaded server. ''' prompts = { 'rpi2': ':~$', 'rpi3': ':~>' } this_dir = os.path.dirname(__file__) with open(os.path.join(this_dir, 'private.key')) as private_blob_file: private_blob = private_blob_file.read() private_key = Key.fromString(data=private_blob) with open(os.path.join(this_dir, 'public.key')) as public_blob_file: public_blob = public_blob_file.read() public_key = Key.fromString(data=public_blob) factory = SSHFactory() factory.privateKeys = {'ssh-rsa': private_key} factory.publicKeys = {'ssh-rsa': public_key} SimpleSession.set_prompt(prompts[device]) factory.portal = Portal(SimpleRealm()) factory.portal.registerChecker(FilePasswordDB(os.path.join(this_dir, 'ssh-passwords'))) reactor.listenTCP(2022, factory, interface='127.0.0.1') thread = Thread(target=reactor.run, args=(False,)) thread.daemon = True thread.start()
def makeService(): public_key = get_key('id_rsa.pub') private_key = get_key('id_rsa') factory = SSHFactory() factory.privateKeys = {'ssh-rsa': private_key} factory.publicKeys = {'ssh-rsa': public_key} factory.portal = Portal(UnixSSHRealm()) factory.portal.registerChecker(DummyChecker()) return internet.TCPServer(2200, factory)
def getFactory(self): """ Create an L{SSHFactory} which allows access to Mantissa accounts. """ privateKey = Key.fromString(data=self.hostKey) public = privateKey.public() factory = SSHFactory() factory.publicKeys = {'ssh-rsa': public} factory.privateKeys = {'ssh-rsa': privateKey} factory.portal = Portal( IRealm(self.store), [ICredentialsChecker(self.store)]) return factory
def makeFactory(): public_key = get_key('id_rsa.pub') private_key = get_key('id_rsa') factory = SSHFactory() log.msg("make Factory") factory.privateKeys = {'ssh-rsa': private_key} factory.publicKeys = {'ssh-rsa': public_key} factory.portal = Portal(MidasRealm()) factory.portal.registerChecker(MidasChecker("http://localhost/midas")) return factory
def getFactory(self): """ Create an L{SSHFactory} which allows access to Mantissa accounts. """ privateKey = Key.fromString(data=self.hostKey) public = privateKey.public() factory = SSHFactory() factory.publicKeys = {'ssh-rsa': public} factory.privateKeys = {'ssh-rsa': privateKey} factory.portal = Portal(IRealm(self.store), [ICredentialsChecker(self.store)]) return factory
def main(keys_path, port): with open(keys_path + '/id_rsa') as privateBlobFile: privateBlob = privateBlobFile.read() privateKey = Key.fromString(data=privateBlob) with open(keys_path + '/id_rsa.pub') as publicBlobFile: publicBlob = publicBlobFile.read() publicKey = Key.fromString(data=publicBlob) factory = SSHFactory() factory.privateKeys = {'ssh-rsa': privateKey} factory.publicKeys = {'ssh-rsa': publicKey} factory.portal = Portal(KeyRealm()) factory.portal.registerChecker(KeyChecker()) factory.portal.registerChecker(PasswordChecker()) reactor.listenTCP(port, factory) reactor.run()
def makeService(cls, config): """ Create the txsftp service. """ if (conf.get('suppress-deprecation-warnings')): warnings.filterwarnings('ignore', r'.*', DeprecationWarning) get_key = lambda path: Key.fromString(data=open(path).read()) ssh_public_key = get_key(conf.get('ssh-public-key')) ssh_private_key = get_key(conf.get('ssh-private-key')) factory = SSHFactory() factory.privateKeys = {'ssh-rsa': ssh_private_key} factory.publicKeys = {'ssh-rsa': ssh_public_key} db = dbapi.connect(conf.get('db-url')) factory.portal = Portal(auth.VirtualizedSSHRealm(db)) factory.portal.registerChecker(auth.UsernamePasswordChecker(db)) factory.portal.registerChecker(auth.SSHKeyChecker(db)) return internet.TCPServer(conf.get('sftp-port'), factory)
def makeService(cls, config): """ Create the txsftp service. """ if(conf.get('suppress-deprecation-warnings')): warnings.filterwarnings('ignore', r'.*', DeprecationWarning) get_key = lambda path: Key.fromString(data=open(path).read()) ssh_public_key = get_key(conf.get('ssh-public-key')) ssh_private_key = get_key(conf.get('ssh-private-key')) factory = SSHFactory() factory.privateKeys = {'ssh-rsa': ssh_private_key} factory.publicKeys = {'ssh-rsa': ssh_public_key} db = dbapi.connect(conf.get('db-url')) factory.portal = Portal(auth.VirtualizedSSHRealm(db)) factory.portal.registerChecker(auth.UsernamePasswordChecker(db)) factory.portal.registerChecker(auth.SSHKeyChecker(db)) return internet.TCPServer(conf.get('sftp-port'), factory)
def startService(self): assert self.realm is not None, ( "When subclassing SSHProtoService, assign a realm to the " "`realm` attribute (e.g. an instance of `SSHDemoRealm`).") with open(self.servicePrivateKey) as privateBlobFile: privateBlob = privateBlobFile.read() privateKey = Key.fromString(data=privateBlob) with open(self.servicePublicKey) as publicBlobFile: publicBlob = publicBlobFile.read() publicKey = Key.fromString(data=publicBlob) factory = SSHFactory() factory.privateKeys = {'ssh-rsa': privateKey} factory.publicKeys = {'ssh-rsa': publicKey} sshRealm = self.realm sshPortal = Portal(sshRealm) factory.portal = sshPortal keydb = UNIXAuthorizedKeysFiles() factory.portal.registerChecker(SSHPublicKeyChecker(keydb)) ep = endpoints.serverFromString(self.reactor, self.endpointStr) d = ep.listen(factory) self.port_info_ = [] d.addCallback(self.onListen)
def runServer(prompt="$ ", private_key='id_rsa', public_key='id_rsa.pub'): if not privateKeyString: raise SSHServerError("Could not load private key file.") if not publicKeyString: raise SSHServerError("Could not load public key file.") log.msg('Initializing Server') sshFactory = SSHFactory() log.msg('loading private key') sshFactory.privateKeys = {'ssh-rsa': privateKeyString} log.msg('loading public key') sshFactory.publicKeys = {'ssh-rsa': publicKeyString} sshFactory.portal = portal.Portal(SSHRealm(prompt=prompt)) sshFactory.portal.registerChecker(FilePasswordDB("ssh-passwords")) log.msg('Listening on 2222') reactor.listenTCP(2222, sshFactory) reactor.run()
user = ConchUser() user.channelLookup["session"] = Session return IConchUser, user, lambda: None if ITelnetProtocol in interfaces: return ITelnetProtocol, TelnetProxy(), lambda: None return None portal = Portal(Realm()) portal.registerChecker(checker) command = ['/usr/bin/socat', 'STDIO,raw,echo=0,escape=0x1d', 'UNIX-CONNECT:/var/run/ganeti/kvm-hypervisor/ctrl/instance1.example.org.serial'] cc = ClientCreator(reactor, CommandTransport, command) private = Key.fromFile("keys/id_rsa_vncap") public = Key.fromFile("keys/id_rsa_vncap.pub") factory = SSHFactory() factory.privateKeys = {"ssh-rsa": private} factory.publicKeys = {"ssh-rsa": public} factory.portal = portal reactor.listenTCP(2022, factory) reactor.listenTCP(2023, TelnetFactory()) reactor.run()
def startService(self): """ This is the main entry point into the service when it starts. Multiple components need to be created and assembled to create the final service. It helps to look at the process in reverse. An endpoint (`ep`) is created that listens on a port. When a connection is received, it uses a protocol `factory` to create a new SSH protocol instance. The factory is configure with a portal that will be used to authenticate users and create avatars for them at the service. The factory portal registered a :py:class:`SSHPublicKeychecker` instance so that users can authenticate using SSH public/private key pairs. The allowed public keys and the matching users are configured in a JSON file that the service reads on start up. The protocol factory (:py:class:`twisted.conch.ssh.factory.SSHFactory`) is indirectly responsible for calling the `login` method on its portal. When the "ssh-userauth" service of the SSH protocol is requested, the factory creates an instance of :py:class:`twisted.conch.ssh.userauth.SSHUserAuthServer` to create a public key credential and pass it to the portal's `login` method. It is at this point the public key checker can authenticate the credential. The portal was also configured with `self.realmFactory` which happens to produce an instance of :py:class:`auth.SSHRealm`. This realm creates an avatar instance which will represent the user on the service side of the connection. The avatar created will be an instance of :py:class:`auth.SSHAvatar`. This avatar is responsible for connecting the user to the service application logic. """ assert self.realmFactory is not None, "`realmFactory` must not be None!" with open(self.servicePrivateKey, "r") as privateBlobFile: privateBlob = privateBlobFile.read() privateKey = Key.fromString(data=privateBlob) with open(self.servicePublicKey, "r") as publicBlobFile: publicBlob = publicBlobFile.read() publicKey = Key.fromString(data=publicBlob) factory = SSHFactory() factory.privateKeys = {b'ssh-rsa': privateKey} factory.publicKeys = {b'ssh-rsa': publicKey} sshRealm = self.realmFactory() sshRealm.reactor = self.reactor sshPortal = Portal(sshRealm) factory.portal = sshPortal with open(self.key_db_path, "r") as f: raw_key_map = json.load(f) l = [] for avatar_id, keys in raw_key_map.items(): key_objects = [Key.fromString(k.encode('utf-8')) for k in keys] l.append((avatar_id.encode('utf-8'), key_objects)) key_map = dict(l) keydb = InMemorySSHKeyDB(key_map) factory.portal.registerChecker(SSHPublicKeyChecker(keydb)) ep = endpoints.serverFromString(self.reactor, self.endpoint_str) d = ep.listen(factory) self.port_info_ = [] d.addCallback(self.onListen)
return True def request_pty_req(self, data): return True def eofReceived(self): print 'eofReceived' def closed(self): print 'closed' def closeReceived(self): print 'closeReceived' class SimpleRealm(object): def requestAvatar(self, avatarId, mind, *interfaces): user = ConchUser() user.channelLookup['session'] = SimpleSession return IConchUser, user, nothing factory = SSHFactory() factory.privateKeys = { 'ssh-rsa': privateKey } factory.publicKeys = { 'ssh-rsa': publicKey } factory.portal = Portal(SimpleRealm()) factory.portal.registerChecker(FilePasswordDB("ssh-passwords")) reactor.listenTCP(2022, factory) reactor.run()
def makeService(options): """ Makes a new swftp-sftp service. The only option is the config file location. See CONFIG_DEFAULTS for list of configuration options. """ from twisted.conch.ssh.connection import SSHConnection from twisted.conch.ssh.factory import SSHFactory from twisted.conch.ssh.keys import Key from twisted.cred.portal import Portal from swftp.realm import SwftpRealm from swftp.sftp.server import SwiftSSHUserAuthServer from swftp.auth import SwiftBasedAuthDB from swftp.utils import ( log_runtime_info, GLOBAL_METRICS, parse_key_value_config) c = get_config(options['config_file'], options) sftp_service = service.MultiService() # ensure timezone is GMT os.environ['TZ'] = 'GMT' time.tzset() print('Starting SwFTP-sftp %s' % VERSION) # Add statsd service if c.get('sftp', 'log_statsd_host'): try: from swftp.statsd import makeService as makeStatsdService makeStatsdService( c.get('sftp', 'log_statsd_host'), c.getint('sftp', 'log_statsd_port'), sample_rate=c.getfloat('sftp', 'log_statsd_sample_rate'), prefix=c.get('sftp', 'log_statsd_metric_prefix') ).setServiceParent(sftp_service) except ImportError: sys.stderr.write('Missing Statsd Module. Requires "txstatsd" \n') if c.get('sftp', 'stats_host'): from swftp.report import makeService as makeReportService known_fields = [ 'command.login', 'command.logout', 'command.gotVersion', 'command.openFile', 'command.removeFile', 'command.renameFile', 'command.makeDirectory', 'command.removeDirectory', 'command.openDirectory', 'command.getAttrs', ] + GLOBAL_METRICS makeReportService( c.get('sftp', 'stats_host'), c.getint('sftp', 'stats_port'), known_fields=known_fields ).setServiceParent(sftp_service) authdb = SwiftBasedAuthDB( c.get('sftp', 'auth_url'), global_max_concurrency=c.getint('sftp', 'num_persistent_connections'), max_concurrency=c.getint('sftp', 'num_connections_per_session'), timeout=c.getint('sftp', 'connection_timeout'), extra_headers=parse_key_value_config(c.get('sftp', 'extra_headers')), verbose=c.getboolean('sftp', 'verbose'), rewrite_scheme=c.get('sftp', 'rewrite_storage_scheme'), rewrite_netloc=c.get('sftp', 'rewrite_storage_netloc'), ) rabbitmq_hosts = c.get('rabbitmq', 'rabbitmq_hosts') rabbitmq_cluster = RabbitClusterClient([RabbitReplica(host, port) \ for host, port in [(h,int(p)) for h,p in [r.split(':') \ for r in rabbitmq_hosts.split(',')]]], \ c.get('rabbitmq', 'username'), \ c.get('rabbitmq', 'password')) \ if rabbitmq_hosts else None queue_name = c.get('rabbitmq', 'queue_name') realm = SwftpRealm(rabbitmq_cluster, queue_name) sftpportal = Portal(realm) sftpportal.registerChecker(authdb) sshfactory = SSHFactory() protocol = SwiftSSHServerTransport protocol.maxConnectionsPerUser = c.getint('sftp', 'sessions_per_user') protocol.supportedCiphers = c.get('sftp', 'chiphers') protocol.supportedMACs = c.get('sftp', 'macs') protocol.supportedCompressions = c.get('sftp', 'compressions') sshfactory.protocol = protocol sshfactory.noisy = False sshfactory.portal = sftpportal sshfactory.services['ssh-userauth'] = SwiftSSHUserAuthServer sshfactory.services['ssh-connection'] = SSHConnection pub_key_string = file(c.get('sftp', 'pub_key')).read() priv_key_string = file(c.get('sftp', 'priv_key')).read() sshfactory.publicKeys = { 'ssh-rsa': Key.fromString(data=pub_key_string)} sshfactory.privateKeys = { 'ssh-rsa': Key.fromString(data=priv_key_string)} signal.signal(signal.SIGUSR1, log_runtime_info) signal.signal(signal.SIGUSR2, log_runtime_info) internet.TCPServer( c.getint('sftp', 'port'), sshfactory, interface=c.get('sftp', 'host')).setServiceParent(sftp_service) return sftp_service
def makeService(options): """ Makes a new swftp-sftp service. The only option is the config file location. See CONFIG_DEFAULTS for list of configuration options. """ from twisted.conch.ssh.factory import SSHFactory from twisted.conch.ssh.keys import Key from twisted.cred.portal import Portal from swftp.sftp.server import SwiftSFTPRealm, SwiftSSHServerTransport, \ SwiftSSHConnection from swftp.auth import SwiftBasedAuthDB from swftp.utils import ( log_runtime_info, GLOBAL_METRICS, parse_key_value_config) c = get_config(options['config_file'], options) sftp_service = service.MultiService() # ensure timezone is GMT os.environ['TZ'] = 'GMT' time.tzset() print('Starting SwFTP-sftp %s' % VERSION) # Add statsd service if c.get('sftp', 'log_statsd_host'): try: from swftp.statsd import makeService as makeStatsdService makeStatsdService( c.get('sftp', 'log_statsd_host'), c.getint('sftp', 'log_statsd_port'), sample_rate=c.getfloat('sftp', 'log_statsd_sample_rate'), prefix=c.get('sftp', 'log_statsd_metric_prefix') ).setServiceParent(sftp_service) except ImportError: sys.stderr.write('Missing Statsd Module. Requires "txstatsd" \n') if c.get('sftp', 'stats_host'): from swftp.report import makeService as makeReportService known_fields = [ 'command.login', 'command.logout', 'command.gotVersion', 'command.openFile', 'command.removeFile', 'command.renameFile', 'command.makeDirectory', 'command.removeDirectory', 'command.openDirectory', 'command.getAttrs', ] + GLOBAL_METRICS makeReportService( c.get('sftp', 'stats_host'), c.getint('sftp', 'stats_port'), known_fields=known_fields ).setServiceParent(sftp_service) authdb = SwiftBasedAuthDB( c.get('sftp', 'auth_url'), global_max_concurrency=c.getint('sftp', 'num_persistent_connections'), max_concurrency=c.getint('sftp', 'num_connections_per_session'), timeout=c.getint('sftp', 'connection_timeout'), extra_headers=parse_key_value_config(c.get('sftp', 'extra_headers')), verbose=c.getboolean('sftp', 'verbose')) sftpportal = Portal(SwiftSFTPRealm()) sftpportal.registerChecker(authdb) sshfactory = SSHFactory() sshfactory.protocol = SwiftSSHServerTransport sshfactory.noisy = False sshfactory.portal = sftpportal sshfactory.services['ssh-connection'] = SwiftSSHConnection pub_key_string = file(c.get('sftp', 'pub_key')).read() priv_key_string = file(c.get('sftp', 'priv_key')).read() sshfactory.publicKeys = { 'ssh-rsa': Key.fromString(data=pub_key_string)} sshfactory.privateKeys = { 'ssh-rsa': Key.fromString(data=priv_key_string)} signal.signal(signal.SIGUSR1, log_runtime_info) signal.signal(signal.SIGUSR2, log_runtime_info) internet.TCPServer( c.getint('sftp', 'port'), sshfactory, interface=c.get('sftp', 'host')).setServiceParent(sftp_service) return sftp_service
def makeService(options): """ Makes a new swftp-sftp service. The only option is the config file location. The config file has the following options: - host - port - auth_url - num_persistent_connections - connection_timeout - pub_key - priv_key """ from twisted.conch.ssh.factory import SSHFactory from twisted.conch.ssh.keys import Key from twisted.web.client import HTTPConnectionPool from twisted.cred.portal import Portal from swftp.sftp.server import SwiftSFTPRealm, SwiftSSHServerTransport from swftp.sftp.connection import SwiftConnection from swftp.auth import SwiftBasedAuthDB from swftp.utils import print_runtime_info c = get_config(options['config_file'], options) pool = HTTPConnectionPool(reactor, persistent=True) pool.maxPersistentPerHost = c.getint('sftp', 'num_persistent_connections') pool.cachedConnectionTimeout = c.getint('sftp', 'connection_timeout') sftp_service = service.MultiService() # ensure timezone is GMT os.environ['TZ'] = 'GMT' time.tzset() log.msg('Starting SwFTP-sftp %s' % VERSION) # Add statsd service if c.get('sftp', 'log_statsd_host'): try: from swftp.statsd import makeService as makeStatsdService makeStatsdService( c.get('sftp', 'log_statsd_host'), c.getint('sftp', 'log_statsd_port'), sample_rate=c.getfloat('sftp', 'log_statsd_sample_rate'), prefix=c.get('sftp', 'log_statsd_metric_prefix') ).setServiceParent(sftp_service) except ImportError: log.err('Missing Statsd Module. Requires "txstatsd"') authdb = SwiftBasedAuthDB(auth_url=c.get('sftp', 'auth_url'), verbose=c.getboolean('sftp', 'verbose')) sftpportal = Portal(SwiftSFTPRealm()) sftpportal.registerChecker(authdb) sshfactory = SSHFactory() sshfactory.protocol = SwiftSSHServerTransport sshfactory.noisy = False sshfactory.portal = sftpportal sshfactory.services['ssh-connection'] = SwiftConnection pub_key_string = file(c.get('sftp', 'pub_key')).read() priv_key_string = file(c.get('sftp', 'priv_key')).read() sshfactory.publicKeys = { 'ssh-rsa': Key.fromString(data=pub_key_string)} sshfactory.privateKeys = { 'ssh-rsa': Key.fromString(data=priv_key_string)} signal.signal(signal.SIGUSR1, print_runtime_info) signal.signal(signal.SIGUSR2, print_runtime_info) internet.TCPServer( c.getint('sftp', 'port'), sshfactory, interface=c.get('sftp', 'host')).setServiceParent(sftp_service) return sftp_service