Menu

TLS: Wrap socket before or after accepting a connection?

Reddit r/learnpython·u/tio-fabi·6 months ago
#9ot4IhMN
#socket#sock#connection#context#true
Reading 0:00
15s threshold

You can use a TLS wrapper to turn a regular socket into a TLS socket. Should this be done before or after accepting a connection? Are there situations where you would prefer one approach over the other?

Below examples both work. In the first example, the socket is wrapped before a client connects:

``` import socket import ssl import threading

context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) context.load_cert_chain(certfile='cert.pem', keyfile='key.pem')

create a generic socket:

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.bind(('localhost', 4711)) sock.listen() # wrap socket (returns a generic ssl socket): with context.wrap_socket(sock, server_side=True) as ssl_sock: while True: # accept connection (returns a new connection socket): conn, addr = ssl_sock.accept() threading.Thread(target=handle_connection, args=(conn, addr), daemon=True).start() # (close socket in thread function) ```

Here, the socket is wrapped only after a client has connected:

``` context =…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.