forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
x509_cert.go
232 lines (195 loc) · 5.13 KB
/
x509_cert.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
// Package x509_cert reports metrics from an SSL certificate.
package x509_cert
import (
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"net"
"net/url"
"strings"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/internal"
_tls "github.com/influxdata/telegraf/internal/tls"
"github.com/influxdata/telegraf/plugins/inputs"
)
const sampleConfig = `
## List certificate sources
sources = ["/etc/ssl/certs/ssl-cert-snakeoil.pem", "tcp://example.org:443"]
## Timeout for SSL connection
# timeout = "5s"
## Optional TLS Config
# tls_ca = "/etc/telegraf/ca.pem"
# tls_cert = "/etc/telegraf/cert.pem"
# tls_key = "/etc/telegraf/key.pem"
`
const description = "Reads metrics from a SSL certificate"
// X509Cert holds the configuration of the plugin.
type X509Cert struct {
Sources []string `toml:"sources"`
Timeout internal.Duration `toml:"timeout"`
tlsCfg *tls.Config
_tls.ClientConfig
}
// Description returns description of the plugin.
func (c *X509Cert) Description() string {
return description
}
// SampleConfig returns configuration sample for the plugin.
func (c *X509Cert) SampleConfig() string {
return sampleConfig
}
func (c *X509Cert) locationToURL(location string) (*url.URL, error) {
if strings.HasPrefix(location, "/") {
location = "file://" + location
}
u, err := url.Parse(location)
if err != nil {
return nil, fmt.Errorf("failed to parse cert location - %s", err.Error())
}
return u, nil
}
func (c *X509Cert) getCert(u *url.URL, timeout time.Duration) ([]*x509.Certificate, error) {
switch u.Scheme {
case "https":
u.Scheme = "tcp"
fallthrough
case "udp", "udp4", "udp6":
fallthrough
case "tcp", "tcp4", "tcp6":
ipConn, err := net.DialTimeout(u.Scheme, u.Host, timeout)
if err != nil {
return nil, err
}
defer ipConn.Close()
c.tlsCfg.ServerName = u.Hostname()
c.tlsCfg.InsecureSkipVerify = true
conn := tls.Client(ipConn, c.tlsCfg)
defer conn.Close()
hsErr := conn.Handshake()
if hsErr != nil {
return nil, hsErr
}
certs := conn.ConnectionState().PeerCertificates
return certs, nil
case "file":
content, err := ioutil.ReadFile(u.Path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(content)
if block == nil {
return nil, fmt.Errorf("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
return []*x509.Certificate{cert}, nil
default:
return nil, fmt.Errorf("unsuported scheme '%s' in location %s", u.Scheme, u.String())
}
}
func getFields(cert *x509.Certificate, now time.Time) map[string]interface{} {
age := int(now.Sub(cert.NotBefore).Seconds())
expiry := int(cert.NotAfter.Sub(now).Seconds())
startdate := cert.NotBefore.Unix()
enddate := cert.NotAfter.Unix()
fields := map[string]interface{}{
"age": age,
"expiry": expiry,
"startdate": startdate,
"enddate": enddate,
}
return fields
}
func getTags(subject pkix.Name, location string) map[string]string {
tags := map[string]string{
"source": location,
"common_name": subject.CommonName,
}
if len(subject.Organization) > 0 {
tags["organization"] = subject.Organization[0]
}
if len(subject.OrganizationalUnit) > 0 {
tags["organizational_unit"] = subject.OrganizationalUnit[0]
}
if len(subject.Country) > 0 {
tags["country"] = subject.Country[0]
}
if len(subject.Province) > 0 {
tags["province"] = subject.Province[0]
}
if len(subject.Locality) > 0 {
tags["locality"] = subject.Locality[0]
}
return tags
}
// Gather adds metrics into the accumulator.
func (c *X509Cert) Gather(acc telegraf.Accumulator) error {
now := time.Now()
for _, location := range c.Sources {
u, err := c.locationToURL(location)
if err != nil {
acc.AddError(err)
return nil
}
certs, err := c.getCert(u, c.Timeout.Duration*time.Second)
if err != nil {
acc.AddError(fmt.Errorf("cannot get SSL cert '%s': %s", location, err.Error()))
}
for i, cert := range certs {
fields := getFields(cert, now)
tags := getTags(cert.Subject, location)
// The first certificate is the leaf/end-entity certificate which needs DNS
// name validation against the URL hostname.
opts := x509.VerifyOptions{
Intermediates: x509.NewCertPool(),
}
if i == 0 {
opts.DNSName = u.Hostname()
for j, cert := range certs {
if j != 0 {
opts.Intermediates.AddCert(cert)
}
}
}
if c.tlsCfg.RootCAs != nil {
opts.Roots = c.tlsCfg.RootCAs
}
_, err = cert.Verify(opts)
if err == nil {
tags["verification"] = "valid"
fields["verification_code"] = 0
} else {
tags["verification"] = "invalid"
fields["verification_code"] = 1
fields["verification_error"] = err.Error()
}
acc.AddFields("x509_cert", fields, tags)
}
}
return nil
}
func (c *X509Cert) Init() error {
tlsCfg, err := c.ClientConfig.TLSConfig()
if err != nil {
return err
}
if tlsCfg == nil {
tlsCfg = &tls.Config{}
}
c.tlsCfg = tlsCfg
return nil
}
func init() {
inputs.Add("x509_cert", func() telegraf.Input {
return &X509Cert{
Sources: []string{},
Timeout: internal.Duration{Duration: 5},
}
})
}