Skip to content

ssl module cannot wrap sockets before connecting after inject_into_ssl() #210

@roelandschoukens

Description

@roelandschoukens

truststore.inject_into_ssl() will break sslcontext.wrap_socket():

import ssl
import socket

import truststore
truststore.inject_into_ssl()

sslcontext = ssl.create_default_context()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = sslcontext.wrap_socket(s, server_hostname="example.com")

causing it to fail with

  File "test.py", line 9, in <module>
    s = sslcontext.wrap_socket(s, server_hostname="example.com")
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\******\Python312\site-packages\truststore\_api.py", line 130, in wrap_socket
    _verify_peercerts(ssl_sock, server_hostname=server_hostname)
  File "C:\******\Python312\site-packages\truststore\_api.py", line 338, in _verify_peercerts
    cert_bytes = _get_unverified_chain_bytes(sslobj)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\******\Python312\site-packages\truststore\_api.py", line 320, in _get_unverified_chain_bytes
    unverified_chain = sslobj.get_unverified_chain() or ()  # type: ignore[attr-defined]
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'get_unverified_chain'

Internally, in truststore/_api.py in _verify_peercerts(), the sock_or_sslobj parameter is an object with a _sslobj field, but that field is set to None. Note that the socket is not yet connected, and the documentation of the ssl module states:

For client-side sockets, the context construction is lazy; if the underlying socket isn’t connected yet, the context construction will be performed after connect() is called on the socket.

implying that the _sslobj field will be set only when calling connect().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions