Преглед изворни кода

fix(snmp): reject MAC PDUs that aren't exactly 6 bytes (#2243)

bridgeMacFromPDU and macFromOctets accepted any value of 6 bytes or more and formatted the first six, so a 7-byte PDU became a plausible but wrong MAC. Both now go through macFromPDU, which requires exactly 6 and logs the rest once per PDU name and length. macFromParts reads FDB index octets with strconv.Atoi instead of Sscanf, which stopped at the first non-digit and read 2abc as 2.

Co-authored-by: Mike Grupenhoff <2231096+mgrupenhoff@users.noreply.github.com>
Mike Grupenhoff пре 4 дана
родитељ
комит
a6e7a1d617

+ 3 - 2
server-go/internal/snmp/fdbTable.go

@@ -2,6 +2,7 @@ package snmp
 
 import (
 	"fmt"
+	"strconv"
 	"strings"
 
 	"github.com/gosnmp/gosnmp"
@@ -140,8 +141,8 @@ func extractMacFromOid(name, prefix string) string {
 func macFromParts(parts []string) string {
 	out := make([]string, 6)
 	for i, p := range parts {
-		var n int
-		if _, err := fmt.Sscanf(p, "%d", &n); err != nil || n < 0 || n > 255 {
+		n, err := strconv.Atoi(p)
+		if err != nil || n < 0 || n > 255 {
 			return ""
 		}
 		out[i] = fmt.Sprintf("%02X", n)

+ 21 - 6
server-go/internal/snmp/lldpRem.go

@@ -12,9 +12,14 @@ import (
 	"strconv"
 	"strings"
 
+	"github.com/gnacho/netpulse/server-go/internal/logonce"
 	"github.com/gosnmp/gosnmp"
 )
 
+// snmpWarn avisa una sola vez por PDU MAC descartada: el sondeo repite el
+// mismo valor en cada ciclo.
+var snmpWarn = logonce.New("[netpulse:snmp] ")
+
 // LldpRemEntry es un vecino LLDP anunciado en un puerto local del switch.
 // Todos los campos del anuncio son opcionales; vacío = no anunciado.
 type LldpRemEntry struct {
@@ -114,7 +119,7 @@ func lldpRemEntries(pdus []gosnmp.SnmpPDU, portToIfIndex map[int]int, mgmt map[s
 			chassisSubtype[k] = int(uint64Val(pdu))
 		case 5: // lldpRemChassisId
 			if chassisSubtype[k] == 4 { // macAddress
-				e.ChassisMac = macFromOctets(octetsVal(pdu))
+				e.ChassisMac = macFromPDU(pdu)
 			} else if s := stringVal(pdu); s != "" {
 				e.Chassis = s
 			}
@@ -122,7 +127,7 @@ func lldpRemEntries(pdus []gosnmp.SnmpPDU, portToIfIndex map[int]int, mgmt map[s
 			portSubtype[k] = int(uint64Val(pdu))
 		case 7: // lldpRemPortId (fallback de PortDesc si no hay descripción)
 			if portSubtype[k] == 3 { // macAddress
-				e.PortDesc = macFromOctets(octetsVal(pdu))
+				e.PortDesc = macFromPDU(pdu)
 			} else {
 				e.PortDesc = stringVal(pdu)
 			}
@@ -293,10 +298,20 @@ func octetsVal(v gosnmp.SnmpPDU) []byte {
 	return nil
 }
 
-// macFromOctets formatea una MAC MAYÚSCULA canónica (#960) de 6 bytes
-// ("" si el dato no es usable).
-func macFromOctets(b []byte) string {
-	if len(b) < 6 {
+// macFromPDU convierte el OCTET STRING de una PDU en una MAC MAYÚSCULAS
+// canónica (#960), o "" si el OID no existe, llega vacío o no tiene
+// exactamente 6 octetos.
+func macFromPDU(v gosnmp.SnmpPDU) string {
+	if v.Type == gosnmp.NoSuchObject || v.Type == gosnmp.NoSuchInstance {
+		return ""
+	}
+	b := octetsVal(v)
+	if len(b) == 0 {
+		return ""
+	}
+	if len(b) != 6 {
+		key := fmt.Sprintf("%s\x00%d", v.Name, len(b))
+		snmpWarn.Printf(key, "ignoring non-6-byte MAC PDU %s (len=%d)", v.Name, len(b))
 		return ""
 	}
 	return fmt.Sprintf("%02X:%02X:%02X:%02X:%02X:%02X", b[0], b[1], b[2], b[3], b[4], b[5])

+ 62 - 0
server-go/internal/snmp/lldpRem_test.go

@@ -250,3 +250,65 @@ func TestApplyLocPortIdentityOmada(t *testing.T) {
 		t.Fatal("la identidad propia no debe marcarse como venida de locPortDesc")
 	}
 }
+
+// TestLldpRemEntriesMacPDULength verifica que lldpRemChassisId (subtype 4) y
+// lldpRemPortId (subtype 3) rechazan PDUs MAC de longitud distinta de 6 bytes
+// en lugar de truncarlas, mientras las de 6 bytes se siguen parseando.
+func TestLldpRemEntriesMacPDULength(t *testing.T) {
+	sixBytes := []byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x01}
+	sevenBytes := []byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x99}
+
+	t.Run("lldpRemChassisId subtype 4 de 7 bytes devuelve vacío", func(t *testing.T) {
+		pdus := []gosnmp.SnmpPDU{
+			{Name: OidLldpRemTable + ".4.0.1.1", Type: gosnmp.Integer, Value: 4},
+			{Name: OidLldpRemTable + ".5.0.1.1", Type: gosnmp.OctetString, Value: sevenBytes},
+			{Name: OidLldpRemTable + ".9.0.1.1", Type: gosnmp.OctetString, Value: []byte("sw1")},
+		}
+		got := lldpRemEntries(pdus, map[int]int{1: 1}, nil)
+		if len(got) != 1 {
+			t.Fatalf("esperaba 1 vecino, obtuve %d", len(got))
+		}
+		if got[0].ChassisMac != "" {
+			t.Fatalf("ChassisMac de 7 bytes se truncó a %q, esperaba vacío", got[0].ChassisMac)
+		}
+	})
+
+	t.Run("lldpRemChassisId subtype 4 de 6 bytes sigue parseando", func(t *testing.T) {
+		pdus := []gosnmp.SnmpPDU{
+			{Name: OidLldpRemTable + ".4.0.1.1", Type: gosnmp.Integer, Value: 4},
+			{Name: OidLldpRemTable + ".5.0.1.1", Type: gosnmp.OctetString, Value: sixBytes},
+			{Name: OidLldpRemTable + ".9.0.1.1", Type: gosnmp.OctetString, Value: []byte("sw1")},
+		}
+		got := lldpRemEntries(pdus, map[int]int{1: 1}, nil)
+		if len(got) != 1 || got[0].ChassisMac != "02:00:00:00:00:01" {
+			t.Fatalf("esperaba ChassisMac 02:00:00:00:00:01, obtuve %+v", got)
+		}
+	})
+
+	t.Run("lldpRemPortId subtype 3 de 7 bytes devuelve vacío", func(t *testing.T) {
+		pdus := []gosnmp.SnmpPDU{
+			{Name: OidLldpRemTable + ".6.0.1.1", Type: gosnmp.Integer, Value: 3},
+			{Name: OidLldpRemTable + ".7.0.1.1", Type: gosnmp.OctetString, Value: sevenBytes},
+			{Name: OidLldpRemTable + ".9.0.1.1", Type: gosnmp.OctetString, Value: []byte("sw1")},
+		}
+		got := lldpRemEntries(pdus, map[int]int{1: 1}, nil)
+		if len(got) != 1 {
+			t.Fatalf("esperaba 1 vecino, obtuve %d", len(got))
+		}
+		if got[0].PortDesc != "" {
+			t.Fatalf("PortId MAC de 7 bytes se truncó a %q, esperaba vacío", got[0].PortDesc)
+		}
+	})
+
+	t.Run("lldpRemPortId subtype 3 de 6 bytes sigue parseando", func(t *testing.T) {
+		pdus := []gosnmp.SnmpPDU{
+			{Name: OidLldpRemTable + ".6.0.1.1", Type: gosnmp.Integer, Value: 3},
+			{Name: OidLldpRemTable + ".7.0.1.1", Type: gosnmp.OctetString, Value: sixBytes},
+			{Name: OidLldpRemTable + ".9.0.1.1", Type: gosnmp.OctetString, Value: []byte("sw1")},
+		}
+		got := lldpRemEntries(pdus, map[int]int{1: 1}, nil)
+		if len(got) != 1 || got[0].PortDesc != "02:00:00:00:00:01" {
+			t.Fatalf("esperaba PortDesc 02:00:00:00:00:01, obtuve %+v", got)
+		}
+	})
+}

+ 9 - 0
server-go/internal/snmp/snmp_test.go

@@ -75,6 +75,15 @@ func TestExtractMacFromOidDot1q(t *testing.T) {
 	}
 }
 
+// TestExtractMacFromOidRejectsTrailingGarbage verifica que un octeto de OID
+// con basura al final (p. ej. "2abc") se rechaza en lugar de aceptarse como 2.
+func TestExtractMacFromOidRejectsTrailingGarbage(t *testing.T) {
+	oid := OidDot1dTpFdbPort + ".2abc.0.0.0.0.1"
+	if got := extractMacFromOid(oid, OidDot1dTpFdbPort); got != "" {
+		t.Fatalf("extractMacFromOid(%q) = %q, esperaba vacío", oid, got)
+	}
+}
+
 func TestPortStatsSpeedString(t *testing.T) {
 	tests := []struct {
 		name string

+ 1 - 22
server-go/internal/snmp/system.go

@@ -74,32 +74,11 @@ func PollBridgeAddress(s *gosnmp.GoSNMP) (string, error) {
 		if v.Name != OidDot1dBaseBridgeAddress {
 			continue
 		}
-		return bridgeMacFromPDU(v), nil
+		return macFromPDU(v), nil
 	}
 	return "", nil
 }
 
-// bridgeMacFromPDU convierte el OCTET STRING de dot1dBaseBridgeAddress a
-// MAC MAYÚSCULAS canónica ("" si el dato no es usable).
-func bridgeMacFromPDU(v gosnmp.SnmpPDU) string {
-	if v.Type == gosnmp.NoSuchObject || v.Type == gosnmp.NoSuchInstance {
-		return ""
-	}
-	var b []byte
-	switch val := v.Value.(type) {
-	case []byte:
-		b = val
-	case string:
-		b = []byte(val)
-	default:
-		return ""
-	}
-	if len(b) < 6 {
-		return ""
-	}
-	return fmt.Sprintf("%02X:%02X:%02X:%02X:%02X:%02X", b[0], b[1], b[2], b[3], b[4], b[5])
-}
-
 // PollMikrotikTemp lee la temperatura de la health table de MikroTik (#1725).
 //
 // Antes era un Get del índice 52 que #1256 copió de un SwOS. En RouterOS la

+ 66 - 12
server-go/internal/snmp/system_test.go

@@ -1,30 +1,84 @@
 package snmp
 
 import (
+	"fmt"
 	"math/big"
+	"strings"
 	"testing"
 
+	"github.com/gnacho/netpulse/server-go/internal/logonce"
 	"github.com/gosnmp/gosnmp"
 )
 
 // #1036: la MAC base del bridge se normaliza a MAYÚSCULAS (#960) o "" si
-// el dato no es usable (OID ausente, payload corto).
-func TestBridgeMacFromPDU(t *testing.T) {
-	good := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: []byte{0x04, 0x95, 0xe6, 0x76, 0x55, 0xa1}}
-	if got := bridgeMacFromPDU(good); got != "04:95:E6:76:55:A1" {
-		t.Errorf("bytes: got %q", got)
+// el dato no es usable (OID ausente, vacío o longitud distinta de 6 octetos).
+func TestMacFromPDU(t *testing.T) {
+	good := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: []byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x01}}
+	if got := macFromPDU(good); got != "02:00:00:00:00:01" {
+		t.Errorf("bytes: obtuve %q, esperaba 02:00:00:00:00:01", got)
 	}
-	str := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: string([]byte{0xa4, 0x7e, 0xfa, 0x65, 0x0c, 0xaa})}
-	if got := bridgeMacFromPDU(str); got != "A4:7E:FA:65:0C:AA" {
-		t.Errorf("string: got %q", got)
+	str := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: string([]byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x02})}
+	if got := macFromPDU(str); got != "02:00:00:00:00:02" {
+		t.Errorf("string: obtuve %q, esperaba 02:00:00:00:00:02", got)
 	}
 	short := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: []byte{0x01, 0x02}}
-	if got := bridgeMacFromPDU(short); got != "" {
-		t.Errorf("short: got %q, want vacío", got)
+	if got := macFromPDU(short); got != "" {
+		t.Errorf("PDU corta: obtuve %q, esperaba vacío", got)
+	}
+	long := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: []byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x99}}
+	if got := macFromPDU(long); got != "" {
+		t.Errorf("PDU de 7 bytes: obtuve %q, esperaba vacío", got)
+	}
+	empty := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.OctetString, Value: []byte{}}
+	if got := macFromPDU(empty); got != "" {
+		t.Errorf("PDU vacía: obtuve %q, esperaba vacío", got)
 	}
 	noObj := gosnmp.SnmpPDU{Name: OidDot1dBaseBridgeAddress, Type: gosnmp.NoSuchObject, Value: nil}
-	if got := bridgeMacFromPDU(noObj); got != "" {
-		t.Errorf("nosuchobject: got %q, want vacío", got)
+	if got := macFromPDU(noObj); got != "" {
+		t.Errorf("nosuchobject: obtuve %q, esperaba vacío", got)
+	}
+}
+
+// TestMacFromPDUWarnsOnce verifica que una PDU de longitud distinta de 6 bytes
+// registra un único aviso con prefijo [netpulse:snmp] nombrando su OID y
+// longitud, que un segundo sondeo idéntico no repite el aviso y que una PDU
+// vacía se descarta en silencio.
+func TestMacFromPDUWarnsOnce(t *testing.T) {
+	var lines []string
+	old := snmpWarn
+	snmpWarn = logonce.NewWithLogf("[netpulse:snmp] ", func(f string, a ...any) {
+		lines = append(lines, fmt.Sprintf(f, a...))
+	})
+	t.Cleanup(func() { snmpWarn = old })
+
+	pdu := gosnmp.SnmpPDU{
+		Name:  OidDot1dBaseBridgeAddress,
+		Type:  gosnmp.OctetString,
+		Value: []byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x99},
+	}
+	empty := gosnmp.SnmpPDU{
+		Name:  OidDot1dBaseBridgeAddress,
+		Type:  gosnmp.OctetString,
+		Value: []byte{},
+	}
+
+	if got := macFromPDU(empty); got != "" {
+		t.Fatalf("PDU vacía: obtuve %q, esperaba vacío", got)
+	}
+	if got := macFromPDU(pdu); got != "" {
+		t.Fatalf("primera PDU de 7 bytes: obtuve %q, esperaba vacío", got)
+	}
+	if got := macFromPDU(pdu); got != "" {
+		t.Fatalf("segunda PDU de 7 bytes: obtuve %q, esperaba vacío", got)
+	}
+
+	if len(lines) != 1 {
+		t.Fatalf("avisos = %d (%q), esperaba exactamente 1", len(lines), lines)
+	}
+	if !strings.HasPrefix(lines[0], "[netpulse:snmp] ") ||
+		!strings.Contains(lines[0], OidDot1dBaseBridgeAddress) ||
+		!strings.Contains(lines[0], "len=7") {
+		t.Fatalf("aviso inesperado: %q (esperaba prefijo [netpulse:snmp], OID %s y len=7)", lines[0], OidDot1dBaseBridgeAddress)
 	}
 }