Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 14 · 50 minutes

Build a tool that traces a web request

After this lesson you can
  • Write a Python tool that times each stage of a web request
  • Report the TLS version, cipher and certificate expiry of a server
  • Test the tool against your local HTTP and HTTPS servers and read its failures
Lab files of this lesson (56)

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

Users of an internal site write "it is down" in the help channel, and each report has a different cause. Your lead is tired of guessing and asks for a small tool: give it a URL, and it tells which stage of the request breaks (the name, the connection, the certificate or the page) and how long each stage took. You build it from the parts of lessons 5, 7, 8 and 9, and the ladder of lesson 13. Then you test it on four services that you do not know, and you name the fault of each.

Recall

What does the exit code 60 of curl tell you?

A certificate check failed: the chain is not trusted, the name does not match, or the dates are wrong. The fix is to trust or renew the right certificate, not to turn the check off.

Why is the first DNS lookup of a name slower than the second?

The first answer has to come from the DNS servers through the recursive resolver. The second comes from a cache, until the TTL ends.

The idea

A web request has four stages, and each stage needs the one before it.

StageQuestionLesson
DNSWhat address does this name have?7
TCPCan I connect to that address and port?5
TLS(HTTPS only) Does the server prove its name, and which version and cipher were agreed?9
HTTPWhat status and headers does the server return?8

These are the upper rungs of the ladder of lesson 13. In the layers of lesson 1, DNS and HTTP are layer 7, TCP is layer 4, and TLS sits at layer 5 or 6.

trace.py takes a URL. It runs the four stages in order, prints one line for each with the time it took, and stops at the first stage that fails. It uses the standard library only, and it never turns certificate checks off. For a server with a private certificate, it takes an option --cacert file, as curl does.

What trace.py does, stage by stage
trace.pyResolverWeb serverDNS: what address has this name?the addressTCP: connect to the portTLS: hello, check the certificatecertificate, name proven, keys agreedHTTP: GET the pathstatus line and headerstrace.pyResolverWeb server1234567
  1. trace.py → Resolver: DNS: what address has this name?
  2. Resolver → trace.py: the address
  3. trace.py → Web server: TCP: connect to the port
  4. trace.py → Web server: TLS: hello, check the certificate
  5. Web server → trace.py: certificate, name proven, keys agreed
  6. trace.py → Web server: HTTP: GET the path
  7. Web server → trace.py: status line and headers
A URL, split by trace.py
https://scheme: TLS or notlocalhosthost: for DNS and SNI:8010port: for the TCP stage/path: for the HTTP stagehttps://scheme: TLS or notlocalhosthost: for DNS and SNI:8010port: for the TCP stage/path: for the HTTP stage

Worked example

1. Write trace.py

Create ~/krlab/networking/trace.py. Read it before you run it: each block is one stage. The variable current holds the name of the stage that runs, so that a failure can say where it happened. The line global current lets a function change a variable that lives outside it.

trace.py

import socket
import ssl
import sys
import time
from urllib.parse import urlsplit

KEY_HEADERS = ("server", "content-type", "content-length", "location",
               "set-cookie", "strict-transport-security")
current = "DNS"  # the stage that runs now, so that a failure can name it


def stage(name, start, detail):
    print(f"{name:<5} {(time.perf_counter() - start) * 1000:7.1f} ms  {detail}")


def trace(url, cafile=None):
    global current
    u = urlsplit(url)
    https = u.scheme == "https"
    host = u.hostname
    port = u.port or (443 if https else 80)
    path = (u.path or "/") + ("?" + u.query if u.query else "")

    t = time.perf_counter()
    infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
    stage("DNS", t, ", ".join(sorted({i[4][0] for i in infos})))

    current = "TCP"
    t = time.perf_counter()
    sock = socket.create_connection((host, port), timeout=5)
    stage("TCP", t, f"connected to {sock.getpeername()[0]}:{port}")

    if https:
        current = "TLS"
        context = ssl.create_default_context(cafile=cafile)
        t = time.perf_counter()
        sock = context.wrap_socket(sock, server_hostname=host)
        cert = sock.getpeercert()
        subject = dict(x[0] for x in cert["subject"])
        left = (ssl.cert_time_to_seconds(cert["notAfter"]) - time.time()) / 86400
        stage("TLS", t, f"{sock.version()}, {sock.cipher()[0]}")
        print(f"      certificate: {subject.get('commonName')}, "
              f"expires {cert['notAfter']} ({left:.0f} days left)")

    current = "HTTP"
    t = time.perf_counter()
    request = f"GET {path} HTTP/1.1\r\nHost: {u.netloc}\r\nConnection: close\r\n\r\n"
    sock.sendall(request.encode())
    data = b""
    while chunk := sock.recv(65536):
        data += chunk
    sock.close()
    head = data.partition(b"\r\n\r\n")[0].decode("latin-1").split("\r\n")
    stage("HTTP", t, head[0])
    for line in head[1:]:
        name, _, value = line.partition(":")
        if name.lower() in KEY_HEADERS:
            print(f"      {name.lower()}: {value.strip()}")


if __name__ == "__main__":
    cafile = sys.argv[sys.argv.index("--cacert") + 1] if "--cacert" in sys.argv else None
    try:
        trace(sys.argv[1], cafile)
    except (OSError, ssl.SSLError) as e:
        print(f"FAILED at {current}: {type(e).__name__}: {e}")
        sys.exit(1)

Some notes on the choices. getaddrinfo is the system resolver, as in lesson 7. create_connection is the TCP step of lesson 5, and it tries each address of the name in turn. ssl.create_default_context turns on the chain check and the name check, and server_hostname sets SNI and the name to check. urlsplit cuts a URL into scheme, host, port and path. getpeercert() returns the checked certificate as a dictionary, and cert_time_to_seconds turns its date text into seconds. After a failure the program exits with code 1, so a script can use it.

2. Start the two servers

You need the web server of lesson 8 and the HTTPS server of lesson 9 with its cert.pem and key.pem. If the certificate is older than 30 days, make a new one with the command of lesson 9. Use two terminals.

cd ~/krlab/networking
python3 -m http.server 8000 --bind 127.0.0.1
cd ~/krlab/networking
python3 https_server.py

3. Trace the HTTP server

Use a third terminal.

cd ~/krlab/networking
python3 trace.py http://127.0.0.1:8000/
DNS       3.0 ms  127.0.0.1
TCP       0.2 ms  connected to 127.0.0.1:8000
HTTP     10.8 ms  HTTP/1.0 200 OK
      server: SimpleHTTP/0.6 Python/3.14.4
      content-type: text/html
      content-length: 17

Your times will differ. The DNS step is not zero even for an address, because getaddrinfo still runs. The TLS stage is missing, because the scheme is http.

4. Trace a page that does not exist

python3 trace.py http://localhost:8000/missing
DNS       3.1 ms  127.0.0.1
TCP       0.2 ms  connected to 127.0.0.1:8000
HTTP      0.9 ms  HTTP/1.0 404 File not found
      server: SimpleHTTP/0.6 Python/3.14.4
      content-type: text/html;charset=utf-8
      content-length: 460

The first three stages are fine and the fourth shows the fault. A 404 is a working network and a wrong path.

5. Trace the HTTPS server, first without trust

python3 trace.py https://localhost:8010/
DNS       3.2 ms  127.0.0.1
TCP       0.2 ms  connected to 127.0.0.1:8010
FAILED at TLS: SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certificate (_ssl.c:1081)

DNS and TCP passed, and the report stops at TLS with a clear reason. Compare this with a user who only sees "connection failed".

6. Trace the HTTPS server with your certificate as the trusted root

python3 trace.py https://localhost:8010/ --cacert cert.pem
DNS       3.2 ms  127.0.0.1
TCP       0.2 ms  connected to 127.0.0.1:8010
TLS       8.6 ms  TLSv1.3, TLS_AES_256_GCM_SHA384
      certificate: localhost, expires Dec 21 08:36:09 2026 GMT (30 days left)
HTTP      7.6 ms  HTTP/1.0 200 OK
      server: SimpleHTTP/0.6 Python/3.14.4
      content-type: text/html
      content-length: 17
The TLS line of trace.py
TLSstage8.6 mstime the stage tookTLSv1.3version agreedTLS_AES_256_GCM_SHA384cipher agreedTLSstage8.6 mstime the stage tookTLSv1.3version agreedTLS_AES_256_GCM_SHA384cipher agreed

The line below it shows the name in the certificate and the time left.

7. Trace two failures and a public site

A port with no server, and a name that does not exist:

python3 trace.py http://127.0.0.1:8002/
python3 trace.py http://nonexistent.invalid/
DNS       2.9 ms  127.0.0.1
FAILED at TCP: ConnectionRefusedError: [Errno 111] Connection refused
FAILED at DNS: gaierror: [Errno -2] Name or service not known

The first fails at TCP, the second at DNS. Now try a public site; this step needs the internet.

python3 trace.py https://example.com/
DNS     134.0 ms  104.20.23.154, 172.66.147.243, 2606:4700:10::6814:179a, 2606:4700:10::ac42:93f3
TCP     108.3 ms  connected to 172.66.147.243:443
TLS     122.0 ms  TLSv1.3, TLS_AES_256_GCM_SHA384
      certificate: example.com, expires Dec 25 22:56:35 2026 GMT (35 days left)
HTTP    257.9 ms  HTTP/1.1 200 OK
      content-type: text/html; charset=utf-8
      server: cloudflare

The result varies with the site and the time. Notice that this server sent HTTP/1.1 and that a remote connection takes a hundred milliseconds for each round trip, not tenths.

8. Stop the servers

Press Ctrl+C in the two server terminals, then check that the ports are free:

ss -tlnp | grep -E ':80(00|10)\b' || echo free
free

Your turn

Find the faults of the four services. There are no steps here: use your trace.py, on targets that you have not seen.

Save the program below as faults.py in ~/krlab/networking. It uses openssl to make a certificate for the name other.lab (the files wrong.pem and wrong.key), and starts three services on 127.0.0.1: port 8091 (HTTP), port 8092 (HTTPS with that certificate) and port 8093 (HTTP). Port 8094 has no service. Start it with python3 faults.py in a terminal and leave it running.

faults.py

import http.server
import ssl
import subprocess
import threading


class Quiet(http.server.BaseHTTPRequestHandler):
    server_version = "faultlab/1"
    sys_version = ""

    def log_message(self, *args):
        pass

    def do_GET(self):
        code, extra = self.server.answer
        self.send_response(code)
        for name, value in extra.items():
            self.send_header(name, value)
        self.send_header("Content-Length", "0")
        self.end_headers()


class Server(http.server.ThreadingHTTPServer):
    def handle_error(self, request, client_address):
        pass  # a client that refuses the certificate is not an error here


def start(port, answer, tls=False):
    server = Server(("127.0.0.1", port), Quiet)
    server.answer = answer
    if tls:
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain("wrong.pem", "wrong.key")
        server.socket = context.wrap_socket(server.socket, server_side=True)
    threading.Thread(target=server.serve_forever, daemon=True).start()


subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", "wrong.key",
                "-out", "wrong.pem", "-days", "30", "-subj", "/CN=other.lab",
                "-addext", "subjectAltName=DNS:other.lab"], check=True, stderr=subprocess.DEVNULL)
start(8091, (503, {"Retry-After": "30"}))
start(8092, (200, {}), tls=True)
start(8093, (302, {"Location": "/login?next=/"}))
print("services on 8091, 8092 (HTTPS) and 8093. Press Ctrl+C to stop.", flush=True)
threading.Event().wait()

In a second terminal, trace these URLs: http://127.0.0.1:8091/, https://localhost:8092/, http://127.0.0.1:8093/ and http://localhost:8094/. For the HTTPS service, trust its certificate with --cacert wrong.pem, so that you see the real reason and not only "self-signed". Then answer.

Stop faults.py. As a last step, add retry-after to KEY_HEADERS in trace.py and trace port 8091 again. Write one line for each service: what it shows, whether that is a fault, and who must fix it (the user, the network team, the owner of the certificate, the owner of the application, or nobody).

Check yourself

A user reports that a site "does not load". Your trace stops after the TCP line, with a timeout. What is your next step?

The name resolved and a connection started, but the TLS handshake or the request did not complete. A timeout here, unlike "refused", suggests that something drops packets or the server hangs. Check from another network, then look at the firewall rules and the server load.

Why does trace.py not offer an option to ignore certificate errors?

A tool that can hide a failed identity check will be used to hide it. When a certificate fails, the report must say so, and the fix is to trust the right certificate (--cacert) or to renew a bad one. This is the rule of lesson 9, built into the tool.

The DNS stage takes 2 seconds on the first run and 3 milliseconds on the second. Why?

The first answer came from the authoritative servers through the recursive resolver. The second came from a cache, until the TTL ends (lesson 7). Slow first lookups can be a resolver problem and not a server problem.

Field notes

  • Add --cacert and the exit code to monitoring. A cron job that runs trace.py against your own services and alerts on exit code 1, or on "days left" below 14, finds an expiring certificate before users do.
  • The tool connects to the first address that works. Sites with IPv6 and IPv4 addresses, or with many servers, can be down on one address only. Loop over the result of getaddrinfo and report each address.
  • Time each stage on its own. A slow DNS stage points to the resolver, a slow TCP stage to distance or packet loss, a slow TLS stage to server load or a large chain, and a slow HTTP stage to the application.
  • getpeercert() gives only a verified certificate. To read the certificate of a server that you cannot yet trust (for an investigation), use openssl s_client and openssl x509, as in lesson 9, and say in your notes that the check was not done.
  • Treat the headers as evidence. A missing strict-transport-security header, or a server header with a version, is a finding that this same tool can report for every site you own.