我如何实际验证给定 url 的 SSL 证书?

How do I actually verify a given url's SSL certificate?

我正在编写一段代码来验证给定 URL 的 SSL 证书是否有效,但是,请求库似乎无法正常工作。这是代码:

import requests
    try:
        response = str(requests.get(url, verify=True, allow_redirects=True))
        print(response)
        if "SSL: CERTIFICATE_VERIFY_FAILED" in response:
            print("url \"" + url + "\" has an invalid SSL certificate")
        else:
            valid = True
            for command in commands:
                if command.title == "get info":
                    if command.expirationDate > datetime.date:
                        print("url has an expired SSL certificate.")
                        valid = False
            if valid:
                print("url \"" + url + "\" has a valid SSL certificate")
    except requests.exceptions.InvalidURL:
        print("Invalid url \"" + url + "\"")
    except requests.exceptions.MissingSchema:
        print("Invalid url \"" + url + "\"")
    except (socket.gaierror, urllib3.exceptions.NewConnectionError, urllib3.exceptions.MaxRetryError, requests.exceptions.ConnectionError):
        print("Could not resolve url \"" + url + "\" to host")

放入 URL "https://expired.badssl.com/ returns Could not resolve url "https://expired.badssl.com/" to host 但是,我实际上可以导航到此页面。 此外,没有有效证书的页面显示为有效。我的一个朋友 运行 他的 beef-xss 服务器上有这个确切的代码,输出是它有一个有效的证书。我看过很多教程都说了同样的话,但是,考虑到我尝试过的所有方法都不起作用,我一定遗漏了一些东西。

您的问题似乎是您的 IF 语句未被评估,因为当 SSL 验证失败时 requests 已经抛出异常。

您可能需要使用专用的 try-except 块来处理它,例如:

import requests

def has_valid_ssl_req(url):
    try:
        response = str(requests.get(url, verify=True, allow_redirects=True))
        print(response)
        print(url+" has valid SSL, response: "+response)

    except Exception as e:
        print(url+": has INVALID SSL, error:"+str(e))

has_valid_ssl_req('http://expired.badssl.com')
has_valid_ssl_req('http://google.com')

基于:我可能会直接使用 SSL

import socket
import ssl

def has_valid_ssl(url):
    try:
        ctx = ssl.create_default_context()
        with ctx.wrap_socket(socket.socket(), server_hostname=url) as s:
            s.connect((url, 443))

        print(url+" has valid SSL")

    except Exception as e:
        print(url+": has INVALID SSL, error:"+str(e))

has_valid_ssl('expired.badssl.com')
has_valid_ssl('google.com')