micropython/tests/net_inet/test_sslcontext_client.py
Carlosgg f3f215e9bd extmod/modssl_mbedtls: Add SSLContext certificate methods.
This commit adds:

1) Methods to SSLContext class that match CPython signature:

	- `SSLContext.load_cert_chain(certfile, keyfile)`
	- `SSLContext.load_verify_locations(cafile=, cadata=)`
	- `SSLContext.get_ciphers()` --> ["CIPHERSUITE"]
	- `SSLContext.set_ciphers(["CIPHERSUITE"])`

2) `sslsocket.cipher()` to get current ciphersuite and protocol
   version.

3) `ssl.MBEDTLS_VERSION` string constant.

4) Certificate verification errors info instead of
   `MBEDTLS_ERR_X509_CERT_VERIFY_FAILED`.

5) Tests in `net_inet` and `multi_net` to test these new methods.

`SSLContext.load_cert_chain` method allows loading key and cert from disk
passing a filepath in `certfile` or `keyfile` options.

`SSLContext.load_verify_locations`'s `cafile` option enables the same
functionality for ca files.

Signed-off-by: Carlos Gil <carlosgilglez@gmail.com>
2023-12-12 16:25:07 +11:00

53 lines
1.6 KiB
Python

import os
import socket
import ssl
# This certificate was obtained from micropython.org using openssl:
# $ openssl s_client -showcerts -connect micropython.org:443 </dev/null 2>/dev/null
# The certificate is from Let's Encrypt:
# 1 s:/C=US/O=Let's Encrypt/CN=R3
# i:/C=US/O=Internet Security Research Group/CN=ISRG Root X1
# Validity
# Not Before: Sep 4 00:00:00 2020 GMT
# Not After : Sep 15 16:00:00 2025 GMT
# Copy PEM content to a file (certmpy.pem) and convert to DER e.g.
# $ openssl x509 -in certmpy.pem -out certmpy.der -outform DER
# Then convert to hex format, eg using binascii.hexlify(data).
ca_cert_chain = "mpycert.der"
try:
os.stat(ca_cert_chain)
except OSError:
print("SKIP")
raise SystemExit
def main(use_stream=True):
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.verify_mode = ssl.CERT_REQUIRED
assert context.verify_mode == ssl.CERT_REQUIRED
context.load_verify_locations(cafile=ca_cert_chain)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = socket.getaddrinfo("micropython.org", 443)[0][-1]
# CPython can wrap the socket even if not connected yet.
# ssl_sock = context.wrap_socket(s, server_hostname='micropython.org')
# ssl_sock.connect(addr)
# MicroPython needs to connect first, CPython can do this too.
s.connect(addr)
# server_hostname must match CN (Common Name) in the certificate
# presented by the server
ssl_sock = context.wrap_socket(s, server_hostname="micropython.org")
ssl_sock.write(b"GET / HTTP/1.0\r\n\r\n")
print(ssl_sock.read(17))
assert isinstance(ssl_sock.cipher(), tuple)
ssl_sock.close()
main()