检查远程主机在TLS握手(mTLS)期间是否要求客户端证书

时间:2020-10-09 18:58:56

标签: python ssl

我试图编写一个接收URL的函数,进行部分TLS握手,并告诉远程服务器在TLS握手(所有版本)中是否要求客户端证书。

这应该怎么做?到目前为止,这是尝试过的:

import socket
import ssl
from urllib.parse import urlparse


def is_mtls_required(url):
    url_info = urlparse(url)
    if url_info.scheme != 'https':
        return False

    host = url_info.netloc
    port = url_info.port if url_info.port else 443

    sock = None
    connection = None
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port))
        ssl_context = ssl.SSLContext()
        connection = ssl_context.wrap_socket(sock, do_handshake_on_connect=False)
        connection.do_handshake()
    except ssl.SSLError as e:
        if "CERTIFICATE_UNKNOWN" in e.reason:
            return True
    finally:
        if connection:
            connection.close()
        if sock:
            sock.close()

    return False

测试:

assert is_mtls_required("https://amazon.com") == False # Ok
assert is_mtls_required("https://secure.court.gov.il") == True # Ok
assert is_mtls_required("https://server.cryptomix.com/secure") == True # Fail the test, when browsing in chrome it prompts with selection of client certificate to use

0 个答案:

没有答案