在twisted / thrift处理程序中访问客户端x509证书

时间:2014-10-21 15:18:55

标签: python ssl twisted thrift

尝试通过访问x509证书来确定如何确定协议处理程序中连接的客户端。 (扭曲,节俭)

我发现twisted passing certificate to ssl handler表示可以在Handler中调用self.transport.getPeerCertificate,但是在使用thrift处理程序时,传输层似乎不可用。有没有办法在使用带有twisted的thrift时在处理程序中获取x509证书?

#!/usr/bin/env python
from OpenSSL import SSL
from twisted.internet import reactor, ssl
from thrift.transport import TTwisted
from thrift.protocol import TBinaryProtocol
from zope.interface import implements

from stwisted.test import TestStuff

class TestHandler:
    implements(TestStuff.Iface)

    def echo(self, instring):
        #Need to be able to see the clients x509 cert here
        return instring[::-1]

def Callback(connection, x509, errnum, errdepth, ok):
    if ok and errnum == 0:
        if errdepth == 0:
        try:
            print 'Cert: %s' % x509.get_subject()
        except:
            print 'Couldn\'t find appropriate tags in cert'
            return False
        return True
    else:
        print 'Invalid cert from subject: %s' % x509.get_subject()
        print 'Error no: %d' % errnum
        return False

def main():
    print 'Started'
    handler =  TestHandler()
    processor = TestStuff.Processor(handler)
    pfactory  = TBinaryProtocol.TBinaryProtocolFactory()
    sfactory  = TTwisted.ThriftServerFactory(processor, protofactory)

    sslCtxFactory = ssl.DefaultOpenSSLContextFactory('server.key', 
                                                     'server.crt',
                                                     SSL.TLSv1_METHOD)

    ctx = sslCtxFactory.getContext()
    ctx.set_verify(
         SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
         Callback
    )

    ctx.load_verify_locations('ca_chain.crt')

    reactor.listenSSL(4444, sfactory, sslCtxFactory)

    print 'Starting Reactor'
    reactor.run()

if __name__ == '__main__':
    main()

0 个答案:

没有答案