firewall

package
v1.38.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2023 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AddRuleCommand = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "add-rule FIREWALL FLAGS",
			Short:                 "Add a single rule to a firewall",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Firewall().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		cmd.Flags().String("direction", "", "Direction (in, out) (required)")
		cmd.RegisterFlagCompletionFunc("direction", cmpl.SuggestCandidates("in", "out"))
		cmd.MarkFlagRequired("direction")

		cmd.Flags().String("protocol", "", "Protocol (icmp, esp, gre, udp or tcp) (required)")
		cmd.RegisterFlagCompletionFunc("protocol", cmpl.SuggestCandidates("icmp", "udp", "tcp", "esp", "gre"))
		cmd.MarkFlagRequired("protocol")

		cmd.Flags().StringArray("source-ips", []string{}, "Source IPs (CIDR Notation) (required when direction is in)")

		cmd.Flags().StringArray("destination-ips", []string{}, "Destination IPs (CIDR Notation) (required when direction is out)")

		cmd.Flags().String("port", "", "Port to which traffic will be allowed, only applicable for protocols TCP and UDP, you can specify port ranges, sample: 80-85")

		cmd.Flags().String("description", "", "Description of the firewall rule")
		return cmd
	},
	Run: func(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		direction, _ := cmd.Flags().GetString("direction")
		protocol, _ := cmd.Flags().GetString("protocol")
		sourceIPs, _ := cmd.Flags().GetStringArray("source-ips")
		destinationIPs, _ := cmd.Flags().GetStringArray("destination-ips")
		port, _ := cmd.Flags().GetString("port")
		description, _ := cmd.Flags().GetString("description")

		idOrName := args[0]
		firewall, _, err := client.Firewall().Get(ctx, idOrName)
		if err != nil {
			return err
		}
		if firewall == nil {
			return fmt.Errorf("Firewall not found: %v", idOrName)
		}

		d := hcloud.FirewallRuleDirection(direction)
		rule := hcloud.FirewallRule{
			Direction: d,
			Protocol:  hcloud.FirewallRuleProtocol(protocol),
		}

		if port != "" {
			rule.Port = hcloud.String(port)
		}

		if description != "" {
			rule.Description = hcloud.String(description)
		}

		switch rule.Protocol {
		case hcloud.FirewallRuleProtocolTCP:
		case hcloud.FirewallRuleProtocolUDP:
			if port == "" {
				return fmt.Errorf("port is required")
			}
		default:
			if port != "" {
				return fmt.Errorf("port is not allowed for this protocol")
			}
		}

		switch d {
		case hcloud.FirewallRuleDirectionOut:
			rule.DestinationIPs = make([]net.IPNet, len(destinationIPs))
			for i, ip := range destinationIPs {
				n, err := validateFirewallIP(ip)
				if err != nil {
					return fmt.Errorf("destination error on index %d: %s", i, err)
				}
				rule.DestinationIPs[i] = *n
			}
		case hcloud.FirewallRuleDirectionIn:
			rule.SourceIPs = make([]net.IPNet, len(sourceIPs))
			for i, ip := range sourceIPs {
				n, err := validateFirewallIP(ip)
				if err != nil {
					return fmt.Errorf("source ips error on index %d: %s", i, err)
				}
				rule.SourceIPs[i] = *n
			}
		}

		rules := append(firewall.Rules, rule)

		actions, _, err := client.Firewall().SetRules(ctx, firewall,
			hcloud.FirewallSetRulesOpts{Rules: rules},
		)
		if err != nil {
			return err
		}
		if err := waiter.WaitForActions(ctx, actions); err != nil {
			return err
		}

		fmt.Printf("Firewall Rules for Firewall %d updated\n", firewall.ID)

		return nil
	},
}
View Source
var ApplyToResourceCommand = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "apply-to-resource FIREWALL FLAGS",
			Short:                 "Applies a Firewall to a single resource",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Firewall().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		cmd.Flags().String("type", "", "Resource Type (server) (required)")
		cmd.RegisterFlagCompletionFunc("type", cmpl.SuggestCandidates("server", "label_selector"))
		cmd.MarkFlagRequired("type")

		cmd.Flags().String("server", "", "Server name of ID (required when type is server)")
		cmd.RegisterFlagCompletionFunc("server", cmpl.SuggestCandidatesF(client.Server().Names))

		cmd.Flags().StringP("label-selector", "l", "", "Label Selector")
		return cmd
	},
	Run: func(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		resourceType, _ := cmd.Flags().GetString("type")

		switch resourceType {
		case string(hcloud.FirewallResourceTypeServer):
			server, _ := cmd.Flags().GetString("server")
			if server == "" {
				return fmt.Errorf("type %s need a --server specific", resourceType)
			}
		case string(hcloud.FirewallResourceTypeLabelSelector):
			labelSelector, _ := cmd.Flags().GetString("label-selector")
			if labelSelector == "" {
				return fmt.Errorf("type %s need a --label-selector specific", resourceType)
			}
		default:
			return fmt.Errorf("unknown type %s", resourceType)
		}

		serverIdOrName, _ := cmd.Flags().GetString("server")
		labelSelector, _ := cmd.Flags().GetString("label-selector")
		idOrName := args[0]
		firewall, _, err := client.Firewall().Get(ctx, idOrName)
		if err != nil {
			return err
		}
		if firewall == nil {
			return fmt.Errorf("Firewall not found: %v", idOrName)
		}
		opts := hcloud.FirewallResource{Type: hcloud.FirewallResourceType(resourceType)}

		switch opts.Type {
		case hcloud.FirewallResourceTypeServer:
			server, _, err := client.Server().Get(ctx, serverIdOrName)
			if err != nil {
				return err
			}
			if server == nil {
				return fmt.Errorf("Server not found: %v", serverIdOrName)
			}
			opts.Server = &hcloud.FirewallResourceServer{ID: server.ID}
		case hcloud.FirewallResourceTypeLabelSelector:
			opts.LabelSelector = &hcloud.FirewallResourceLabelSelector{Selector: labelSelector}
		default:
			return fmt.Errorf("unknown type %s", opts.Type)
		}

		actions, _, err := client.Firewall().ApplyResources(ctx, firewall, []hcloud.FirewallResource{opts})
		if err != nil {
			return err
		}
		if err := waiter.WaitForActions(ctx, actions); err != nil {
			return err
		}
		fmt.Printf("Firewall %d applied\n", firewall.ID)

		return nil
	},
}
View Source
var DeleteRuleCommand = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "delete-rule FIREWALL FLAGS",
			Short:                 "Delete a single rule to a firewall",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Firewall().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		cmd.Flags().String("direction", "", "Direction (in, out) (required)")
		cmd.RegisterFlagCompletionFunc("direction", cmpl.SuggestCandidates("in", "out"))
		cmd.MarkFlagRequired("direction")

		cmd.Flags().String("protocol", "", "Protocol (icmp, esp, gre, udp or tcp) (required)")
		cmd.RegisterFlagCompletionFunc("protocol", cmpl.SuggestCandidates("icmp", "udp", "tcp", "esp", "gre"))
		cmd.MarkFlagRequired("protocol")

		cmd.Flags().StringArray("source-ips", []string{}, "Source IPs (CIDR Notation) (required when direction is in)")

		cmd.Flags().StringArray("destination-ips", []string{}, "Destination IPs (CIDR Notation) (required when direction is out)")

		cmd.Flags().String("port", "", "Port to which traffic will be allowed, only applicable for protocols TCP and UDP")

		cmd.Flags().String("description", "", "Description of the firewall rule")
		return cmd
	},
	Run: func(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		direction, _ := cmd.Flags().GetString("direction")
		protocol, _ := cmd.Flags().GetString("protocol")
		sourceIPs, _ := cmd.Flags().GetStringArray("source-ips")
		destinationIPs, _ := cmd.Flags().GetStringArray("destination-ips")
		port, _ := cmd.Flags().GetString("port")
		description, _ := cmd.Flags().GetString("description")

		idOrName := args[0]
		firewall, _, err := client.Firewall().Get(ctx, idOrName)
		if err != nil {
			return err
		}
		if firewall == nil {
			return fmt.Errorf("Firewall not found: %v", idOrName)
		}

		d := hcloud.FirewallRuleDirection(direction)
		rule := hcloud.FirewallRule{
			Direction: d,
			Protocol:  hcloud.FirewallRuleProtocol(protocol),
		}
		if port != "" {
			rule.Port = hcloud.String(port)
		}
		if description != "" {
			rule.Description = hcloud.String(description)
		}

		switch rule.Protocol {
		case hcloud.FirewallRuleProtocolTCP:
		case hcloud.FirewallRuleProtocolUDP:
			if port == "" {
				return fmt.Errorf("port is required")
			}
		default:
			if port != "" {
				return fmt.Errorf("port is not allowed for this protocol")
			}
		}

		switch d {
		case hcloud.FirewallRuleDirectionOut:
			rule.DestinationIPs = make([]net.IPNet, len(destinationIPs))
			for i, ip := range destinationIPs {
				n, err := validateFirewallIP(ip)
				if err != nil {
					return fmt.Errorf("destination ips error on index %d: %s", i, err)
				}
				rule.DestinationIPs[i] = *n
				rule.SourceIPs = make([]net.IPNet, 0)
			}
		case hcloud.FirewallRuleDirectionIn:
			rule.SourceIPs = make([]net.IPNet, len(sourceIPs))
			for i, ip := range sourceIPs {
				n, err := validateFirewallIP(ip)
				if err != nil {
					return fmt.Errorf("source ips error on index %d: %s", i, err)
				}
				rule.DestinationIPs = make([]net.IPNet, 0)
				rule.SourceIPs[i] = *n
			}
		}

		var rules []hcloud.FirewallRule
		for _, existingRule := range firewall.Rules {
			if !reflect.DeepEqual(existingRule, rule) {
				rules = append(rules, existingRule)
			}
		}
		if len(rules) == len(firewall.Rules) {
			return fmt.Errorf("the specified rule was not found in the ruleset of Firewall %d", firewall.ID)
		}
		actions, _, err := client.Firewall().SetRules(ctx, firewall,
			hcloud.FirewallSetRulesOpts{Rules: rules},
		)
		if err != nil {
			return err
		}
		if err := waiter.WaitForActions(ctx, actions); err != nil {
			return err
		}
		fmt.Printf("Firewall Rules for Firewall %d updated\n", firewall.ID)

		return nil
	},
}
View Source
var RemoveFromResourceCommand = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "remove-from-resource FIREWALL FLAGS",
			Short:                 "Removes a Firewall from a single resource",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Firewall().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		cmd.Flags().String("type", "", "Resource Type (server) (required)")
		cmd.RegisterFlagCompletionFunc("type", cmpl.SuggestCandidates("server", "label_selector"))
		cmd.MarkFlagRequired("type")

		cmd.Flags().String("server", "", "Server name of ID (required when type is server)")
		cmd.RegisterFlagCompletionFunc("server", cmpl.SuggestCandidatesF(client.Server().Names))

		cmd.Flags().StringP("label-selector", "l", "", "Label Selector")
		return cmd
	},
	Run: func(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		resourceType, _ := cmd.Flags().GetString("type")

		switch resourceType {
		case string(hcloud.FirewallResourceTypeServer):
			server, _ := cmd.Flags().GetString("server")
			if server == "" {
				return fmt.Errorf("type %s need a --server specific", resourceType)
			}
		case string(hcloud.FirewallResourceTypeLabelSelector):
			labelSelector, _ := cmd.Flags().GetString("label-selector")
			if labelSelector == "" {
				return fmt.Errorf("type %s need a --label-selector specific", resourceType)
			}
		default:
			return fmt.Errorf("unknown type %s", resourceType)
		}
		serverIdOrName, _ := cmd.Flags().GetString("server")
		labelSelector, _ := cmd.Flags().GetString("label-selector")

		idOrName := args[0]
		firewall, _, err := client.Firewall().Get(ctx, idOrName)
		if err != nil {
			return err
		}
		if firewall == nil {
			return fmt.Errorf("Firewall not found: %v", idOrName)
		}
		opts := hcloud.FirewallResource{Type: hcloud.FirewallResourceType(resourceType)}

		switch opts.Type {
		case hcloud.FirewallResourceTypeServer:
			server, _, err := client.Server().Get(ctx, serverIdOrName)
			if err != nil {
				return err
			}
			if server == nil {
				return fmt.Errorf("Server not found: %v", serverIdOrName)
			}
			opts.Server = &hcloud.FirewallResourceServer{ID: server.ID}
		case hcloud.FirewallResourceTypeLabelSelector:
			opts.LabelSelector = &hcloud.FirewallResourceLabelSelector{Selector: labelSelector}
		default:
			return fmt.Errorf("unknown type %s", opts.Type)
		}
		actions, _, err := client.Firewall().RemoveResources(ctx, firewall, []hcloud.FirewallResource{opts})
		if err != nil {
			return err
		}
		if err := waiter.WaitForActions(ctx, actions); err != nil {
			return err
		}
		fmt.Printf("Firewall %d applied\n", firewall.ID)

		return nil
	},
}
View Source
var ReplaceRulesCommand = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "replace-rules FIREWALL FLAGS",
			Short:                 "Replaces all rules from a Firewall from a file",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Firewall().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		cmd.Flags().String("rules-file", "", "JSON file containing your routes (use - to read from stdin). The structure of the file needs to be the same as within the API: https://docs.hetzner.cloud/#firewalls-get-a-firewall")
		cmd.MarkFlagRequired("rules-file")
		return cmd
	},
	Run: func(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		firewall, _, err := client.Firewall().Get(ctx, idOrName)
		if err != nil {
			return err
		}
		if firewall == nil {
			return fmt.Errorf("Firewall not found: %v", idOrName)
		}

		opts := hcloud.FirewallSetRulesOpts{}

		rulesFile, _ := cmd.Flags().GetString("rules-file")

		var data []byte
		if rulesFile == "-" {
			data, err = ioutil.ReadAll(os.Stdin)
		} else {
			data, err = ioutil.ReadFile(rulesFile)
		}
		if err != nil {
			return err
		}
		var rules []schema.FirewallRule
		err = json.Unmarshal(data, &rules)
		if err != nil {
			return err
		}
		for _, rule := range rules {
			d := hcloud.FirewallRuleDirection(rule.Direction)
			r := hcloud.FirewallRule{
				Direction:   d,
				Protocol:    hcloud.FirewallRuleProtocol(rule.Protocol),
				Port:        rule.Port,
				Description: rule.Description,
			}
			switch d {
			case hcloud.FirewallRuleDirectionOut:
				r.DestinationIPs = make([]net.IPNet, len(rule.DestinationIPs))
				for i, ip := range rule.DestinationIPs {
					_, n, err := net.ParseCIDR(ip)
					if err != nil {
						return fmt.Errorf("invalid CIDR on index %d : %s", i, err)
					}
					r.DestinationIPs[i] = *n
				}
			case hcloud.FirewallRuleDirectionIn:
				r.SourceIPs = make([]net.IPNet, len(rule.SourceIPs))
				for i, ip := range rule.SourceIPs {
					_, n, err := net.ParseCIDR(ip)
					if err != nil {
						return fmt.Errorf("invalid CIDR on index %d : %s", i, err)
					}
					r.SourceIPs[i] = *n
				}
			}
			opts.Rules = append(opts.Rules, r)
		}

		actions, _, err := client.Firewall().SetRules(ctx, firewall, opts)
		if err != nil {
			return err
		}
		if err := waiter.WaitForActions(ctx, actions); err != nil {
			return err
		}
		fmt.Printf("Firewall Rules for Firewall %d updated\n", firewall.ID)

		return nil
	},
}

Functions

func NewCommand

func NewCommand(cli *state.State, client hcapi2.Client) *cobra.Command

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL