From e1c5d82971b1c9ab89585fe68a08957edcf6694d Mon Sep 17 00:00:00 2001 From: Will Bollock Date: Sat, 24 Sep 2022 19:19:28 -0400 Subject: [PATCH] fix: santize API key from HTTP GET errors NagiosXI seems to only support using an API key as a URL parameter, which leads to leakage on errors stemming from HTTP requests, such as the scrape.uri not being a Nagios endpoint. This introduces a small custom method to scrub the API key from errors, and adds it to errors returned when querying the NagiosXI API. --- nagios_exporter.go | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/nagios_exporter.go b/nagios_exporter.go index c54782e..7079a72 100644 --- a/nagios_exporter.go +++ b/nagios_exporter.go @@ -3,9 +3,11 @@ package main import ( "crypto/tls" "encoding/json" + "errors" "flag" "io" "net/http" + "regexp" "time" "github.com/BurntSushi/toml" @@ -145,7 +147,7 @@ var ( // System versionInfo = prometheus.NewDesc(prometheus.BuildFQName(namespace, "", "version_info"), "Nagios version information", []string{"version"}, nil) - buildInfo = prometheus.NewDesc(prometheus.BuildFQName(namespace, "", "build_info"), "Nagios exporter build information", []string{"version", "build_date", "commit"}, nil) + buildInfo = prometheus.NewDesc(prometheus.BuildFQName(namespace, "", "build_info"), "Nagios exporter build information", []string{"version", "build_date", "commit"}, nil) // System Detail hostchecks = prometheus.NewDesc(prometheus.BuildFQName(namespace, "", "host_checks_minutes"), "Host checks over time", []string{"check_type"}, nil) @@ -232,6 +234,14 @@ func (e *Exporter) Collect(ch chan<- prometheus.Metric) { } +// NagiosXI only supports submitting an API token as a URL parameter, so we need to scrub the API key from HTTP client errors +func sanitizeAPIKeyErrors(err error) error { + var re = regexp.MustCompile("(apikey=)(.*)") + sanitizedString := re.ReplaceAllString(err.Error(), "${1}") + + return errors.New(sanitizedString) +} + func QueryAPIs(url string, sslVerify bool, nagiosAPITimeout time.Duration) (body []byte) { // https://github.com/prometheus/haproxy_exporter/blob/main/haproxy_exporter.go#L337-L345 @@ -246,7 +256,7 @@ func QueryAPIs(url string, sslVerify bool, nagiosAPITimeout time.Duration) (body req, err := http.NewRequest("GET", url, nil) if err != nil { - log.Warn(err) + log.Warn(sanitizeAPIKeyErrors(err)) } req.Header.Set("Content-Type", "application/json") @@ -255,7 +265,7 @@ func QueryAPIs(url string, sslVerify bool, nagiosAPITimeout time.Duration) (body resp, err := client.Do(req) if err != nil { - log.Fatal(err) + log.Fatal(sanitizeAPIKeyErrors(err)) } if resp.Body != nil { @@ -267,7 +277,7 @@ func QueryAPIs(url string, sslVerify bool, nagiosAPITimeout time.Duration) (body body, readErr := io.ReadAll(resp.Body) if readErr != nil { - log.Fatal(readErr) + log.Fatal(sanitizeAPIKeyErrors(readErr)) } return body