summaryrefslogtreecommitdiffstatshomepage
path: root/tests/net_inet/test_sslcontext_client.py
diff options
context:
space:
mode:
Diffstat (limited to 'tests/net_inet/test_sslcontext_client.py')
-rw-r--r--tests/net_inet/test_sslcontext_client.py52
1 files changed, 52 insertions, 0 deletions
diff --git a/tests/net_inet/test_sslcontext_client.py b/tests/net_inet/test_sslcontext_client.py
new file mode 100644
index 0000000000..860b053d5b
--- /dev/null
+++ b/tests/net_inet/test_sslcontext_client.py
@@ -0,0 +1,52 @@
+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()