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) else: root.putChild('clk', ClickHandler(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 start_binding(): """ Starts the :class:`PoloBinding` """ try: with open(conf.SECRET_FILE, 'r') as sf: secret = sf.read() except Exception: logging.error("Could not parse secret file: %s. Binding will not start" % s) return polobinding = PoloBindingSSL factory = PoloBindingSSLFactory(secret, offered_services, user_services, conf.MULTICAST_ADDRS) factory.protocol = polobinding myContextFactory = ssl.DefaultOpenSSLContextFactory( '/etc/marcopolo/certs/polossl.key', '/etc/marcopolo/certs/polossl.crt' ) ctx = myContextFactory.getContext() reactor.listenSSL(conf.POLO_BINDING_PORT, factory, myContextFactory, interface='127.0.0.1')
def process_nmap_commands(logger_name): """ Main function. Here we set up the environment, factory and port """ global nmap_commands_file global nmap_command global port global mlog global verbose_level global client_timeout observer = log.PythonLoggingObserver(logger_name) observer.start() # Create the factory factory = Factory() factory.protocol = NmapServerProtocol # Create the time based print loop = task.LoopingCall(show_info) loop.start(5) # Create the time based file read loop2 = task.LoopingCall(read_file_and_fill_nmap_variable) loop2.start(1) # To mark idel clients as hold loop3 = task.LoopingCall(timeout_idle_clients) loop3.start(client_timeout) # call every second if not sql_file =="": loop4 = task.LoopingCall(sql_import_loop) loop4.start(5) # Create the reactor reactor.listenSSL(port, factory, ServerContextFactory()) reactor.run()
def build_reactor(options, **kwargs): web_socket_instance = FilteredWebSocketFactory(**kwargs) subscriber = kwargs.pop("subscriber", None) if options.key and options.cert: with open(options.key) as keyFile: with open(options.cert) as certFile: cert = ssl.PrivateCertificate.loadPEM(keyFile.read() + certFile.read()) reactor.listenSSL(options.port, web_socket_instance, cert.options()) else: reactor.listenTCP( options.port, web_socket_instance ) if subscriber is not None: reactor.callInThread( subscriber.listener, web_socket_instance ) reactor.addSystemEventTrigger( "before", "shutdown", subscriber.kill ) # Start the consumer loop consumer_loop = LoopingCall( web_socket_instance.consumer ) consumer_loop.start(0.001, now=False) return web_socket_instance
def main(argv): host = HOST port = PORT global _VERBOSE _VERBOSE = False try: opts, args = getopt.getopt(argv, "hvH:P:", ["help", "verbose", "host=", "port="]) except getopt.GetoptError: usage(sys.argv[0]) sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage(sys.argv[0]) sys.exit() elif opt in ("-v", "--verbose"): _VERBOSE = True elif opt in ("-H", "--host"): host = arg elif opt in ("-P", "--port"): port = arg factory = ImapProxyServerFactory(host,port) reactor.listenSSL(port, factory, ssl.DefaultOpenSSLContextFactory('ssl/server.key', 'ssl/server.crt')) #SSL key and self signed cert generated following instructions at https://help.ubuntu.com/10.04/serverguide/certificates-and-security.html if _VERBOSE: print "VERBOSE MODE" else: print "QUIET MODE" print "Proxy Started" reactor.run() print "Proxy Stopped"
def startagent(port = myport): if agentdaemonize: print "Daemonizing" from hqdaemon import daemonize daemonize('/dev/null','/tmp/daemon.log','/tmp/daemon.log') if sys.platform.find("win32") != -1: import win32file win32file._setmaxstdio(2048) if use_ssl: print "Agent is started on port ", myport, " SSL is enabled " try: myContextFactory = ssl.DefaultOpenSSLContextFactory(agent_ssl_key, agent_ssl_cert) ctx = myContextFactory.getContext() # ctx.set_verify( SSL.VERIFY_PEER, verifyCallback) # ctx.set_options( SSL.OP_ALL ) # Since we have self-signed certs we have to explicitly # tell the server to trust them. ctx.load_verify_locations(agent_ssl_pem) except Exception, e: print "Failed to start, SSL keys are specified but do not exist ", e sys.exit(1) reactor.listenSSL(myport, ExecuteActionFactory(), myContextFactory) reactor.run(installSignalHandlers=False)
def run(self): if config._get(config, 'sslcert', False): with open(config.sslcert.certificate_file, 'rb') as fp: cert = fp.read() certificate = ssl.PrivateCertificate.loadPEM(cert) co = certificate.options() ssl_cert_options = ssl.CertificateOptions(co.privateKey, co.certificate, method=SSLv23_METHOD) tls_cert_options = co for proto_config in config.protocols: factory = get_class_from_string(proto_config.factory)(proto_config, tls_cert_options, ssl_cert_options) if proto_config.ssl and factory.supports_ssl: reactor.listenSSL(proto_config.ssl.port, factory, ssl_cert_options) if config._get(proto_config, 'transport') and proto_config.transport.lower() == 'udp': reactor.listenUDP(proto_config.port, factory) elif config._get(proto_config, 'tls') and proto_config.tls.enable and factory.supports_tls: factory.options = tls_cert_options reactor.listenTCP(proto_config.port, factory) else: reactor.listenTCP(proto_config.port, factory) reactor.run()
def run(self): self.logger.info('XMLRPC Proxy of scheduler %s: starting' % self.config.name) try: if self.config.enablessl: OpenSSLContext().setup(self.config.localcert, self.config.cacert, self.config.verifypeer) reactor.listenSSL( self.config.port, SchedulerSite(self.xmlrpc_proxy), interface = self.config.host, contextFactory = OpenSSLContext().getContext() ) self.logger.info('XMLRPC Proxy of scheduler %s: activating SSL mode' % (self.config.name)) else: self.listening_port = reactor.listenTCP( self.config.port, Site(self.xmlrpc_proxy), interface = self.config.host ) except Exception, e: self.logger.error('XMLRPC Proxy of scheduler %s: can\'t bind to %s:%d, reason is %s' % (self.config.name, self.config.host, self.config.port, e)) return False
def start(config): """Start twisted event loop and the fun should begin...""" host = config.get('broker', 'host') port = int(config.get('broker', 'port')) username = config.get('broker', 'username') password = config.get('broker', 'password') fileServerPort = int(config.get('fileserver', 'port')) fileServerDirectory = config.get('fileserver', 'directory') # Start File Server try: privkey = os.path.abspath( os.path.dirname(__file__) + '/services/privkey.pem') cacert = os.path.abspath( os.path.dirname(__file__) + '/services/cacert.pem') logger.info('Using SSL, privkey = %s, cacert = %s' % (privkey, cacert)) reactor.listenSSL(fileServerPort, FileServerFactory(fileServerDirectory), ssl.DefaultOpenSSLContextFactory(privkey, cacert) ) logger.info('Listening on port %d, serving files from directory: %s' % (fileServerPort, fileServerDirectory)) except: logger.fatal("Unable to start file server at port: %d, please check." % fileServerPort) stompProtocolFactory = StompProtocolFactory() reactor.connectTCP(host, port, stompProtocolFactory) reactor.run() return internet.TCPClient(host, port, stompProtocolFactory)
def Start(): Globals.serverIP = "192.168.1.40" #MySQL Data Globals.dbHost = "127.0.0.1" Globals.dbUser = "******" Globals.dbPass = "******" Globals.dbDatabase = "db" CheckMySqlConn() SSLInfo = ssl.DefaultOpenSSLContextFactory('crt/privkey.pem', 'crt/cacert.pem') factory = Factory() factory.protocol = GosRedirector.GOSRedirector reactor.listenSSL(42127, factory, SSLInfo) print("[SSL REACTOR] GOSREDIRECTOR STARTED [42127]") factory = Factory() factory.protocol = BlazeMain_Client.BLAZEHUB reactor.listenTCP(10041, factory) print("[TCP REACTOR] BLAZE CLIENT [10041]") factory = Factory() factory.protocol = BlazeMain_Server.BLAZEHUB reactor.listenTCP(10071, factory) print("[TCP REACTOR] BLAZE SERVER [10071]") sites = server.Site(Https.Simple()) reactor.listenSSL(443, sites, SSLInfo) print("[WEB REACTOR] Https [443]") reactor.run()
def listen(self): # Listen on UDP port logging.info('AgentListener: Trying to listen UDP on port %s',\ str(self.udp_port)) try: reactor.listenUDP(self.udp_port, AgentDatagramProtocol(self)) logging.info('AgentListener: Listening UDP on port %s',\ str(self.udp_port)) except: logging.error('AgentListener: Failed to listen UDP on port %s',\ str(self.udp_port)) # Make sure we have enabled SSL if not self.ssl_enabled: return # Listen on SSL port ssl_factory = Factory() AgentSSLProtocol.agent_listener = self ssl_factory.protocol = AgentSSLProtocol ssl_context_factory = twisted.internet.ssl.DefaultOpenSSLContextFactory(\ self.key_file_name, self.cert_file_name) logging.info('AgentListener: Trying to listen SSL on port %s',\ str(self.ssl_port)) try: reactor.listenSSL(self.ssl_port, ssl_factory, ssl_context_factory) logging.info('AgentListener: Listening SSL on port %s',\ str(self.ssl_port)) except: logging.error('AgentListener: Failed to listen SSL on port %s',\ str(self.ssl_port))
def __init__(self, port=58846, interface=""): self.factory = Factory() self.factory.protocol = AfmRPCProtocol # Holds the registered methods self.factory.methods = {} # Holds the session_ids and auth levels self.factory.authorized_sessions = {} # Holds the protocol objects with the session_id as key self.factory.session_protocols = {} # Holds the interested event list for the sessions self.factory.interested_events = {} hostname = "" if interface: hostname = interface log.info("Starting DelugeRPC server %s:%s", hostname, port) try: reactor.listenSSL(port, self.factory, ServerContextFactory(), interface=hostname) except Exception, e: log.info("Daemon already running or port not available..") log.error(e) sys.exit(0)
def main(argv): FLAGS(argv) if not FLAGS.logfile and not FLAGS.daemonize: # No log file and not daemonized. log.startLogging(sys.stderr) elif not FLAGS.logfile and FLAGS.daemonize: # Daemonized, but no log file. fd, name = tempfile.mkstemp(prefix='flamongo', suffix='.log') os.close(fd) sys.stderr.write('Logging to %s\n' % name) log.startLogging(open(name, 'a')) else: f = open(FLAGS.logfile, 'a') log.startLogging(f) # FIXME mongoengine.connect('flamongo') # TODO define connection options. site = server.Site(TopLevel(lambda: Connection())) reactor.listenTCP(FLAGS.port, site) try: from twisted.internet import ssl ssl_context = ssl.DefaultOpenSSLContextFactory(FLAGS.privatekey, FLAGS.certificate) reactor.listenSSL(FLAGS.secureport, site, ssl_context) except ImportError: # removes the partial import. ssl = None log.err('SSL not enabled. Needs PyOpenSSL.') except Exception as ex: log.err(str(ex)) if FLAGS.daemonize: utils.daemonize() reactor.run()
def main(argv): (certFile, keyFile, sslListenPort, httpListenPort, logLevel, background, psyco, incomingInterface, outgoingInterface) = parseOptions(argv) proxyFactory = http.HTTPFactory(timeout=10) proxyFactory.protocol = GoogleProxy proxyFactory.outgoingInterface = outgoingInterface reactor.listenSSL(int(sslListenPort), proxyFactory, ServerContextFactory(certFile, keyFile), interface=incomingInterface) reactor.listenTCP(int(httpListenPort), proxyFactory, interface=incomingInterface) initializeLogging(logLevel) initializeIdentities() if background: print "\ngoogleshare " + str(gVersion) + " by Moxie Marlinspike backgrounding..." googleshare.daemonize.createDaemon() else: print "\ngoogleshare " + str(gVersion) + " by Moxie Marlinspike running..." writePidFile() dropPrivileges() if psyco: initializePsyco() reactor.run()
def main(): #init logger logger = logging.getLogger('psp') hdlr = logging.FileHandler('psp.log') strm_out = logging.StreamHandler(sys.__stdout__) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) strm_out.setFormatter(formatter) logger.addHandler(hdlr) logger.addHandler(strm_out) logger.setLevel(logging.INFO) mdns_client = mdns.Mdns_client('laptop', 'haris.sp', 8080, logger) #init web server site = server.Site(signpost_server.Singpost_server(logger)) # run method in thread reactor.suggestThreadPoolSize(30) factory = Factory() reactor.listenSSL(8080, site, HTTPSVerifyingContextFactory()) #myContextFactory) mdns_client.setup_mdns() #service discovery module discovery = server_discovery.Server_discovery(logger) discovery.service_update() #initial discovery to fetch entries gobject.timeout_add(30000, discovery.service_update) # run the loop gobject.threads_init() gobject.MainLoop().run()
def runApplication(): opts = Options() opts.parseOptions() common.initLogs(opts['logfile']) common.installReactor(opts['reactor']) config = common.loadConfig(opts['config']) #starting services with options from config if opts['ssl']: reactor.listenSSL( config.getint('finger', 'port'), FingerFactory(), DefaultOpenSSLContextFactory( config.get('ssl', 'cert'), config.get('ssl', 'private') ) ) reactor.listenSSL( config.getint('web', 'port'), server.Site(SomeLeafResource()), DefaultOpenSSLContextFactory( config.get('ssl', 'cert'), config.get('ssl', 'private') ) ) else: reactor.listenTCP(config.getint('finger', 'port'), FingerFactory()) reactor.listenTCP(config.getint('web', 'port'), server.Site(SomeLeafResource())) reactor.run()
def main(): parser = OptionParser() parser.add_option('-l', '--loglevel', default='info', dest='logLevel', help='This sets the logging level you have these options: debug, info, warning, error, critical \t\tThe standard value is info') parser.add_option('-p', '--port', default=4443, type='int', dest='port', help='This options lets you use a custom port instead of 443 (use a port > 1024 to run as non root user)') parser.add_option('--logfile', default=None, dest='logfile', help='Log to a file instead of stdout.') (options, _) = parser.parse_args() x = logging.getLogger() x.setLevel(log_levels[options.logLevel]) if options.logfile != None: h = logging.FileHandler(options.logfile) else: h = logging.StreamHandler() f = logging.Formatter(u"%(levelname)s %(message)s") h.setFormatter(f) x.addHandler(h) x.info("Starting server on port {0}".format(options.port)) reactor.listenSSL(options.port, SiriFactory(), ssl.DefaultOpenSSLContextFactory('keys/server.key', 'keys/server.crt')) reactor.run() x.info("Server shutdown complete")
def _run_server(): # parse some options from config config_file = msconstants.CONFIG_FILE parser = ConfigParser.SafeConfigParser() parser.read(config_file) server_address1 = parser.get('misc', 'address1') server_address2 = parser.get('misc', 'address2') # start up master = managementserver.ManagementServerMaster(parser) pf1 = managementserver.ManagementServerProtocolFactory(master) pf2 = managementserver.ManagementServerProtocolFactory(master) # build certificate chain temporary files cert_chain1 = _create_certificate_chain(1) cert_chain2 = _create_certificate_chain(2) # NB: the context cf1 (for management protocol versions 1-3) must accept both # SSL 3.0 and TLS 1.0 (SSL 3.1) for backward compatibility cf1 = ManagementServerOpenSSLContextFactory(msconstants.SERVER_PRIVATE_KEY1, cert_chain1) cf2 = ManagementServerOpenSSLContextFactory(msconstants.SERVER_PRIVATE_KEY2, cert_chain2) master.start() # XXX reactor.listenSSL(msconstants.SERVER_PORT, pf1, cf1, backlog=50, interface=server_address1) reactor.listenSSL(msconstants.SERVER_PORT, pf2, cf2, backlog=50, interface=server_address2) reactor.run()
def addWebServer(cfg, dist, sched): """Set up a web server. cfg -- a configuration object from Main. We use these options: HTTPS_N_BRIDGES_PER_ANSWER HTTP_UNENCRYPTED_PORT HTTP_UNENCRYPTED_BIND_IP HTTP_USE_IP_FROM_FORWARDED_HEADER HTTPS_PORT HTTPS_BIND_IP HTTPS_USE_IP_FROM_FORWARDED_HEADER dist -- an IPBasedDistributor object. sched -- an IntervalSchedule object. """ Site = twisted.web.server.Site site = None if cfg.HTTP_UNENCRYPTED_PORT: ip = cfg.HTTP_UNENCRYPTED_BIND_IP or "" resource = WebResource(dist, sched, cfg.HTTPS_N_BRIDGES_PER_ANSWER, cfg.HTTP_USE_IP_FROM_FORWARDED_HEADER, includeFingerprints=cfg.HTTPS_INCLUDE_FINGERPRINTS) site = Site(resource) reactor.listenTCP(cfg.HTTP_UNENCRYPTED_PORT, site, interface=ip) if cfg.HTTPS_PORT: from twisted.internet.ssl import DefaultOpenSSLContextFactory #from OpenSSL.SSL import SSLv3_METHOD ip = cfg.HTTPS_BIND_IP or "" factory = DefaultOpenSSLContextFactory(cfg.HTTPS_KEY_FILE, cfg.HTTPS_CERT_FILE) resource = WebResource(dist, sched, cfg.HTTPS_N_BRIDGES_PER_ANSWER, cfg.HTTPS_USE_IP_FROM_FORWARDED_HEADER, includeFingerprints=cfg.HTTPS_INCLUDE_FINGERPRINTS) site = Site(resource) reactor.listenSSL(cfg.HTTPS_PORT, site, factory, interface=ip) return site
def __init__( self, port, ssl, server_context_factory = None, reactor = None, interface = '', **keywords ): if reactor is None: from twisted.internet import reactor if ssl and server_context_factory is None: from planes.sh.ssl import ServerContextFactory server_context_factory = ServerContextFactory() self.port = port self.ssl = ssl self.reactor = reactor self.factory = self.Factory(reactor = reactor, **keywords) if ssl: reactor.listenSSL( self.port, self.factory, server_context_factory, interface = interface, ) else: reactor.listenTCP( port, self.factory, interface = interface, )
def main(): logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-s: %(message)s') args = _getArgs() ippool = IPPool(args.remote) ippool.register(args.local) factory = SSTPProtocolFactory(pppd=args.pppd, pppdConfigFile=args.pppd_config, local=args.local, remotePool=ippool) if args.no_ssl: logging.info('Running without SSL.') reactor.listenTCP(args.listen_port, factory) else: certificate = _load_cert(args.pem_cert) if certificate is None: logging.critical('Cannot read certificate.') sys.exit(2) return reactor.listenSSL(args.listen_port, factory, certificate.options(), interface=args.listen) logging.info('Listening on %s:%s...' % (args.listen, args.listen_port)) reactor.run()
def main(): """ Run the server. """ # setup logger first initLog() # Load the client's self-signed certificate. clientCert = open(CLIENT_CERT_FILE).read() clientCertObj = ssl.Certificate.loadPEM(clientCert) # Load the server's key and the server's self-signed certificate. serverKey = open(SERVER_KEY_FILE).read() serverCert = open(SERVER_CERT_FILE).read() serverPEM = serverKey + serverCert serverCertObj = ssl.PrivateCertificate.loadPEM(serverPEM) # Create an SSL context factory. Passing the client's certificate along enables client authentication. sslContextFactory = serverCertObj.options(clientCertObj) kinectServerFactory = KinectServerFactory() # Set the Twisted reactor up to listen for connections. For each incoming connection, create a KinectServer # (using the KinectServerFactory) and create an SSL context (using the sslContextFactory). The SSL context is used # to verify clients and set up an SSL layer. The KinectServer is used to handle all messages their decrypted state; # messages are relayed to all other connections. reactor.listenSSL(PORT, kinectServerFactory, sslContextFactory) # Run the reactor (which enters Twisted's main loop). reactor.run()
def main(argv): (logLevel, sslPort, httpPort, certFile, keyFile, userName, groupName, background, incomingInterface) = parseOptions(argv) privateKey = initializeKey(keyFile) database = initializeDatabase() sslFactory = initializeFactory(database, privateKey) connectFactory = http.HTTPFactory(timeout=10) connectFactory.protocol = ConnectChannel reactor.listenSSL(sslPort, sslFactory, ServerContextFactory(certFile, keyFile), interface=incomingInterface) reactor.listenSSL(4242, sslFactory, ServerContextFactory(certFile, keyFile), interface=incomingInterface) reactor.listenTCP(port=httpPort, factory=connectFactory, interface=incomingInterface) initializeLogging(logLevel) checkPrivileges(userName, groupName) if background: print "\nconvergence " + str(gVersion) + " by Moxie Marlinspike backgrounding..." convergence.daemonize.createDaemon() else: print "\nconvergence " + str(gVersion) + " by Moxie Marlinspike running..." writePidFile() dropPrivileges(userName, groupName) reactor.run()
def start_listening(self): config = self.get_config() if not config.no_tls and config.bind_port is not None: reactor.listenSSL( config.bind_port, Site(self.root_resource), self.tls_context_factory, interface=config.bind_host ) logger.info("Synapse now listening on port %d", config.bind_port) if config.unsecure_port is not None: reactor.listenTCP( config.unsecure_port, Site(self.root_resource), interface=config.bind_host ) logger.info("Synapse now listening on port %d", config.unsecure_port) metrics_resource = self.get_resource_for_metrics() if metrics_resource and config.metrics_port is not None: reactor.listenTCP( config.metrics_port, Site(metrics_resource), interface="127.0.0.1", ) logger.info("Metrics now running on 127.0.0.1 port %d", config.metrics_port)
def main(): args = _getArgs() logging.basicConfig(level=args.log_level, format='%(asctime)s %(levelname)-s: %(message)s') logging.addLevelName(5, 'VERBOSE') ippool = IPPool(args.remote) ippool.register(args.local) if args.no_ssl: logging.info('Running without SSL.') factory = SSTPProtocolFactory(pppd=args.pppd, pppdConfigFile=args.pppd_config, local=args.local, remotePool=ippool, certHash=None) reactor.listenTCP(args.listen_port, factory) else: cert = _load_cert(args.pem_cert) sha1 = cert.digest('sha1').replace(':', '').decode('hex') sha256 = cert.digest('sha256').replace(':', '').decode('hex') cert_options = cert.options() if args.ciphers: cert_options.getContext().set_cipher_list(args.ciphers) factory = SSTPProtocolFactory(pppd=args.pppd, pppdConfigFile=args.pppd_config, local=args.local, remotePool=ippool, certHash=[sha1, sha256]) reactor.listenSSL(args.listen_port, factory, cert_options, interface=args.listen) logging.info('Listening on %s:%s...' % (args.listen, args.listen_port)) reactor.run()
def run(self, host, port, logFile=None, keyFile=None, certFile=None): """ Run a minimal twisted.web server on the specified C{port}, bound to the interface specified by C{host} and logging to C{logFile}. This function will run the default reactor for your platform and so will block the main thread of your application. It should be the last thing your klein application does. @param host: The hostname or IP address to bind the listening socket to. "0.0.0.0" will allow you to listen on all interfaces, and "127.0.0.1" will allow you to listen on just the loopback interface. @type host: str @param port: The TCP port to accept HTTP requests on. @type port: int @param logFile: The file object to log to, by default C{sys.stdout} @type logFile: file object """ if logFile is None: logFile = sys.stdout log.startLogging(logFile) if keyFile and certFile: sslContext = ssl.DefaultOpenSSLContextFactory(keyFile, certFile) reactor.listenSSL(port, Site(self.resource()), interface=host, contextFactory=sslContext) else: reactor.listenTCP(port, Site(self.resource()), interface=host) reactor.run()
def process_nmap_commands(loggerName): """ Main function. Here we set up the environment, factory, interface, and port """ global nmapCommandsFile global nmapCommand global port global mlog global verboseLevel global clientTimeout observer = log.PythonLoggingObserver(loggerName) observer.start() # Create the factory factory = Factory() factory.protocol = NmapServerProtocol # Create the time based print loop = task.LoopingCall(show_info) loop.start(5.0) # call every second # Create the time based file read loop2 = task.LoopingCall(read_file_and_fill_nmap_variable) loop2.start(30.0) # call every second # To mark idle clients as hold loop3 = task.LoopingCall(timeout_idle_clients) loop3.start(clientTimeout) # call every second # Create the reactor reactor.listenSSL(port, factory, ServerContextFactory(), interface=interface) reactor.run()
def start_site(config, resource): log.info('Starting the API on port %s' % config.port) if config.sslkey and config.sslcert: reactor.listenSSL(config.port, PixelatedSite(resource), _ssl_options(config.sslkey, config.sslcert), interface=config.host) else: reactor.listenTCP(config.port, PixelatedSite(resource), interface=config.host)
def Run(withListen=True): global instance_SBProtocolFactory, bReactorStopped instance_SBProtocolFactory = SBProtocolFactory() InternalMessage.protocolInternal = SBProtocol() InternalMessage.protocolInternal.role = "internal" InternalMessage.protocolInternal.factory = instance_SBProtocolFactory threading.Thread(target=InternalMessage.Run).start() if withListen: reactor.listenTCP(9630, instance_SBProtocolFactory) # @UndefinedVariable cert = None with open("server.pem") as keyAndCert: cert = ssl.PrivateCertificate.loadPEM(keyAndCert.read()) reactor.listenSSL(9631, instance_SBProtocolFactory, cert.options()) reactor.listenTCP(9632, EchoProtocolFactory()) # @UndefinedVariable try: reactor.run() # @UndefinedVariable except: pass InternalMessage.Stop() bReactorStopped = True try: # reactor.stop() import sys sys.exit(0) except: pass
def main(): """This runs the protocol on port 25000""" factory = protocol.Factory() factory.protocol = Echo reactor.listenSSL(25000, factory, ssl.DefaultOpenSSLContextFactory(KEYFILE, CERTFILE)) reactor.run()
def test_bothSidesLoseConnection(self): """ Both sides of SSL connection close connection; the connections should close cleanly, and only after the underlying TCP connection has disconnected. """ @implementer(interfaces.IHandshakeListener) class CloseAfterHandshake(protocol.Protocol): gotData = False def __init__(self): self.done = defer.Deferred() def handshakeCompleted(self): self.transport.loseConnection() def connectionLost(self, reason): self.done.errback(reason) del self.done org = "twisted.test.test_ssl" self.setupServerAndClient((org, org + ", client"), {}, (org, org + ", server"), {}) serverProtocol = CloseAfterHandshake() serverProtocolFactory = protocol.ServerFactory() serverProtocolFactory.protocol = lambda: serverProtocol serverPort = reactor.listenSSL(0, serverProtocolFactory, self.serverCtxFactory) self.addCleanup(serverPort.stopListening) clientProtocol = CloseAfterHandshake() clientProtocolFactory = protocol.ClientFactory() clientProtocolFactory.protocol = lambda: clientProtocol reactor.connectSSL( "127.0.0.1", serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory, ) def checkResult(failure): failure.trap(ConnectionDone) return defer.gatherResults([ clientProtocol.done.addErrback(checkResult), serverProtocol.done.addErrback(checkResult), ])
def Start(*args, **kwargs): try: port = service.GetPort() if HydrusNetworking.LocalPortInUse(port): raise Exception( 'Something was already bound to port ' + str(port)) if service_type == HC.SERVER_ADMIN: http_factory = ServerServer.HydrusServiceAdmin(service) elif service_type == HC.FILE_REPOSITORY: http_factory = ServerServer.HydrusServiceRepositoryFile( service) elif service_type == HC.TAG_REPOSITORY: http_factory = ServerServer.HydrusServiceRepositoryTag( service) else: return (ssl_cert_path, ssl_key_path) = self.db.GetSSLPaths() sslmethod = twisted.internet.ssl.SSL.TLSv1_2_METHOD context_factory = twisted.internet.ssl.DefaultOpenSSLContextFactory( ssl_key_path, ssl_cert_path, sslmethod) self._service_keys_to_connected_ports[ service_key] = reactor.listenSSL( port, http_factory, context_factory) if not HydrusNetworking.LocalPortInUse(port): raise Exception('Tried to bind port ' + str(port) + ' but it failed.') except Exception as e: HydrusData.Print(traceback.format_exc())
def test_ssl_verification_positive(self): """ The L{VerifyingContextFactory} properly allows to connect to the endpoint if the certificates match. """ context_factory = WebDefaultOpenSSLContextFactory(PRIVKEY, PUBKEY) self.port = reactor.listenSSL(0, self.site, context_factory, interface="127.0.0.1") self.portno = self.port.getHost().port endpoint = AWSServiceEndpoint(ssl_hostname_verification=True) query = BaseQuery("an action", "creds", endpoint) d = query.get_page(self._get_url("file")) return d.addCallback(self.assertEquals, "0123456789")
def run(port_num, sslport_num, proxyport_num): root = Root(port_num, sslport_num, proxyport_num) factory = Site(root) port = reactor.listenTCP(port_num, factory) sslport = reactor.listenSSL(sslport_num, factory, ssl_factory()) proxyport = reactor.listenTCP(proxyport_num, ProxyFactory()) def print_listening(): h = port.getHost() s = sslport.getHost() p = proxyport.getHost() print "Mock server running at http://%s:%d (http), https://%s:%d (https) and http://%s:%d (proxy)" % \ (h.host, h.port, s.host, s.port, p.host, p.port) reactor.callWhenRunning(print_listening) reactor.run()
def test_ssl_subject_alt_name(self): """ L{VerifyingContextFactory} supports checking C{subjectAltName} in the certificate if it's available. """ context_factory = DefaultOpenSSLContextFactory(PRIVSANKEY, PUBSANKEY) self.port = reactor.listenSSL(0, self.site, context_factory, interface="127.0.0.1") self.portno = self.port.getHost().port endpoint = AWSServiceEndpoint(ssl_hostname_verification=True) query = BaseQuery("an action", "creds", endpoint) d = query.get_page("https://127.0.0.1:%d/file" % (self.portno, )) return d.addCallback(self.assertEquals, "0123456789")
def start_ssl(self): check_ssl_keys() log.debug('Enabling SSL with PKey: %s, Cert: %s', self.pkey, self.cert) cert = configmanager.get_config_dir(self.cert) pkey = configmanager.get_config_dir(self.pkey) self.socket = reactor.listenSSL( self.port, self.site, get_context_factory(cert, pkey), interface=self.interface, ) ip = self.socket.getHost().host ip = '[%s]' % ip if is_ipv6(ip) else ip log.info('Serving at https://%s:%s%s', ip, self.port, self.base)
def start_ssl(self): log.debug("Enabling SSL with PKey: %s, Cert: %s", self.pkey, self.cert) check_ssl_keys() with open(configmanager.get_config_dir(self.cert)) as cert: certificate = Certificate.loadPEM(cert.read()).original with open(configmanager.get_config_dir(self.pkey)) as pkey: private_key = KeyPair.load(pkey.read(), FILETYPE_PEM).original options = CertificateOptions(privateKey=private_key, certificate=certificate, method=SSL.SSLv23_METHOD) options.getContext().set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3) self.socket = reactor.listenSSL(self.port, self.site, options) log.info("Serving on %s:%s view at https://127.0.0.1:%s", "0.0.0.0", self.port, self.port)
def test_ssl_verification_negative(self): """ The L{VerifyingContextFactory} fails with a SSL error the certificates can't be checked. """ context_factory = DefaultOpenSSLContextFactory(BADPRIVKEY, BADPUBKEY) self.port = reactor.listenSSL(0, self.site, context_factory, interface="127.0.0.1") self.portno = self.port.getHost().port endpoint = AWSServiceEndpoint(ssl_hostname_verification=True) query = BaseQuery("an action", "creds", endpoint) d = query.get_page(self._get_url("file")) return self.assertFailure(d, SSLError)
def lineReceived(self, line): log.msg("Received line %s" % line) try: d = loads(line) # Required names. host = d["daddr"] dport = d["dport"] password = d["password"] # Optional names. sport = d.get("sport") ws = d.get("ws", False) tls = d.get("tls", False) client_opts = d.get("client", {}) # Allocate the source port. sport = self.factory.allocate_port(sport) factory = VNCProxy(host, dport, password, client_opts) if ws: factory = WebSocketFactory(factory) if tls: context = DefaultOpenSSLContextFactory("keys/vncap.key", "keys/vncap.crt") listening = reactor.listenSSL(sport, factory, context) else: listening = reactor.listenTCP(sport, factory) # Set up our timeout. def timeout(): log.msg("Timed out connection on port %d" % sport) listening.stopListening() self.factory.free_port(sport) reactor.callLater(30, timeout) log.msg("New forwarder (%d->%s:%d)" % (sport, host, dport)) self.sendLine("%d" % sport) except (KeyError, ValueError): log.msg("Couldn't handle line %s" % line) self.sendLine("FAILED") except CannotListenError: # Couldn't bind the port. Don't free it, as it's probably not # available to us. log.msg("Couldn't bind port %d" % sport) self.sendLine("FAILED") self.transport.loseConnection()
def start(self): callbacks = {'connected': [CalvinCB(self._connected)]} tcp_f = TCPServerFactory(callbacks) runtime_to_runtime_security = _conf.get("security", "runtime_to_runtime_security") trusted_ca_certs = [] if runtime_to_runtime_security == "tls": _log.debug("TwistedCalvinServer with TLS chosen") try: self._runtime_credentials = runtime_credentials.RuntimeCredentials( self._node_name) ca_cert_list_str = certificate.get_truststore_as_list_of_strings( certificate.TRUSTSTORE_TRANSPORT) for ca_cert in ca_cert_list_str: trusted_ca_certs.append(ssl.Certificate.loadPEM(ca_cert)) server_credentials_data = self._runtime_credentials.get_credentials( ) server_credentials = ssl.PrivateCertificate.loadPEM( server_credentials_data) except Exception as err: _log.exception( "Server failed to load credentials, err={}".format(err)) try: self._tcp_server = reactor.listenSSL( self._port, tcp_f, server_credentials.options(*trusted_ca_certs), interface=self._iface) except Exception as err: _log.exception("Server failed listenSSL, err={}".format(err)) else: _log.debug("TwistedCalvinServer without TLS chosen") try: self._tcp_server = reactor.listenTCP(self._port, tcp_f, interface=self._iface) except error.CannotListenError: _log.exception("Could not listen on port %s:%s", self._iface, self._port) raise except Exception as exc: _log.exception("Failed when trying listening on port %s:%s", self._iface, self._port) raise self._port = self._tcp_server.getHost().port self._callback_execute('server_started', self._port) return self._port
def test_bothSidesLoseConnection(self): """ Both sides of SSL connection close connection; the connections should close cleanly, and only after the underlying TCP connection has disconnected. """ class CloseAfterHandshake(protocol.Protocol): def __init__(self): self.done = defer.Deferred() def connectionMade(self): self.transport.write("a") def dataReceived(self, data): # If we got data, handshake is over: self.transport.loseConnection() def connectionLost(self2, reason): self2.done.errback(reason) del self2.done org = "twisted.test.test_ssl" self.setupServerAndClient((org, org + ", client"), {}, (org, org + ", server"), {}) serverProtocol = CloseAfterHandshake() serverProtocolFactory = protocol.ServerFactory() serverProtocolFactory.protocol = lambda: serverProtocol serverPort = reactor.listenSSL(0, serverProtocolFactory, self.serverCtxFactory) self.addCleanup(serverPort.stopListening) clientProtocol = CloseAfterHandshake() clientProtocolFactory = protocol.ClientFactory() clientProtocolFactory.protocol = lambda: clientProtocol clientConnector = reactor.connectSSL('127.0.0.1', serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory) def checkResult(failure): failure.trap(ConnectionDone) return defer.gatherResults([ clientProtocol.done.addErrback(checkResult), serverProtocol.done.addErrback(checkResult) ])
def daemon_init(): for ip in [ipv4, ipv6]: if ip == None: continue if config.transport in ('HTTPS', 'BOTH'): service_https = reactor.listenSSL(port=int( t2w.config.listen_port_https), factory=factory, contextFactory=context_factory, interface=ip) if config.transport in ('HTTP', 'BOTH'): service_http = reactor.listenTCP(port=int( t2w.config.listen_port_http), factory=factory, interface=ip)
def test_ssl_verification_bypassed(self): """ L{BaseQuery} doesn't use L{VerifyingContextFactory} if C{ssl_hostname_verification} is C{False}, thus allowing to connect to non-secure endpoints. """ context_factory = DefaultOpenSSLContextFactory(BADPRIVKEY, BADPUBKEY) self.port = reactor.listenSSL(0, self.site, context_factory, interface="127.0.0.1") self.portno = self.port.getHost().port endpoint = AWSServiceEndpoint(ssl_hostname_verification=False) query = BaseQuery("an action", "creds", endpoint) d = query.get_page(self._get_url("file")) return d.addCallback(self.assertEquals, "0123456789")
def __init__(self): self.done = False self.cb = CBService() self.site = CumulusSite(self.cb) # figure out if we need http of https if pycb.config.use_https: pycb.log(logging.INFO, "using https") sslContext = ssl.DefaultOpenSSLContextFactory( pycb.config.https_key, pycb.config.https_cert) self.iconnector = reactor.listenSSL(self.cb.get_port(), self.site, sslContext) else: pycb.log(logging.INFO, "using http") self.iconnector = reactor.listenTCP(self.cb.get_port(), self.site)
def get_api_service(application=None, interface='', port=33610, ssl_context_factory=None): """ Return a service suitable for creating an application object. This service is a simple web server that serves files on port 8080 from underneath the current working directory. """ # if not ssl_context_factory: # ssl_context_factory = make_SSL_context() # check if an API KEY exists? config = ConfigFile() config.read(settings.CONFIG_FILE) key = config.get('CM_MASTER', 'API_KEY', '') if not key: logging.warn("API KEY not found. Generating a new one...") config.set('CM_MASTER', 'API_KEY', "".join([random.choice("abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)") for i in range(50)])) with file(settings.CONFIG_FILE, 'wt') as f: config.write(f) home_page = HomePage() home_page.put_child('CloudMailing', CloudMailingRpc(useDateTime=True), True) home_page.put_child('api', make_rest_api(xmlrpc_port=port, xmlrpc_use_ssl=ssl_context_factory is not None, api_key=key)) home_page.make_home_page() webServer = AuthenticatedSite( home_page ) webServer.credentialFactories = [BasicCredentialFactory("CloudMailing API"), DigestCredentialFactory("md5", "CloudMailing API")] webServer.credentialsCheckers = [AdminChecker()] if application: if ssl_context_factory: apiService = internet.SSLServer(port, webServer, ssl_context_factory, interface=interface) else: apiService = internet.TCPServer(port, webServer, interface=interface) apiService.setServiceParent(application) else: if ssl_context_factory: apiService = reactor.listenSSL(port, webServer, ssl_context_factory, interface=interface) else: apiService = reactor.listenTCP(port, webServer, interface=interface) logging.info("Supervisor XMLRPC%s server started on port %d", ssl_context_factory and " SSL" or "", port) return apiService
def setUp(self): self.tmpname = self.mktemp() os.mkdir(self.tmpname) FilePath(self.tmpname).child("file").setContent(b"0123456789") r = static.File(self.tmpname) self.site = server.Site(r, timeout=None) self.wrapper = WrappingFactory(self.site) self.host = 'localhost' self.port = reactor.listenSSL(0, self.wrapper, ssl_context_factory( self.keyfile, self.certfile, cipher_string='CAMELLIA256-SHA'), interface=self.host) self.portno = self.port.getHost().port self.download_handler = self.download_handler_cls( Settings({'DOWNLOADER_CLIENT_TLS_CIPHERS': 'CAMELLIA256-SHA'})) self.download_request = self.download_handler.download_request
def listen_ssl( bind_addresses, port, factory, context_factory, reactor=reactor, backlog=50 ): """ Create an TLS-over-TCP socket for a port and several addresses Returns: list of twisted.internet.tcp.Port listening for TLS connections """ r = [] for address in bind_addresses: try: r.append( reactor.listenSSL(port, factory, context_factory, backlog, address) ) except error.CannotListenError as e: check_bind_error(e, address, bind_addresses) return r
def start(self): interface = WebServerConfig.local_ip port = WebServerConfig.local_port cert_path = WebServerConfig.certificate.normalized if WebServerConfig.certificate else None cert_chain_path = WebServerConfig.certificate_chain.normalized if WebServerConfig.certificate_chain else None if cert_path is not None: if not os.path.isfile(cert_path): log.error('Certificate file %s could not be found' % cert_path) return try: ssl_ctx_factory = DefaultOpenSSLContextFactory( cert_path, cert_path) except Exception: log.exception('Creating TLS context') return if cert_chain_path is not None: if not os.path.isfile(cert_chain_path): log.error('Certificate chain file %s could not be found' % cert_chain_path) return ssl_ctx = ssl_ctx_factory.getContext() try: ssl_ctx.use_certificate_chain_file(cert_chain_path) except Exception: log.exception('Setting TLS certificate chain file') return self.listener = reactor.listenSSL(port, self.site, ssl_ctx_factory, backlog=511, interface=interface) scheme = 'https' else: self.listener = reactor.listenTCP(port, self.site, backlog=511, interface=interface) scheme = 'http' port = self.listener.getHost().port self.__dict__['url'] = '%s://%s:%d' % (scheme, WebServerConfig.hostname or interface.normalized, port) log.info('Web server listening for requests on: %s' % self.url)
def test_openSSLBuffering(self): serverProto = self.serverProto = SingleLineServerProtocol() clientProto = self.clientProto = RecordingClientProtocol() server = protocol.ServerFactory() client = self.client = protocol.ClientFactory() server.protocol = lambda: serverProto client.protocol = lambda: clientProto sCTX = ssl.DefaultOpenSSLContextFactory(certPath, certPath) cCTX = ssl.ClientContextFactory() port = reactor.listenSSL(0, server, sCTX, interface='127.0.0.1') self.addCleanup(port.stopListening) reactor.connectSSL('127.0.0.1', port.getHost().port, client, cCTX) return clientProto.deferred.addCallback(self.assertEquals, "+OK <some crap>\r\n")
def startServerInstance(session, ipaddress, port, useauth=False, l2k=None, usessl=False): if hw.get_device_name().lower() != "dm7025": l3k = None l3c = tpm.getCert(eTPM.TPMD_DT_LEVEL3_CERT) if l3c is None: return False l3k = validate_certificate(l3c, l2k) if l3k is None: return False random = get_random() if random is None: return False value = tpm.challenge(random) result = decrypt_block(value, l3k) if result is None: return False else: if result [80:88] != random: return False if useauth: # HTTPAuthResource handles the authentication for every Resource you want it to root = HTTPAuthResource(toplevel, "Enigma2 WebInterface") site = server.Site(root) else: site = server.Site(toplevel) if usessl: ctx = ssl.DefaultOpenSSLContextFactory('/etc/enigma2/server.pem', '/etc/enigma2/cacert.pem', sslmethod=SSL.SSLv23_METHOD) d = reactor.listenSSL(port, site, ctx, interface=ipaddress) else: d = reactor.listenTCP(port, site, interface=ipaddress) running_defered.append(d) print "[Webinterface] started on %s:%i auth=%s ssl=%s" % (ipaddress, port, useauth, usessl) return True
def setUp(self): plainRoot = Data(b'not me', 'text/plain') tlsRoot = Data(b'me neither', 'text/plain') plainSite = server.Site(plainRoot, timeout=None) tlsSite = server.Site(tlsRoot, timeout=None) self.tlsPort = reactor.listenSSL( 0, tlsSite, contextFactory=ssl.DefaultOpenSSLContextFactory( serverPEMPath, serverPEMPath), interface="127.0.0.1") self.plainPort = reactor.listenTCP(0, plainSite, interface="127.0.0.1") self.plainPortno = self.plainPort.getHost().port self.tlsPortno = self.tlsPort.getHost().port plainRoot.putChild(b'one', Redirect(self.getHTTPS('two'))) tlsRoot.putChild(b'two', Redirect(self.getHTTP('three'))) plainRoot.putChild(b'three', Redirect(self.getHTTPS('four'))) tlsRoot.putChild(b'four', Data(b'FOUND IT!', 'text/plain'))
def startServerInstance(session, ipaddress, port, useauth=False, usessl=False): try: toplevel = getToplevel(session) if useauth: # HTTPAuthResource handles the authentication for every Resource you want it to root = HTTPAuthResource(toplevel, "Enigma2 WebInterface") site = server.Site(root) else: site = server.Site(toplevel) if usessl: ctx = ssl.DefaultOpenSSLContextFactory('/etc/enigma2/server.pem', '/etc/enigma2/cacert.pem', sslmethod=SSL.SSLv23_METHOD) d = reactor.listenSSL(port, site, ctx, interface=ipaddress) else: d = reactor.listenTCP(port, site, interface=ipaddress) running_defered.append(d) print "[Webinterface] started on %s:%i" % (ipaddress, port), "auth=", useauth, "ssl=", usessl except Exception, e: print "[Webinterface] starting FAILED on %s:%i!" % (ipaddress, port), e session.open(MessageBox, 'starting FAILED on %s:%i!\n\n%s' % (ipaddress, port, str(e)), MessageBox.TYPE_ERROR)
def testImmediateDisconnect(self): org = "twisted.test.test_ssl" self.setupServerAndClient((org, org + ", client"), {}, (org, org + ", server"), {}) # Set up a server, connect to it with a client, which should work since our verifiers # allow anything, then disconnect. serverProtocolFactory = protocol.ServerFactory() serverProtocolFactory.protocol = protocol.Protocol self.serverPort = serverPort = reactor.listenSSL( 0, serverProtocolFactory, self.serverCtxFactory) clientProtocolFactory = protocol.ClientFactory() clientProtocolFactory.protocol = ImmediatelyDisconnectingProtocol clientProtocolFactory.connectionDisconnected = defer.Deferred() reactor.connectSSL('127.0.0.1', serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory) return clientProtocolFactory.connectionDisconnected.addCallback( lambda ignoredResult: self.serverPort.stopListening())
def start_master_service(application=None, master_port=33620, ssl_context_factory=None): global service_master, service_manager from mailing_manager import start_mailing_manager service_manager = start_mailing_manager() from cloud_master import get_cloud_master_factory factory = get_cloud_master_factory() if application: if ssl_context_factory: service_master = internet.SSLServer(master_port, factory, ssl_context_factory) else: service_master = internet.TCPServer(master_port, factory) service_master.setServiceParent(application) else: if ssl_context_factory: service_master = reactor.listenSSL(master_port, factory, ssl_context_factory) else: service_master = reactor.listenTCP(master_port, factory) logging.info("CLOUD MASTER started on port %d", master_port)
def run(port_num, sslport_num, proxyport_num, verbose=True): root = Root(port_num, sslport_num, proxyport_num) factory = Site(root) port = reactor.listenTCP(port_num, factory) sslport = reactor.listenSSL(sslport_num, factory, ssl_factory()) proxyport = reactor.listenTCP(proxyport_num, ProxyFactory()) def print_listening(): h = port.getHost() s = sslport.getHost() p = proxyport.getHost() print "Mock server running at http://%s:%d (http), https://%s:%d (https) and http://%s:%d (proxy)" % \ (h.host, h.port, s.host, s.port, p.host, p.port) if verbose: import sys from twisted.python import log log.startLogging(sys.stdout) reactor.callWhenRunning(print_listening) reactor.run()
def loopback(self, serverCertOpts, clientCertOpts, onServerLost=None, onClientLost=None, onData=None): if onServerLost is None: self.onServerLost = onServerLost = defer.Deferred() if onClientLost is None: self.onClientLost = onClientLost = defer.Deferred() if onData is None: onData = defer.Deferred() serverFactory = protocol.ServerFactory() serverFactory.protocol = DataCallbackProtocol serverFactory.onLost = onServerLost serverFactory.onData = onData clientFactory = protocol.ClientFactory() clientFactory.protocol = WritingProtocol clientFactory.onLost = onClientLost self.serverPort = reactor.listenSSL(0, serverFactory, serverCertOpts) self.clientConn = reactor.connectSSL('127.0.0.1', self.serverPort.getHost().port, clientFactory, clientCertOpts)
def HttpdStart(session): if config.OpenWebif.enabled.value == True: global listener port = config.OpenWebif.port.value root = buildRootTree(session) if config.OpenWebif.auth.value == True: root = AuthResource(session, root) site = server.Site(root) # start http webserver on configured port try: listener.append(reactor.listenTCP(port, site)) print "[OpenWebif] started on %i" % (port) except CannotListenError: print "[OpenWebif] failed to listen on Port %i" % (port) if config.OpenWebif.https_enabled.value == True: httpsPort = config.OpenWebif.https_port.value installCertificates(session) # start https webserver on port configured port try: context = ssl.DefaultOpenSSLContextFactory(KEY_FILE, CERT_FILE) listener.append(reactor.listenSSL(httpsPort, site, context)) print "[OpenWebif] started on", httpsPort except CannotListenError: print "[OpenWebif] failed to listen on Port", httpsPort #Streaming requires listening on 127.0.0.1:80 if port != 80: if not isOriginalWebifInstalled(): root = buildRootTree(session) site = server.Site(root) try: listener.append( reactor.listenTCP(80, site, interface='127.0.0.1')) print "[OpenWebif] started stream listening on port 80" except CannotListenError: print "[OpenWebif] port 80 busy"
def setUp(self): test_tcp.PortCleanerUpper.setUp(self) self.serverConns = [] f = protocol.ServerFactory() f.protocol = protocol.Protocol self.listener = reactor.listenSSL( 0, f, ssl.DefaultOpenSSLContextFactory(certPath, certPath), interface="127.0.0.1", ) self.ports.append(self.listener) f = protocol.ClientFactory() f.protocol = test_tcp.ConnectionLosingProtocol f.protocol.master = self L = [] def connector(): p = self.listener.getHost().port ctx = ssl.ClientContextFactory() return reactor.connectSSL('127.0.0.1', p, f, ctx) self.connector = connector self.totalConnections = 0
def start(self, host, port): control_interface_security = _conf.get("security","control_interface_security") if control_interface_security=="tls": _log.debug("ServerProtocolFactory with TLS enabled chosen") try: #TODO: figure out how to set more than one root cert in twisted truststore runtime_cred = runtime_credentials.RuntimeCredentials(self._node_name) server_credentials_data = runtime_cred.get_runtime_credentials() server_credentials = ssl.PrivateCertificate.loadPEM(server_credentials_data) except Exception as err: _log.error("Failed to fetch server credentials, err={}".format(err)) raise try: self._tls_server = reactor.listenSSL(port, self, server_credentials.options(), interface=host) except Exception as err: _log.error("Server failed listenSSL, err={}".format(err)) self._port = self._tls_server.getHost().port else: self._port = reactor.listenTCP(port, self, interface=host) # WORKAROUND This is here due to an obscure error in twisted trying to write to a listening port # on some architectures/OSes. The default is to raise a RuntimeError. self._port.doWrite = lambda : None
def setup_webhook(self): # HTTP(s) server for github/gitlab webhooks if self.webhook_port: return if (self.config["GitWebhook"] and ("port" in self.config["GitWebhook"] or "sshport" in self.config["GitWebhook"])): webhook_server = GitWebhookServer(self, self.config) factory = Site(webhook_server) # https sslport = self.config["GitWebhook"].get("sslport", None) privkey = self.config["GitWebhook"].get("privkey", None) cert = self.config["GitWebhook"].get("certificate", None) if sslport and privkey and cert: sslContext = ssl.DefaultOpenSSLContextFactory(privkey, cert) self.webhook_port = reactor.listenSSL(sslport, factory, sslContext) return # http port = self.config["GitWebhook"].get("port", None) if port: self.webhook_port = reactor.listenTCP(port, factory)