使用 pyOpenSSL 处理 SNI - Python

2023-12-09

我正在与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/如果无效,则直接拒绝连接。我怎样才能做到这一点?


你需要使用set_tlsext_host_name. From 文档:

Connection.set_tlsext_host_name(name)
  Specify the byte string to send as the server name in the client hello message.
  New in version 0.13.

除此之外,您的主机名验证是错误的,因为它仅与 CN 进行比较,而不与主题备用名称进行比较。它还允许在任何地方使用通配符,这违反了仅在最左边的标签中允许使用通配符的规则:*.example.com很好,同时www.*.com甚至*.*.*不允许,但已被您的代码接受。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 pyOpenSSL 处理 SNI - Python 的相关文章

随机推荐