使用客户端证书的自定义urllib打开器
我有一个需要使用的API,这个API是通过HTTPS来保护的,并且使用了双向认证/客户端证书。我手里有一个PEM文件和一个CRT文件。
当我正常连接到服务器时,使用PyOpenSSL没有问题,下面是我的代码:
import settings
from OpenSSL import SSL
import socket
def verify(conn, cert, errnum, depth, ok):
# This obviously has to be updated
print 'Got certificate: %s' % cert.get_subject()
return ok
def password_callback(maxlen, verify, extra):
print (maxlen, verify, extra)
return settings.DEPOSIT_CODE
context = SSL.Context(SSL.SSLv23_METHOD)
context.set_verify(SSL.VERIFY_NONE, verify)
context.set_passwd_cb(password_callback)
context.use_certificate_file(settings.CLIENT_CERT_FILE)
context.use_privatekey_file(settings.PEM_FILE)
sock = SSL.Connection(context, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
sock.connect(("someserver.com",443))
http_get_request = """
GET / HTTP/1.1
"""
sock.write(http_get_request)
print sock.recv(1000)
但是,由于这是一个需要客户端证书的HTTPS API,我为它实现了一个打开器,稍微修改过的代码如下:
import settings
import socket
import urllib2
def verify(conn, cert, errnum, depth, ok):
# This obviously has to be updated
print 'Got certificate: %s' % cert.get_subject()
return ok
def password_callback(maxlen, verify, extra):
print (maxlen, verify, extra)
return settings.DEPOSIT_CODE
class MyHTTPSConnection(httplib.HTTPSConnection):
def connect(self):
context = SSL.Context(SSL.SSLv23_METHOD)
context.set_passwd_cb(password_callback)
context.use_certificate_file(settings.CLIENT_CERT_FILE)
context.set_verify(SSL.VERIFY_NONE, verify)
context.use_privatekey_file(settings.PEM_FILE)
self.sock = SSL.Connection(context, socket.socket(socket.AF_INET, socket.SOCK_STREAM))
class MyHTTPSHandler(urllib2.HTTPSHandler):
def https_open(self,req):
return self.do_open(MyHTTPSConnection,req)
opener = urllib2.build_opener(urllib2.HTTPHandler,MyCHTTPSHandler)
urllib2.install_opener(opener)
f = urllib2.urlopen("https://sampleapiserver.com")
print f.code
可是,当我运行第二段代码时,我遇到了以下错误:
File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.6/urllib2.py", line 391, in open
response = self._open(req, data)
File "/usr/lib/python2.6/urllib2.py", line 409, in _open
'_open', req)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "network.py", line 37, in https_open
return self.do_open(IRNICHTTPSConnection,req)
File "/usr/lib/python2.6/urllib2.py", line 1142, in do_open
h.request(req.get_method(), req.get_selector(), req.data, headers)
File "/usr/lib/python2.6/httplib.py", line 914, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.6/httplib.py", line 951, in _send_request
self.endheaders()
File "/usr/lib/python2.6/httplib.py", line 908, in endheaders
self._send_output()
File "/usr/lib/python2.6/httplib.py", line 780, in _send_output
self.send(msg)
File "/usr/lib/python2.6/httplib.py", line 759, in send
self.sock.sendall(str)
OpenSSL.SSL.Error: [('SSL routines', 'SSL_write', 'uninitialized')]
最后,我是不是做错了什么?如果没有,请帮我理解这个错误...
谢谢。
2 个回答
3
看起来你这里添加了很多其实不必要的复杂内容。如果你只是想做简单的客户端证书认证,其实可以用下面这段代码就够了(来源):
import httplib
import urllib2
# HTTPS Client Auth solution for urllib2, inspired by
# http://bugs.python.org/issue3466
# and improved by David Norton of Three Pillar Software. In this
# implementation, we use properties passed in rather than static module
# fields.
class HTTPSClientAuthHandler(urllib2.HTTPSHandler):
def __init__(self, key, cert):
urllib2.HTTPSHandler.__init__(self)
self.key = key
self.cert = cert
def https_open(self, req):
#Rather than pass in a reference to a connection class, we pass in
# a reference to a function which, for all intents and purposes,
# will behave as a constructor
return self.do_open(self.getConnection, req)
def getConnection(self, host):
return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)
cert_handler = HTTPSClientAuthHandler(settings.PEMFILE, settings.CLIENT_CERT_FILE)
opener = urllib2.build_opener(cert_handler)
urllib2.install_opener(opener)
f = urllib2.urlopen("https://sampleapiserver.com")
print f.code
这段代码原本是用来给Suds的Client
构造函数提供一个证书认证的URL打开器,所以我把那些多余的部分去掉了,直接做成一个打开器。
1
我不太确定,但看起来你在 connect() 方法里漏掉了调用 connect() 这个函数:
self.sock.connect(("someserver.com",443))
另外,httplib
处理 https 的时候,有一些包装类是用来处理 SSL 套接字的,所以可能需要这些才能正常工作?