summaryrefslogtreecommitdiffstatshomepage
path: root/tests/net_inet/test_sslcontext_client.py
blob: 860b053d5b481d1ab8816688f90e1392110611b0 (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
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()