我正在与pyOpenSSL
最近,但是我遇到了一些使用SNI
为同一 IP 地址提供多个证书。这是我的代码:
from OpenSSL import SSL
from socket import socket
from sys import argv, stdout
import re
from urlparse import urlparse
def callback(conn, cert, errno, depth, result):
if depth == 0 and (errno == 9 or errno == 10):
return False # or raise Exception("Certificate not yet valid or expired")
return True
def main():
if len(argv) < 2:
print 'Usage: %s <hostname>' % (argv[0],)
return 1
o = urlparse(argv[1])
host_name = o.netloc
context = SSL.Context(SSL.TLSv1_METHOD) # Use TLS Method
context.set_options(SSL.OP_NO_SSLv2) # Don't accept SSLv2
context.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
callback)
# context.load_verify_locations(ca_file, ca_path)
sock = socket()
ssl_sock = SSL.Connection(context, sock)
ssl_sock.connect((host_name, 443))
ssl_sock.do_handshake()
cert = ssl_sock.get_peer_certificate()
common_name = cert.get_subject().commonName.decode()
print "Common Name: ", common_name
print "Cert number: ", cert.get_serial_number()
regex = common_name.replace('.', r'\.').replace('*',r'.*') + '$'
if re.match(regex, host_name):
print "matches"
else:
print "invalid"
if __name__ == "__main__":
main()
例如,假设我有以下网址:
https://example.com
当我得到以下输出时:
python sni.py https://example.com/
Common Name: *.example.com
Cert number: 63694395280496902491340707875731768741
invalid
这是相同的证书https://another.example.com
:
python sni.py https://another.example.com/
Common Name: *.example.com
Cert number: 63694395280496902491340707875731768741
matches
但是,比方说,证书https://another.example.com
已过期,连接无论如何都会被接受,因为它正在使用*.example.com
证书,有效。不过我希望能够使用https://another.example.com/
如果无效,则直接拒绝连接。我怎样才能做到这一点?