From a9497fad3ff5e9d26910183f3cf163c6d92c2dfd Mon Sep 17 00:00:00 2001 From: MohsenKasraeifar Date: Sat, 11 Jan 2025 11:21:54 +0330 Subject: [PATCH] feat(cert_pool): add AppendCertsFromFile func --- src/crypto/x509/cert_pool.go | 14 ++++++++++++++ src/crypto/x509/root_plan9.go | 3 +-- src/crypto/x509/root_unix.go | 8 ++------ 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/crypto/x509/cert_pool.go b/src/crypto/x509/cert_pool.go index e4c5694fbe4f89..c66d2b31263163 100644 --- a/src/crypto/x509/cert_pool.go +++ b/src/crypto/x509/cert_pool.go @@ -8,6 +8,7 @@ import ( "bytes" "crypto/sha256" "encoding/pem" + "os" "sync" ) @@ -210,6 +211,19 @@ func (s *CertPool) addCertFunc(rawSum224 sum224, rawSubject string, getCert func s.byName[rawSubject] = append(s.byName[rawSubject], len(s.lazyCerts)-1) } +// AppendCertsFromFile attempts to parse a series of File certificates. +// It appends any certificates found to s and reports whether any certificates +// were successfully parsed. +// If an error occurs while reading the file, an error will be returned. +func (s *CertPool) AppendCertsFromFile(path string) (bool, error) { + file, err := os.ReadFile(path) + if err != nil { + return false, err + } + + return s.AppendCertsFromPEM(file), nil +} + // AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. // It appends any certificates found to s and reports whether any certificates // were successfully parsed. diff --git a/src/crypto/x509/root_plan9.go b/src/crypto/x509/root_plan9.go index 3bd06fe50d85bf..61af94668ec1b5 100644 --- a/src/crypto/x509/root_plan9.go +++ b/src/crypto/x509/root_plan9.go @@ -23,9 +23,8 @@ func loadSystemRoots() (*CertPool, error) { roots := NewCertPool() var bestErr error for _, file := range certFiles { - data, err := os.ReadFile(file) + _, err := roots.AppendCertsFromFile(file) if err == nil { - roots.AppendCertsFromPEM(data) return roots, nil } if bestErr == nil || (os.IsNotExist(bestErr) && !os.IsNotExist(err)) { diff --git a/src/crypto/x509/root_unix.go b/src/crypto/x509/root_unix.go index c513b20169d1d9..14518a13f37096 100644 --- a/src/crypto/x509/root_unix.go +++ b/src/crypto/x509/root_unix.go @@ -39,9 +39,8 @@ func loadSystemRoots() (*CertPool, error) { var firstErr error for _, file := range files { - data, err := os.ReadFile(file) + _, err := roots.AppendCertsFromFile(file) if err == nil { - roots.AppendCertsFromPEM(data) break } if firstErr == nil && !os.IsNotExist(err) { @@ -67,10 +66,7 @@ func loadSystemRoots() (*CertPool, error) { continue } for _, fi := range fis { - data, err := os.ReadFile(directory + "/" + fi.Name()) - if err == nil { - roots.AppendCertsFromPEM(data) - } + _, err := roots.AppendCertsFromFile(directory + "/" + fi.Name()) } }