`ssl`
En esta página
ssl -- SSL/TLS module#
ssl
|see_cpython_module| python:ssl.
This module provides access to Transport Layer Security (previously and widely known as “Secure Sockets Layer”) encryption and peer authentication facilities for network sockets, both client-side and server-side.
Functions#
ssl.wrap_socket(sock, server_side=False, key=None, cert=None, cert_reqs=CERT_NONE, cadata=None, server_hostname=None, do_handshake=True)
Wrap the given sock and return a new wrapped-socket object. The implementation of this function is to first create an SSLContext and then call the SSLContext.wrap_socket method on that context object. The arguments sock, server_side and server_hostname are passed through unchanged to the method call. The argument do_handshake is passed through as do_handshake_on_connect. The remaining arguments have the following behaviour:
- cert_reqs determines whether the peer (server or client) must present a valid certificate.
Note that for mbedtls based ports, ssl.CERT_NONE and ssl.CERT_OPTIONAL will not validate any certificate, only ssl.CERT_REQUIRED will.
- cadata is a str or bytes object containing the CA certificate chain that will validate the
peer's certificate. It can be one or more certificates in PEM format, or single DER-encoded certificate.
Depending on the underlying module implementation in a particular MicroPython port, some or all keyword arguments above may be not supported.
class SSLContext#
Create a new SSLContext instance. The protocol argument must be one of the PROTOCOL_* constants.
SSLContext.load_cert_chain(certfile, keyfile)
Load a private key and the corresponding certificate. The certfile is a string with the file path of the certificate. The keyfile is a string with the file path of the private key.
Difference to CPython
MicroPython extension: certfile and keyfile can be bytes objects instead of strings, in which case they are interpreted as the actual certificate/key data.
SSLContext.load_verify_locations(cafile=None, cadata=None)
Load the CA certificate chain that will validate the peer's certificate. cafile is the file path of the CA certificates. cadata is a bytes object containing the CA certificates. Only one of these arguments should be provided.
SSLContext.get_ciphers()
Get a list of enabled ciphers, returned as a list of strings.
SSLContext.set_ciphers(ciphers)
Set the available ciphers for sockets created with this context. ciphers should be a list of strings in the IANA cipher suite format .
SSLContext.psk_identity SSLContext.psk_key
The pre-shared key (PSK) identity and key to authenticate with as a client. Set both to use PSK: psk_identity is the identity sent to the server and psk_key is the shared key, both as bytes objects.
While PSK is configured the context offers only PSK cipher suites, so the connection cannot fall back to a non-PSK (e.g. certificate-based) suite.
Availability depends on the port's mbedTLS being built with PSK support.
SSLContext.server_psk_keys
A mapping used by a server to look up the key for the identity presented by a connecting client. Set it to accept PSK clients:
ctx.server_psk_keys = {b"my-identity": b"my-key"}
Its get() method is called with the client's identity (a bytes object) and should return the corresponding key as a bytes object, or None to reject an unknown identity. Any object providing such a get() method may be used, so keys can be computed or fetched on demand. As with the client, the context is restricted to PSK cipher suites while this is set.
SSLContext.wrap_socket(sock, *, server_side=False, do_handshake_on_connect=True, server_hostname=None, client_id=None)
Takes a stream sock (usually socket.socket instance of SOCK_STREAM type), and returns an instance of ssl.SSLSocket, wrapping the underlying stream. The returned object has the usual stream interface methods like read(), write(), etc.
- server_side selects whether the wrapped socket is on the server or client side. A server-side SSL socket should be created from a normal socket returned from
~socket.socket.accept()on a non-SSL listening server socket. - do_handshake_on_connect determines whether the handshake is done as part of the
wrap_socketor whether it is deferred to be done as part of the initial reads or writes For blocking sockets doing the handshake immediately is standard. For non-blocking sockets (i.e. when the sock passed intowrap_socketis in non-blocking mode) the handshake should generally be deferred because otherwisewrap_socketblocks until it completes. Note that in AXTLS the handshake can be deferred until the first read or write but it then blocks until completion. - server_hostname is for use as a client, and sets the hostname to check against the received server certificate. It also sets the name for Server Name Indication (SNI), allowing the server to present the proper certificate.
- client_id is a MicroPython-specific extension argument used only when implementing a DTLS Server. See
dtlsfor details.
[!WARNING] Some implementations of
sslmodule do NOT validate server certificates, which makes an SSL connection established prone to man-in-the-middle attacks.CPython's
wrap_socketreturns anSSLSocketobject which has methods typical for sockets, such assend,recv, etc. MicroPython'swrap_socketreturns an object more similar to CPython'sSSLObjectwhich does not have these socket methods.
SSLContext.verify_mode
Set or get the behaviour for verification of peer certificates. Must be one of the CERT_* constants.
[!NOTE]
ssl.CERT_REQUIREDrequires the device's date/time to be properly set, e.g. usingmpremote rtc --set \<mpremote_command_rtc\>orntptime, andserver_hostnamemust be specified when on the client side.
Exceptions#
ssl.SSLError
This exception does NOT exist. Instead its base class, OSError, is used.
DTLS support#
Difference to CPython
This is a MicroPython extension.
On most ports, this module supports DTLS in client and server mode via the PROTOCOL_DTLS_CLIENT and PROTOCOL_DTLS_SERVER constants that can be used as the protocol argument of SSLContext.
In this case the underlying socket is expected to behave as a datagram socket (i.e. like the socket opened with socket.socket with socket.AF_INET as af and socket.SOCK_DGRAM as type).
DTLS is only supported on ports that use mbedTLS, and it is enabled by default in most configurations but can be manually disabled by defining MICROPY_PY_SSL_DTLS to 0.
DTLS server support#
MicroPython's DTLS server support is configured with "Hello Verify" as required for DTLS 1.2. This is transparent for DTLS clients, but there are relevant considerations when implementing a DTLS server in MicroPython:
- The server should pass an additional argument client_id when calling
SSLContext.wrap_socket(). This ID must be abytesobject (or similar) with a transport-specific identifier representing the client.
The simplest approach is to convert the tuple of (client_ip, client_port) returned from socket.recv_from() into a byte string, i.e.:
_, client_addr = sock.recvfrom(1, socket.MSG_PEEK)
sock.connect(client_addr) # Connect back to the client
sock = ssl_ctx.wrap_socket(sock, server_side=True,
client_id=repr(client_addr).encode())
-
The first time a client connects, the server call to
wrap_socketwill fail with aOSErrorerror "Hello Verify Required". This is because the DTLS "Hello Verify" cookie is not yet known by the client. If the same client connects a second time thenwrap_socketwill succeed. -
DTLS cookies for "Hello Verify" are associated with the
SSLContextobject, so the sameSSLContextobject should be used to wrap a subsequent connection from the same client. The cookie implementation includes a timeout and has constant memory use regardless of how many clients connect, so it's OK to reuse the sameSSLContextobject for the lifetime of the server.
Constants#
ssl.PROTOCOL_TLS_CLIENT ssl.PROTOCOL_TLS_SERVER ssl.PROTOCOL_DTLS_CLIENT (when DTLS support is enabled) ssl.PROTOCOL_DTLS_SERVER (when DTLS support is enabled)
Supported values for the protocol parameter.
ssl.CERT_NONE ssl.CERT_OPTIONAL ssl.CERT_REQUIRED
Supported values for cert_reqs parameter, and the SSLContext.verify_mode attribute.