|
| 1 | +// Copyright 2021 The Prometheus Authors |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +package main |
| 15 | + |
| 16 | +import ( |
| 17 | + "crypto/tls" |
| 18 | + "crypto/x509" |
| 19 | + "io/ioutil" |
| 20 | +) |
| 21 | + |
| 22 | +func createTLSConfig(pemFile, pemCertFile, pemPrivateKeyFile string, insecureSkipVerify bool) *tls.Config { |
| 23 | + tlsConfig := tls.Config{} |
| 24 | + if insecureSkipVerify { |
| 25 | + // pem settings are irrelevant if we're skipping verification anyway |
| 26 | + tlsConfig.InsecureSkipVerify = true |
| 27 | + } |
| 28 | + if len(pemFile) > 0 { |
| 29 | + rootCerts, err := loadCertificatesFrom(pemFile) |
| 30 | + if err != nil { |
| 31 | + log.Fatalf("Couldn't load root certificate from %s. Got %s.", pemFile, err) |
| 32 | + return nil |
| 33 | + } |
| 34 | + tlsConfig.RootCAs = rootCerts |
| 35 | + } |
| 36 | + if len(pemCertFile) > 0 && len(pemPrivateKeyFile) > 0 { |
| 37 | + // Load files once to catch configuration error early. |
| 38 | + _, err := loadPrivateKeyFrom(pemCertFile, pemPrivateKeyFile) |
| 39 | + if err != nil { |
| 40 | + log.Fatalf("Couldn't setup client authentication. Got %s.", err) |
| 41 | + return nil |
| 42 | + } |
| 43 | + // Define a function to load certificate and key lazily at TLS handshake to |
| 44 | + // ensure that the latest files are used in case they have been rotated. |
| 45 | + tlsConfig.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { |
| 46 | + return loadPrivateKeyFrom(pemCertFile, pemPrivateKeyFile) |
| 47 | + } |
| 48 | + } |
| 49 | + return &tlsConfig |
| 50 | +} |
| 51 | + |
| 52 | +func loadCertificatesFrom(pemFile string) (*x509.CertPool, error) { |
| 53 | + caCert, err := ioutil.ReadFile(pemFile) |
| 54 | + if err != nil { |
| 55 | + return nil, err |
| 56 | + } |
| 57 | + certificates := x509.NewCertPool() |
| 58 | + certificates.AppendCertsFromPEM(caCert) |
| 59 | + return certificates, nil |
| 60 | +} |
| 61 | + |
| 62 | +func loadPrivateKeyFrom(pemCertFile, pemPrivateKeyFile string) (*tls.Certificate, error) { |
| 63 | + privateKey, err := tls.LoadX509KeyPair(pemCertFile, pemPrivateKeyFile) |
| 64 | + if err != nil { |
| 65 | + return nil, err |
| 66 | + } |
| 67 | + return &privateKey, nil |
| 68 | +} |
0 commit comments