Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate CIDR on firewall_rule_create.go #383

Merged
merged 1 commit into from
Apr 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions cmd/firewall/firewall_rule_create.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package firewall

import (
"fmt"
"net"
"strings"

"github.com/civo/civogo"
Expand Down Expand Up @@ -40,6 +41,12 @@ var firewallRuleCreateCmd = &cobra.Command{
os.Exit(1)
}

// Validate CIDR input
if err := validateCIDRs(cidr); err != nil {
utility.Error(err.Error())
os.Exit(1)
}

newRuleConfig := &civogo.FirewallRuleConfig{
FirewallID: firewall.ID,
Protocol: protocol,
Expand Down Expand Up @@ -98,3 +105,16 @@ var firewallRuleCreateCmd = &cobra.Command{
}
},
}

// validateCIDRs checks if each CIDR in a comma-separated list is valid
func validateCIDRs(cidrs string) error {
for _, cidr := range strings.Split(cidrs, ",") {
if cidr = strings.TrimSpace(cidr); cidr == "" {
continue
}
if _, _, err := net.ParseCIDR(cidr); err != nil {
return fmt.Errorf("invalid CIDR address '%s': %s", cidr, err)
}
}
return nil
}
Loading