Skip to content

Commit

Permalink
fix(lint): prevent against integer overflow errors
Browse files Browse the repository at this point in the history
  • Loading branch information
aauren committed Feb 14, 2025
1 parent 5cdc417 commit 858fdf6
Show file tree
Hide file tree
Showing 7 changed files with 118 additions and 26 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ require (
require (
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/ccoveille/go-safecast v1.5.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/containerd/log v0.1.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ github.com/aws/aws-sdk-go v1.55.6 h1:cSg4pvZ3m8dgYcgqB97MrcdjUmZ1BeMYKUxMMB89IPk
github.com/aws/aws-sdk-go v1.55.6/go.mod h1:eRwEWoyTWFMVYVQzKMNHWP5/RV4xIUGMQfXQHfHkpNU=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/ccoveille/go-safecast v1.5.0 h1:cT/3uVQ/i5PTiJvhvkSU81HeKNurtyQtBndXEH3hDg4=
github.com/ccoveille/go-safecast v1.5.0/go.mod h1:QqwNjxQ7DAqY0C721OIO9InMk9zCwcsO7tnRuHytad8=
github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM=
github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
Expand Down
34 changes: 27 additions & 7 deletions pkg/controllers/proxy/linux_networking.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"syscall"
"time"

"github.com/ccoveille/go-safecast"
"github.com/cloudnativelabs/kube-router/v2/pkg/cri"
"github.com/cloudnativelabs/kube-router/v2/pkg/utils"
"github.com/docker/docker/client"
Expand Down Expand Up @@ -265,10 +266,18 @@ func (ln *linuxNetworking) ipvsAddService(svcs []*ipvs.Service, vip net.IP, prot
vip, svc.Address, protocol, svc.Protocol, port, svc.Port)
if vip.Equal(svc.Address) && protocol == svc.Protocol && port == svc.Port {
klog.V(2).Info("Service matched VIP")
ptim, err := safecast.ToUint32(persistentTimeout)
if err != nil {
return svcs, nil, fmt.Errorf("failed to convert persistent timeout to uint32: %v", err)
}
if (persistent && (svc.Flags&ipvsPersistentFlagHex) == 0) ||
(!persistent && (svc.Flags&ipvsPersistentFlagHex) != 0) ||
svc.Timeout != uint32(persistentTimeout) {
ipvsSetPersistence(svc, persistent, persistentTimeout)
svc.Timeout != ptim {
err = ipvsSetPersistence(svc, persistent, persistentTimeout)
if err != nil {
return svcs, nil, fmt.Errorf("failed to set persistence for service %s due to: %v",
ipvsServiceString(svc), err)
}

err = ln.ipvsUpdateService(svc)
if err != nil {
Expand Down Expand Up @@ -323,7 +332,11 @@ func (ln *linuxNetworking) ipvsAddService(svcs []*ipvs.Service, vip net.IP, prot
Netmask: ipMask,
}

ipvsSetPersistence(&svc, persistent, persistentTimeout)
err = ipvsSetPersistence(&svc, persistent, persistentTimeout)
if err != nil {
return svcs, nil, fmt.Errorf("failed to set persistence for service %s due to: %v",
ipvsServiceString(&svc), err)
}
ipvsSetSchedFlags(&svc, flags)

klog.V(1).Infof("%s didn't match any existing IPVS services, creating a new IPVS service",
Expand Down Expand Up @@ -356,13 +369,17 @@ func (ln *linuxNetworking) ipvsAddFWMarkService(svcs []*ipvs.Service, fwMark uin
if fwMark == svc.FWMark {
if (persistent && (svc.Flags&ipvsPersistentFlagHex) == 0) ||
(!persistent && (svc.Flags&ipvsPersistentFlagHex) != 0) {
ipvsSetPersistence(svc, persistent, persistentTimeout)
err := ipvsSetPersistence(svc, persistent, persistentTimeout)
if err != nil {
return nil, fmt.Errorf("failed to set persistence for service %s due to: %v",
ipvsServiceString(svc), err)
}

if changedIpvsSchedFlags(svc, flags) {
ipvsSetSchedFlags(svc, flags)
}

err := ln.ipvsUpdateService(svc)
err = ln.ipvsUpdateService(svc)
if err != nil {
return nil, fmt.Errorf("failed to update persistence flags for service %s due to %v",
ipvsServiceString(svc), err)
Expand Down Expand Up @@ -419,10 +436,13 @@ func (ln *linuxNetworking) ipvsAddFWMarkService(svcs []*ipvs.Service, fwMark uin
SchedName: ipvs.RoundRobin,
}

ipvsSetPersistence(&svc, persistent, persistentTimeout)
err := ipvsSetPersistence(&svc, persistent, persistentTimeout)
if err != nil {
return nil, fmt.Errorf("failed to set persistence for service %s due to: %v", ipvsServiceString(&svc), err)
}
ipvsSetSchedFlags(&svc, flags)

err := ln.ipvsNewService(&svc)
err = ln.ipvsNewService(&svc)
if err != nil {
return nil, err
}
Expand Down
20 changes: 16 additions & 4 deletions pkg/controllers/proxy/network_services_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"syscall"
"time"

"github.com/ccoveille/go-safecast"
"github.com/cloudnativelabs/kube-router/v2/pkg/healthcheck"
"github.com/cloudnativelabs/kube-router/v2/pkg/metrics"
"github.com/cloudnativelabs/kube-router/v2/pkg/options"
Expand Down Expand Up @@ -746,16 +747,20 @@ func (nsc *NetworkServicesController) publishMetrics(serviceInfoMap serviceInfoM
protocol = convertSvcProtoToSysCallProto(svc.protocol)
for _, ipvsSvc := range ipvsSvcs {

uPort, err := safecast.ToUint16(svc.port)
if err != nil {
klog.Errorf("failed to convert port %d to uint16: %v", svc.port, err)
}
switch svcAddress := ipvsSvc.Address.String(); svcAddress {
case svc.clusterIP.String():
if protocol == ipvsSvc.Protocol && uint16(svc.port) == ipvsSvc.Port {
if protocol == ipvsSvc.Protocol && uPort == ipvsSvc.Port {
pushMetric = true
svcVip = svc.clusterIP.String()
} else {
pushMetric = false
}
case nsc.krNode.GetPrimaryNodeIP().String():
if protocol == ipvsSvc.Protocol && uint16(svc.port) == ipvsSvc.Port {
if protocol == ipvsSvc.Protocol && uPort == ipvsSvc.Port {
pushMetric = true
svcVip = nsc.krNode.GetPrimaryNodeIP().String()
} else {
Expand Down Expand Up @@ -1556,14 +1561,21 @@ func ipvsDestinationString(d *ipvs.Destination) string {
return fmt.Sprintf("%s:%v (Family: %s, Weight: %v)", d.Address, d.Port, family, d.Weight)
}

func ipvsSetPersistence(svc *ipvs.Service, p bool, timeout int32) {
func ipvsSetPersistence(svc *ipvs.Service, p bool, timeout int32) error {
if p {
uTimeout, err := safecast.ToUint32(timeout)
if err != nil {
return fmt.Errorf("failed to convert timeout to uint32: %v", err)
}

svc.Flags |= ipvsPersistentFlagHex
svc.Timeout = uint32(timeout)
svc.Timeout = uTimeout
} else {
svc.Flags &^= ipvsPersistentFlagHex
svc.Timeout = 0
}

return nil
}

func ipvsSetSchedFlags(svc *ipvs.Service, s schedFlags) {
Expand Down
48 changes: 39 additions & 9 deletions pkg/controllers/proxy/service_endpoints_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"syscall"
"time"

"github.com/ccoveille/go-safecast"
"github.com/cloudnativelabs/kube-router/v2/pkg/metrics"
"github.com/cloudnativelabs/kube-router/v2/pkg/utils"
"github.com/moby/ipvs"
Expand Down Expand Up @@ -135,6 +136,10 @@ func (nsc *NetworkServicesController) setupClusterIPServices(serviceInfoMap serv
if err != nil {
return fmt.Errorf("failed creating dummy interface: %v", err)
}
sPort, err := safecast.ToUint16(svc.port)
if err != nil {
return fmt.Errorf("failed to convert service port to uint16: %v", err)
}

for family, famClusIPs := range clusterIPs {
var nodeIP string
Expand All @@ -159,7 +164,7 @@ func (nsc *NetworkServicesController) setupClusterIPServices(serviceInfoMap serv

// create IPVS service for the service to be exposed through the cluster ip
ipvsSvcs, svcID, ipvsSvc = nsc.addIPVSService(ipvsSvcs, activeServiceEndpointMap, svc, clusterIP,
protocol, uint16(svc.port))
protocol, sPort)
// We weren't able to create the IPVS service, so we won't be able to add endpoints to it
if svcID == "" {
// not logging an error here because it was already logged in the addIPVSService function
Expand Down Expand Up @@ -241,13 +246,19 @@ func (nsc *NetworkServicesController) addEndpointsToIPVSService(endpoints []endp
syscallINET = syscall.AF_INET6
}

ePort, err := safecast.ToUint16(endpoint.port)
if err != nil {
klog.Errorf("failed to convert endpoint port to uint16: %v", err)
continue
}

dst := ipvs.Destination{
Address: eIP,
AddressFamily: syscallINET,
Port: uint16(endpoint.port),
Port: ePort,
Weight: 1,
}
err := nsc.ln.ipvsAddServer(ipvsSvc, &dst)
err = nsc.ln.ipvsAddServer(ipvsSvc, &dst)
if err != nil {
klog.Errorf("encountered error adding endpoint to service: %v", err)
continue
Expand Down Expand Up @@ -282,6 +293,11 @@ func (nsc *NetworkServicesController) setupNodePortServices(serviceInfoMap servi
continue
}

nPort, err := safecast.ToUint16(svc.nodePort)
if err != nil {
return fmt.Errorf("failed to convert node port to uint16: %v", err)
}

var svcID string
var ipvsSvc *ipvs.Service
if nsc.nodeportBindOnAllIP {
Expand Down Expand Up @@ -312,7 +328,7 @@ func (nsc *NetworkServicesController) setupNodePortServices(serviceInfoMap servi
for _, addr := range addrs {

ipvsSvcs, svcID, ipvsSvc = nsc.addIPVSService(ipvsSvcs, activeServiceEndpointMap, svc, addr,
protocol, uint16(svc.nodePort))
protocol, nPort)
// We weren't able to create the IPVS service, so we won't be able to add endpoints to it
if svcID == "" {
continue
Expand All @@ -322,7 +338,7 @@ func (nsc *NetworkServicesController) setupNodePortServices(serviceInfoMap servi
}
} else {
ipvsSvcs, svcID, ipvsSvc = nsc.addIPVSService(ipvsSvcs, activeServiceEndpointMap, svc,
nsc.krNode.GetPrimaryNodeIP(), protocol, uint16(svc.nodePort))
nsc.krNode.GetPrimaryNodeIP(), protocol, nPort)
// We weren't able to create the IPVS service, so we won't be able to add endpoints to it
if svcID == "" {
continue
Expand Down Expand Up @@ -416,6 +432,11 @@ func (nsc *NetworkServicesController) setupExternalIPForService(svc *serviceInfo
return fmt.Errorf("failed get list of IPVS services due to: %v", err)
}

sPort, err := safecast.ToUint16(svc.port)
if err != nil {
return fmt.Errorf("failed to convert service port to uint16: %v", err)
}

// ensure director with vip assigned
err = nsc.ln.ipAddrAdd(dummyVipInterface, externalIP.String(), nodeIP.String(), true)
if err != nil && err.Error() != IfaceHasAddr {
Expand All @@ -424,8 +445,7 @@ func (nsc *NetworkServicesController) setupExternalIPForService(svc *serviceInfo
}

// create IPVS service for the service to be exposed through the external ip
_, svcID, ipvsExternalIPSvc = nsc.addIPVSService(ipvsSvcs, svcEndpointMap, svc, externalIP, protocol,
uint16(svc.port))
_, svcID, ipvsExternalIPSvc = nsc.addIPVSService(ipvsSvcs, svcEndpointMap, svc, externalIP, protocol, sPort)
if svcID == "" {
return fmt.Errorf("failed to create ipvs service for external ip: %s", externalIP)
}
Expand Down Expand Up @@ -510,7 +530,12 @@ func (nsc *NetworkServicesController) setupExternalIPForDSRService(svcIn *servic
return fmt.Errorf("failed to generate FW mark")
}

ipvsExternalIPSvc, err := nsc.ln.ipvsAddFWMarkService(ipvsSvcs, fwMark, sysFamily, protocol, uint16(svcIn.port),
sInPort, err := safecast.ToUint16(svcIn.port)
if err != nil {
return fmt.Errorf("failed to convert serviceIn port to uint16: %v", err)
}

ipvsExternalIPSvc, err := nsc.ln.ipvsAddFWMarkService(ipvsSvcs, fwMark, sysFamily, protocol, sInPort,
svcIn.sessionAffinity, svcIn.sessionAffinityTimeoutSeconds, svcIn.scheduler, svcIn.flags)
if err != nil {
return fmt.Errorf("failed to create IPVS service for FWMark service: %d (external IP: %s) due to: %s",
Expand Down Expand Up @@ -570,12 +595,17 @@ func (nsc *NetworkServicesController) setupExternalIPForDSRService(svcIn *servic
syscallINET = syscall.AF_INET6
}

ePort, err := safecast.ToUint16(endpoint.port)
if err != nil {
return fmt.Errorf("failed to convert endpoint port to uint16: %v", err)
}

// create the basic IPVS destination record
dst := ipvs.Destination{
Address: eIP,
AddressFamily: syscallINET,
ConnectionFlags: ipvs.ConnectionFlagTunnel,
Port: uint16(endpoint.port),
Port: ePort,
Weight: 1,
}

Expand Down
17 changes: 14 additions & 3 deletions pkg/controllers/routing/bgp_policies.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"strconv"
"strings"

"github.com/ccoveille/go-safecast"
gobgpapi "github.com/osrg/gobgp/v3/api"
v1core "k8s.io/api/core/v1"
"k8s.io/klog/v2"
Expand Down Expand Up @@ -135,10 +136,14 @@ func (nrc *NetworkRoutingController) addPodCidrDefinedSet() error {
if cidrLen < 0 || cidrLen > cidrMax {
return fmt.Errorf("the pod CIDR IP given is not a proper mask: %d", cidrLen)
}
uCIDRLen, err := safecast.ToUint32(cidrLen)
if err != nil {
return fmt.Errorf("failed to convert CIDR length to uint32: %v", err)
}
prefixes = append(prefixes, &gobgpapi.Prefix{
IpPrefix: cidr,
MaskLengthMin: uint32(cidrLen),
MaskLengthMax: uint32(cidrLen),
MaskLengthMin: uCIDRLen,
MaskLengthMax: uCIDRLen,
})
}
podCidrDefinedSet := &gobgpapi.DefinedSet{
Expand Down Expand Up @@ -318,7 +323,13 @@ func (nrc *NetworkRoutingController) addCustomImportRejectDefinedSet() error {
prefix := new(gobgpapi.Prefix)
prefix.IpPrefix = ipNet.String()
mask, _ := ipNet.Mask.Size()
prefix.MaskLengthMin = uint32(mask)

uIntMask, err := safecast.ToUint32(mask)
if err != nil {
return fmt.Errorf("failed to convert mask to uint32: %v", err)
}

prefix.MaskLengthMin = uIntMask
prefix.MaskLengthMax = uint32(ipv4MaskMinBits)
prefixes = append(prefixes, prefix)
}
Expand Down
22 changes: 19 additions & 3 deletions pkg/controllers/routing/network_routes_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (

"google.golang.org/protobuf/types/known/anypb"

"github.com/ccoveille/go-safecast"
"github.com/cloudnativelabs/kube-router/v2/pkg/bgp"
"github.com/cloudnativelabs/kube-router/v2/pkg/healthcheck"
"github.com/cloudnativelabs/kube-router/v2/pkg/metrics"
Expand Down Expand Up @@ -1060,11 +1061,16 @@ func (nrc *NetworkRoutingController) startBgpServer(grpcServer bool) error {
localAddressList = append(localAddressList, addr)
}

intBGPPort, err := safecast.ToInt32(nrc.bgpPort)
if err != nil {
return fmt.Errorf("failed to convert BGP port to int32: %v", err)
}

global := &gobgpapi.Global{
Asn: nodeAsnNumber,
RouterId: nrc.routerID,
ListenAddresses: localAddressList,
ListenPort: int32(nrc.bgpPort),
ListenPort: intBGPPort,
}

if err := nrc.bgpServer.StartBgp(context.Background(), &gobgpapi.StartBgpRequest{Global: global}); err != nil {
Expand Down Expand Up @@ -1402,13 +1408,23 @@ func NewNetworkRoutingController(clientset kubernetes.Interface,
// Convert ints to uint32s
peerASNs := make([]uint32, 0)
for _, i := range kubeRouterConfig.PeerASNs {
peerASNs = append(peerASNs, uint32(i))
ui, err := safecast.ToUint32(i)
if err != nil {
return nil, fmt.Errorf("failed to convert Peer ASNs to uint32: %s", err)
}

peerASNs = append(peerASNs, ui)
}

// Convert uints to uint16s
peerPorts := make([]uint32, 0)
for _, i := range kubeRouterConfig.PeerPorts {
peerPorts = append(peerPorts, uint32(i))
ui, err := safecast.ToUint32(i)
if err != nil {
return nil, fmt.Errorf("failed to convert Peer Port to uint32: %s", err)
}

peerPorts = append(peerPorts, ui)
}

// PeerPasswords as cli params take precedence over password file
Expand Down

0 comments on commit 858fdf6

Please sign in to comment.