/
firewall.go
229 lines (202 loc) · 8.02 KB
/
firewall.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package cmd
import (
"encoding/base64"
"fmt"
"time"
"github.com/metal-stack/metal-go/api/client/firewall"
"github.com/metal-stack/metal-go/api/models"
"github.com/metal-stack/metal-lib/pkg/genericcli"
"github.com/metal-stack/metal-lib/pkg/genericcli/printers"
"github.com/metal-stack/metal-lib/pkg/pointer"
"github.com/metal-stack/metalctl/cmd/sorters"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
type firewallCmd struct {
*config
}
func newFirewallCmd(c *config) *cobra.Command {
w := firewallCmd{
config: c,
}
cmdsConfig := &genericcli.CmdsConfig[*models.V1FirewallCreateRequest, any, *models.V1FirewallResponse]{
BinaryName: binaryName,
GenericCLI: genericcli.NewGenericCLI[*models.V1FirewallCreateRequest, any, *models.V1FirewallResponse](w).WithFS(c.fs),
OnlyCmds: genericcli.OnlyCmds(
genericcli.ListCmd,
genericcli.DescribeCmd,
genericcli.CreateCmd,
),
Singular: "firewall",
Plural: "firewalls",
Description: "firewalls are used to establish network connectivity between metal-stack networks. firewalls are similar to machines but are managed by the provider. almost every command of the machine command subset works on firewalls, too.",
Aliases: []string{"fw"},
CreateRequestFromCLI: w.createRequestFromCLI,
Sorter: sorters.FirewallSorter(),
DescribePrinter: func() printers.Printer { return c.describePrinter },
ListPrinter: func() printers.Printer { return c.listPrinter },
ValidArgsFn: c.comp.FirewallListCompletion,
CreateCmdMutateFn: func(cmd *cobra.Command) {
c.addMachineCreateFlags(cmd, "firewall")
cmd.Aliases = []string{"allocate"}
},
ListCmdMutateFn: func(cmd *cobra.Command) {
cmd.Flags().String("id", "", "ID to filter [optional]")
cmd.Flags().String("partition", "", "partition to filter [optional]")
cmd.Flags().String("size", "", "size to filter [optional]")
cmd.Flags().String("name", "", "allocation name to filter [optional]")
cmd.Flags().String("project", "", "allocation project to filter [optional]")
cmd.Flags().String("image", "", "allocation image to filter [optional]")
cmd.Flags().String("hostname", "", "allocation hostname to filter [optional]")
cmd.Flags().StringSlice("mac", []string{}, "mac to filter [optional]")
cmd.Flags().StringSlice("tags", []string{}, "tags to filter, use it like: --tags \"tag1,tag2\" or --tags \"tag3\".")
must(cmd.RegisterFlagCompletionFunc("partition", c.comp.PartitionListCompletion))
must(cmd.RegisterFlagCompletionFunc("size", c.comp.SizeListCompletion))
must(cmd.RegisterFlagCompletionFunc("project", c.comp.ProjectListCompletion))
must(cmd.RegisterFlagCompletionFunc("id", c.comp.FirewallListCompletion))
must(cmd.RegisterFlagCompletionFunc("image", c.comp.ImageListCompletion))
},
}
firewallSSHCmd := &cobra.Command{
Use: "ssh <firewall ID>",
Short: "SSH to a firewall",
Long: `SSH to a firewall via VPN.`,
RunE: func(cmd *cobra.Command, args []string) error {
return w.firewallSSH(args)
},
ValidArgsFunction: c.comp.FirewallListCompletion,
}
firewallSSHCmd.Flags().StringP("identity", "i", "~/.ssh/id_rsa", "specify identity file to SSH to the firewall like: -i path/to/id_rsa")
return genericcli.NewCmds(cmdsConfig, firewallSSHCmd)
}
func (c firewallCmd) Get(id string) (*models.V1FirewallResponse, error) {
resp, err := c.client.Firewall().FindFirewall(firewall.NewFindFirewallParams().WithID(id), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func (c firewallCmd) List() ([]*models.V1FirewallResponse, error) {
resp, err := c.client.Firewall().FindFirewalls(firewall.NewFindFirewallsParams().WithBody(&models.V1FirewallFindRequest{
ID: viper.GetString("id"),
PartitionID: viper.GetString("partition"),
Sizeid: viper.GetString("size"),
Name: viper.GetString("name"),
AllocationProject: viper.GetString("project"),
AllocationImageID: viper.GetString("image"),
AllocationHostname: viper.GetString("hostname"),
NicsMacAddresses: viper.GetStringSlice("mac"),
Tags: viper.GetStringSlice("tags"),
}), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func (c firewallCmd) Delete(_ string) (*models.V1FirewallResponse, error) {
return nil, fmt.Errorf("firewall entity does not support delete operation, use machine delete")
}
func (c firewallCmd) Create(rq *models.V1FirewallCreateRequest) (*models.V1FirewallResponse, error) {
resp, err := c.client.Firewall().AllocateFirewall(firewall.NewAllocateFirewallParams().WithBody(rq), nil)
if err != nil {
return nil, err
}
return resp.Payload, nil
}
func (c firewallCmd) Update(rq any) (*models.V1FirewallResponse, error) {
return nil, fmt.Errorf("firewall entity does not support update operation, use machine update")
}
func (c firewallCmd) Convert(r *models.V1FirewallResponse) (string, *models.V1FirewallCreateRequest, any, error) {
if r.ID == nil {
return "", nil, nil, fmt.Errorf("id is nil")
}
return *r.ID, firewallResponseToCreate(r), nil, nil
}
func firewallResponseToCreate(r *models.V1FirewallResponse) *models.V1FirewallCreateRequest {
var (
ips []string
networks []*models.V1MachineAllocationNetwork
allocation = pointer.SafeDeref(r.Allocation)
)
for _, s := range allocation.Networks {
ips = append(ips, s.Ips...)
networks = append(networks, &models.V1MachineAllocationNetwork{
Autoacquire: pointer.Pointer(len(s.Ips) == 0),
Networkid: s.Networkid,
})
}
return &models.V1FirewallCreateRequest{
Description: allocation.Description,
Filesystemlayoutid: pointer.SafeDeref(pointer.SafeDeref(allocation.Filesystemlayout).ID),
Hostname: pointer.SafeDeref(allocation.Hostname),
Imageid: pointer.SafeDeref(allocation.Image).ID,
Ips: ips,
Name: r.Name,
Networks: networks,
Partitionid: r.Partition.ID,
Projectid: allocation.Project,
Sizeid: r.Size.ID,
SSHPubKeys: allocation.SSHPubKeys,
Tags: r.Tags,
UserData: base64.StdEncoding.EncodeToString([]byte(allocation.UserData)),
UUID: pointer.SafeDeref(r.ID),
}
}
func (c *firewallCmd) createRequestFromCLI() (*models.V1FirewallCreateRequest, error) {
mcr, err := machineCreateRequest()
if err != nil {
return nil, fmt.Errorf("firewall create error:%w", err)
}
return &models.V1FirewallCreateRequest{
Description: mcr.Description,
Filesystemlayoutid: mcr.Filesystemlayoutid,
Partitionid: mcr.Partitionid,
Hostname: mcr.Hostname,
Imageid: mcr.Imageid,
Name: mcr.Name,
UUID: mcr.UUID,
Projectid: mcr.Projectid,
Sizeid: mcr.Sizeid,
SSHPubKeys: mcr.SSHPubKeys,
UserData: mcr.UserData,
Tags: mcr.Tags,
Networks: mcr.Networks,
Ips: mcr.Ips,
}, nil
}
func (c *firewallCmd) firewallSSH(args []string) (err error) {
firewallID, err := genericcli.GetExactlyOneArg(args)
if err != nil {
return err
}
firewall, err := c.Get(firewallID)
if err != nil {
return fmt.Errorf("failed to find firewall: %w", err)
}
if firewall.Allocation != nil && firewall.Allocation.Vpn != nil && firewall.Allocation.Vpn.Connected != nil && *firewall.Allocation.Vpn.Connected {
return c.firewallSSHViaVPN(firewall)
}
// Try to connect to firewall via SSH
if err := c.firewallPureSSH(firewall.Allocation); err != nil {
return fmt.Errorf("failed to connect to firewall via SSH: %w", err)
}
return nil
}
func (c *firewallCmd) firewallPureSSH(fwAllocation *models.V1MachineAllocation) (err error) {
networks := fwAllocation.Networks
for _, nw := range networks {
if *nw.Underlay || *nw.Private {
continue
}
for _, ip := range nw.Ips {
if portOpen(ip, "22", time.Second) {
err = sshClient("metal", viper.GetString("identity"), ip, 22, nil)
if err != nil {
return err
}
return nil
}
}
}
return fmt.Errorf("no ip with a open ssh port found")
}