From 4e2816dba5804ca2a922ca28f836b73d01846bce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rodrigo=20Pe=C3=B1a?= Date: Fri, 4 Aug 2023 18:42:06 -0400 Subject: [PATCH] Fix crash on ListPathRequest with malformed prefix When ListPathRequest is done by a gRPC client including a malformed prefix, the server would crash an invalid memory address reference. This commit fixes the crash by checking whether the parseCIDR method returned an error. --- pkg/packet/bgp/bgp.go | 16 ++++++++++------ pkg/packet/bgp/bgp_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/pkg/packet/bgp/bgp.go b/pkg/packet/bgp/bgp.go index 9f24fd106..88a327d46 100644 --- a/pkg/packet/bgp/bgp.go +++ b/pkg/packet/bgp/bgp.go @@ -9604,26 +9604,30 @@ func GetRouteFamily(name string) (RouteFamily, error) { func NewPrefixFromRouteFamily(afi uint16, safi uint8, prefixStr ...string) (prefix AddrPrefixInterface, err error) { family := AfiSafiToRouteFamily(afi, safi) - f := func(s string) AddrPrefixInterface { - addr, net, _ := net.ParseCIDR(s) + f := func(s string) (AddrPrefixInterface, error) { + addr, net, err := net.ParseCIDR(s) + if err != nil { + fmt.Printf("Invalid CIDR: %v", s) + return nil, err + } len, _ := net.Mask.Size() switch family { case RF_IPv4_UC, RF_IPv4_MC: - return NewIPAddrPrefix(uint8(len), addr.String()) + return NewIPAddrPrefix(uint8(len), addr.String()), nil } - return NewIPv6AddrPrefix(uint8(len), addr.String()) + return NewIPv6AddrPrefix(uint8(len), addr.String()), nil } switch family { case RF_IPv4_UC, RF_IPv4_MC: if len(prefixStr) > 0 { - prefix = f(prefixStr[0]) + prefix, err = f(prefixStr[0]) } else { prefix = NewIPAddrPrefix(0, "") } case RF_IPv6_UC, RF_IPv6_MC: if len(prefixStr) > 0 { - prefix = f(prefixStr[0]) + prefix, err = f(prefixStr[0]) } else { prefix = NewIPv6AddrPrefix(0, "") } diff --git a/pkg/packet/bgp/bgp_test.go b/pkg/packet/bgp/bgp_test.go index 3de35797b..ac6e8800c 100644 --- a/pkg/packet/bgp/bgp_test.go +++ b/pkg/packet/bgp/bgp_test.go @@ -88,6 +88,33 @@ func Test_IPAddrPrefixString(t *testing.T) { assert.Equal(t, "3343:faba:3903:128::/63", ipv6.String()) } +func Test_MalformedPrefixLookup(t *testing.T) { + assert := assert.New(t) + + var tests = []struct { + inPrefix string + routeFamily RouteFamily + want AddrPrefixInterface + err bool + }{ + {"129.6.128/22", RF_IPv4_UC, nil, true}, + {"foo", RF_IPv4_UC, nil, true}, + {"3343:faba:3903:128::::/63", RF_IPv6_UC, nil, true}, + {"foo", RF_IPv6_UC, nil, true}, + } + + for _, test := range tests { + afi, safi := RouteFamilyToAfiSafi(RF_IPv4_UC) + p, err := NewPrefixFromRouteFamily(afi, safi, test.inPrefix) + if test.err { + assert.Error(err) + } else { + assert.Equal(test.want, p) + } + } + +} + func Test_IPAddrDecode(t *testing.T) { r := IPAddrPrefixDefault{} b := make([]byte, 16)