| 1 |
Encrypt connections |
| 2 |
==================== |
| 3 |
|
| 4 |
.. currentmodule:: websockets |
| 5 |
|
| 6 |
You should always secure WebSocket connections with TLS_ (Transport Layer |
| 7 |
Security). |
| 8 |
|
| 9 |
.. admonition:: TLS vs. SSL |
| 10 |
:class: tip |
| 11 |
|
| 12 |
TLS is sometimes referred to as SSL (Secure Sockets Layer). SSL was an |
| 13 |
earlier encryption protocol; the name stuck. |
| 14 |
|
| 15 |
The ``wss`` protocol is to ``ws`` what ``https`` is to ``http``. |
| 16 |
|
| 17 |
Secure WebSocket connections require certificates just like HTTPS. |
| 18 |
|
| 19 |
.. _TLS: https://developer.mozilla.org/en-US/docs/Web/Security/Transport_Layer_Security |
| 20 |
|
| 21 |
.. admonition:: Configure the TLS context securely |
| 22 |
:class: attention |
| 23 |
|
| 24 |
The examples below demonstrate the ``ssl`` argument with a TLS certificate |
| 25 |
shared between the client and the server. This is a simplistic setup. |
| 26 |
|
| 27 |
Please review the advice and security considerations in the documentation of |
| 28 |
the :mod:`ssl` module to configure the TLS context appropriately. |
| 29 |
|
| 30 |
Servers |
| 31 |
------- |
| 32 |
|
| 33 |
In a typical :doc:`deployment <../deploy/index>`, the server is behind a reverse |
| 34 |
proxy that terminates TLS. The client connects to the reverse proxy with TLS and |
| 35 |
the reverse proxy connects to the server without TLS. |
| 36 |
|
| 37 |
In that case, you don't need to configure TLS in websockets. |
| 38 |
|
| 39 |
If needed in your setup, you can terminate TLS in the server. |
| 40 |
|
| 41 |
In the example below, :func:`~asyncio.server.serve` is configured to receive |
| 42 |
secure connections. Before running this server, download |
| 43 |
:download:`localhost.pem <../../example/tls/localhost.pem>` and save it in the |
| 44 |
same directory as ``server.py``. |
| 45 |
|
| 46 |
.. literalinclude:: ../../example/tls/server.py |
| 47 |
:caption: server.py |
| 48 |
|
| 49 |
Receive both plain and TLS connections on the same port isn't supported. |
| 50 |
|
| 51 |
Clients |
| 52 |
------- |
| 53 |
|
| 54 |
:func:`~asyncio.client.connect` enables TLS automatically when connecting to a |
| 55 |
``wss://...`` URI. |
| 56 |
|
| 57 |
This works out of the box when the TLS certificate of the server is valid, |
| 58 |
meaning it's signed by a certificate authority that your Python installation |
| 59 |
trusts. |
| 60 |
|
| 61 |
In the example above, since the server uses a self-signed certificate, the |
| 62 |
client needs to be configured to trust the certificate. Here's how to do so. |
| 63 |
|
| 64 |
.. literalinclude:: ../../example/tls/client.py |
| 65 |
:caption: client.py |