Service Mesh — Istio & Linkerd›05 · Inside the sidecar & the mTLS handshake

Lesson 05 of 9 · Modules

Inside the sidecar & the mTLS handshake

What really happens between two meshed pods. How the sidecar gets into a pod (the mutating admission webhook), what runs inside istio-proxy, where the SPIFFE ID and trust domain come from, who manages the certificates, and the mutual TLS handshake message by message: what is sent, what each side checks, and why each common attack fails.

Advanced
Key wordssidecar injectionmutating admission webhookvalidating admissionAdmissionReviewJSON patchistio-proxypilot-agentEnvoyistio-initiptablesUID 1337SDSTLS 1.3 handshakemutual TLSECDHECertificateVerifysecure namingforward secrecytrust domaincluster.localistio-ca-root-certcacertsistio-csr

The previous lesson covered what mesh identity is. This one opens the box: how the proxy gets into the pod, what runs inside it, and exactly what the two proxies say to each other when one pod calls another.

How the sidecar gets in: the mutating admission webhook

Every request to the API server passes through a fixed pipeline before the object is stored:

kubectl apply ─► API server
                   │ 1. Authentication      who are you?
                   │ 2. Authorization       are you allowed? (RBAC)
                   │ 3. MUTATING admission  may CHANGE the object   ◄── Istio's injector
                   │ 4. Schema validation   is it still a valid Pod?
                   │ 5. VALIDATING admission may only ACCEPT or REJECT
                   ▼ 6. Stored in etcd ─► scheduler ─► kubelet runs it
Mutating Validating
Can change the object? Yes: add, edit or remove fields No
Can reject? Yes Yes
Runs First After all mutations, so it sees the final object
Examples Add a sidecar, default labels, resource limits Reject untrusted images, privileged pods

A webhook means the API server makes an HTTPS call to a service you run (here, istiod) and waits for the answer. For Istio:

  1. A pod is created in a namespace labelled istio-injection=enabled.
  2. The MutatingWebhookConfiguration named istio-sidecar-injector matches, and the API server sends istiod an AdmissionReview containing the pod.
  3. istiod replies allowed: true with a JSON Patch:
[
  { "op": "add", "path": "/spec/initContainers/-", "value": { "name": "istio-init" } },
  { "op": "add", "path": "/spec/containers/-",     "value": { "name": "istio-proxy" } },
  { "op": "add", "path": "/spec/volumes/-",        "value": { "name": "istio-token" } }
]
  1. The API server applies the patch, validates the result, and stores a pod with two containers.
$ kubectl -n demo get deploy sleep -o jsonpath='{.spec.template.spec.containers[*].name}{"\n"}'
sleep
$ kubectl -n demo get pod -l app=sleep -o jsonpath='{.items[0].spec.containers[*].name}{"\n"}'
sleep istio-proxy

What you asked for has one container; what was stored has two. That difference is the mutation. Injection only happens on CREATE, which is why existing pods need a rollout restart.

At the post office, the first clerk adds a barcode sticker and a customs form to your parcel (mutating). The second clerk only checks it and says "accepted" or "too heavy" (validating). Then it ships. You handed over a small parcel; what ships has extra things on it.

Webhooks can stop a cluster

With failurePolicy: Fail, a webhook that is down means no pods can be created in the namespaces it matches. Run it highly available, give it a short timeoutSeconds, exclude system namespaces with a namespaceSelector, make it idempotent (it may be called again), and restrict who can edit webhook configurations: a mutating webhook can inject anything into every pod.

What runs inside the istio-proxy container

One container (image istio/proxyv2), two programs:

┌──────────── Pod: sleep ─────────────────────────────────────────────────────┐
│ sleep (your app)        sends plain HTTP; knows nothing about certificates  │
│ istio-init (exited)     set iptables: all traffic in/out → Envoy,           │
│                         except traffic from UID 1337                        │
│ ┌──────── istio-proxy (runs as UID 1337) ─────────────────────────────────┐ │
│ │ pilot-agent  starts and watches Envoy; makes the private key; sends the │ │
│ │              CSR + ServiceAccount token to istiod; renews the cert;     │ │
│ │              hands it to Envoy over SDS (local Unix socket)             │ │
│ │ envoy        15001 outbound · 15006 inbound · 15000 admin (localhost)   │ │
│ │              15090 stats · does the mTLS handshake, policy, retries     │ │
│ │ files        /var/run/secrets/tokens/istio-token  (ServiceAccount JWT)  │ │
│ │              /var/run/secrets/istio/root-cert.pem (trusted root)        │ │
│ │ in memory    the workload certificate and private key (not on disk)     │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘

Why UID 1337? The iptables rules send every packet to Envoy except packets from UID 1337. Without that exception, Envoy's own outgoing traffic would be redirected back into Envoy forever. With the Istio CNI plugin, the same rules are set by the CNI instead of the istio-init container.

$ kubectl -n demo exec deploy/sleep -c istio-proxy -- id
uid=1337(istio-proxy) gid=1337(istio-proxy) groups=1337(istio-proxy)
$ kubectl -n demo exec deploy/sleep -c istio-proxy -- pilot-agent request GET listeners

pilot-agent request forwards to Envoy's admin API on localhost:15000, which is never exposed outside the pod.

Where the identity string comes from

spiffe://cluster.local/ns/demo/sa/sleep
         └─ trust domain ─┘└ namespace ┘└ service account ┘

It looks like a URL, but it is a name, not an address: it is written in the certificate's SAN as a URI: entry and compared during the handshake. Nothing ever looks it up.

Kubernetes DNS name SPIFFE trust domain
Example httpbin.demo.svc.cluster.local spiffe://cluster.local/ns/demo/sa/httpbin
Is An address An identity
Used by CoreDNS, to return a Service IP Envoy, to verify a peer
Configured in kubelet clusterDomain, CoreDNS Istio meshConfig.trustDomain
Resolved over the network? Yes Never

Istio's default trust domain is cluster.local to match Kubernetes, but they are separate settings. Every cluster left on the default calls itself cluster.local, so give each environment its own trust domain (for example prod.example.com).

The namespace and service account come from the pod's projected ServiceAccount token: istiod checks it with a TokenReview, so the pod cannot choose its own identity.

Who manages the certificates

          Root CA  (self-signed by istiod by default, or your PKI in production)
             │
             ▼
   istiod (mesh CA) ── signs 24h workload certificates
     ▲         │
 CSR + token   └─► root cert copied to ConfigMap istio-ca-root-cert in every namespace
     │
 pilot-agent (each pod) ──SDS──► Envoy      renews at about half the lifetime
CA mode How Use for
Default self-signed istiod generates a root on first start (Secret istio-ca-secret) Labs
Plug-in CA An intermediate from your company root in Secret cacerts (ca-cert.pem, ca-key.pem, root-cert.pem, cert-chain.pem), created before install Production, multi-cluster (shared root)
External CA cert-manager istio-csr signs via Vault, a cloud private CA or your PKI CA key kept outside the cluster

There is no revocation list for workload certificates: the 24-hour lifetime is the revocation strategy. The real risk moves to the CA: a root or intermediate that expires breaks the whole mesh at once, and a stolen CA key can mint any identity.

What each proxy holds before connecting

Item Secret? Comes from
Its own certificate: public key + SPIFFE ID, signed by istiod No, shown to everyone istiod
Its own private key Yes, never sent anywhere Generated inside the pod
The root certificate No ConfigMap istio-ca-root-cert

One rule underlies everything below: a signature made with a private key can be checked by anyone with the matching public key, but only the key's owner can make it.

The mutual TLS handshake, step by step

sleep's Envoy (client) calls httpbin's Envoy (server). TLS 1.3:

sleep's Envoy                                            httpbin's Envoy
   │ ① ClientHello: random, ciphers, key share  ─────────────► │
   │ ◄──────────────  ② ServerHello: random, cipher, key share │
   │          ══ both sides compute the same secret ══         │
   │ ◄── ③ Certificate(httpbin) + CertificateVerify            │  encrypted
   │       + CertificateRequest + Finished ─────────────────── │  from here
   │ ④ check: CA ✓ dates ✓ private key ✓ identity ✓            │
   │ ── ⑤ Certificate(sleep) + CertificateVerify + Finished ─► │
   │                         ⑥ check: CA ✓ dates ✓ private key ✓
   │                         ⑦ AuthorizationPolicy: demo/sleep allowed?
   │ ◄══════════════ ⑧ encrypted HTTP both ways ═════════════► │

⓪ Before: the app sends plain HTTP; iptables hands it to its own Envoy. From istiod's configuration Envoy knows the destination is in the mesh and which identity should serve it: spiffe://cluster.local/ns/demo/sa/httpbin.

① ClientHello (in the clear): a fresh random number, supported ciphers, and a key share: the public half of a one-time Diffie-Hellman (ECDHE) key pair made just for this connection. ALPN marks it as Istio mTLS.

② ServerHello: the server's random, chosen cipher, and its own key share. Each side combines its private half with the other's public half and gets the same secret. A listener saw both public halves and still cannot compute it. Everything after this point is encrypted, including the certificates.

③ The server proves who it is:

  • Certificate: spiffe://cluster.local/ns/demo/sa/httpbin, signed by istiod.
  • CertificateVerify: a signature over the whole handshake so far (both randoms, both key shares, the certificate), made with the server's private key.
  • CertificateRequest: "now show me yours". This line is what makes it mutual.
  • Finished: a keyed checksum of the conversation.

④ The client checks the server:

Check How Stops
Signed by a trusted CA? Verify istiod's signature using the root Forged certificates
Still valid? notBefore / notAfter Expired certificates
Holds the private key? Verify CertificateVerify with the public key in the certificate A copied certificate without its key
The right service? SAN equals the identity expected for httpbin.demo (secure naming) Another mesh pod pretending to be httpbin

⑤ The client proves who it is: its own Certificate (…/sa/sleep), CertificateVerify with its private key, and Finished. A pod without a sidecar has no certificate, so under STRICT the handshake cannot complete.

⑥ The server checks the client in the same way and now knows, cryptographically, that the caller is demo/sleep. Authentication is done.

⑦ Authorization: the server's Envoy evaluates AuthorizationPolicy for that identity: allowed, or 403 RBAC: access denied. It also adds an X-Forwarded-Client-Cert header so the application can see the verified caller.

⑧ Data: every request is encrypted and integrity-protected (for example AES-GCM) with keys derived from the secret in ②. The connection is reused for many requests, so the handshake is not repeated per call.

Two spies meet in a café. First they do a paint-mixing trick: each mixes a secret colour into a shared public colour and swaps the pots; both end up with the same final colour, and someone watching cannot recreate it. Then each shows a passport from the same government and signs today's conversation in front of the other, which a photocopied passport cannot do. The doorman checks the guest list. After that, they talk in a code only the two of them know.

Why the common attacks fail

The attacker tries… It fails because… Step
Reading the traffic Only public key shares are visible; the secret cannot be computed ②, ⑧
Making their own certificate for sa/httpbin Not signed by the mesh CA: the chain check fails ④, ⑥
Copying a real certificate Cannot produce CertificateVerify without the private key ④, ⑥
Replaying a recorded handshake Fresh randoms every time; the old signature no longer matches ①–③
Sitting in the middle, swapping key shares The signatures cover the transcript, key shares included ③, ⑤
A real mesh pod with the wrong identity Secure naming (client) and AuthorizationPolicy (server) ④, ⑦
Recording now, stealing a key later Forward secrecy: session keys came from one-time key shares ②
Using an old certificate Date check, and certificates only live about 24 hours ④, ⑥

Watch it in a cluster

Envoy counts handshakes and verification failures:

$ kubectl -n demo exec deploy/httpbin -c istio-proxy -- pilot-agent request GET stats \
    | grep -E 'ssl\.(handshake|connection_error|fail_verify)'
Stat Means
ssl.handshake Successful handshakes
ssl.connection_error Handshakes that failed
ssl.fail_verify_no_cert The peer sent no certificate
ssl.fail_verify_error The certificate did not verify (wrong CA, expired)
ssl.fail_verify_san Valid certificate, unexpected identity

Exact stat names vary slightly between Envoy versions; the grep catches the usual ones.

Try it: see each layer

  1. On a meshed namespace, compare the containers in a Deployment's template with those in its running pod, then read the istio-sidecar-injector webhook's namespaceSelector.
  2. Exec into istio-proxy: check id, list /var/run/secrets/tokens and /var/run/secrets/istio, and list Envoy's listeners.
  3. Find the trust domain in the istio ConfigMap, then find the same string in a workload certificate's SAN with pilot-agent request GET certs.
  4. Note the ssl.handshake counter on a server pod, make a few calls from a meshed client, and read it again.
  5. With STRICT enabled, call from an un-meshed pod and find the failure in the stats.

Going deeper

  • Ambient mode moves the handshake out of the pod: the per-node ztunnel holds certificates for the pods on its node and carries traffic in mTLS (HBONE) tunnels; L7 policy moves to optional waypoint proxies.
  • Root rotation without downtime: trust both old and new roots in the bundle, reissue workload certificates from the new CA, then remove the old root.
  • Treat webhook configurations, create pods RBAC and the CA key as part of the mesh's attack surface: each one lets someone obtain or mint identities.

Recap

  • The sidecar arrives through a mutating admission webhook that patches pods at creation.
  • istio-proxy = pilot-agent (key, CSR, rotation, SDS) + Envoy (traffic, handshake, policy), running as UID 1337 behind iptables redirection.
  • The SPIFFE ID's trust domain is a name, not DNS; namespace and service account come from a TokenReview-verified token.
  • In the handshake, ECDHE creates the shared secret, certificates say who each side is, CertificateVerify proves the private key, secure naming checks the expected identity, and AuthorizationPolicy decides access.
  • Workload certificates are short-lived; protect and monitor the CA.

This site is a public version of my personal engineering knowledge hub. It intentionally excludes confidential company information and internal operational details.