-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtlsprom.go
256 lines (225 loc) · 6.46 KB
/
tlsprom.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// SPDX-License-Identifier: MIT
//
// Copyright 2020 Andrew Bursavich. All rights reserved.
// Use of this source code is governed by The MIT License
// which can be found in the LICENSE file.
// Package tlsprom provides Prometheus instrumentation for TLS configuration.
package tlsprom
import (
"crypto/tls"
"crypto/x509"
"sort"
"time"
"bursavich.dev/dynamictls"
"github.com/go-logr/logr"
"github.com/prometheus/client_golang/prometheus"
)
const (
updateErrorName = "tls_config_update_error"
verifyErrorName = "tls_config_certificate_verify_error"
expirationName = "tls_config_earliest_certificate_expiration_time_seconds"
)
type config struct {
namespace string
subsystem string
usages []x509.ExtKeyUsage
log logr.Logger
}
// An Option applies optional configuration.
type Option interface {
apply(*config) error
weight() int
}
type opt struct {
fn func(*config) error
w int
}
func optionFunc(fn func(*config) error) Option {
return opt{fn: fn}
}
func weightedOptionFunc(weight int, fn func(*config) error) Option {
return opt{fn: fn, w: weight}
}
func (o opt) apply(c *config) error { return o.fn(c) }
func (o opt) weight() int { return o.w }
type byWeight []Option
func (s byWeight) Len() int { return len(s) }
func (s byWeight) Less(i, k int) bool { return s[i].weight() < s[k].weight() }
func (s byWeight) Swap(i, k int) { s[i], s[k] = s[k], s[i] }
func sortedOptions(options []Option) []Option {
if sort.IsSorted(byWeight(options)) {
return options
}
// sort a copy
options = append(make([]Option, 0, len(options)), options...)
sort.Stable(byWeight(options))
return options
}
// WithLogger returns an Option that sets the logger for errors.
func WithLogger(log logr.Logger) Option {
return optionFunc(func(c *config) error {
c.log = log
return nil
})
}
// WithHTTP returns an Option that sets the namespace to "http".
func WithHTTP() Option {
return optionFunc(func(c *config) error {
c.namespace = "http"
return nil
})
}
// WithGRPC returns an Option that sets the namespace to "grpc".
func WithGRPC() Option {
return optionFunc(func(c *config) error {
c.namespace = "grpc"
return nil
})
}
// WithClient returns an Option that sets the subsystem to "client"
// and the key usage to ClientAuth.
func WithClient() Option {
return optionFunc(func(c *config) error {
c.subsystem = "client"
c.usages = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
return nil
})
}
// WithServer returns an Option that sets the subsystem to "server"
// and the key usage to ServerAuth.
func WithServer() Option {
return optionFunc(func(c *config) error {
c.subsystem = "server"
c.usages = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}
return nil
})
}
// WithNamespace returns an Option that sets the namespace of metrics.
func WithNamespace(namespace string) Option {
return weightedOptionFunc(1, func(c *config) error {
c.namespace = namespace
return nil
})
}
// WithSubsystem returns an Option that sets the subsystem of metrics.
func WithSubsystem(subsystem string) Option {
return weightedOptionFunc(1, func(c *config) error {
c.subsystem = subsystem
return nil
})
}
// WithKeyUsages returns an Option that specifies the
// key usages for certificate verification.
func WithKeyUsages(usages ...x509.ExtKeyUsage) Option {
return weightedOptionFunc(1, func(c *config) error {
c.usages = usages
return nil
})
}
// Observer is a collection of TLS config metrics.
type Observer interface {
dynamictls.Observer
prometheus.Collector
}
type observer struct {
updateError prometheus.Gauge
verifyError prometheus.Gauge
expiration prometheus.Gauge
usages []x509.ExtKeyUsage
log logr.Logger
}
// NewObserver returns a new Observer with the given options.
func NewObserver(options ...Option) (Observer, error) {
cfg := &config{
usages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
log: logr.Discard(),
}
for _, o := range sortedOptions(options) {
if err := o.apply(cfg); err != nil {
return nil, err
}
}
o := &observer{
updateError: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: cfg.namespace,
Subsystem: cfg.subsystem,
Name: updateErrorName,
Help: "Indicates if there was an error updating the TLS configuration.",
}),
verifyError: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: cfg.namespace,
Subsystem: cfg.subsystem,
Name: verifyErrorName,
Help: "Indicates if there was an error verifying the TLS configuration's certificates and expirations.",
}),
expiration: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: cfg.namespace,
Subsystem: cfg.subsystem,
Name: expirationName,
Help: "Earliest expiration time of the TLS configuration's certificates in seconds since the Unix epoch.",
}),
usages: cfg.usages,
log: cfg.log,
}
return o, nil
}
// Describe sends the super-set of all possible descriptors of metrics
// to the provided channel and returns once the last descriptor has been sent.
func (o *observer) Describe(ch chan<- *prometheus.Desc) {
o.updateError.Describe(ch)
o.verifyError.Describe(ch)
o.expiration.Describe(ch)
}
// Collect sends each collected metric via the provided channel
// and returns once the last metric has been sent.
func (o *observer) Collect(ch chan<- prometheus.Metric) {
o.updateError.Collect(ch)
o.verifyError.Collect(ch)
o.expiration.Collect(ch)
}
func (o *observer) ObserveConfig(cfg *tls.Config) {
o.updateError.Set(0)
t, err := o.earliestExpiration(cfg)
if err != nil || t.IsZero() {
o.verifyError.Set(1)
o.expiration.Set(0)
return
}
o.verifyError.Set(0)
o.expiration.Set(float64(t.Unix()))
}
func (o *observer) ObserveReadError(err error) {
o.updateError.Set(1)
}
func (o *observer) earliestExpiration(cfg *tls.Config) (time.Time, error) {
var t time.Time
for _, cert := range cfg.Certificates {
x509Cert := cert.Leaf
if x509Cert == nil {
var err error
if x509Cert, err = x509.ParseCertificate(cert.Certificate[0]); err != nil {
o.log.Error(err, "Failed to parse TLS certificate")
return time.Time{}, err
}
}
chains, err := x509Cert.Verify(x509.VerifyOptions{
Roots: cfg.RootCAs,
KeyUsages: o.usages,
})
if err != nil {
o.log.Error(err, "Failed to validate TLS certificate")
return time.Time{}, err
}
for _, chain := range chains {
for _, cert := range chain {
if v := cert.NotAfter; t.IsZero() || v.Before(t) {
t = v
}
}
}
}
if t.IsZero() {
o.log.Error(nil, "Failed to find a certificate in the TLS config")
}
return t, nil
}