| 1 | /* |
| 2 | Copyright 2019 The Kubernetes 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 util |
| 18 | |
| 19 | import ( |
| 20 | "crypto/tls" |
| 21 | "crypto/x509" |
| 22 | "fmt" |
| 23 | "os" |
| 24 | "path/filepath" |
| 25 | ) |
| 26 | |
| 27 | // getCACertPool loads CA certificates to pool |
| 28 | func getCACertPool(caFile string) (*x509.CertPool, error) { |
| 29 | certPool := x509.NewCertPool() |
| 30 | caCert, err := os.ReadFile(filepath.Clean(caFile)) |
| 31 | if err != nil { |
| 32 | return nil, fmt.Errorf("failed to read CA cert %s: %v", caFile, err) |
| 33 | } |
| 34 | ok := certPool.AppendCertsFromPEM(caCert) |
| 35 | if !ok { |
| 36 | return nil, fmt.Errorf("failed to append CA cert to the cert pool") |
| 37 | } |
| 38 | return certPool, nil |
| 39 | } |
| 40 | |
| 41 | // GetClientTLSConfig returns tlsConfig based on x509 certs |
| 42 | func GetClientTLSConfig(caFile, certFile, keyFile, serverName string, protos []string) (*tls.Config, error) { |
| 43 | certPool, err := getCACertPool(caFile) |
| 44 | if err != nil { |
| 45 | return nil, err |
| 46 | } |
| 47 | |
| 48 | tlsConfig := &tls.Config{ |
| 49 | RootCAs: certPool, |
| 50 | MinVersion: tls.VersionTLS12, |
| 51 | } |
| 52 | if len(protos) != 0 { |
| 53 | tlsConfig.NextProtos = protos |
| 54 | } |
| 55 | if certFile == "" && keyFile == "" { |
| 56 | // return TLS config based on CA only |
| 57 | return tlsConfig, nil |
| 58 | } |
| 59 | |
| 60 | cert, err := tls.LoadX509KeyPair(certFile, keyFile) |
| 61 | if err != nil { |
| 62 | return nil, fmt.Errorf("failed to load X509 key pair %s and %s: %v", certFile, keyFile, err) |
| 63 | } |
| 64 | |
| 65 | tlsConfig.ServerName = serverName |
| 66 | tlsConfig.Certificates = []tls.Certificate{cert} |
| 67 | return tlsConfig, nil |
| 68 | } |