feat: add exclude_root_certs option to x509_cert plugin (#9822)

This commit is contained in:
Jarno Huuskonen 2021-12-22 22:39:36 +02:00 committed by GitHub
parent e6cd83f1e7
commit e906698bba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 4 deletions

View File

@ -37,6 +37,9 @@ const sampleConfig = `
## example: server_name = "myhost.example.org"
# server_name = ""
## Don't include root or intermediate certificates in output
# exclude_root_certs = false
## Optional TLS Config
# tls_ca = "/etc/telegraf/ca.pem"
# tls_cert = "/etc/telegraf/cert.pem"
@ -46,10 +49,11 @@ const description = "Reads metrics from a SSL certificate"
// X509Cert holds the configuration of the plugin.
type X509Cert struct {
Sources []string `toml:"sources"`
Timeout config.Duration `toml:"timeout"`
ServerName string `toml:"server_name"`
tlsCfg *tls.Config
Sources []string `toml:"sources"`
Timeout config.Duration `toml:"timeout"`
ServerName string `toml:"server_name"`
ExcludeRootCerts bool `toml:"exclude_root_certs"`
tlsCfg *tls.Config
_tls.ClientConfig
locations []*url.URL
globpaths []*globpath.GlobPath
@ -334,6 +338,9 @@ func (c *X509Cert) Gather(acc telegraf.Accumulator) error {
}
acc.AddFields("x509_cert", fields, tags)
if c.ExcludeRootCerts {
break
}
}
}

View File

@ -219,6 +219,35 @@ func TestTags(t *testing.T) {
_, validSerialNumber := serialNumber.SetString(acc.TagValue("x509_cert", "serial_number"), 16)
require.Truef(t, validSerialNumber, "Expected a valid Hex serial number but got %s", acc.TagValue("x509_cert", "serial_number"))
require.Equal(t, big.NewInt(1), serialNumber)
// expect root/intermediate certs (more than one cert)
require.Greater(t, acc.NMetrics(), uint64(1))
}
func TestGatherExcludeRootCerts(t *testing.T) {
cert := fmt.Sprintf("%s\n%s", pki.ReadServerCert(), pki.ReadCACert())
f, err := os.CreateTemp("", "x509_cert")
require.NoError(t, err)
_, err = f.Write([]byte(cert))
require.NoError(t, err)
require.NoError(t, f.Close())
defer os.Remove(f.Name())
sc := X509Cert{
Sources: []string{f.Name()},
ExcludeRootCerts: true,
}
require.NoError(t, sc.Init())
acc := testutil.Accumulator{}
require.NoError(t, sc.Gather(&acc))
require.True(t, acc.HasMeasurement("x509_cert"))
require.Equal(t, acc.NMetrics(), uint64(1))
}
func TestGatherChain(t *testing.T) {