Skip to content

Commit

Permalink
Add certificate distinguished name as a tags in x509_cert input (infl…
Browse files Browse the repository at this point in the history
  • Loading branch information
onurguzel authored and Jean-Louis Dupond committed Apr 22, 2019
1 parent 43f3b99 commit beff0ab
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 4 deletions.
31 changes: 27 additions & 4 deletions plugins/inputs/x509_cert/x509_cert.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package x509_cert
import (
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
Expand Down Expand Up @@ -133,6 +134,31 @@ func getFields(cert *x509.Certificate, now time.Time) map[string]interface{} {
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()
Expand All @@ -143,12 +169,9 @@ func (c *X509Cert) Gather(acc telegraf.Accumulator) error {
return fmt.Errorf("cannot get SSL cert '%s': %s", location, err.Error())
}

tags := map[string]string{
"source": location,
}

for _, cert := range certs {
fields := getFields(cert, now)
tags := getTags(cert.Subject, location)

acc.AddFields("x509_cert", fields, tags)
}
Expand Down
50 changes: 50 additions & 0 deletions plugins/inputs/x509_cert/x509_cert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,56 @@ func TestGatherLocal(t *testing.T) {
}
}

func TestGatherChain(t *testing.T) {
cert := fmt.Sprintf("%s\n%s", pki.ReadServerCert(), pki.ReadCACert())

tests := []struct {
name string
content string
error bool
}{
{name: "chain certificate", content: cert},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
f, err := ioutil.TempFile("", "x509_cert")
if err != nil {
t.Fatal(err)
}

_, err = f.Write([]byte(test.content))
if err != nil {
t.Fatal(err)
}

err = f.Close()
if err != nil {
t.Fatal(err)
}

defer os.Remove(f.Name())

sc := X509Cert{
Sources: []string{f.Name()},
}

error := false

acc := testutil.Accumulator{}
err = sc.Gather(&acc)
if err != nil {
error = true
}

if error != test.error {
t.Errorf("%s", err)
}
})
}

}

func TestStrings(t *testing.T) {
sc := X509Cert{}

Expand Down

0 comments on commit beff0ab

Please sign in to comment.