Implementing TLS and mTLS
1. Generating TLS Certificates
Example: Self-signed dev certs
openssl req -x509 -newkey rsa:2048 -nodes -days 365 \
-subj "/CN=localhost" -keyout server.key -out server.crt
| For Production | Use |
|---|---|
| Internal PKI | cert-manager + private CA |
| Public | Let's Encrypt via ACME |
| Service mesh | Istio/Linkerd auto-mTLS |
2. Loading Server Certificates
Example: Load cert pair
cert, err := tls.LoadX509KeyPair("server.crt", "server.key")
if err != nil { log.Fatal(err) }
3. Creating Server TLS Config
Example: Server with TLS
tlsCfg := &tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS13,
}
srv := grpc.NewServer(grpc.Creds(credentials.NewTLS(tlsCfg)))
| Field | Purpose |
|---|---|
MinVersion | TLS 1.3 recommended (2026) |
ClientCAs | CA pool for verifying clients (mTLS) |
ClientAuth | mTLS mode |
4. Creating Client TLS Config
Example: Client TLS
creds := credentials.NewTLS(&tls.Config{
ServerName: "users.internal",
MinVersion: tls.VersionTLS13,
})
conn, _ := grpc.NewClient(addr, grpc.WithTransportCredentials(creds))
5. Using System Certificate Pool
| API | Detail |
|---|---|
x509.SystemCertPool() | OS root CAs |
| Default | Used when RootCAs nil |
6. Adding Custom CA Certificates
Example: Append custom CA
pool, _ := x509.SystemCertPool()
caPEM, _ := os.ReadFile("ca.crt")
pool.AppendCertsFromPEM(caPEM)
tlsCfg := &tls.Config{RootCAs: pool}
7. Setting Server Name
| Field | Use |
|---|---|
ServerName | SNI + hostname verification |
| Mismatch | TLS handshake fails |
InsecureSkipVerify=true | Dev only — disables verification |
8. Enabling Client Certificate Verification
| ClientAuth Value | Behavior |
|---|---|
| NoClientCert | Don't request |
| RequestClientCert | Request, don't require |
| RequireAnyClientCert | Any cert |
| VerifyClientCertIfGiven | Verify if provided |
| RequireAndVerifyClientCert | Strict mTLS |
9. Implementing Mutual TLS
Example: Strict mTLS server
caPEM, _ := os.ReadFile("ca.crt")
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(caPEM)
tlsCfg := &tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: pool,
ClientAuth: tls.RequireAndVerifyClientCert,
MinVersion: tls.VersionTLS13,
}
| Client extract identity | Method |
|---|---|
| In interceptor | peer.FromContext(ctx) → creds.TLSInfo |
| CN / SAN | Read from VerifiedChains[0][0] |
10. Using Let's Encrypt Certificates
| Tool | Use |
|---|---|
| certbot | Issue + renew |
| autocert (Go) | Embedded ACME — only for HTTPS, not raw gRPC |
| cert-manager (K8s) | ACME + secret rotation |