Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add certificate verification status to x509_cert input #6143

Merged
merged 3 commits into from
Jul 22, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions plugins/inputs/x509_cert/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@ file or network connection.
# tls_ca = "/etc/telegraf/ca.pem"
# tls_cert = "/etc/telegraf/cert.pem"
# tls_key = "/etc/telegraf/key.pem"

## Use TLS but skip chain & host verification
# insecure_skip_verify = false
```


Expand All @@ -35,7 +32,10 @@ file or network connection.
- country
- province
- locality
- validation
- fields:
- validation (int)
- validation_error (string)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs updated

- expiry (int, seconds)
- age (int, seconds)
- startdate (int, seconds)
Expand All @@ -45,6 +45,8 @@ file or network connection.
### Example output

```
x509_cert,host=myhost,source=https://example.org age=1753627i,expiry=5503972i,startdate=1516092060i,enddate=1523349660i 1517845687000000000
x509_cert,host=myhost,source=/etc/ssl/certs/ssl-cert-snakeoil.pem age=7522207i,expiry=308002732i,startdate=1510323480i,enddate=1825848420i 1517845687000000000
x509_cert,common_name=ubuntu,source=/etc/ssl/certs/ssl-cert-snakeoil.pem,validation=success age=7693222i,enddate=1871249033i,expiry=307666777i,startdate=1555889033i,validation=0i 1563582256000000000
x509_cert,common_name=www.example.org,country=US,locality=Los\ Angeles,organization=Internet\ Corporation\ for\ Assigned\ Names\ and\ Numbers,organizational_unit=Technology,province=California,source=https://example.org:443,validation=fail age=20219055i,enddate=1606910400i,expiry=43328144i,startdate=1543363200i,validation=1i,validation_error="x509: certificate signed by unknown authority" 1563582256000000000
x509_cert,common_name=DigiCert\ SHA2\ Secure\ Server\ CA,country=US,organization=DigiCert\ Inc,source=https://example.org:443,validation=success age=200838255i,enddate=1678276800i,expiry=114694544i,startdate=1362744000i,validation=0i 1563582256000000000
x509_cert,common_name=DigiCert\ Global\ Root\ CA,country=US,organization=DigiCert\ Inc,organizational_unit=www.digicert.com,source=https://example.org:443,validation=success age=400465455i,enddate=1952035200i,expiry=388452944i,startdate=1163116800i,validation=0i 1563582256000000000
```
3 changes: 1 addition & 2 deletions plugins/inputs/x509_cert/dev/telegraf.conf
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
[[inputs.x509_cert]]
sources = ["https://www.influxdata.com:443"]
sources = ["https://expired.badssl.com:443", "https://wrong.host.badssl.com:443"]

[[outputs.file]]
files = ["stdout"]
71 changes: 48 additions & 23 deletions plugins/inputs/x509_cert/x509_cert.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,6 @@ const sampleConfig = `
# tls_ca = "/etc/telegraf/ca.pem"
# tls_cert = "/etc/telegraf/cert.pem"
# tls_key = "/etc/telegraf/key.pem"

## Use TLS but skip chain & host verification
# insecure_skip_verify = false
`
const description = "Reads metrics from a SSL certificate"

Expand All @@ -53,14 +50,26 @@ func (c *X509Cert) SampleConfig() string {
return sampleConfig
}

func (c *X509Cert) getCert(location string, timeout time.Duration) ([]*x509.Certificate, error) {
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\n", err.Error())
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, *tls.Config, error) {
tlsCfg, err := c.ClientConfig.TLSConfig()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would make sense to set this up once in an Init function. Since it is used in the parent function, I would have this function take the tls.Config instead of returning it.

if err != nil {
return nil, nil, err
}
if tlsCfg == nil {
tlsCfg = &tls.Config{}
}

switch u.Scheme {
Expand All @@ -70,51 +79,44 @@ func (c *X509Cert) getCert(location string, timeout time.Duration) ([]*x509.Cert
case "udp", "udp4", "udp6":
fallthrough
case "tcp", "tcp4", "tcp6":
tlsCfg, err := c.ClientConfig.TLSConfig()
if err != nil {
return nil, err
}

ipConn, err := net.DialTimeout(u.Scheme, u.Host, timeout)
if err != nil {
return nil, err
return nil, nil, err
}
defer ipConn.Close()

if tlsCfg == nil {
tlsCfg = &tls.Config{}
}
tlsCfg.ServerName = u.Hostname()
tlsCfg.InsecureSkipVerify = true
conn := tls.Client(ipConn, tlsCfg)
defer conn.Close()

hsErr := conn.Handshake()
if hsErr != nil {
return nil, hsErr
return nil, nil, hsErr
}

certs := conn.ConnectionState().PeerCertificates

return certs, nil
return certs, tlsCfg, nil
case "file":
content, err := ioutil.ReadFile(u.Path)
if err != nil {
return nil, err
return nil, nil, err
}

block, _ := pem.Decode(content)
if block == nil {
return nil, fmt.Errorf("failed to parse certificate PEM")
return nil, nil, fmt.Errorf("failed to parse certificate PEM")
}

cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
return nil, nil, err
}

return []*x509.Certificate{cert}, nil
return []*x509.Certificate{cert}, tlsCfg, nil
default:
return nil, fmt.Errorf("unsuported scheme '%s' in location %s\n", u.Scheme, location)
return nil, nil, fmt.Errorf("unsuported scheme '%s' in location %s", u.Scheme, u.String())
}
}

Expand Down Expand Up @@ -164,15 +166,38 @@ func (c *X509Cert) Gather(acc telegraf.Accumulator) error {
now := time.Now()

for _, location := range c.Sources {
certs, err := c.getCert(location, c.Timeout.Duration*time.Second)
u, err := c.locationToURL(location)
if err != nil {
acc.AddError(err)
}

certs, tlsCfg, 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 _, cert := range certs {
for i, cert := range certs {
fields := getFields(cert, now)
tags := getTags(cert.Subject, location)

opts := x509.VerifyOptions{}
if i == 0 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here would be a great place for a comment:

// The first certificate is the leaf/end-entity certificate which needs DNS
// name validation against the URL hostname.

opts.DNSName = u.Hostname()
}
if tlsCfg.RootCAs != nil {
opts.Roots = tlsCfg.RootCAs
}

_, err = cert.Verify(opts)
if err == nil {
tags["validation"] = "success"
fields["validation"] = 0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't name the tag and field with the same key since it is a bit tricky to query, instead use validation and validation_code.

I'm not totally on board with the validation key, the validation is always a success, its just that sometimes the cert is invalid. What do you think about verification=valid, verification=invalid. Sending the error is a bit of a new pattern, but I think it will work.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do like verification and verification_code

} else {
tags["validation"] = "fail"
fields["validation"] = 1
fields["validation_error"] = err.Error()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

verification_error

}

acc.AddFields("x509_cert", fields, tags)
}
}
Expand Down