Skip to content

Commit

Permalink
Force a new allocation for sans in NamesFromCSR (#6759)
Browse files Browse the repository at this point in the history
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/
  • Loading branch information
pgporada committed Mar 21, 2023
1 parent b2224eb commit 8a65f71
Showing 1 changed file with 4 additions and 1 deletion.
5 changes: 4 additions & 1 deletion csr/csr.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down

0 comments on commit 8a65f71

Please sign in to comment.