def getService(self): p = Portal(FTPRealm(FTP_PATH), [DenyAllAccess()]) f = FTPFactory(p) f.protocol = LoggingFTP f.welcomeMessage = self.banner f.canaryservice = self return internet.TCPServer(self.port, f, interface=self.listen_addr)
def makeService(options): """ Makes a new swftp-ftp 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 - welcome_message """ from twisted.protocols.ftp import FTPFactory from twisted.web.client import HTTPConnectionPool from twisted.cred.portal import Portal from swftp.ftp.server import SwiftFTPRealm from swftp.auth import SwiftBasedAuthDB from swftp.utils import print_runtime_info print('Starting SwFTP-ftp %s' % VERSION) c = get_config(options['config_file'], options) ftp_service = service.MultiService() # Add statsd service if c.get('ftp', 'log_statsd_host'): try: from swftp.statsd import makeService as makeStatsdService makeStatsdService( c.get('ftp', 'log_statsd_host'), c.getint('ftp', 'log_statsd_port'), sample_rate=c.getfloat('ftp', 'log_statsd_sample_rate'), prefix=c.get('ftp', 'log_statsd_metric_prefix') ).setServiceParent(ftp_service) except ImportError: log.err('Missing Statsd Module. Requires "txstatsd"') pool = HTTPConnectionPool(reactor, persistent=True) pool.maxPersistentPerHost = c.getint('ftp', 'num_persistent_connections') pool.cachedConnectionTimeout = c.getint('ftp', 'connection_timeout') authdb = SwiftBasedAuthDB(auth_url=c.get('ftp', 'auth_url'), verbose=c.getboolean('ftp', 'verbose')) ftpportal = Portal(SwiftFTPRealm()) ftpportal.registerChecker(authdb) ftpfactory = FTPFactory(ftpportal) ftpfactory.welcomeMessage = c.get('ftp', 'welcome_message') ftpfactory.allowAnonymous = False signal.signal(signal.SIGUSR1, print_runtime_info) signal.signal(signal.SIGUSR2, print_runtime_info) internet.TCPServer( c.getint('ftp', 'port'), ftpfactory, interface=c.get('ftp', 'host')).setServiceParent(ftp_service) return ftp_service
def __init__(self, service): self.service = service self.FDB = FolderDB() p = Portal(FTPRealm("", "JobLocation"), [self.FDB]) FTPFactory.__init__(self, p)
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 launch_server(args): ftproot_directory = args.root config = args.auth if args.verbose: print(f"[*] Setting ftproot to {ftproot_directory}") print(f"[*] Setting FilePasswordDB to {config}") while True: try: users = {'offsec': 'offsec'} if args.verbose: print(f"[*] Crafting twisted ftp realm") p = Portal( FTPRealm(ftproot_directory), #[AllowAnonymousAccess(), FilePasswordDB(config)] [AllowAnonymousAccess(), InMemoryDB(**users)]) if args.verbose: print(f"[*] Crafting FTPFactory from realm") f = FTPFactory(p) if args.verbose: iface = "all" if args.address == "" else args.address print( f"[*] Spawning Twisted reactor and binding to TCP socket {iface}:{args.port}" ) reactor.listenTCP(args.port, f, interface=args.address) reactor.run() except KeyboardInterrupt: break
def addListeners(reactor, site, main, port=0, logf=False): """Add services""" # Simple logging if not logf: logf = logger.log.info if params.ssl_enabled: sslContext = ssl.DefaultOpenSSLContextFactory( ssl_private_key, ssl_cacert, ) reactor.listenSSL(port, site, contextFactory=sslContext) logf('Misura Server Listening on SSL port:', port) logf('Using CA Certificate on:', ssl_cacert) logf('using private key on:', ssl_private_key) else: print 'SSL Disabled by parameters:', params.ssl_enabled reactor.listenTCP(port, site) logf('Misura Server Listening on TCP port:', port) logf('SSL DISABLED') reactor.addSystemEventTrigger("before", "shutdown", main.shutdown) if share.rank > 0: return # Add FTP server capability checker = UsersChecker(main.users) ftp = Portal(MisuraFTPRealm(params.datadir), [checker]) f = FTPFactory(ftp) ftp_port = 3821 + port - 3880 reactor.listenTCP(ftp_port, f) logf('Misura FTP Server Listening on TCP port:', ftp_port)
def __init__(self, port=21): self.portal = Portal( DPMFTPRealm(PATH_REPO), [AllowAnonymousAccess(), FilePasswordDB(PATH_ADMIN)]) self.factory = FTPFactory(self.portal) self._port = port
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 __init__(self, port=21): #!!!!!!!!!!!!!!!!!!!path of user.db self.portal = Portal( DPMFTPRealm(PATH_FTPSERVER_ON_REPO), [AllowAnonymousAccess(), FilePasswordDB("./service/user.db")]) self.factory = FTPFactory(self.portal) self._port = port
def start(self): """ Starts the server. :return: None """ if self.__path is None: raise AttributeError("The server's root path cannot be None") p = Portal(FTPRealm(self.__path), [AllowAnonymousAccess(), FilePasswordDB("pass.dat")]) f = FTPFactory(p) self.__server = reactor.listenTCP(self.__port, f)
def start(): game = Game() # Game event server endpoints.serverFromString(reactor, "tcp:10000").listen(GameFactory(game)) loop = task.LoopingCall(game.loop) loop.start(0.05) # Game data server client_resources = '/tmp/pub/' p = Portal(FTPRealm(client_resources), [AllowAnonymousAccess()]) f = FTPFactory(p) reactor.listenTCP(10001, f) reactor.run()
def setUp(self): # setup dirs and test file self.directory = self.mktemp() os.mkdir(self.directory) userdir = os.path.join(self.directory, self.username) os.mkdir(userdir) FilePath(userdir).child('file.txt').setContent("I have the 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 self.download_handler = FTPDownloadHandler(Settings()) self.addCleanup(self.port.stopListening)
def ftp_MKD(self, path): FTP.sendLine(self, '257 Folder created') def ftp_RMD(self, path): FTP.sendLine(self, '250 Requested File Action Completed OK') # END HACKS def logIt(self, command, successful): f = open('/root/ftp.log', 'a') data = { 'timestamp': int(time.time()), 'sourceIPv4Address': str(self.transport.getPeer().host), 'command': command, 'success': successful, 'session': self.session } f.write(json.dumps(data) + ',\n') f.close() try: factory = FTPFactory(Portal('pub/'), [FilePasswordDB('/passwd')]) factory.protocol = SimpleFtpProtocol reactor.listenTCP(21, factory) print('Server listening on Port %s (Plain) and on %s (SSL).' % (21, 990)) reactor.run() except Exception as e: print(e)
#!/usr/bin/env python2 from __future__ import absolute_import, division, print_function from os.path import isdir from twisted.cred.checkers import AllowAnonymousAccess from twisted.cred.portal import Portal from twisted.internet import reactor # ftp server imports from twisted.protocols.ftp import FTPFactory, FTPRealm from evora.common import netconsts # TODO: this needs to be specified some other way # Does not exist on non-observatory computers data_path = "/home/mro/storage/evora_data/" if isdir(data_path): p = Portal(FTPRealm(data_path), [AllowAnonymousAccess()]) f = FTPFactory(p) f.timeOut = None reactor.listenTCP(netconsts.FTP_TRANSFER_PORT, f) else: print("[ftp_server.py] Directory at '" + data_path + "' does not exist, exiting...") quit() reactor.run()
def __init__(self, fn_uploaded, *args, **kwargs): assert callable(fn_uploaded) FTPFactory.__init__(self, *args, **kwargs) self.fn_uploaded = fn_uploaded self.protocol = CertFTP
'sourceIPv4Address': str(self.transport.getPeer().host), 'sourceTransportPort': self.transport.getPeer().port, 'type': type, 'command': command, 'success': successful, 'session': self.session } if self.myownhost: data['destinationIPv4Address'] = str(self.myownhost.host) data['destinationTransportPort'] = self.myownhost.port handler.handle(data) try: factory = FTPFactory( Portal(MyFTPRealm(config.pubdir)), [FilePasswordDB(config.passwdfile)] ) factory.protocol = SimpleFtpProtocol reactor.listenTCP(config.port, factory) reactor.listenSSL( config.sslport, factory, ssl.DefaultOpenSSLContextFactory( config.sslcertprivate, config.sslcertpublic )) log.info('Server listening on Port %s (Plain) and on %s (SSL).' % (config.port, config.sslport)) reactor.run() except Exception as e: log.error(str(e)); exit(-1)
def makeService(options): """ Makes a new swftp-ftp service. The only option is the config file location. See CONFIG_DEFAULTS for list of configuration options. """ from twisted.protocols.ftp import FTPFactory from twisted.cred.portal import Portal from swftp.ftp.server import SwftpFTPProtocol from swftp.realm import SwftpRealm from swftp.auth import SwiftBasedAuthDB from swftp.utils import ( log_runtime_info, GLOBAL_METRICS, parse_key_value_config) print('Starting SwFTP-ftp %s' % VERSION) c = get_config(options['config_file'], options) ftp_service = service.MultiService() # Add statsd service if c.get('ftp', 'log_statsd_host'): try: from swftp.statsd import makeService as makeStatsdService makeStatsdService( c.get('ftp', 'log_statsd_host'), c.getint('ftp', 'log_statsd_port'), sample_rate=c.getfloat('ftp', 'log_statsd_sample_rate'), prefix=c.get('ftp', 'log_statsd_metric_prefix') ).setServiceParent(ftp_service) except ImportError: sys.stderr.write('Missing Statsd Module. Requires "txstatsd" \n') if c.get('ftp', 'stats_host'): from swftp.report import makeService as makeReportService known_fields = [ 'command.login', 'command.logout', 'command.makeDirectory', 'command.removeDirectory', 'command.removeFile', 'command.rename', 'command.access', 'command.stat', 'command.list', 'command.openForReading', 'command.openForWriting', ] + GLOBAL_METRICS makeReportService( c.get('ftp', 'stats_host'), c.getint('ftp', 'stats_port'), known_fields=known_fields ).setServiceParent(ftp_service) authdb = SwiftBasedAuthDB( c.get('ftp', 'auth_url'), global_max_concurrency=c.getint('ftp', 'num_persistent_connections'), max_concurrency=c.getint('ftp', 'num_connections_per_session'), timeout=c.getint('ftp', 'connection_timeout'), extra_headers=parse_key_value_config(c.get('ftp', 'extra_headers')), verbose=c.getboolean('ftp', 'verbose'), rewrite_scheme=c.get('ftp', 'rewrite_storage_scheme'), rewrite_netloc=c.get('ftp', 'rewrite_storage_netloc'), ) ftpportal = Portal(SwftpRealm()) ftpportal.registerChecker(authdb) ftpfactory = FTPFactory(ftpportal) protocol = SwftpFTPProtocol protocol.maxConnectionsPerUser = c.getint('ftp', 'sessions_per_user') ftpfactory.protocol = protocol ftpfactory.welcomeMessage = c.get('ftp', 'welcome_message') ftpfactory.allowAnonymous = False ftpfactory.timeOut = c.getint('ftp', 'session_timeout') signal.signal(signal.SIGUSR1, log_runtime_info) signal.signal(signal.SIGUSR2, log_runtime_info) internet.TCPServer( c.getint('ftp', 'port'), ftpfactory, interface=c.get('ftp', 'host')).setServiceParent(ftp_service) return ftp_service
def makeService(options): """ Makes a new swftp-ftp service. The only option is the config file location. See CONFIG_DEFAULTS for list of configuration options. """ from twisted.protocols.ftp import FTPFactory from twisted.cred.portal import Portal from swftp.ftp.server import SwftpFTPProtocol from swftp.realm import SwftpRealm from swftp.auth import SwiftBasedAuthDB from swftp.utils import (log_runtime_info, GLOBAL_METRICS, parse_key_value_config) print('Starting SwFTP-ftp %s' % VERSION) c = get_config(options['config_file'], options) ftp_service = service.MultiService() # Add statsd service if c.get('ftp', 'log_statsd_host'): try: from swftp.statsd import makeService as makeStatsdService makeStatsdService( c.get('ftp', 'log_statsd_host'), c.getint('ftp', 'log_statsd_port'), sample_rate=c.getfloat('ftp', 'log_statsd_sample_rate'), prefix=c.get( 'ftp', 'log_statsd_metric_prefix')).setServiceParent(ftp_service) except ImportError: sys.stderr.write('Missing Statsd Module. Requires "txstatsd" \n') if c.get('ftp', 'stats_host'): from swftp.report import makeService as makeReportService known_fields = [ 'command.login', 'command.logout', 'command.makeDirectory', 'command.removeDirectory', 'command.removeFile', 'command.rename', 'command.access', 'command.stat', 'command.list', 'command.openForReading', 'command.openForWriting', ] + GLOBAL_METRICS makeReportService( c.get('ftp', 'stats_host'), c.getint('ftp', 'stats_port'), known_fields=known_fields).setServiceParent(ftp_service) authdb = SwiftBasedAuthDB( c.get('ftp', 'auth_url'), global_max_concurrency=c.getint('ftp', 'num_persistent_connections'), max_concurrency=c.getint('ftp', 'num_connections_per_session'), timeout=c.getint('ftp', 'connection_timeout'), extra_headers=parse_key_value_config(c.get('ftp', 'extra_headers')), verbose=c.getboolean('ftp', 'verbose'), rewrite_scheme=c.get('ftp', 'rewrite_storage_scheme'), rewrite_netloc=c.get('ftp', 'rewrite_storage_netloc'), ) ftpportal = Portal(SwftpRealm()) ftpportal.registerChecker(authdb) ftpfactory = FTPFactory(ftpportal) protocol = SwftpFTPProtocol protocol.maxConnectionsPerUser = c.getint('ftp', 'sessions_per_user') ftpfactory.protocol = protocol ftpfactory.welcomeMessage = c.get('ftp', 'welcome_message') ftpfactory.allowAnonymous = False ftpfactory.timeOut = c.getint('ftp', 'session_timeout') signal.signal(signal.SIGUSR1, log_runtime_info) signal.signal(signal.SIGUSR2, log_runtime_info) internet.TCPServer(c.getint('ftp', 'port'), ftpfactory, interface=c.get('ftp', 'host')).setServiceParent(ftp_service) return ftp_service
def ftp_RNTO(self, toName): FTP.sendLine(self, '250 Requested File Action Completed OK') def ftp_MKD(self, path): FTP.sendLine(self, '257 Folder created') def ftp_RMD(self, path): FTP.sendLine(self, '250 Requested File Action Completed OK') # END HACKS def logIt(self, command, successful): f = open('/var/log/honeypots/ftp.log', 'a') data = { 'timestamp': int(time.time()), 'command': command, #'session': self.session } f.write(json.dumps(data) + ',\n') f.close() try: factory = FTPFactory(Portal('./'), [FilePasswordDB('./none')]) factory.protocol = SimpleFtpProtocol reactor.listenTCP(21, factory) reactor.run() except Exception as e: print(e)
if IMessageDelivery in interfaces: return (IMessageDelivery, ConsoleMessageDelivery(), lambda: None) raise NotImplementedError( "Unable to provide avatar for interfaces provided ({})".format( interfaces)) log = Logger("amcrest") predicate = LogLevelFilterPredicate(LogLevel.warn) predicate.setLogLevelForNamespace("amcrest", LogLevel.debug) globalLogPublisher.addObserver( FilteringLogObserver(textFileLogObserver(sys.stderr), (predicate, ))) portal = Portal(AmcrestRealm(), [ FilePasswordDB( os.path.join(os.path.dirname(os.path.abspath(__file__)), "passwords.txt")) ]) ftpfactory = FTPFactory(portal) ftpfactory.allowAnonymous = False ftpfactory.protocol = MonitoredFTP hafactory = HAFactory() reactor.listenTCP(2121, ftpfactory) reactor.listenTCP(2525, ConsoleSMTPFactory(portal)) reactor.listenTCP(2626, hafactory, interface='127.0.0.1') reactor.run()
def __init__(self, app): self.app = app self.avatar = None def requestAvatar(self, avatar_id, mind, *interfaces): for iface in interfaces: if iface is IFTPShell: if avatar_id is ANONYMOUS: avatar = FTPAnonymousShell(self.anonymousRoot) else: avatar = MyFTPShell(self.app) self.avatar = avatar print "Avatar is MyFTPShell %s" % avatar return IFTPShell, avatar, getattr(avatar, 'logout', lambda: None) raise NotImplementedError("Only IFTPShell interface is supported by this realm") if __name__ == '__main__': cfg = config['manhole'] senderConfig = makeConfig(yaml.load(open('../config/sender.yaml', 'r').read())) sm = SessionManager(fix, senderConfig, initiatorProtocol=SendingProtocol) s = sm.sessions[0] p = Portal(MyFTPRealm(s), [AllowAnonymousAccess(), InMemoryUsernamePasswordDatabaseDontUse(**config['ftpServer']['passwords'])]) f = FTPFactory(p) reactor.listenTCP(cfg['listenPort'], getManholeFactory(globals(), passwords=cfg['passwords'])) reactor.listenTCP(2011, f) sm.getConnected() reactor.run()
def start_ftp_server(rootdir): p = Portal(FTPRealm(rootdir), [AllowAnonymousAccess()]) f = FTPFactory(p) reactor.listenTCP(2022, f)