Chapters

TLS & HTTPS

Every request to api.kade.lk carries passwords, addresses and order details. TLS is what stops the café WiFi, the ISP, or anyone in between from reading or changing them, and what proves the laptop is really talking to Kadé. This chapter builds it up from the crypto basics to the certificates on kade-api.

Application protocols · chapter 25 of 34 · 12 min read

Part AWhere TLS fits

HTTPS = HTTP inside TLS

TLS (Transport Layer Security) wraps a connection so that traffic is private and tamper-evident. HTTPS is not a different protocol: it is plain HTTP (chapter 24) running inside a TLS-encrypted connection. Everything about HTTP still applies; TLS just protects it in transit. (SSL is TLS's old name; all SSL versions are broken and switched off.)

How HTTP, TLS and TCP fit together

TLS sits between HTTP and TCP. HTTP hands its bytes to TLS; TLS encrypts them into records and hands those to TCP; TCP delivers them reliably (chapters 16-20):

one HTTPS packet on the wire

frameIP headerTCP headerTLS record headerencrypted HTTP requestauth tag
LayerJob hereVisible to someone on the path?
HTTPGET /orders/1042, the token, the JSONNo: encrypted
TLSEncrypts, checks integrity, proves identityOnly the record headers, plus the handshake's first messages
TCPPorts, sequence numbers, retransmissionYes: port 443, sizes, timing
IPAddresses, routingYes: 34.87.120.15
The café can still see that you talk to 34.87.120.15 on 443, how much and when, and (see section 12) the site name. It cannot see what you send. HTTP/3 is the exception to this stack: QUIC builds TLS 1.3 into the transport itself (chapter 24).

Three guarantees

#GuaranteeMeansProvided by
1ConfidentialityEavesdroppers see only scrambled dataSymmetric encryption (AES or ChaCha20)
2IntegrityAny change on the way is detectedAn authentication tag on every record (AEAD)
3AuthenticationYou are really talking to api.kade.lkThe server's certificate and a signature made with its private key
Encryption alone is not enough. Without authentication you could have a perfectly encrypted conversation with an attacker. Part C is about how the third guarantee works.

Part BThe cryptography

Symmetric encryption: fast, one shared key

In symmetric encryption, the same key locks and unlocks. Modern ciphers like AES (sped up by special CPU instructions) and ChaCha20 (fast on phones without them) encrypt gigabytes per second per CPU core. TLS 1.3 uses them in AEAD mode ("authenticated encryption"): each record is encrypted and gets a tag that proves it was not changed, in one step.

The catch: both sides need the same key, and they have never met. Sending the key over the network would let anyone listening read everything after it.

Asymmetric cryptography: key pairs

In asymmetric (public-key) cryptography, each party has a key pair: a private key kept secret and a public key shared with everyone. What one key does, only the other can undo. It is used in two ways:

Signatures

Sign with the private key; anyone checks with the public key. Proves "the owner of this key made this, and it was not changed".

TLS use: kade-api proves it owns its certificate.

Key exchange

Two sides each combine their own private value with the other's public value and arrive at the same secret, without ever sending it.

TLS use: laptop and kade-api agree on the symmetric key.

Asymmetric operations rely on hard maths (large-number and elliptic-curve problems), which makes them thousands of times slower than symmetric encryption. Fine for a few operations per connection; far too slow for every byte of a video.

Key exchange: agreeing on a secret in public

The idea behind TLS's key exchange is Diffie-Hellman. Both sides agree on public numbers, each picks a private number, and they swap only the results. Anyone listening sees the swapped values but cannot work out the shared secret, because undoing the maths is extremely hard at real sizes. Try it with tiny numbers:

LaptopOn the network (anyone can see)kade-api
secret a = 6p = 23, g = 5secret b = 15
A = ga mod p = 8A = 8 →
← B = 19
B = gb mod p = 19
Ba mod p = 2To get the secret, a listener would have to find a from A (or b from B). Easy for p = 23; practically impossible for real key sizes.Ab mod p = 2

Both sides computed 2 without ever sending it. This shared secret becomes the seed for the symmetric keys.

Real TLS uses the elliptic-curve version (ECDHE, usually the curve X25519) with 256-bit numbers. The "E" means ephemeral: fresh private numbers for every connection, thrown away afterwards (section 9).

Why TLS uses both

#PhaseCryptoUsed forWhy this kind
1HandshakeAsymmetric: ECDHE key exchangeAgree on a shared secret over an open networkSolves "how do we share a key we never met to swap"
2HandshakeAsymmetric: signature with the certificate's keyProve the server is api.kade.lkOnly the real private key can make it
3HandshakeHash-based key derivation (HKDF)Turn the shared secret into separate keys for each directionOne secret, many keys, all unguessable
4Every record afterSymmetric AEAD (AES-GCM or ChaCha20-Poly1305)Encrypt and protect all HTTP dataFast enough for every byte
Slow, clever maths a few times per connection to set things up; fast, simple maths for everything else. This split is called hybrid encryption.

The TLS 1.3 handshake

After the TCP handshake, the laptop and kade-api run the TLS handshake:

Laptopkade-api :443after the TCP handshake (chapter 16)ClientHello · versions, cipher suites, key share, SNI, ALPNreadable by anyone on the pathServerHello · chosen suite, key shareboth sides now compute the same secretencrypted: Certificate · CertificateVerify · Finishedencrypted: Finishedhandshake done: 1 round tripencrypted: GET /orders/1042encrypted: 200 OK + JSON
ClientHelloSupported TLS versions and cipher suites; a key share (the laptop's public ECDHE value); the server name SNI = api.kade.lk (section 12); ALPN = "h2, http/1.1" (chapter 24); a random number.
ServerHelloThe chosen suite (e.g. TLS_AES_128_GCM_SHA256) and kade-api's key share. Both sides can now compute the shared secret: everything after this is encrypted.
Certificatekade-api's certificate chain (Part C).
CertificateVerifyA signature over the whole handshake so far, made with the certificate's private key. This is the proof: a stolen copy of the certificate is useless without the private key.
FinishedEach side sends a check value over the whole handshake, so any tampering with the hellos (like forcing a weaker cipher) is detected.
TLS 1.3 needs 1 round trip. TLS 1.2 needed 2 and sent the certificate unencrypted. TLS 1.0 and 1.1 are switched off everywhere; allow 1.2 and 1.3 only.

Forward secrecy

Because the key-exchange numbers are ephemeral, each connection's keys exist only in memory for that connection. If an attacker records today's traffic and steals kade-api's private key next year, they still cannot decrypt the recording: the private key was only used to sign, never to protect the session keys. This is forward secrecy. TLS 1.3 always has it. Old TLS 1.2 setups with "RSA key exchange" did not: there, one stolen key opened every recorded session.

The full timeline: TCP + TLS + HTTP

A brand-new HTTPS request from home to kade-api (41 ms round trip), counted in round trips:

Laptop (home)kade-api0 ms · TCP SYN41 ms · SYN-ACK41 ms · ACK + ClientHelloTCP done after 1 round trip82 ms · ServerHello … Finished82 ms · Finished + GET /orders/1042TLS done after 2 round trips123 ms · 200 OKthe response arrives after 3 round trips
#SetupRound trips before the response arrivesFrom home
1TCP + TLS 1.2 + HTTP1 + 2 + 1 = 4~164 ms
2TCP + TLS 1.3 + HTTP1 + 1 + 1 = 3~123 ms
3QUIC (HTTP/3), new1 + 1 = 2~82 ms
4QUIC or TLS 1.3 resumed with 0-RTT1~41 ms
5Reused keep-alive connection1~41 ms
0-RTT lets a returning client send its request with the first handshake message, using keys from an earlier session. The risk: an attacker can replay that first flight, so servers accept 0-RTT only for safe requests like GET (chapter 24's "safe methods"). Row 5 is the cheapest of all, and it is why connection reuse matters so much (chapter 21).

Part CCertificates

What a certificate is

A certificate is a signed statement: "this public key belongs to api.kade.lk", signed by someone the browser already trusts. The format is called X.509. kade-api's certificate (as issued for the load balancer later):

SubjectCN = api.kade.lk
Subject Alternative Names (SAN)api.kade.lk, kade.lk, www.kade.lk the names browsers actually check
Issueran intermediate CA of Google Trust Services allowed by the CAA record (chapter 23)
Validitynot before 2026-09-01 · not after 2026-11-30 90 days
Public keyECDSA P-256 (the matching private key never leaves the server)
Key usagedigital signature · TLS server authentication
Serial numberunique per issuer; used for revocation
Signaturethe issuer's signature over all of the above
The certificate is public: the server sends it to everyone. The private key is the secret, and protecting it is what matters.

The chain of trust, and SNI

Browsers and operating systems ship with a trust store of about 150 root CA certificates. Roots are kept offline and rarely used; they sign intermediate CAs, which sign server certificates. The server sends its own certificate plus the intermediates; the client builds the chain up to a root it already trusts:

Root CAself-signed, kept offlinealready in your trust storeIntermediate CAsigned by the rootsent by the serverapi.kade.lk (leaf)signed by the intermediatesent by the serversignssignsThe client checks from the bottom up:1 · the leaf's signature verifies with the intermediate's public key2 · the intermediate's signature verifies with the root's public key3 · the root is in the trust store · plus: names match, dates valid, not revoked, allowed usageAn attacker can make a certificate that says "api.kade.lk", but no trusted CA will sign it for them.

Wide by design - scroll it sideways.

One IP often serves many sites (a load balancer or Cloudflare). Before any certificate is sent, the server needs to know which one to pick, so the ClientHello includes the name: SNI (Server Name Indication). SNI is sent in clear text, which is how the café can see the site name even over HTTPS. A newer extension, Encrypted ClientHello (ECH), hides it where both sides support it.

Try it: will the browser trust this?

Pick a situation. The checks run in the order a browser does them:

Situation
  1. Build a chain from the certificate up to a root in the trust store
  2. Each certificate's signature verifies with its issuer's public key
  3. Today's date (on the client) is inside every certificate's validity dates
  4. The name typed (api.kade.lk) is in the leaf's SAN list
  5. Not revoked; allowed for TLS server use
  6. CertificateVerify: the server's signature over this handshake verifies with the leaf's public key

Trusted. The connection continues.

Every check passes. The padlock appears and the request goes ahead.

Getting a certificate

A CA only signs for a name after you prove you control it. With ACME, the automated protocol used by Let's Encrypt, Google Trust Services and others, the whole process takes seconds:

1Create a key pair on the server. Build a CSR (certificate signing request): the names plus the public key, signed with the private key.
2The CA gives you a challenge to prove control of each name.
3You answer it (next table). The CA checks the CAA record too (chapter 23).
4The CA signs and returns the certificate and its chain, and logs it publicly (section 16).
#ChallengeHow you prove controlGood for
1HTTP-01Serve a given token at http://api.kade.lk/.well-known/acme-challenge/…Simple setups with port 80 open
2DNS-01Create a TXT record at _acme-challenge.api.kade.lk (chapter 23)Wildcards (*.kade.lk) and servers not reachable from the internet
3TLS-ALPN-01Answer a special TLS handshake on port 443When only 443 is open
Free, automated certificates are why almost the whole web is now HTTPS. On GCP, a Google-managed certificate on the load balancer does all of this for you and renews automatically.
DV (domain validated)Proves control of the name only. What ACME issues, and what almost everyone uses.
OV / EVThe CA also checks the organisation. Browsers no longer show it differently, so it adds little for websites.
Wildcard*.kade.lk covers api, www, admin … but one level only, and not kade.lk itself.

Lifetimes, renewal and revocation

  • Short lifetimes. ACME certificates last 90 days, and the industry has agreed to cut the maximum for all public certificates in steps, down to 47 days by 2029. Short lives limit the damage from a leaked key. Renewal must be automated: an expired certificate is one of the most common causes of outages.
  • Revocation. If a private key leaks, the certificate should be revoked before it expires. Clients learn about revocations through lists (CRLs) or an online check (OCSP), which the server can attach to its handshake ("OCSP stapling"). In practice browsers check unevenly, which is another reason for short lifetimes.

Certificate Transparency

Every publicly trusted certificate must be written to public, append-only Certificate Transparency (CT) logs, and browsers refuse certificates that are not logged. So Kadé can search the logs (for example on crt.sh) for every certificate ever issued for kade.lk, and spot one it did not request. Attackers use the same logs to discover new subdomains, so do not rely on a secret-sounding name like admin-7f3.kade.lk to hide anything.

Common certificate errors

#Browser saysCauseFix
1NET::ERR_CERT_DATE_INVALIDExpired, or the client's clock is wrongAutomate renewal; check the device clock
2NET::ERR_CERT_COMMON_NAME_INVALIDThe name is not in the SAN listAdd the name (e.g. www) to the certificate
3NET::ERR_CERT_AUTHORITY_INVALIDSelf-signed, or a CA the client does not trustUse a public CA; for internal services, install your own root on your own machines
4Works in Chrome, fails in curl or an Android appThe server does not send the intermediate (missing chain)Serve the full chain file, not just the leaf
5Every site shows the company's name as issuerA corporate proxy decrypts traffic with its own root installed on work laptops (TLS inspection)Expected on managed devices; apps with pinned certificates break there

TLS in the Kadé setup

#Where TLS endsCertificateNotes
1Today: on kade-api itselfFrom Let's Encrypt, renewed by a cron job on the VMThe private key lives on the VM; Node does the TLS work
2Later: at the Google load balancerGoogle-managed, auto-renewed"TLS termination" at the edge. The load balancer → kade-api hop runs inside Google's network, as HTTP or re-encrypted HTTPS.
3If Cloudflare sits in frontCloudflare's edge certificate + an origin certificateUse "Full (strict)": Cloudflare also checks the origin's certificate. "Flexible" sends the second hop unencrypted.
4kade-api → PayGatePayGate's certificate, plus optionally Kadé's own client certificateMutual TLS (mTLS): both sides show certificates. Common for server-to-server APIs.
One more header: Strict-Transport-Security: max-age=31536000 (HSTS) tells browsers to use HTTPS for kade.lk for a year, even if someone types http://. It closes the gap where the very first plain-HTTP request could be intercepted before the redirect.

Summary

#IdeaIn one lineNew terms
1-2HTTPSHTTP inside TLS, on top of TCP; IPs, ports and SNI stay visibleTLS, HTTPS, TLS record
3GuaranteesConfidentiality, integrity, authenticationAEAD
4-5Crypto kindsSymmetric: fast, one shared key. Asymmetric: key pairs, slow; signatures and key exchange.public/private key, signature
6-7HybridECDHE agrees on a secret; the certificate key signs; AES/ChaCha20 protects the dataDiffie-Hellman, ECDHE, HKDF
8HandshakeClientHello, ServerHello, Certificate, CertificateVerify, Finished: 1 RTTcipher suite, key share, ALPN
9Forward secrecyEphemeral keys: a stolen private key cannot open old recordingsforward secrecy
10TimelineTCP + TLS 1.3 + HTTP = 3 RTT; QUIC 2; 0-RTT or reuse 10-RTT
11-12CertificatesX.509: SAN names, issuer, dates, key; chain to a trusted root; SNI picks the certificateX.509, SAN, trust store, intermediate, SNI
14-16LifecycleACME challenges, DV/wildcard, short lifetimes, revocation, CT logsACME, CSR, OCSP, CT
17-18PracticeCommon errors; where TLS terminates; mTLS; HSTSTLS termination, mTLS, HSTS

Try it yourself

A full TLS handshake

  • What to look for: The certificate chain (depth 0, 1, 2), Protocol: TLSv1.3, the cipher.
  • From section: 8. The TLS 1.3 handshake
openssl s_client -connect example.com:443 -servername example.com

The certificate's main fields

openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | openssl x509 -noout -subject -issuer -dates -ext subjectAltName

Where the time goes

curl -o /dev/null -s -w 'tcp %{time_connect} tls %{time_appconnect} first byte %{time_starttransfer}\n' https://example.com

TLS version, ALPN result, certificate

curl -v --tlsv1.3 https://example.com 2>&1 | grep -i -E 'SSL connection|ALPN|subject|issuer'

Every certificate issued for it

  • Steps: Search your domain at crt.sh
  • What to look for: Issuers and dates you recognise, and nothing you do not.
  • From section: 16. Certificate Transparency
crt.sh

Certificates on GCP load balancers

gcloud compute ssl-certificates list

Spotted a mistake, or something unclear? Suggest an edit on GitHub