]> go.fuhry.dev Git - runtime.git/commitdiff
[mtls] auto-discover root cert from system trust store
authorDan Fuhry <dan@fuhry.com>
Wed, 28 Oct 2026 03:49:41 +0000 (23:49 -0400)
committerDan Fuhry <dan@fuhry.com>
Wed, 28 Oct 2026 03:49:41 +0000 (23:49 -0400)
- replace hardcoded root cert path with openssl hash based lookup
- add code to mimic openssl's hashing of pkix names

Prompt:

> Give me a Golang version of x509_name_canon, accepting a pkix.Name as a parameter and returning a byte array containing the canonical encoding.
>
> [uploaded file: x509_cmp.c]

Co-Authored-By: Gemini Pro 3 <noreply@gemini.google>
mtls/certutil/BUILD.bazel
mtls/certutil/certutil.go
mtls/certutil/certutil_test.go [new file with mode: 0644]
mtls/certutil/find_root.go [new file with mode: 0644]
mtls/certutil/name_canon.go [new file with mode: 0644]
mtls/provider_file.go

index 9456348ef71831d6dd2c6f3d79de881910a4b1da..1e0b6176e51b5729ce1d2cf4f3b9c3b4d80d929c 100644 (file)
@@ -1,8 +1,20 @@
+load("@rules_go//go:def.bzl", "go_test")
 load("//bazel:go.bzl", "go_multi_library")
 
 go_multi_library(
     name = "certutil",
-    srcs = ["certutil.go"],
+    srcs = [
+        "certutil.go",
+        "find_root.go",
+        "name_canon.go",
+    ],
     importpath = "go.fuhry.dev/runtime/mtls/certutil",
     visibility = ["//visibility:public"],
+    deps = ["//utils/fsutil"],
+)
+
+go_test(
+    name = "certutil_test",
+    srcs = ["certutil_test.go"],
+    embed = [":certutil"],
 )
index c86237c485d3272e5a727136b0fad6208c970e54..08bf8ae31ffa5a5cd45137ae9ff80cbe123cb878 100644 (file)
@@ -2,8 +2,11 @@ package certutil
 
 import (
        "crypto"
+       "crypto/sha1"
        "crypto/x509"
+       "crypto/x509/pkix"
        "encoding/asn1"
+       "encoding/hex"
        "encoding/pem"
        "fmt"
        "net/url"
@@ -15,14 +18,18 @@ import (
 var oidSubjectAltName = asn1.ObjectIdentifier{2, 5, 29, 17}
 
 func LoadCertificatesFromPEM(path string) ([]*x509.Certificate, error) {
-       var pemBlock *pem.Block
-
-       certs := make([]*x509.Certificate, 0)
        contents, err := os.ReadFile(path)
        if err != nil {
                return nil, err
        }
 
+       return LoadCertificatesFromPEMBytes(contents)
+}
+
+func LoadCertificatesFromPEMBytes(contents []byte) ([]*x509.Certificate, error) {
+       var pemBlock *pem.Block
+       var certs []*x509.Certificate
+
        for {
                pemBlock, contents = pem.Decode(contents)
                if pemBlock == nil {
@@ -208,3 +215,29 @@ func ValidNow(cert *x509.Certificate) error {
 
        return nil
 }
+
+func EncodeCertificatePEM(cert *x509.Certificate) []byte {
+       pemBlock := &pem.Block{
+               Type:  "CERTIFICATE",
+               Bytes: cert.Raw,
+       }
+
+       return pem.EncodeToMemory(pemBlock)
+}
+
+func OpenSSLCertsDirectoryHash(name pkix.Name) (string, error) {
+       canon, err := X509NameCanon(name)
+       if err != nil {
+               return "", err
+       }
+       sum := sha1.Sum(canon)
+       return hex.EncodeToString([]byte{sum[3], sum[2], sum[1], sum[0]}), nil
+}
+
+func MakePool(certs []*x509.Certificate) *x509.CertPool {
+       pool := x509.NewCertPool()
+       for _, c := range certs {
+               pool.AddCert(c)
+       }
+       return pool
+}
diff --git a/mtls/certutil/certutil_test.go b/mtls/certutil/certutil_test.go
new file mode 100644 (file)
index 0000000..03278ba
--- /dev/null
@@ -0,0 +1,52 @@
+package certutil
+
+import (
+       "crypto/x509/pkix"
+       "testing"
+)
+
+func TestOpenSSLCertsDirectoryHash(t *testing.T) {
+       type testCase struct {
+               input  pkix.Name
+               expect string
+       }
+
+       testCases := []testCase{
+               {
+                       input: pkix.Name{
+                               Country:      []string{"US"},
+                               Organization: []string{"Internet Security Research Group"},
+                               CommonName:   "ISRG Root X1",
+                       },
+                       expect: "4042bcee",
+               },
+               {
+                       input: pkix.Name{
+                               Country:      []string{"US"},
+                               Organization: []string{"Internet Security Research Group"},
+                               CommonName:   "ISRG Root X2",
+                       },
+                       expect: "0b9bc432",
+               },
+               {
+                       input: pkix.Name{
+                               Country:      []string{"US"},
+                               Organization: []string{"ISRG"},
+                               CommonName:   "Root YE",
+                       },
+                       expect: "8ed85ee6",
+               },
+       }
+
+       for _, tc := range testCases {
+               t.Run(tc.input.String(), func(t *testing.T) {
+                       out, err := OpenSSLCertsDirectoryHash(tc.input)
+                       if err != nil {
+                               t.Fatalf("unexpected err: %v", err)
+                       }
+                       if out != tc.expect {
+                               t.Fatalf("expected: %q  got: %q", tc.expect, out)
+                       }
+               })
+       }
+}
diff --git a/mtls/certutil/find_root.go b/mtls/certutil/find_root.go
new file mode 100644 (file)
index 0000000..db49e78
--- /dev/null
@@ -0,0 +1,72 @@
+package certutil
+
+import (
+       "bytes"
+       "crypto/x509"
+       "errors"
+       "fmt"
+       "os"
+       "path"
+       "slices"
+
+       "go.fuhry.dev/runtime/utils/fsutil"
+)
+
+const (
+       systemTrustedRootsPath = "/etc/ssl/certs"
+)
+
+// FindRootInSystemTrustStore searches the system trust store for root certificates matching the
+// provided certificate chain.
+func FindRootInSystemTrustStore(chain []*x509.Certificate) (string, error) {
+       leaf, chain := SplitChain(chain)
+
+       systemPool, err := x509.SystemCertPool()
+       if err != nil {
+               return "", err
+       }
+
+       vopts := x509.VerifyOptions{
+               Roots:         systemPool,
+               Intermediates: MakePool(chain),
+       }
+
+       chains, err := leaf.Verify(vopts)
+       if err != nil {
+               return "", err
+       }
+
+       slices.SortFunc(chains, func(i, j []*x509.Certificate) int {
+               return len(j) - len(i)
+       })
+
+       for _, chain := range chains {
+               root := chain[len(chain)-1]
+               hash, err := OpenSSLCertsDirectoryHash(root.Subject)
+               if err != nil {
+                       continue
+               }
+
+               for i := 0; ; i++ {
+                       rootPath := path.Join(systemTrustedRootsPath, fmt.Sprintf("%s.%d", hash, i))
+                       if err := fsutil.FileExistsAndIsReadable(rootPath); err == nil {
+                               rootContents, err := LoadCertificatesFromPEM(rootPath)
+                               if err != nil {
+                                       continue
+                               }
+
+                               if len(rootContents) != 1 {
+                                       continue
+                               }
+
+                               if bytes.Equal(rootContents[0].Raw, root.Raw) {
+                                       return rootPath, nil
+                               }
+                       } else if os.IsNotExist(err) {
+                               break
+                       }
+               }
+       }
+
+       return "", errors.New("could not find any root certificate matching the provided chain")
+}
diff --git a/mtls/certutil/name_canon.go b/mtls/certutil/name_canon.go
new file mode 100644 (file)
index 0000000..5ea3b20
--- /dev/null
@@ -0,0 +1,241 @@
+package certutil
+
+// ðŸ¤– generated by Gemini
+
+import (
+       "bytes"
+       "crypto/x509/pkix"
+       "encoding/asn1"
+       "sort"
+       "unicode/utf16"
+)
+
+// Internal struct matching ASN.1 AttributeTypeAndValue for marshaling.
+type attributeTypeAndValue struct {
+       Type  asn1.ObjectIdentifier
+       Value asn1.RawValue
+}
+
+// X509NameCanon generates the OpenSSL canonical encoding of a pkix.Name structure.
+//
+// Returns a byte slice containing the canonical encoding (or an error if marshaling fails).
+// An empty pkix.Name returns an empty byte slice.
+func X509NameCanon(name pkix.Name) ([]byte, error) {
+       rdnSeq := name.ToRDNSequence()
+       if len(rdnSeq) == 0 {
+               return []byte{}, nil
+       }
+
+       var totalEntries int
+       for _, rdn := range rdnSeq {
+               totalEntries += len(rdn)
+       }
+       if totalEntries == 0 {
+               return []byte{}, nil
+       }
+
+       var result []byte
+
+       for _, rdn := range rdnSeq {
+               if len(rdn) == 0 {
+                       continue
+               }
+
+               encodedEntries := make([][]byte, 0, len(rdn))
+               for _, attr := range rdn {
+                       canonAttr, err := canonicalizeAttribute(attr)
+                       if err != nil {
+                               return nil, err
+                       }
+
+                       entryBytes, err := asn1.Marshal(canonAttr)
+                       if err != nil {
+                               return nil, err
+                       }
+                       encodedEntries = append(encodedEntries, entryBytes)
+               }
+
+               // DER Rule: Elements within multi-valued RDN SET must be sorted lexicographically
+               if len(encodedEntries) > 1 {
+                       sort.Slice(encodedEntries, func(i, j int) bool {
+                               return bytes.Compare(encodedEntries[i], encodedEntries[j]) < 0
+                       })
+               }
+
+               // Concatenate entry bytes for this RDN
+               var rdnContent []byte
+               for _, entryBytes := range encodedEntries {
+                       rdnContent = append(rdnContent, entryBytes...)
+               }
+
+               // Wrap RDN entries in an ASN.1 SET (Tag 17 / 0x31)
+               rdnSetRaw := asn1.RawValue{
+                       Class:      asn1.ClassUniversal,
+                       Tag:        asn1.TagSet,
+                       IsCompound: true,
+                       Bytes:      rdnContent,
+               }
+
+               rdnSetBytes, err := asn1.Marshal(rdnSetRaw)
+               if err != nil {
+                       return nil, err
+               }
+
+               result = append(result, rdnSetBytes...)
+       }
+
+       return result, nil
+}
+
+// canonicalizeAttribute handles ASN.1 string canonicalization for a single AttributeTypeAndValue.
+func canonicalizeAttribute(attr pkix.AttributeTypeAndValue) (attributeTypeAndValue, error) {
+       var rawVal asn1.RawValue
+
+       switch v := attr.Value.(type) {
+       case string:
+               canon := canonicalizeString(v)
+               rawVal = asn1.RawValue{
+                       Class: asn1.ClassUniversal,
+                       Tag:   asn1.TagUTF8String,
+                       Bytes: []byte(canon),
+               }
+
+       case asn1.RawValue:
+               rv := v
+               if rv.Tag == 0 && len(rv.FullBytes) > 0 {
+                       var parsedRV asn1.RawValue
+                       if _, err := asn1.Unmarshal(rv.FullBytes, &parsedRV); err == nil {
+                               rv = parsedRV
+                       }
+               }
+
+               if isCanonStringTag(rv.Tag) {
+                       str, ok := decodeToString(rv)
+                       if ok {
+                               canon := canonicalizeString(str)
+                               rawVal = asn1.RawValue{
+                                       Class: asn1.ClassUniversal,
+                                       Tag:   asn1.TagUTF8String,
+                                       Bytes: []byte(canon),
+                               }
+                       } else {
+                               rawVal = rv
+                       }
+               } else {
+                       rawVal = rv
+               }
+
+       default:
+               // Non-string types (e.g. integer, octet string) are marshaled directly as RawValue
+               data, err := asn1.Marshal(v)
+               if err != nil {
+                       return attributeTypeAndValue{}, err
+               }
+               var rv asn1.RawValue
+               if _, err := asn1.Unmarshal(data, &rv); err != nil {
+                       return attributeTypeAndValue{}, err
+               }
+               rawVal = rv
+       }
+
+       return attributeTypeAndValue{
+               Type:  attr.Type,
+               Value: rawVal,
+       }, nil
+}
+
+// canonicalizeString performs space-collapsing and lowercasing according to OpenSSL asn1_string_canon.
+func canonicalizeString(in string) string {
+       start := 0
+       for start < len(in) && isOsslSpace(in[start]) {
+               start++
+       }
+
+       end := len(in)
+       for end > start && isOsslSpace(in[end-1]) {
+               end--
+       }
+
+       if start >= end {
+               return ""
+       }
+
+       s := in[start:end]
+       var out []byte
+       out = make([]byte, 0, len(s))
+
+       i := 0
+       for i < len(s) {
+               b := s[i]
+               if b >= 0x80 {
+                       // Non-ASCII character: keep byte untouched
+                       out = append(out, b)
+                       i++
+               } else if isOsslSpace(b) {
+                       // Collapse multiple ASCII spaces into a single ' '
+                       out = append(out, ' ')
+                       for i < len(s) && isOsslSpace(s[i]) {
+                               i++
+                       }
+               } else {
+                       // ASCII character: lowercase 'A'-'Z'
+                       if b >= 'A' && b <= 'Z' {
+                               b += 'a' - 'A'
+                       }
+                       out = append(out, b)
+                       i++
+               }
+       }
+
+       return string(out)
+}
+
+// isOsslSpace matches OpenSSL's ossl_isspace (ASCII space, \t, \n, \v, \f, \r).
+func isOsslSpace(b byte) bool {
+       return b == ' ' || b == '\t' || b == '\n' || b == '\r' || b == '\f' || b == '\v'
+}
+
+// isCanonStringTag checks if tag is in ASN1_MASK_CANON.
+func isCanonStringTag(tag int) bool {
+       switch tag {
+       case asn1.TagUTF8String,
+               asn1.TagPrintableString,
+               asn1.TagT61String,
+               asn1.TagIA5String,
+               26, /* TagVisibleString */
+               28, /* TagUniversalString */
+               asn1.TagBMPString:
+               return true
+       default:
+               return false
+       }
+}
+
+// decodeToString converts canonicalizable ASN.1 string types to UTF-8 Go strings.
+func decodeToString(rv asn1.RawValue) (string, bool) {
+       if !isCanonStringTag(rv.Tag) {
+               return "", false
+       }
+       switch rv.Tag {
+       case asn1.TagBMPString:
+               if len(rv.Bytes)%2 != 0 {
+                       return string(rv.Bytes), true
+               }
+               u16 := make([]uint16, len(rv.Bytes)/2)
+               for i := 0; i < len(u16); i++ {
+                       u16[i] = uint16(rv.Bytes[2*i])<<8 | uint16(rv.Bytes[2*i+1])
+               }
+               return string(utf16.Decode(u16)), true
+       case 28: // TagUniversalString (UTF-32BE)
+               if len(rv.Bytes)%4 != 0 {
+                       return string(rv.Bytes), true
+               }
+               runes := make([]rune, len(rv.Bytes)/4)
+               for i := 0; i < len(runes); i++ {
+                       runes[i] = rune(uint32(rv.Bytes[4*i])<<24 | uint32(rv.Bytes[4*i+1])<<16 | uint32(rv.Bytes[4*i+2])<<8 | uint32(rv.Bytes[4*i+3]))
+               }
+               return string(runes), true
+       default:
+               return string(rv.Bytes), true
+       }
+}
index 90a667a528cafbc9f015ed82f57ab2623d600519..88933451fd45fdddeec20ad531e2b6ae4a05bf2e 100644 (file)
@@ -54,7 +54,8 @@ type fileBackedRoots struct {
 type fileProviderFactory struct{}
 
 const (
-       defaultMtlsRootPath = "/etc/ssl/mtls"
+       defaultMtlsRootPath    = "/etc/ssl/mtls"
+       systemTrustedRootsPath = "/etc/ssl/certs"
 )
 
 var (
@@ -262,30 +263,56 @@ func LoadUserIdentityFromFilesystem(username string) (*FileBackedCertificate, er
 }
 
 func LoadSSLCertificateFromFilesystem(certName string) (*FileBackedCertificate, error) {
+       type fileNamingConvention struct {
+               fullchain string
+               key       string
+       }
+
        certDirectory := path.Join(sslCertsBaseDir, certName)
 
        logger.V(2).Debugf("trying to load ssl cert %q from root path %q", certName, certDirectory)
 
-       leafPath := path.Join(certDirectory, "cert.pem")
-       chainPath := path.Join(certDirectory, "chain.pem")
-       keyPath := path.Join(certDirectory, "privkey.pem")
-       // FIXME!!
-       rootPath := "/etc/ssl/certs/ISRG_Root_X1.pem"
+       namingConventions := []*fileNamingConvention{
+               {"tls.crt", "tls.key"},
+               {"fullchain.pem", "privkey.pem"},
+       }
 
-       for _, file := range []string{leafPath, chainPath, keyPath, rootPath} {
-               if err := fsutil.FileExistsAndIsReadable(file); err != nil {
-                       logger.V(2).Errorf("cannot load ssl cert %q from %s: error reading file %q: %v", certName, certDirectory, file, err)
-                       return nil, err
+       for _, nc := range namingConventions {
+               leafPath := path.Join(certDirectory, nc.fullchain)
+               keyPath := path.Join(certDirectory, nc.key)
+
+               ok := true
+               for _, file := range []string{leafPath, keyPath} {
+                       if err := fsutil.FileExistsAndIsReadable(file); err != nil {
+                               ok = false
+                       }
+               }
+
+               if !ok {
+                       continue
+               }
+
+               logger.V(1).Debugf("fullchain and key found at path %q using naming convention %+v", certDirectory, nc)
+               certs, err := certutil.LoadCertificatesFromPEM(leafPath)
+               if err != nil {
+                       logger.V(1).Debugf("failed reading certs from fullchain %q: %v", leafPath, err)
+                       continue
+               }
+
+               foundRoot, err := certutil.FindRootInSystemTrustStore(certs)
+               if err == nil {
+                       logger.V(1).Debugf("found root cert at %q", foundRoot)
+                       return &FileBackedCertificate{
+                               LeafPath:          leafPath,
+                               IntermediatesPath: leafPath,
+                               PrivateKeyPath:    keyPath,
+                               RootPath:          foundRoot,
+                               obj:               NewEmptySwappableCert(),
+                       }, nil
                }
        }
 
-       return &FileBackedCertificate{
-               LeafPath:          leafPath,
-               IntermediatesPath: chainPath,
-               PrivateKeyPath:    keyPath,
-               RootPath:          rootPath,
-               obj:               NewEmptySwappableCert(),
-       }, nil
+       return nil, fmt.Errorf("cannot find TLS certificate: %q", certDirectory)
 }
 
 func (c *FileBackedCertificate) LeafCertificate() (*x509.Certificate, error) {