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()
python类listenSSL()的实例源码
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 = 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 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 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 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 _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)
daemon_protocol.py 文件源码
项目:joinmarket-clientserver
作者: JoinMarket-Org
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
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 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):
"""
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)