From 8a65f7104ea7377cdeb4f3f15fedbc659299f659 Mon Sep 17 00:00:00 2001 From: Phil Porada Date: Tue, 21 Mar 2023 17:06:18 -0400 Subject: [PATCH] Force a new allocation for sans in NamesFromCSR (#6759) In `csr.NamesFromCSR`, there's a subtle trap when appending to a slice. We set `sans := csr.DNSNames` and then depending on the existence of a CommonName, we append to sans which could mutate the backing array in `csr.DNSNames`. Instead, we will force a new allocation meaning that `sans` has its own pointer to a distinct memory unrelated to the pointer of `csr.DNSNames`. See this blog post too: https://build-your-own.org/blog/20230316_go_full_slice/ --- csr/csr.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/csr/csr.go b/csr/csr.go index c8105166cae..3a10a91aa65 100644 --- a/csr/csr.go +++ b/csr/csr.go @@ -107,7 +107,10 @@ type names struct { // a CN, then it also attempts to promote a SAN to the CN (if any is short // enough to fit). func NamesFromCSR(csr *x509.CertificateRequest) names { - sans := csr.DNSNames + // Produce a new "sans" slice with the same memory address as csr.DNSNames + // but force a new allocation if an append happens so that we don't + // accidentally mutate the underlying csr.DNSNames array. + sans := csr.DNSNames[0:len(csr.DNSNames):len(csr.DNSNames)] if csr.Subject.CommonName != "" { sans = append(sans, csr.Subject.CommonName) }