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

Adding x509_cert input plugin #3768

Merged
merged 14 commits into from
Jul 30, 2018
1 change: 1 addition & 0 deletions plugins/inputs/all/all.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ import (
_ "github.com/influxdata/telegraf/plugins/inputs/webhooks"
_ "github.com/influxdata/telegraf/plugins/inputs/win_perf_counters"
_ "github.com/influxdata/telegraf/plugins/inputs/win_services"
_ "github.com/influxdata/telegraf/plugins/inputs/x509_cert"
_ "github.com/influxdata/telegraf/plugins/inputs/zfs"
_ "github.com/influxdata/telegraf/plugins/inputs/zipkin"
_ "github.com/influxdata/telegraf/plugins/inputs/zookeeper"
Expand Down
45 changes: 45 additions & 0 deletions plugins/inputs/x509_cert/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# X509 Cert Input Plugin

This plugin provides information about X509 certificate accessible via local
file or network connection.


### Configuration

```toml
# Reads metrics from a SSL certificate
[[inputs.x509_cert]]
## List of local SSL files
# files = ["/etc/ssl/certs/ssl-cert-snakeoil.pem"]
## List of servers
# servers = ["tcp://example.org:443"]
## Timeout for SSL connection
# timeout = 5
## Optional TLS Config
# 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
```


### Metrics

- `x509_cert`
- tags:
- `server` (only if `servers` parameter is defined)
- `file` (only if `files` parameter is defined)
- fields:
- `expiry` (int, seconds)
- `age` (int, seconds)
- `startdate` (int, seconds)
- `enddate` (int, seconds)


### Example output

```
x509_cert,server=google.com:443,host=myhost age=1753627i,expiry=5503972i,startdate=1516092060i,enddate=1523349660i 1517845687000000000
x509_cert,host=myhost,file=/path/to/the.crt age=7522207i,expiry=308002732i,startdate=1510323480i,enddate=1825848420i 1517845687000000000
```
188 changes: 188 additions & 0 deletions plugins/inputs/x509_cert/x509_cert.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
package x509_cert

import (
"crypto/tls"
"crypto/x509"
"encoding/pem"
"errors"
Copy link
Contributor

Choose a reason for hiding this comment

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

Replace errors.New with fmt.Errorf

"fmt"
"io/ioutil"
"net"
"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 of local SSL files
# files = ["/etc/ssl/certs/ssl-cert-snakeoil.pem"]
## List of servers
# servers = ["tcp://example.org:443"]
## Timeout for SSL connection
# timeout = 5
Copy link
Contributor

Choose a reason for hiding this comment

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

Since this is an internal.Duration, it should be like timeout = "5s"

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixed.

## Optional TLS Config
# 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"

// X509Cert holds the configuration of the plugin.
type X509Cert struct {
Servers []string `toml:"servers"`
Files []string `toml:"files"`
Timeout internal.Duration `toml:"timeout"`
_tls.ClientConfig
}

// For tests
var (
closeConn bool
Copy link
Contributor

Choose a reason for hiding this comment

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

There isn't a need for test only variables in here, the same can be accomplished without them. (see this commit)

unsetCerts bool
)

// 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) getRemoteCert(server string, timeout time.Duration) (*x509.Certificate, error) {
tlsCfg, err := c.ClientConfig.TLSConfig()
if err != nil {
return nil, err
}

network := "tcp"
host_port := server
vals := strings.Split(server, "://")

if len(vals) > 1 {
network = vals[0]
host_port = vals[1]
}

ipConn, err := net.DialTimeout(network, host_port, timeout)
if err != nil {
return nil, err
}
defer ipConn.Close()

conn := tls.Client(ipConn, tlsCfg)
defer conn.Close()

if closeConn {
conn.Close()
}

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

certs := conn.ConnectionState().PeerCertificates

if unsetCerts {
certs = nil
}

if certs == nil || len(certs) < 1 {
return nil, errors.New("couldn't get remote certificate")
}

return certs[0], nil
}

func getLocalCert(filename string) (*x509.Certificate, error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}

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

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

return cert, nil
}

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())
Copy link
Contributor

Choose a reason for hiding this comment

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

Aren't these already ints?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

startdate := cert.NotBefore.Unix()
enddate := cert.NotAfter.Unix()
valid := expiry > 0
Copy link
Contributor

Choose a reason for hiding this comment

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

I think we should drop this field for now. There are various aspects of the certificate which currently we do not take into account, such as hostname and chain of trust. We can add it back in if/when we include these features.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Fixed.


fields := map[string]interface{}{
"age": age,
"expiry": expiry,
"startdate": startdate,
"enddate": enddate,
"valid": valid,
}

return fields
}

// Gather adds metrics into the accumulator.
func (c *X509Cert) Gather(acc telegraf.Accumulator) error {
now := time.Now()

for _, server := range c.Servers {
cert, err := c.getRemoteCert(server, c.Timeout.Duration*time.Second)
if err != nil {
return fmt.Errorf("cannot get remote SSL cert '%s': %s", server, err)
}

tags := map[string]string{
"server": server,
}

fields := getFields(cert, now)

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

for _, file := range c.Files {
cert, err := getLocalCert(file)
if err != nil {
return fmt.Errorf("cannot get local SSL cert '%s': %s", file, err)
}

tags := map[string]string{
"file": file,
}

fields := getFields(cert, now)

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

return nil
}

func init() {
inputs.Add("x509_cert", func() telegraf.Input {
return &X509Cert{
Files: []string{},
Servers: []string{},
Timeout: internal.Duration{Duration: 5},
}
})
}
Loading