我们从Python开源项目中,提取了以下33个代码示例,用于说明如何使用twisted.internet.reactor.listenSSL()。
def run(self): ''' Called by twisted ''' # load initial config self.refresh_config() if self.config is None: logging.critical("cannot start due to error in config file") return # refresh and check status every event_period seconds self.refresh_task = task.LoopingCall(self.refresh_loop) refresh_deferred = self.refresh_task.start(self.config['event_period'], now=False) refresh_deferred.addErrback(errorCallback) # setup server for receiving blinded counts from the DC nodes and key shares from the SK nodes listen_port = self.config['listen_port'] key_path = self.config['key'] cert_path = self.config['cert'] ssl_context = ssl.DefaultOpenSSLContextFactory(key_path, cert_path) logging.info("Tally Server listening on port {}".format(listen_port)) reactor.listenSSL(listen_port, self, ssl_context) reactor.run()
def setUp(self): plainRoot = static.Data('not me', 'text/plain') tlsRoot = static.Data('me neither', 'text/plain') plainSite = server.Site(plainRoot, timeout=None) tlsSite = server.Site(tlsRoot, timeout=None) from twisted import test self.tlsPort = reactor.listenSSL(0, tlsSite, contextFactory=ssl.DefaultOpenSSLContextFactory( sibpath(test.__file__, 'server.pem'), sibpath(test.__file__, 'server.pem'), ), 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('one', util.Redirect(self.getHTTPS('two'))) tlsRoot.putChild('two', util.Redirect(self.getHTTP('three'))) plainRoot.putChild('three', util.Redirect(self.getHTTPS('four'))) tlsRoot.putChild('four', static.Data('FOUND IT!', 'text/plain'))
def testOpenSSLBuffering(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 client.buffer = [] sCTX = ssl.DefaultOpenSSLContextFactory(certPath, certPath) cCTX = ssl.ClientContextFactory() port = self.port = reactor.listenSSL(0, server, sCTX, interface='127.0.0.1') reactor.connectSSL('127.0.0.1', port.getHost().port, client, cCTX) i = 0 while i < 5000 and not client.buffer: i += 1 reactor.iterate() self.assertEquals(client.buffer, ["+OK <some crap>\r\n"])
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 listenSsl(self, site, ports, ignore=[]): privateKeyFile = open(self.options.sslPrivateKey, "r") privateKey = privateKeyFile.read() privateKeyFile.close() certificateFile = open(self.options.sslCertificate) certificate = certificateFile.read() certificateFile.close() import twisted.internet.ssl as ssl cert = ssl.PrivateCertificate.loadPEM(privateKey + certificate) contextFactory = cert.options() import itertools listenPorts = map(lambda x: x[0], itertools.groupby(sorted(ports))) for port in listenPorts: if port not in ignore: reactor.listenSSL(port, site, contextFactory)
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 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) clientConnector = reactor.connectSSL('127.0.0.1', port.getHost().port, client, cCTX) self.addCleanup(clientConnector.disconnect) return clientProto.deferred.addCallback( self.assertEqual, b"+OK <some crap>\r\n")
def main(): resolver = DNSResolver() factory = server.DNSServerFactory( clients=[resolver] ) protocol = dns.DNSDatagramProtocol(controller=factory) httpserver = webserver.Site(HTTPServer(resolver)) context = Context(TLSv1_METHOD) context.use_certificate_chain_file(SERVER_CONFIG["ssl_crt"]) context.use_privatekey_file(SERVER_CONFIG["ssl_key"]) reactor.listenUDP(SERVER_CONFIG["dns_port"], protocol) reactor.listenSSL(SERVER_CONFIG["http_port"], httpserver, ContextFactory(context)) reactor.run()
def _listen(self, site): from twisted import test return reactor.listenSSL(0, site, contextFactory=ssl.DefaultOpenSSLContextFactory( sibpath(test.__file__, 'server.pem'), sibpath(test.__file__, 'server.pem'), ), interface="127.0.0.1")
def testSSL(self, ssl=ssl): pem = util.sibpath(__file__, 'server.pem') p = reactor.listenSSL(0, protocol.ServerFactory(), ssl.DefaultOpenSSLContextFactory(pem, pem)) portNo = p.getHost().port self.assertNotEqual(str(p).find(str(portNo)), -1, "%d not found in %s" % (portNo, p)) return p.stopListening()
def createServer(self, address, portNumber, factory): contextFactory = ssl.CertificateOptions() return reactor.listenSSL( portNumber, factory, contextFactory, interface=address)
def testFailedVerify(self): org = "twisted.test.test_ssl" self.setupServerAndClient( (org, org + ", client"), {}, (org, org + ", server"), {}) def verify(*a): return False self.clientCtxFactory.getContext().set_verify(SSL.VERIFY_PEER, verify) serverConnLost = defer.Deferred() serverProtocol = protocol.Protocol() serverProtocol.connectionLost = serverConnLost.callback serverProtocolFactory = protocol.ServerFactory() serverProtocolFactory.protocol = lambda: serverProtocol self.serverPort = serverPort = reactor.listenSSL(0, serverProtocolFactory, self.serverCtxFactory) clientConnLost = defer.Deferred() clientProtocol = protocol.Protocol() clientProtocol.connectionLost = clientConnLost.callback clientProtocolFactory = protocol.ClientFactory() clientProtocolFactory.protocol = lambda: clientProtocol clientConnector = reactor.connectSSL('127.0.0.1', serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory) dl = defer.DeferredList([serverConnLost, clientConnLost], consumeErrors=True) return dl.addCallback(self._cbLostConns)
def test_ssl_verification_positive(self): """ The client transport should complete an upload of messages to a host which provides SSL data which can be verified by the public key specified. """ resource = DataCollectingResource() context_factory = DefaultOpenSSLContextFactory(PRIVKEY, PUBKEY) port = reactor.listenSSL(0, server.Site(resource), context_factory, interface="127.0.0.1") self.ports.append(port) transport = HTTPTransport( None, "https://localhost:%d/" % (port.getHost().port,), PUBKEY) result = deferToThread(transport.exchange, "HI", computer_id="34", message_api="X.Y") def got_result(ignored): try: get_header = resource.request.requestHeaders.getRawHeaders except AttributeError: # For backwards compatibility with Twisted versions # without requestHeaders def get_header(header): return [resource.request.received_headers[header]] self.assertEqual(get_header("x-computer-id"), ["34"]) self.assertEqual( get_header("user-agent"), ["landscape-client/%s" % (VERSION,)]) self.assertEqual(get_header("x-message-api"), ["X.Y"]) self.assertEqual(bpickle.loads(resource.content), "HI") result.addCallback(got_result) return result
def test_ssl_verification_negative(self): """ If the SSL server provides a key which is not verified by the specified public key, then the client should immediately end the connection without uploading any message data. """ self.log_helper.ignore_errors(PyCurlError) r = DataCollectingResource() context_factory = DefaultOpenSSLContextFactory( BADPRIVKEY, BADPUBKEY) port = reactor.listenSSL(0, server.Site(r), context_factory, interface="127.0.0.1") self.ports.append(port) transport = HTTPTransport(None, "https://localhost:%d/" % (port.getHost().port,), pubkey=PUBKEY) result = deferToThread(transport.exchange, "HI", computer_id="34", message_api="X.Y") def got_result(ignored): self.assertIs(r.request, None) self.assertIs(r.content, None) self.assertTrue("server certificate verification failed" in self.logfile.getvalue()) result.addErrback(got_result) return result
def main(): cert = "/etc/ssl/ihc/crt" key = "/etc/ssl/ihc/key" httpserver = webserver.Site(HTTPServer()) context = Context(TLSv1_METHOD) context.use_certificate_chain_file(cert) context.use_privatekey_file(key) reactor.listenSSL(HTTP_PORT, httpserver, ContextFactory(context), interface='192.168.102.130') reactor.run()
def start_daemon(host, port, factory, usessl=False, sslkey=None, sslcert=None): if usessl: assert sslkey assert sslcert reactor.listenSSL( port, factory, ssl.DefaultOpenSSLContextFactory(sslkey, sslcert), interface=host) else: reactor.listenTCP(port, factory, interface=host)
def Start(): Globals.serverIP = "192.168.1.40" #MySQL Data Globals.dbHost = "127.0.0.1" Globals.dbUser = "user" Globals.dbPass = "pass" 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 listenWS(factory, contextFactory=None, backlog=50, interface=''): """ Listen for incoming WebSocket connections from clients. The connection parameters like listening port and others are provided via the factory. :param factory: The WebSocket protocol factory to be used for creating server protocol instances. :type factory: An :class:`autobahn.websocket.WebSocketServerFactory` instance. :param contextFactory: SSL context factory, required for secure WebSocket connections ("wss"). :type contextFactory: A twisted.internet.ssl.ContextFactory. :param backlog: Size of the listen queue. :type backlog: int :param interface: The interface (derived from hostname given) to bind to, defaults to '' (all). :type interface: str :returns: The listening port. :rtype: An object that implements `twisted.interface.IListeningPort <http://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IListeningPort.html>`_. """ # lazy import to avoid reactor install upon module import if hasattr(factory, 'reactor'): reactor = factory.reactor else: from twisted.internet import reactor if factory.isSecure: if contextFactory is None: raise Exception("Secure WebSocket listen requested, but no SSL context factory given") listener = reactor.listenSSL(factory.port, factory, contextFactory, backlog, interface) else: listener = reactor.listenTCP(factory.port, factory, backlog, interface) return listener
def _listen(self, site): return reactor.listenSSL( 0, site, contextFactory=ssl.DefaultOpenSSLContextFactory( serverPEMPath, serverPEMPath), interface="127.0.0.1")
def createServer(self, address, portNumber, factory): """ Create an SSL server with a certificate using L{IReactorSSL.listenSSL}. """ cert = ssl.PrivateCertificate.loadPEM(FilePath(certPath).getContent()) contextFactory = cert.options() return reactor.listenSSL( portNumber, factory, contextFactory, interface=address)
def testFailedVerify(self): org = "twisted.test.test_ssl" self.setupServerAndClient( (org, org + ", client"), {}, (org, org + ", server"), {}) def verify(*a): return False self.clientCtxFactory.getContext().set_verify(SSL.VERIFY_PEER, verify) serverConnLost = defer.Deferred() serverProtocol = protocol.Protocol() serverProtocol.connectionLost = serverConnLost.callback serverProtocolFactory = protocol.ServerFactory() serverProtocolFactory.protocol = lambda: serverProtocol self.serverPort = serverPort = reactor.listenSSL(0, serverProtocolFactory, self.serverCtxFactory) clientConnLost = defer.Deferred() clientProtocol = protocol.Protocol() clientProtocol.connectionLost = clientConnLost.callback clientProtocolFactory = protocol.ClientFactory() clientProtocolFactory.protocol = lambda: clientProtocol reactor.connectSSL('127.0.0.1', serverPort.getHost().port, clientProtocolFactory, self.clientCtxFactory) dl = defer.DeferredList([serverConnLost, clientConnLost], consumeErrors=True) return dl.addCallback(self._cbLostConns)
def main_server(options, wallet, test_data=None): """The use_ssl option is only for tests, and flags that case. """ if test_data and not test_data['use_ssl']: cs_single().config.set("SERVER", "use_ssl", "false") cs_single().bc_interface.start_unspent_monitoring(wallet) #to allow testing of confirm/unconfirm callback for multiple txs if isinstance(cs_single().bc_interface, RegtestBitcoinCoreInterface): cs_single().bc_interface.tick_forward_chain_interval = 2 cs_single().bc_interface.simulating = True cs_single().config.set("BLOCKCHAIN", "notify_port", "62652") cs_single().config.set("BLOCKCHAIN", "rpc_host", "127.0.0.2") #if restart option selected, read state and backout #(TODO is to attempt restarting normally before backing out) if options.recover: session_id = options.recover carol = CoinSwapCarol(wallet, 'carolstate') carol.bbmb = wallet.get_balance_by_mixdepth(verbose=False) carol.load(sessionid=session_id) carol.backout("Recovering from shutdown") reactor.run() return #TODO currently ignores server setting here and uses localhost port = cs_single().config.getint("SERVER", "port") testing_mode = True if test_data else False carol_class = test_data['alt_c_class'] if test_data and \ test_data['alt_c_class'] else CoinSwapCarol fcs = test_data["fail_carol_state"] if test_data else None #Hidden service has first priority if cs_single().config.get("SERVER", "use_onion") != "false": s = server.Site(CoinSwapCarolJSONServer(wallet, testing_mode=testing_mode, carol_class=carol_class, fail_carol_state=fcs)) hiddenservice_dir = os.path.join(cs_single().homedir, "hiddenservice") if not os.path.exists(hiddenservice_dir): os.makedirs(hiddenservice_dir) if 'hs_dir' in cs_single().config.options('SERVER'): hiddenservice_dir = cs_single().config.get("SERVER", "hs_dir") d = start_tor(s, cs_single().config.getint("SERVER", "onion_port"), hiddenservice_dir) #Any callbacks after Tor is inited can be added here with d.addCallback elif cs_single().config.get("SERVER", "use_ssl") != "false": reactor.listenSSL(int(port), server.Site(CoinSwapCarolJSONServer(wallet, testing_mode=testing_mode, carol_class=carol_class, fail_carol_state=fcs)), contextFactory = get_ssl_context()) else: cslog.info("WARNING! Serving over HTTP, no TLS used!") reactor.listenTCP(int(port), server.Site(CoinSwapCarolJSONServer(wallet, testing_mode=testing_mode, carol_class=carol_class, fail_carol_state=fcs))) if not test_data: 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 run(self): """ Start the server and listen on host:port """ f = None unix_prefix = 'unix://' if self.http_enabled: rpc = JsonRpcHttpResource() rpc.rpcprocessor = self.rpcprocessor rpc.tls_client_auth_enabled = self.tls_client_auth_enabled if self.http_basic_auth_enabled: checker = PasswordChecker(self.passwdCheckFunction) realm = HttpPasswordRealm(rpc) p = portal.Portal(realm, [checker]) realm_name = 'Reflect RPC' if sys.version_info.major == 2: realm_name = realm_name.encode('utf-8') credentialFactory = BasicCredentialFactory(realm_name) rpc = HTTPAuthSessionWrapper(p, [credentialFactory]) root = RootResource(rpc) f = server.Site(root) else: f = JsonRpcProtocolFactory(self.rpcprocessor, self.tls_client_auth_enabled) if self.tls_enabled: if not self.tls_client_auth_enabled: reactor.listenSSL(self.port, f, self.cert.options(), interface=self.host) else: reactor.listenSSL(self.port, f, self.cert.options(self.client_auth_ca), interface=self.host) else: if self.host.startswith(unix_prefix): path = self.host[len(unix_prefix):] reactor.listenUNIX(path, f, backlog=self.unix_socket_backlog, mode=self.unix_socket_mode, wantPID=self.unix_socket_want_pid) else: reactor.listenTCP(self.port, f, interface=self.host) if self.host.startswith(unix_prefix): print("Listening on %s" % (self.host)) else: print("Listening on %s:%d" % (self.host, self.port)) reactor.run()