跳到主要内容

Go x509: certificate relies on legacy Common Name field — Causes, Fixes, and Verification

1. What the Error Actually Means

When a Go program verifies a TLS peer, it compares the hostname it dialed against the certificate’s subjectAltName (SAN) extension. If the certificate carries no SAN at all, Go refuses to fall back to the legacy Common Name (CN) field and fails the handshake:

x509: certificate relies on legacy Common Name field, use SANs instead

Wrapped by net/http on Go 1.20+ the same failure reads:

Get "https://a.internal/health": tls: failed to verify certificate: x509: certificate relies on legacy Common Name field, use SANs instead

The confusing part: the CN value is irrelevant. The handshake fails even when CN=a.internal and you dialed a.internal. The presence of a CN without a SAN is the error. The same certificate often works fine in curl or an older Java client, which is why these failures look like they appear out of nowhere after a toolchain upgrade.

2. Why Go 1.15+ Rejects CN-Only Certificates

Using CN as an identity source was deprecated by RFC 6125 and the CA/Browser Forum Baseline Requirements years ago. Clients followed in stages:

  • Chrome 58 (2017) — first mainstream client to hard-fail on certificates without SAN.
  • Go 1.15 (Aug 2020) — SAN became mandatory for verification. An escape hatch existed: GODEBUG=x509ignoreCN=0.
  • Go 1.17 (Aug 2021) — the escape hatch was removed. There is no environment variable, build tag, or tls.Config field that restores CN fallback.

The check lives in crypto/x509 hostname verification, so it applies to every Go TLS consumer: net/http, gRPC, database drivers, Kubernetes clients, and your own tls.Dial calls.

Where it typically bites:

  • Internal tooling that generated self-signed certificates with openssl req -new -subj "/CN=host" and no req_extensions.
  • Appliances and vendor images shipping a certificate created years ago.
  • mTLS setups where the client certificate is CN-only — the server side then fails with the identical message.
  • An internal signing step that drops CSR extensions (see §4.2).

3. Diagnose: Confirm Your Certificate Has No SAN

Start with the certificate file itself:

openssl x509 -in server.crt -noout -subject -ext subjectAltName

Healthy output:

subject=CN = a.internal
X509v3 Subject Alternative Name:
    DNS:a.internal, DNS:localhost, IP Address:127.0.0.1

Broken output — no extensions on the certificate at all:

subject=CN = a.internal
No extensions in certificate

A version-proof alternative that also works on OpenSSL 1.0.2:

openssl x509 -in server.crt -noout -text | grep -A1 "Subject Alternative Name"

If that prints nothing, there is no SAN. If it prints DNS:..., the SAN exists and your problem is elsewhere — jump to §7.

Next, confirm you are looking at the certificate the endpoint actually serves, not just the file on disk:

openssl s_client -connect a.internal:443 -servername a.internal </dev/null 2>/dev/null 
  | openssl x509 -noout -subject -ext subjectAltName

And from Go, to see exactly what the runtime sees:

package main

import (
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"os"
)

func main() {
	raw, err := os.ReadFile("server.crt")
	if err != nil {
		panic(err)
	}
	block, _ := pem.Decode(raw)
	cert, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		panic(err)
	}
	fmt.Printf("CN=%q DNSNames=%v IPs=%v Emails=%v URIs=%vn",
		cert.Subject.CommonName, cert.DNSNames, cert.IPAddresses,
		cert.EmailAddresses, cert.URIs)
}

Empty DNSNames and IPAddresses confirms the diagnosis.

4. Fix: Reissue the Certificate with a SAN

You cannot add a SAN to an existing certificate. Reissue or re-sign it. The CN can stay — it is harmless and some legacy dashboards still display it — but it carries no authority any more. Note also that CN is capped at 64 characters, which is another reason long service names belong in SAN.

4.1 Self-signed certificate in one command (OpenSSL 1.1.1+)

openssl req -x509 -newkey rsa:2048 -nodes -days 397 -sha256 
  -keyout a.key -out a.crt 
  -subj "/CN=a.internal" 
  -addext "subjectAltName=DNS:a.internal,DNS:localhost,IP:127.0.0.1"

4.2 CSR with SAN, then sign with your internal CA

openssl req -new -newkey rsa:2048 -nodes -sha256 
  -keyout a.key -out a.csr 
  -subj "/CN=a.internal" 
  -addext "subjectAltName=DNS:a.internal,DNS:a.internal.svc.cluster.local,DNS:localhost,IP:10.0.0.5"

Verify the CSR before signing, because openssl x509 -req silently drops extensions it is not told to copy:

openssl req -in a.csr -noout -text | grep -A2 "Subject Alternative Name"

Then sign, passing the SAN through explicitly with -extfile:

printf '%sn' 
  'subjectAltName=DNS:a.internal,DNS:a.internal.svc.cluster.local,DNS:localhost,IP:10.0.0.5' 
  'basicConstraints=critical,CA:FALSE' 
  'keyUsage=critical,digitalSignature,keyEncipherment' 
  'extendedKeyUsage=serverAuth' > san.ext

openssl x509 -req -in a.csr -CA ca.crt -CAkey ca.key -CAcreateserial 
  -out a.crt -days 397 -sha256 -extfile san.ext

This is the single most common way people “fix” the error and still get it: the CSR had SAN, the signed certificate does not, because -extfile was omitted. Always re-check the issued certificate with the commands in §5.

4.3 OpenSSL older than 1.1.1 (no -addext)

On 1.0.2 the command above fails with req: Unknown option addext. Use a config file instead:

cat > san.cnf <<'EOF'
[req]
distinguished_name = dn
req_extensions = v3_req
prompt = no

[dn]
CN = a.internal

[v3_req]
subjectAltName = @alt_names

[alt_names]
DNS.1 = a.internal
DNS.2 = a.internal.svc.cluster.local
DNS.3 = localhost
IP.1  = 10.0.0.5
IP.2  = 127.0.0.1
EOF

openssl req -new -newkey rsa:2048 -nodes -sha256 
  -keyout a.key -out a.csr -config san.cnf

When signing via the config-file route, add -extensions v3_req -extfile san.cnf to the openssl x509 -req call.

4.4 Production and internal-PKI certificates

  • Reissue through your CA. Modern public CAs (Let’s Encrypt, DigiCert, and the rest) always populate SAN and ignore CN; with ACME the SAN set is simply the identifiers in the order.
  • With cert-manager, the SAN set comes only from what you list — nothing is inferred from the CN:
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: a-internal
  namespace: default
spec:
  secretName: a-internal-tls
  dnsNames:
    - a.internal
    - a.internal.svc.cluster.local
  ipAddresses:
    - 10.0.0.5
  issuerRef:
    name: internal-ca
    kind: ClusterIssuer

If your PKI is Microsoft AD CS or HashiCorp Vault, confirm the certificate template or role actually includes the SAN entries; a template that only fills CN reproduces the bug on every renewal.

5. Verify the New Certificate Before You Deploy

# 1. SAN present and complete
openssl x509 -in a.crt -noout -subject -ext subjectAltName

# 2. Chain validates against your CA for a specific hostname
openssl verify -CAfile ca.crt -verify_hostname a.internal a.crt

# 3. Private key matches the certificate
openssl x509 -in a.crt -noout -pubkey | openssl sha256
openssl pkey -in a.key -pubout | openssl sha256

# 4. What the running server actually serves
openssl s_client -connect a.internal:443 -servername a.internal </dev/null 2>/dev/null 
  | openssl x509 -noout -ext subjectAltName

Then exercise the exact code path your application uses:

package main

import (
	"crypto/tls"
	"fmt"
	"os"
)

func main() {
	conn, err := tls.Dial("tcp", "a.internal:443", &tls.Config{
		ServerName: "a.internal",
		MinVersion: tls.VersionTLS12,
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, "handshake failed:", err)
		os.Exit(1)
	}
	defer conn.Close()
	fmt.Println("OK:", conn.ConnectionState().PeerCertificates[0].DNSNames)
}

Which SAN entry you need depends on how clients address the service:

Access pattern Required SAN entry Common mistake
https://a.internal DNS:a.internal listing it only in CN
https://10.0.0.5 IP:10.0.0.5 DNS:10.0.0.5 — never matches
https://[fd00::5] IP:fd00::5 including the brackets in the value
https://api.a.internal via wildcard DNS:*.a.internal expecting it to cover a.internal or x.y.a.internal
mTLS client identity DNS: entry plus extendedKeyUsage=clientAuth a clientAuth-less client certificate

6. Comparison: Which Generation Method Actually Writes SANs

Method Writes SAN? OpenSSL Use when
openssl req -new ... -addext "subjectAltName=..." Yes 1.1.1+ CSR for an internal CA — preferred
openssl req -x509 ... -addext Yes 1.1.1+ Self-signed dev/test certificates
openssl req -config san.cnf with req_extensions Yes All Legacy hosts, scripted PKI
openssl x509 -req without -extfile No — CSR extensions are dropped All Never, for SAN-bearing certificates
openssl x509 -req ... -extfile san.ext Yes All Signing with an internal CA
openssl req ... -subj "/CN=host" only No All Nothing — this is the bug itself
GODEBUG=x509ignoreCN=0 n/a Go 1.15–1.16 only Removed in Go 1.17; do not depend on it
mkcert / step ca certificate / cfssl Yes n/a Local dev and automated internal PKI

7. Troubleshooting: Real Error Messages

x509: certificate relies on legacy Common Name field, use SANs instead

The certificate has no SAN at all. Reissue it (§4). Do not hunt for a Go flag — on 1.17+ there is none.

tls: failed to verify certificate: x509: certificate relies on legacy Common Name field, use SANs instead

The same failure surfaced through net/http on Go 1.20+. The prefix is cosmetic. If it only happens inside a container, check whether the container is dialing a different endpoint than your shell test — a short service name and a cluster FQDN can resolve to different backends with different certificates.

x509: cannot validate certificate for 10.0.0.5 because it doesn't contain any IP SANs

The SAN exists but holds only DNS: entries. Add IP:10.0.0.5. A DNS:10.0.0.5 entry does not satisfy an IP address check, and vice versa.

x509: certificate is valid for a.internal, not b.internal

This is the good failure mode: SAN is present but does not cover the name you dialed, and the message lists what it does cover. Add the missing name. Remember Go matches case-insensitively and wildcards cover exactly one label — *.internal matches a.internal but not a.b.internal, and never matches the bare internal.

x509: certificate signed by unknown authority right after reissuing

You replaced the leaf but not the trust store, or the new leaf is signed by a different intermediate. Inspect the served chain:

openssl s_client -connect a.internal:443 -servername a.internal -showcerts </dev/null

Confirm the server sends leaf and intermediate, not just the leaf. In containers, also confirm ca-certificates is installed — a scratch or distroless image with no roots produces x509: failed to load system roots and no roots provided.

x509: certificate specifies an incompatible key usage

SAN is fine, but extendedKeyUsage lacks serverAuth (or clientAuth for mTLS). Add it in the -extfile and re-sign.

x509: certificate has expired or is not yet valid

Unrelated to SAN but common in the same reissue cycle. Check with openssl x509 -in a.crt -noout -dates. A freshly issued certificate that reports “not yet valid” almost always means a skewed clock on the host or VM.

Other runtimes, same root cause

  • Java: java.security.cert.CertificateException: No subject alternative names present
  • Python: ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch
  • curl may still succeed — some builds fall back to CN and may use a different CA bundle. curl succeeding is not evidence that the certificate is correct.

8. Preventing Regressions in CI

Gate the build on certificate shape so a CN-only certificate can never reach an environment:

#!/usr/bin/env bash
set -euo pipefail
status=0
for crt in "$@"; do
  if ! openssl x509 -in "$crt" -noout -ext subjectAltName 2>/dev/null | grep -q 'DNS:'; then
    echo "FAIL: $crt has no DNS SAN"
    status=1
  fi
done
exit $status

Run it against every certificate in the repository and against what staging actually serves:

openssl s_client -connect staging.internal:443 -servername staging.internal </dev/null 2>/dev/null 
  | openssl x509 -outform PEM > /tmp/served.pem
./check-san.sh /tmp/served.pem

Pair it with expiry monitoring (expiry is the silent failure; missing SAN is the loud one) and a Go integration test that dials each internal service using the production tls.Config. That test catches both the certificate problem and the wrong-endpoint problem in one place.

9. FAQ

Does the Common Name field still matter at all?

Not for hostname verification in Go, Chrome, or any current runtime. Keep it populated for compatibility with old dashboards and human readers, but treat SAN as the only source of truth.

Can I just set InsecureSkipVerify: true?

It makes the error disappear by disabling all verification — chain, expiry, and hostname. It is not a fix; it converts a configuration error into a silent man-in-the-middle exposure. Restrict it to throwaway tests and never ship it.

Is GODEBUG=x509ignoreCN=0 still an option?

No. Go 1.17 removed the setting. On 1.15 and 1.16 it worked; on anything newer it is silently ignored. Downgrading Go is not a fix either — every other client is moving in the same direction.

Why did this start failing when nothing changed on my side?

Two usual causes: the Go toolchain was upgraded (1.16 to 1.17 is the classic), or the certificate was reissued by a process that does not copy SANs — typically an openssl x509 -req signing step without -extfile.

My certificate has a SAN but Go still fails. Why?

Check in order: (1) the SAN contains the exact name you dialed, with IP addresses as IP: not DNS:; (2) wildcards match exactly one label; (3) extendedKeyUsage includes serverAuth. Then confirm the process is actually serving the new certificate — stale processes and load balancers holding old certs are common.

Does this affect TLS servers too, not just clients?

Yes. A Go server configured with ClientAuth verifies client certificates the same way and emits the identical error when a client presents a CN-only certificate. mTLS rollouts frequently hit this on the client-certificate side after the server side has been fixed.

Do I need to restart the service after replacing the certificate?

Yes, unless the server reloads per handshake via tls.Config.GetCertificate reading from disk or a secret watcher. Otherwise the process keeps whatever it loaded at startup.

How long should the replacement certificate be valid?

Public CAs cap at 398 days and are moving shorter. Internal certificates can be longer, but if your tooling cannot reissue safely, that is the real problem — automate issuance rather than stretching lifetimes.