[Twisted-Python] getpeername from verify callback

Nathan Mower nathanm at securitymetrics.com
Thu Oct 18 22:41:08 MDT 2012


The following sample code worked until Twisted began to prefer memory BIOs over socket BIOs.  Now it produces this error...

exceptions.AttributeError: 'NoneType' object has no attribute 'getpeername'

...on line 9 where getpeername() is called by the verify() callback.

Is there any way to obtain the peer name, given the OpenSSL.SSL.Connection object passed into verify()?  Anything that surfaces the underlying socket?  (Perhaps something similar to what is done in connectionMade(), which does work.)  Or alternatively, is there a way to tell the reactor to employ socket BIOs?

Thanks,
Nathan

----------------------------------------------
from OpenSSL import SSL
from twisted.internet import reactor, ssl
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineReceiver

class VerifyContextFactory(ssl.ClientContextFactory):

    def verify(self, connection, x509, errnum, errdepth, ok):
        print connection.getpeername()[0]
        return ok

    def getContext(self):
        ctx = ssl.ClientContextFactory.getContext(self)
        ctx.set_verify(SSL.VERIFY_PEER|SSL.VERIFY_FAIL_IF_NO_PEER_CERT, self.verify)
        return ctx

class MyClient(LineReceiver):

    def connectionMade(self):
        print "connected to", self.transport.socket.getpeername()[0]
        return

    def connectionFailed(self, reason):
        reactor.stop()

    def connectionLost(self, reason):
        reactor.stop()

class MyClientFactory(ClientFactory):

    protocol = MyClient

if __name__ == "__main__":
    reactor.connectSSL('www.example.com', 443, MyClientFactory(), VerifyContextFactory())
    reactor.run()





More information about the Twisted-Python mailing list