Lesson 09 · 40 minutes
Make a certificate and serve HTTPS
- Explain what TLS protects and what a certificate proves
- Create a self-signed certificate and serve HTTPS with Python
- Read a certificate and say why a client refuses it, and how to trust it correctly
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
The team starts an internal API at the name api.krlab.test. A colleague has already written in the ticket: "Clients fail with a certificate error. I will use curl -k to make it work." You must stop that, and do it properly. You make a certificate with the right fields, serve HTTPS with it, and show which names the certificate accepts and what a client does when the certificate is not trusted.
Recall
In lesson 8 a cookie travelled in a plain HTTP request. Who on the network path can read it?
Everyone who can see the traffic on the path: the Wi-Fi, the routers, a proxy. HTTP has no encryption, so the headers, the cookie and the body are plain text.
A false DNS answer sends your browser to the attacker's server. Which later check can still stop the attack?
The certificate check of TLS. The attacker's server has no valid certificate for the real name, so the client sees a name or a chain that does not fit and refuses the connection.
The idea
TLS (Transport Layer Security) wraps a TCP connection. It gives three things:
| Property | Meaning |
|---|---|
| Confidentiality | A person who watches the network cannot read the data. |
| Integrity | A person who changes the data on the way is detected. |
| Server identity | The client knows that it talks to the real owner of the name. |
The first two come from keys that client and server agree on in the handshake. The third needs a certificate: a document that says "this public key belongs to this name", signed by someone. Without the third property, the first two are weak: you could have a private conversation with an attacker.
- Client → Server: ClientHello: name (SNI), key share
- Server → Client: ServerHello: its key share
- Server → Client: certificate and Finished, encrypted
- Client: check chain, name and dates
- Client → Server: Finished
- Client → Server: encrypted HTTP request
This is the TLS 1.3 order: the key shares travel in the first two messages, and everything after them is encrypted.
A client decides to trust a certificate by following a chain. The server certificate is signed by an intermediate CA (certificate authority). That one is signed by a root CA. Your system keeps a store of root certificates that it trusts, and the chain must end in one of them. The client also checks four more things: the name it wanted is in the certificate (in the Subject Alternative Name, SAN, list), the dates are valid, the signature is right, and the certificate is allowed for this use.
- Client → Server certificate: is my name in the SAN list? dates valid?
- Server certificate → Intermediate CA: signed by this intermediate CA
- Intermediate CA → Trusted root: signed by a root in the store: trusted
A self-signed certificate signs itself. Its chain has one link and ends in nothing that your system trusts, so a client refuses it, correctly.
SNI (Server Name Indication) is a field in the first message of the handshake. The client writes the name it wants, so one server and one address can hold the certificates of many sites and choose the right one.
Worked example
1. Make a key and a self-signed certificate
openssl is the standard toolbox for keys and certificates. The command openssl req -x509 makes a self-signed certificate. -newkey rsa:2048 makes a new 2048-bit RSA key, -nodes leaves the key without a password (OpenSSL 3 also accepts the newer spelling -noenc), -keyout and -out name the two files, -days 30 sets the life of the certificate, -subj sets its name (CN is the common name) and -addext adds the SAN list with localhost and 127.0.0.1. The text 2>/dev/null hides the progress output of openssl. ls -l lists the files with their sizes and modes.
cd ~/krlab/networking
openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 30 \
-subj "/CN=localhost" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1" 2>/dev/null
ls -l *.pem-rw-rw-r-- 1 you you 1151 Nov 21 08:36 cert.pem
-rw------- 1 you you 1704 Nov 21 08:36 key.pemcert.pem is public. key.pem is secret: anyone who has it can pretend to be the server, so openssl gives it the mode 600. This key is only for the lab.
2. Read the certificate
openssl x509 reads a certificate. -noout hides the encoded copy, and the other options pick the fields to print.
openssl x509 -in cert.pem -noout -subject -issuer -dates -ext subjectAltNamesubject=CN=localhost
issuer=CN=localhost
notBefore=Nov 21 08:36:09 2026 GMT
notAfter=Dec 21 08:36:09 2026 GMT
X509v3 Subject Alternative Name:
DNS:localhost, IP Address:127.0.0.1The subject and the issuer are the same name. That is what "self-signed" means. Run openssl x509 -in cert.pem -noout -text for the whole certificate, including the public key and the signature.
3. Serve HTTPS
Write https_server.py. It serves the folder over TLS and prints the name that each client asks for in SNI. Without arguments it uses port 8010 and the files cert.pem and key.pem. With arguments, the order is port, certificate, key. lambda writes a one-line function (as in lesson 4): the server calls it with the name of each client that connects. The module ssl does the TLS work: ssl.SSLContext holds the TLS settings of the server, load_cert_chain loads your certificate and key, wrap_socket makes the listening socket speak TLS, and sni_callback is called once for each client with the name that it asked for.
https_server.py
import http.server
import ssl
import sys
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8010
cert = sys.argv[2] if len(sys.argv) > 2 else "cert.pem"
key = sys.argv[3] if len(sys.argv) > 3 else "key.pem"
server = http.server.ThreadingHTTPServer(("127.0.0.1", port), http.server.SimpleHTTPRequestHandler)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain(cert, key)
context.sni_callback = lambda sock, name, ctx: print("client asked for name:", name, flush=True)
server.socket = context.wrap_socket(server.socket, server_side=True)
print(f"HTTPS on https://localhost:{port}/", flush=True)
server.serve_forever()python3 https_server.pyHTTPS on https://localhost:8010/Leave it running and use a second terminal. This server sends every file of the folder, key.pem too. It listens on the loopback only, so only users of this machine can fetch it. Use it on a machine that only you use.
4. See curl refuse the certificate
curl -sS https://localhost:8010/curl: (60) SSL certificate OpenSSL verify result: self-signed certificate (18)The wording depends on your curl version, and curl adds a longer help text. The exit code is 60: a certificate check failed. The meaning is the same on every version: the chain does not end in a root that your system trusts. Curl is right to refuse. The server could be anyone. The server terminal may print an error trace, because the client closed the connection. That is expected.
5. Trust this one certificate, and only it
--cacert tells curl to use your file as the trusted root, in place of the system store.
curl -sS --cacert cert.pem https://localhost:8010/hello from krlabYou did not turn the check off. You told curl which certificate to trust, and the other checks (name, dates, signature) still ran. See this in the next step.
6. Check that the name is checked
The --resolve option makes curl send wrong.example to your local server, as if DNS had given that answer. The certificate does not list that name.
curl -sS --cacert cert.pem --resolve wrong.example:8010:127.0.0.1 https://wrong.example:8010/curl: (60) SSL: no alternative certificate subject name matches target hostname 'wrong.example'The signature was valid and the chain was trusted, but the name was wrong, so the client refused. This is the check that stops an attacker with a valid certificate for another name.
7. Inspect the handshake with s_client
openssl s_client opens a TLS connection and reports what was agreed. -servername sets the SNI. -CAfile is the trusted root. The echo | in front sends an empty line, so the connection closes at once, and grep -E keeps the lines that we want.
echo | openssl s_client -connect localhost:8010 -servername localhost -CAfile cert.pem 2>&1 | grep -E '^(New,|Protocol:|Verification|Verify return)'Verification: OK
New, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384
Protocol: TLSv1.3
Verify return code: 0 (ok)The order of these lines depends on your OpenSSL version. The ^ in the pattern means "at the start of a line", so the copy of the session details further down does not match.
Try -tls1_2 to force the older version: the server accepts it, and the cipher changes to ECDHE-RSA-AES256-GCM-SHA384. Look at the terminal of the server. It printed one line for each client: localhost for curl https://localhost, and None for a connection by IP address, because a client sends no name when you give it a bare address. Stop the server with Ctrl+C.
Your turn
Make the certificate for the API of the scenario. There are no steps here: use the commands of the worked example, with these different values.
Make a certificate and a key in the files api-cert.pem and api-key.pem with these fixed fields:
- the common name
api.krlab.test - the SAN list with two DNS names:
api.krlab.testandadmin.krlab.test - an RSA key of 3072 bits
- a life of 90 days
Start https_server.py with port 8011 and your new files. Ask https://api.krlab.test:8011/ with curl and no trust option. The name does not exist in DNS, so make curl send it to 127.0.0.1. Note the exit code of curl (the shell shows it in the variable $? after the command). Read the issuer of the certificate. Then test three names against the certificate with openssl x509 -checkhost: api.krlab.test, admin.krlab.test and www.krlab.test. Last, run -checkend with 7776000 seconds (90 days): it says whether the certificate ends within that time.
Stop the server. Then trust the certificate the right way with --cacert and show that the page loads. Do not use -k.
Check yourself
Why is "curl -k" a wrong fix for "self-signed certificate"?
-k turns off the identity check. Then the connection is encrypted, but to anyone, including an attacker in the middle. You lose the one property that makes TLS useful. The right fix is to trust the right certificate (--cacert), or to use a certificate from a CA that the client already trusts.
The certificate is valid and trusted, but the client says the name does not match. What is wrong?
The name in the address is not in the SAN list of the certificate. The certificate was made for another name. Request a certificate that lists the real name. The old CN field is no longer used for this check by modern clients.
What does an observer on the network still see when you use HTTPS?
The addresses and ports, the amount and timing of the data, and usually the server name in SNI (the name is plain text in the first message, unless the system uses Encrypted Client Hello). The paths, headers, cookies and bodies are hidden.
Field notes
- A self-signed certificate made with
openssl req -x509is also markedCA:TRUE, so it is a root as well. For a team lab, make a small private CA, sign server certificates with it, and give clients only the CA certificate. Then you can replace server certificates without changing the clients. - Expired certificates cause real outages. Check the date from a script:
openssl x509 -in cert.pem -noout -checkend 2592000exits with a non-zero code if the certificate ends in 30 days. Lesson 14 reads the expiry of a live server. - Force a minimum version in your own servers.
context.minimum_version = ssl.TLSVersion.TLSv1_2in Python refuses TLS 1.0 and 1.1, which are obsolete (RFC 8996). TLS 1.3 is defined in RFC 8446. - Never commit
key.pemor send it by chat or mail. If a private key leaks, replace the certificate and revoke it. Keys on a server belong to the service account only (mode600). - Certificate transparency logs record every public certificate. Search them for your domains to find certificates that you did not request: this is an early sign of a phishing site or a mis-issued certificate.