summaryrefslogtreecommitdiffstatshomepage
path: root/tests/net_inet/asyncio_tls_open_connection_readline.py
blob: 70145d91a794be9047a3cd77ddc8a411bc3b94c7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import ssl
import os
import asyncio

# 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).

# Note that the instructions above is to obtain an intermediate
# root CA cert that works for MicroPython. However CPython needs the ultimate root CA
# cert from ISRG

ca_cert_chain = "isrg.der"

try:
    os.stat(ca_cert_chain)
except OSError:
    print("SKIP")
    raise SystemExit

with open(ca_cert_chain, "rb") as ca:
    cadata = ca.read()

client_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
client_ctx.verify_mode = ssl.CERT_REQUIRED
client_ctx.load_verify_locations(cadata=cadata)


async def http_get(url, port, sslctx):
    reader, writer = await asyncio.open_connection(url, port, ssl=sslctx)

    print("write GET")
    writer.write(b"GET / HTTP/1.0\r\n\r\n")
    await writer.drain()

    print("read response")
    while True:
        data = await reader.readline()
        # avoid printing datetime which makes the test fail
        if b"GMT" not in data:
            print("read:", data)
        if not data:
            break

    print("close")
    writer.close()
    await writer.wait_closed()
    print("done")


asyncio.run(http_get("micropython.org", 443, client_ctx))