github.com/google/cloudprober@v0.11.3/common/tlsconfig/tlsconfig.go (about) 1 // Copyright 2019 The Cloudprober Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package tlsconfig implements utilities to parse TLSConfig. 16 package tlsconfig 17 18 import ( 19 "crypto/tls" 20 "crypto/x509" 21 "fmt" 22 23 "github.com/google/cloudprober/common/file" 24 configpb "github.com/google/cloudprober/common/tlsconfig/proto" 25 ) 26 27 // UpdateTLSConfig parses the provided protobuf and updates the tls.Config object. 28 func UpdateTLSConfig(tlsConfig *tls.Config, c *configpb.TLSConfig, addClientCACerts bool) error { 29 if c.GetDisableCertValidation() { 30 tlsConfig.InsecureSkipVerify = true 31 } 32 33 if c.GetCaCertFile() != "" { 34 caCert, err := file.ReadFile(c.GetCaCertFile()) 35 if err != nil { 36 return fmt.Errorf("common/tlsconfig: error reading CA cert file (%s): %v", c.GetCaCertFile(), err) 37 } 38 caCertPool := x509.NewCertPool() 39 if !caCertPool.AppendCertsFromPEM(caCert) { 40 return fmt.Errorf("error while adding CA certs from: %s", c.GetCaCertFile()) 41 } 42 43 tlsConfig.RootCAs = caCertPool 44 // Client CA certs are used by servers to authenticate clients. 45 if addClientCACerts { 46 tlsConfig.ClientCAs = caCertPool 47 } 48 } 49 50 if c.GetTlsCertFile() != "" { 51 certPEMBlock, err := file.ReadFile(c.GetTlsCertFile()) 52 if err != nil { 53 return fmt.Errorf("common/tlsconfig: error reading TLS cert file (%s): %v", c.GetTlsCertFile(), err) 54 } 55 keyPEMBlock, err := file.ReadFile(c.GetTlsKeyFile()) 56 if err != nil { 57 return fmt.Errorf("common/tlsconfig: error reading TLS key file (%s): %v", c.GetTlsKeyFile(), err) 58 } 59 60 cert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) 61 if err != nil { 62 return fmt.Errorf("common/tlsconfig: error initializing cert from cert key pair: %v", err) 63 } 64 tlsConfig.Certificates = append(tlsConfig.Certificates, cert) 65 } 66 67 if c.GetServerName() != "" { 68 tlsConfig.ServerName = c.GetServerName() 69 } 70 71 return nil 72 }