1 2 from twisted.internet.protocol import Protocol, Factory 3 from twisted.internet import reactor 4 from twisted.protocols.policies import WrappingFactory 5 from twisted.protocols.basic import LineReceiver 6 from twisted.python import log 7 from twisted.python.failure import Failure 8 import sys 9 from tlslite.api import * 10 11 s = open("./serverX509Cert.pem").read() 12 x509 = X509() 13 x509.parse(s) 14 certChain = X509CertChain([x509]) 15 16 s = open("./serverX509Key.pem").read() 17 privateKey = parsePEMKey(s, private=True) 18 19 verifierDB = VerifierDB("verifierDB") 20 verifierDB.open() 21 22 class Echo(LineReceiver): 23 def connectionMade(self): 24 self.transport.write("Welcome to the echo server!\r\n") 25 26 def lineReceived(self, line): 27 self.transport.write(line + "\r\n") 28 29 class Echo1(Echo): 30 def connectionMade(self): 31 if not self.transport.tlsStarted: 32 self.transport.setServerHandshakeOp(certChain=certChain, 33 privateKey=privateKey, 34 verifierDB=verifierDB) 35 else: 36 Echo.connectionMade(self) 37 38 def connectionLost(self, reason): 39 pass #Handle any TLS exceptions here 40 41 class Echo2(Echo): 42 def lineReceived(self, data): 43 if data == "STARTTLS": 44 self.transport.setServerHandshakeOp(certChain=certChain, 45 privateKey=privateKey, 46 verifierDB=verifierDB) 47 else: 48 Echo.lineReceived(self, data) 49 50 def connectionLost(self, reason): 51 pass #Handle any TLS exceptions here 52 53 factory = Factory() 54 factory.protocol = Echo1 55 #factory.protocol = Echo2 56 57 wrappingFactory = WrappingFactory(factory) 58 wrappingFactory.protocol = TLSTwistedProtocolWrapper 59 60 log.startLogging(sys.stdout) 61 reactor.listenTCP(1079, wrappingFactory) 62 reactor.run() 63