ssl: why wrap newly accept()ed connections?

Kushal Kumaran kushal at locationd.net
Thu Feb 3 14:37:35 EST 2022


On Thu, Feb 03 2022 at 11:17:17 AM, Grant Edwards <grant.b.edwards at gmail.com> wrote:
> According to the docs, when you accept() an ssl connection,
> you need to wrap the new connection:
>
>  https://docs.python.org/3/library/ssl.html?highlight=ssl#ssl-sockets
>
>    When a client connects, you’ll call accept() on the socket to get
>    the new socket from the other end, and use the context’s
>    SSLContext.wrap_socket() method to create a server-side SSL socket
>    for the connection:
>
>     while True:
>         newsocket, fromaddr = bindsocket.accept()
>         connstream = context.wrap_socket(newsocket, server_side=True)
>         try:
>             deal_with_client(connstream)
>         finally:
>             connstream.shutdown(socket.SHUT_RDWR)
>             connstream.close()
>            
> However, example server code I've found does not wrap the newly
> accepted connection. I've checked, and newsocket is already an
> <ssl:SSLSocket> object.  The examples I've seen/tried simply call
> ..recv() and .send() methods of newsocket, and that seems to work fine.
>
> What is the purpose of wrapping newsocket?

That section is talking about using an "ordinary" socket for the server.
bindsocket is a socket.socket.  If bindsocket was already a
ssl.SSLSocket, the wrapping would be already done by accept.

I suppose this kind of functionality is useful for protocols that start
off as cleartext and then switch to TLS (such as the mail-related
protocols that use STARTTLS).

-- 
regards,
kushal


More information about the Python-list mailing list