使用客户端证书与urllib2

19

我需要在我的服务器和远程网络服务之间创建一个安全通道。 我将使用带有客户端证书的HTTPS。 我还需要验证远程服务呈现的证书。

  1. 如何使用urllib2使用自己的客户端证书?

  2. 我需要在我的代码中做什么来确保远程证书是正确的?

4个回答

37

由于Alex的回答是一个链接,而且该页面上的代码格式不佳,因此我只是为了留念将其放在这里:

import urllib2, httplib

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, timeout=300):
        return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)

opener = urllib2.build_opener(HTTPSClientAuthHandler('/path/to/file.pem', '/path/to/file.pem.') )
response = opener.open("https://example.org")
print response.read()

非常感谢您!我使用私有证书和证书颁发机构连接到Apache服务器,使用Python中的requests库追踪错误已经几天了。我可以验证我的证书在浏览器中工作,但是每次都会出现“握手错误”。最终我使用上面的类来证明客户端证书正在正常工作和认证。结果发现我使用的requests库版本存在一个错误,确切地说是1.2.3版本。希望这条评论能帮助遇到同样问题的其他人。 - ihatecache
1
我刚接触Python,所以想知道在这里 https_open() 函数是什么时候被调用的?如果可能,请描述一下此代码的执行流程。 - rrsuj
1
所以我按照这些说明操作,但在使用Python 2.7.9或更高版本时出现以下urlopen错误:"ssl certificate verify failed"。我认为我需要添加一个带有自己证书链的SSLContext,但并不完全确定,您能提供任何关于如何将其融入您的示例中的建议或提示吗?谢谢! - macguru2000

12

这里有一个官方Python bug跟踪器中的问题,看起来很相关,并提供了一个建议的修补程序。


7

根据 Antoine Pitrou 对 Hank Gay 的回答中提到的问题,(截至 2011 年) 可以使用内置的 ssl 库来简化这个过程。

import ssl
import urllib.request

context = ssl.create_default_context()
context.load_cert_chain('/path/to/file.pem', '/path/to/file.key')
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(context=context))
response = opener.open('https://example.org')
print(response.read())

这段代码是Python 3代码,但是ssl库也可以在Python 2中使用。

load_cert_chain函数还接受一个可选的密码参数,允许对私钥进行加密。


根据https://docs.python.org/2.7/library/ssl.html,`create_default_context`函数是在2.7.9中引入的,因此在(诚然非常)旧的Python 2版本中无法使用。 - Coderer

1

死链,最后存档内容为https://web.archive.org/web/20190302113828/http://www.osmonov.com/2009/04/client-certificates-with-urllib2.html,这正是@tghw在上面向我们展示的。 - Martin Dorey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接