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