go / expert
Snippet
Isolated X.509 Certificate Chain Validation with Custom Verification Options
Standard TLS validation relies on default system environment roots, which can introduce non-deterministic security behavior. Creating an explicit x509.CertPool and passing strict x509.VerifyOptions enforces explicit trust anchors, host SAN restrictions, and key usage constraints.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package mainimport ("crypto/x509""fmt""time")func ValidateCertChain(leaf, root *x509.Certificate, dnsName string) error {roots := x509.NewCertPool()roots.AddCert(root)opts := x509.VerifyOptions{DNSName: dnsName,Roots: roots,CurrentTime: time.Now(),KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},}chains, err := leaf.Verify(opts)if err != nil {return fmt.Errorf("certificate verification failed: %w", err)}fmt.Printf("Verified %d valid trust chain(s)\n", len(chains))return nil}
Breakdown
1
chains, err := leaf.Verify(opts)
Performs full certificate graph path validation against explicit root anchors, DNS names, and validity timeframes.