From 25a88431d5ad33a5ecf07592402e2e88bf83de99 Mon Sep 17 00:00:00 2001 From: SuperQ Date: Sun, 27 Aug 2023 16:15:43 +0200 Subject: [PATCH] Sanitize invalid UTF-8 Avoid sending raw invalid UTF-8 to metrics by replacing invalid chars with U+FFFD. Fixes: https://github.com/prometheus/snmp_exporter/issues/279 Signed-off-by: SuperQ --- collector/collector.go | 4 ++-- collector/collector_test.go | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/collector/collector.go b/collector/collector.go index 1b62288b..3187dd73 100644 --- a/collector/collector.go +++ b/collector/collector.go @@ -754,7 +754,7 @@ func pduValueAsString(pdu *gosnmp.SnmpPDU, typ string, metrics internalMetrics) return pdu.Value.(string)[1:] } // DisplayString. - return pdu.Value.(string) + return strings.ToValidUTF8(pdu.Value.(string), "�") case []byte: if typ == "" || typ == "Bits" { typ = "OctetString" @@ -769,7 +769,7 @@ func pduValueAsString(pdu *gosnmp.SnmpPDU, typ string, metrics internalMetrics) parts = append([]int{len(pdu.Value.([]byte))}, parts...) } str, _, _ := indexOidsAsString(parts, typ, 0, false, nil) - return str + return strings.ToValidUTF8(str, "�") case nil: return "" default: diff --git a/collector/collector_test.go b/collector/collector_test.go index 818a8703..d1a7a80f 100644 --- a/collector/collector_test.go +++ b/collector/collector_test.go @@ -718,6 +718,11 @@ func TestPduValueAsString(t *testing.T) { pdu: &gosnmp.SnmpPDU{Value: 10.1, Type: gosnmp.OpaqueDouble}, result: "10.1", }, + { + pdu: &gosnmp.SnmpPDU{Value: []byte{115, 97, 110, 101, 253, 190, 214}}, + typ: "DisplayString", + result: "sane�", + }, } for _, c := range cases { got := pduValueAsString(c.pdu, c.typ, internalMetrics{})