Skip to content

Commit

Permalink
Add port validator to ensure configurable ports are valid
Browse files Browse the repository at this point in the history
Signed-off-by: Lan Luo <[email protected]>
  • Loading branch information
luolanzone committed Mar 3, 2025
1 parent c33622c commit 96bde59
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
7 changes: 5 additions & 2 deletions cmd/antrea-agent/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -430,13 +430,13 @@ func (o *Options) setK8sNodeDefaultOptions() {
if o.config.AntreaProxy.DefaultLoadBalancerMode == "" {
o.config.AntreaProxy.DefaultLoadBalancerMode = config.LoadBalancerModeNAT.String()
}
if o.config.ClusterMembershipPort == 0 {
if !isValidPort(o.config.ClusterMembershipPort) {
o.config.ClusterMembershipPort = apis.AntreaAgentClusterMembershipPort
}
if o.config.EnablePrometheusMetrics == nil {
o.config.EnablePrometheusMetrics = ptr.To(true)
}
if o.config.WireGuard.Port == 0 {
if !isValidPort(o.config.WireGuard.Port) {
o.config.WireGuard.Port = apis.WireGuardListenPort
}

Expand Down Expand Up @@ -534,6 +534,9 @@ func (o *Options) validateK8sNodeOptions() error {
o.config.TunnelType != ovsconfig.GRETunnel && o.config.TunnelType != ovsconfig.STTTunnel {
return fmt.Errorf("tunnel type %s is invalid", o.config.TunnelType)
}
if !isValidPort(int(o.config.TunnelPort)) {
return fmt.Errorf("tunnel port %d is invalid", o.config.TunnelPort)
}
ok, encryptionMode := config.GetTrafficEncryptionModeFromStr(o.config.TrafficEncryptionMode)
if !ok {
return fmt.Errorf("TrafficEncryptionMode %s is unknown", o.config.TrafficEncryptionMode)
Expand Down
8 changes: 8 additions & 0 deletions cmd/antrea-agent/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,11 @@ func parsePortRange(portRangeStr string) (start, end int, err error) {

return start, end, nil
}

// isValidPort checks if the given port number is within the valid range of 1 to 65535.
func isValidPort(port int) bool {
if port < 1 || port > 65535 {
return false
}
return true
}
31 changes: 31 additions & 0 deletions cmd/antrea-agent/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,34 @@ func TestParsePortRange(t *testing.T) {
})
}
}

func TestIsValidPort(t *testing.T) {
tests := []struct {
name string
port int
expected bool
}{
{
name: "invalid port 0",
port: 0,
expected: false,
},
{
name: "invalid port 70000",
port: 70000,
expected: false,
},
{
name: "valid port",
port: 65500,
expected: true,
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
result := isValidPort(tc.port)
assert.Equal(t, tc.expected, result)
})
}
}

0 comments on commit 96bde59

Please sign in to comment.