Search code examples
pythonpython-3.xsocketswebsocketvalueerror

ValueError: check_hostname requires server_hostname when using socket and ssl modules


I am trying to make a socket server, I would like to use SSL.

I had a version of this working just fine with asyncio (including the ssl bit) but wanted to rebuild it with just the socket module.

My goal is a I need my website to be able to send binary data back and forth with this back end server. The amount of data is 3.6KB, don't feel like you guys would need that info but I thought I would include it.

I am very new to python and sockets so most of this is copy pasta, ELI5 (like 14 at best) is appreciated!

Thanks for reading!

The error below happens when I go to my browser and have javascript run

websocket = new WebSocket("wss://smolroom.com:8001/");

Server:

def webServerListener():
    print("webServerListener()")
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)

    ssl_cert = "/path/to/cert/this/is/filler"
    ssl_key = "/path/to/cert/this/is/filler"

    ssl_context.load_cert_chain(ssl_cert, keyfile=ssl_key)

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
        sock.bind(('', 8001))
        sock.listen(5)
        print("socket server listening")
        while True:
            (clientConnection, clientAddress) = sock.accept()

            with ssl_context.wrap_socket(clientConnection, server_side=True) as ssock:
                try:
                    dealWithClient(ssock)
                finally:
                    ssock.shutdown(socket.SHUT_RDWR)
                    ssock.close()

Error:

webServerListener()
Exception in thread web-server-listener-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "./server-test.py", line 24, in run
    webServerListener()
  File "./server-test.py", line 86, in webServerListener
    with ssl_context.wrap_socket(clientConnection, server_side=True) as ssock:
  File "/usr/lib/python3.8/ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "/usr/lib/python3.8/ssl.py", line 997, in _create
    raise ValueError("check_hostname requires server_hostname")
ValueError: check_hostname requires server_hostname

Solution

  • Ignoring the other glaring issues with my originally posted code, the main problem that was causing the issue exemplified above was actually the following line of code right there at the start:

    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    

    Since I am running this code as a server, I need to be using the correct ssl protocol:

    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)