-
Notifications
You must be signed in to change notification settings - Fork 1
/
certs.go
198 lines (169 loc) · 5.77 KB
/
certs.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
/*
* Copyright 2024 Johan Stenstam, [email protected]
*/
package tapir
import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"log"
"os"
"path/filepath"
"time"
"github.com/spf13/viper"
)
type Config struct {
CAFile string `validate:"existing-file-ro"`
KeyFile string `validate:"existing-file-ro"`
CertFile string `validate:"existing-file-ro"`
}
type SimpleConfig struct {
CAFile string `validate:"existing-file-ro"`
}
func loadCertPool(filename string) (*x509.CertPool, error) {
caCert, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
return caCertPool, nil
}
// Create a tls.Config for a server.
// clientAuth: tls.NoClientCert => Accept any client.
// clientAuth: tls.RequireAndVerifyClientCert => Only accept client with valid cert.
func NewServerConfig(caFile string, clientAuth tls.ClientAuthType) (*tls.Config, error) {
caCertPool, err := loadCertPool(caFile)
if err != nil {
return nil, err
}
config := &tls.Config{
ClientCAs: caCertPool,
ClientAuth: clientAuth,
NextProtos: []string{"h2", "http/1.1"},
}
return config, nil
}
func NewClientConfig(caFile, keyFile, certFile string) (*tls.Config, error) {
caCertPool, err := loadCertPool(caFile)
if err != nil {
return nil, err
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
config := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}
return config, nil
}
// NewSimpleClientConfig creates a TLS config with a common CA cert,
// specified in caFile, but without a client certificate.
func NewSimpleClientConfig(caFile string) (*tls.Config, error) {
caCertPool, err := loadCertPool(caFile)
if err != nil {
return nil, err
}
config := &tls.Config{
RootCAs: caCertPool,
}
return config, nil
}
func FetchTapirClientCert(lg *log.Logger, statusch chan<- ComponentStatusUpdate) (string, *x509.CertPool, *tls.Certificate, error) {
clientCertFile := viper.GetString("tapir.mqtt.clientcert")
if clientCertFile == "" {
return "", nil, nil, fmt.Errorf("MQTT client cert file not specified in config")
}
clientKeyFile := viper.GetString("tapir.mqtt.clientkey")
if clientKeyFile == "" {
return "", nil, nil, fmt.Errorf("MQTT client key file not specified in config")
}
cacertFile := viper.GetString("tapir.mqtt.cacert")
if cacertFile == "" {
return "", nil, nil, fmt.Errorf("MQTT CA cert file not specified in config")
}
// Setup CA cert for validating the MQTT connection
cacertFile = filepath.Clean(cacertFile)
caCert, err := os.ReadFile(cacertFile)
if err != nil {
return "", nil, nil, fmt.Errorf("failed to read CA certificate in file %s: %w", cacertFile, err)
}
caCertPool := x509.NewCertPool()
ok := caCertPool.AppendCertsFromPEM([]byte(caCert))
if !ok {
return "", nil, nil, fmt.Errorf("failed to parse CA certificate in file %s", cacertFile)
}
// Setup client cert/key for mTLS authentication
clientCert, err := tls.LoadX509KeyPair(clientCertFile, clientKeyFile)
if err != nil {
return "", nil, nil, fmt.Errorf("failed to load client certificate in file %s: %w", clientCertFile, err)
}
// Parse the certificate to get the Common Name (CN)
cert, err := x509.ParseCertificate(clientCert.Certificate[0])
if err != nil {
return "", nil, nil, fmt.Errorf("failed to parse client certificate: %w", err)
}
commonName := cert.Subject.CommonName
log.Printf("Client certificate Common Name (CN): %s", commonName)
// Check if the client certificate is expiring soon (less than a month away)
now := time.Now()
expirationDays := viper.GetInt("certs.expirationwarning")
if expirationDays == 0 {
expirationDays = 30
}
expirationWarningThreshold := now.AddDate(0, 0, expirationDays)
if clientCert.Leaf == nil {
// Parse the certificate if Leaf is not available
cert, err := x509.ParseCertificate(clientCert.Certificate[0])
if err != nil {
return "", nil, nil, fmt.Errorf("failed to parse client certificate: %w", err)
}
clientCert.Leaf = cert
}
log.Printf("*** Parsed DNS TAPIR client cert (from file %s):", clientCertFile)
for _, cert := range clientCert.Certificate {
cert, err := x509.ParseCertificate(cert)
if err != nil {
return "", nil, nil, fmt.Errorf("failed to parse client certificate: %w", err)
}
log.Printf("*** Subject: %s, Issuer: %s", cert.Subject, cert.Issuer)
}
if clientCert.Leaf.NotAfter.Before(expirationWarningThreshold) {
msg := fmt.Sprintf("Client certificate will expire on %v (< %d days away)", clientCert.Leaf.NotAfter.Format(TimeLayout), expirationDays)
lg.Printf("WARNING: %s", msg)
statusch <- ComponentStatusUpdate{
Component: "cert-status",
Status: StatusWarn,
Msg: msg,
TimeStamp: time.Now(),
}
}
// Check if any of the CA certificates are expiring soon
block, _ := pem.Decode([]byte(caCert))
if block == nil {
return "", nil, nil, fmt.Errorf("failed to decode PEM block containing the certificate")
}
// log.Printf("Parsed CA cert: %+v", block)
certs, err := x509.ParseCertificates(block.Bytes)
if err != nil {
return "", nil, nil, fmt.Errorf("failed to parse CA certificates in file %s: %w", cacertFile, err)
}
for _, caCert := range certs {
log.Printf("*** Parsed DNS TAPIR CA cert (from file %s):\n*** Issuer: %s, Subject: %s",
cacertFile, caCert.Issuer, caCert.Subject)
if caCert.NotAfter.Before(expirationWarningThreshold) {
msg := fmt.Sprintf("CA certificate with subject %s will expire on %v (< %d days away)", caCert.Subject, caCert.NotAfter.Format(TimeLayout), expirationDays)
lg.Printf("WARNING: %s", msg)
statusch <- ComponentStatusUpdate{
Component: "cert-status",
Status: StatusWarn,
Msg: msg,
TimeStamp: time.Now(),
}
}
}
return commonName, caCertPool, &clientCert, nil
}