简体   繁体   中英

Where to give path of ssl certificate files in Python websocket server

I've this snippet from: https://websockets.readthedocs.io/en/stable/intro.html

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
localhost_pem = pathlib.Path(__file__).with_name("localhost.pem")
ssl_context.load_verify_locations(localhost_pem)

I've CA signed certificate with Key,Cert and Bundle files. Where to specify them?

In my actual code it looks like though all browsers report invalid certificate issue:

def start_server():
    ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    localhost_pem = pathlib.Path(__file__).with_name("server.pem")
    ssl_context.load_cert_chain(localhost_pem)

    ip = ''

    if os.name =='nt':
        ip = '127.0.0.1'
    else:
        ip = "x.x.x.x"

    start_server = websockets.serve(
        hello, ip, 31333,ssl=ssl_context
    )

    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()

For example I've created a Python webserver and specified those files correctly and this is working properly and no invalid certification issue comes:

server = HTTPServer(('0.0.0.0', 443), PostHandler)
    if USE_HTTPS:
        import ssl
        server.socket = ssl.wrap_socket(server.socket, keyfile='./ssl/key.pem', certfile='./ssl/public.pem'
                , ca_certs="./ssl/cap1_traf_com.ca-bundle" , server_side=True)

        server.serve_forever()
 

Most libraries, including websockets accept an ssl context parameter.

In your case, for server side, you'd want to create the socket as so:

import ssl
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain("<cert path>", "<key path>")

This will create a server-side socket for the purpose of "client authentication". If you're not using client-certificates (chances are low) then this should be enough.

If your certificate requires additional intermediate ones ("bundle"), they should be part of the <cert_path> file. The .pem format allows for multiple certificates, one after the other.

A simple concatenation will usually do the trick. For more information you can see the Python Docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM