github.com/stefanmcshane/helm@v0.0.0-20221213002717-88a4a2c6e77d/internal/tlsutil/tls.go (about) 1 /* 2 Copyright The Helm Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package tlsutil 18 19 import ( 20 "crypto/tls" 21 "crypto/x509" 22 "io/ioutil" 23 24 "github.com/pkg/errors" 25 ) 26 27 // NewClientTLS returns tls.Config appropriate for client auth. 28 func NewClientTLS(certFile, keyFile, caFile string) (*tls.Config, error) { 29 config := tls.Config{} 30 31 if certFile != "" && keyFile != "" { 32 cert, err := CertFromFilePair(certFile, keyFile) 33 if err != nil { 34 return nil, err 35 } 36 config.Certificates = []tls.Certificate{*cert} 37 } 38 39 if caFile != "" { 40 cp, err := CertPoolFromFile(caFile) 41 if err != nil { 42 return nil, err 43 } 44 config.RootCAs = cp 45 } 46 47 return &config, nil 48 } 49 50 // CertPoolFromFile returns an x509.CertPool containing the certificates 51 // in the given PEM-encoded file. 52 // Returns an error if the file could not be read, a certificate could not 53 // be parsed, or if the file does not contain any certificates 54 func CertPoolFromFile(filename string) (*x509.CertPool, error) { 55 b, err := ioutil.ReadFile(filename) 56 if err != nil { 57 return nil, errors.Errorf("can't read CA file: %v", filename) 58 } 59 cp := x509.NewCertPool() 60 if !cp.AppendCertsFromPEM(b) { 61 return nil, errors.Errorf("failed to append certificates from file: %s", filename) 62 } 63 return cp, nil 64 } 65 66 // CertFromFilePair returns an tls.Certificate containing the 67 // certificates public/private key pair from a pair of given PEM-encoded files. 68 // Returns an error if the file could not be read, a certificate could not 69 // be parsed, or if the file does not contain any certificates 70 func CertFromFilePair(certFile, keyFile string) (*tls.Certificate, error) { 71 cert, err := tls.LoadX509KeyPair(certFile, keyFile) 72 if err != nil { 73 return nil, errors.Wrapf(err, "can't load key pair from cert %s and key %s", certFile, keyFile) 74 } 75 return &cert, err 76 }