[Python] Can someone explain this callback function for SSL certificates?

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    My apologies right off if this isn't in the right SO (Information Security or Crypto).Anyways, I'm trying to figure out how to validate SSL certs client side in Python. I found a callback function here that looks similar to other functions I've seen online. However, in my code I'm unsure of how (or why, really) it works. It seems to work when I run my code, but why (in PyCharm) are the first four parameters grayed out, and only the fifth in white? Is there a way I can use this callback function to check for particular certificate errors?

    Here's the output when I run it

    Certs are fine
    Certs are fine
    Certs are fine
    b'HTTP/1.1 200 OK\r\nDate: Tue, 12 Apr 2016...etc


    I assume each line of "Certs are fine" is validating each cert in the chain?

    import socket
    from OpenSSL import SSL

    HOST = "www.google.com"
    PORT = 443

    def verify_callback(connection, x509, errnum, errdepth, ok):
    if not ok:
    print("Bad Certs")
    else:
    print("Certs are fine")
    return ok


    context = SSL.Context(SSL.TLSv1_2_METHOD)
    context.load_verify_locations("cacerts.pem")
    context.set_options(SSL.OP_NO_SSLv2)
    context.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback)


    # create socket and connect to server
    sock = socket.socket()
    sock = SSL.Connection(context, sock)
    sock.connect((HOST, PORT))
    sock.do_handshake()
    sock.sendall("GET / HTTP/1.1\r\n\r\n")

    Continue reading...

Compartilhe esta Página