-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
redirect_traffic.go
253 lines (209 loc) · 8.05 KB
/
redirect_traffic.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
package redirecttraffic
import (
"flag"
"fmt"
"net"
"strconv"
"github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/command/flags"
"github.com/hashicorp/consul/sdk/iptables"
"github.com/mitchellh/cli"
"github.com/mitchellh/mapstructure"
)
func New(ui cli.Ui) *cmd {
ui = &cli.PrefixedUi{
OutputPrefix: "==> ",
InfoPrefix: " ",
ErrorPrefix: "==> ",
Ui: ui,
}
c := &cmd{
UI: ui,
}
c.init()
return c
}
type cmd struct {
UI cli.Ui
flags *flag.FlagSet
http *flags.HTTPFlags
help string
client *api.Client
// Flags.
proxyUID string
proxyID string
proxyInboundPort int
proxyOutboundPort int
excludeInboundPorts []string
excludeOutboundPorts []string
excludeOutboundCIDRs []string
excludeUIDs []string
netNS string
}
func (c *cmd) init() {
c.flags = flag.NewFlagSet("", flag.ContinueOnError)
c.flags.StringVar(&c.proxyUID, "proxy-uid", "", "The user ID of the proxy to exclude from traffic redirection.")
c.flags.StringVar(&c.proxyID, "proxy-id", "", "The service ID of the proxy service registered with Consul.")
c.flags.IntVar(&c.proxyInboundPort, "proxy-inbound-port", 0, "The inbound port that the proxy is listening on.")
c.flags.IntVar(&c.proxyOutboundPort, "proxy-outbound-port", iptables.DefaultTProxyOutboundPort,
"The outbound port that the proxy is listening on. When not provided, 15001 is used by default.")
c.flags.Var((*flags.AppendSliceValue)(&c.excludeInboundPorts), "exclude-inbound-port",
"Inbound port to exclude from traffic redirection. May be provided multiple times.")
c.flags.Var((*flags.AppendSliceValue)(&c.excludeOutboundPorts), "exclude-outbound-port",
"Outbound port to exclude from traffic redirection. May be provided multiple times.")
c.flags.Var((*flags.AppendSliceValue)(&c.excludeOutboundCIDRs), "exclude-outbound-cidr",
"Outbound CIDR to exclude from traffic redirection. May be provided multiple times.")
c.flags.Var((*flags.AppendSliceValue)(&c.excludeUIDs), "exclude-uid",
"Additional user ID to exclude from traffic redirection. May be provided multiple times.")
c.flags.StringVar(&c.netNS, "netns", "", "The network namespace where traffic redirection rules should apply."+
"This must be a path to the network namespace, e.g. /var/run/netns/foo.")
c.http = &flags.HTTPFlags{}
flags.Merge(c.flags, c.http.ClientFlags())
flags.Merge(c.flags, c.http.NamespaceFlags())
c.help = flags.Usage(help, c.flags)
}
func (c *cmd) Run(args []string) int {
if err := c.flags.Parse(args); err != nil {
c.UI.Error(fmt.Sprintf("Failed to parse args: %v", err))
return 1
}
if c.proxyUID == "" {
c.UI.Error("-proxy-uid is required")
return 1
}
if c.proxyID == "" && c.proxyInboundPort == 0 {
c.UI.Error("either -proxy-id or -proxy-inbound-port are required")
return 1
}
if c.proxyID != "" && (c.proxyInboundPort != 0 || c.proxyOutboundPort != iptables.DefaultTProxyOutboundPort) {
c.UI.Error("-proxy-inbound-port or -proxy-outbound-port cannot be provided together with -proxy-id. " +
"Proxy's inbound and outbound ports are retrieved from the proxy's configuration instead.")
return 1
}
cfg, err := c.generateConfigFromFlags()
if err != nil {
c.UI.Error(fmt.Sprintf("Failed to create configuration to apply traffic redirection rules: %s", err))
return 1
}
err = iptables.Setup(cfg)
if err != nil {
c.UI.Error(fmt.Sprintf("Error setting up traffic redirection rules: %s", err.Error()))
return 1
}
c.UI.Info("Successfully applied traffic redirection rules")
return 0
}
func (c *cmd) Synopsis() string {
return synopsis
}
func (c *cmd) Help() string {
return c.help
}
// trafficRedirectProxyConfig is a snippet of xds/config.go
// with only the configuration values that we need to parse from Proxy.Config
// to apply traffic redirection rules.
type trafficRedirectProxyConfig struct {
BindPort int `mapstructure:"bind_port"`
PrometheusBindAddr string `mapstructure:"envoy_prometheus_bind_addr"`
StatsBindAddr string `mapstructure:"envoy_stats_bind_addr"`
}
// generateConfigFromFlags generates iptables.Config based on command flags.
func (c *cmd) generateConfigFromFlags() (iptables.Config, error) {
cfg := iptables.Config{
ProxyUserID: c.proxyUID,
ProxyInboundPort: c.proxyInboundPort,
ProxyOutboundPort: c.proxyOutboundPort,
NetNS: c.netNS,
}
// When proxyID is provided, we set up cfg with values
// from proxy's service registration in Consul.
if c.proxyID != "" {
var err error
if c.client == nil {
c.client, err = c.http.APIClient()
if err != nil {
return iptables.Config{}, fmt.Errorf("error creating Consul API client: %s", err)
}
}
svc, _, err := c.client.Agent().Service(c.proxyID, nil)
if err != nil {
return iptables.Config{}, fmt.Errorf("failed to fetch proxy service from Consul Agent: %s", err)
}
if svc.Proxy == nil {
return iptables.Config{}, fmt.Errorf("service %s is not a proxy service", c.proxyID)
}
// Decode proxy's opaque config so that we can use it later to configure
// traffic redirection with iptables.
var trCfg trafficRedirectProxyConfig
if err := mapstructure.WeakDecode(svc.Proxy.Config, &trCfg); err != nil {
return iptables.Config{}, fmt.Errorf("failed parsing Proxy.Config: %s", err)
}
// Set the proxy's inbound port.
cfg.ProxyInboundPort = svc.Port
if trCfg.BindPort != 0 {
cfg.ProxyInboundPort = trCfg.BindPort
}
// Set the proxy's outbound port.
cfg.ProxyOutboundPort = iptables.DefaultTProxyOutboundPort
if svc.Proxy.TransparentProxy != nil && svc.Proxy.TransparentProxy.OutboundListenerPort != 0 {
cfg.ProxyOutboundPort = svc.Proxy.TransparentProxy.OutboundListenerPort
}
// Exclude envoy_prometheus_bind_addr port from inbound redirection rules.
if trCfg.PrometheusBindAddr != "" {
_, port, err := net.SplitHostPort(trCfg.PrometheusBindAddr)
if err != nil {
return iptables.Config{}, fmt.Errorf("failed parsing host and port from envoy_prometheus_bind_addr: %s", err)
}
cfg.ExcludeInboundPorts = append(cfg.ExcludeInboundPorts, port)
}
// Exclude envoy_stats_bind_addr port from inbound redirection rules.
if trCfg.StatsBindAddr != "" {
_, port, err := net.SplitHostPort(trCfg.StatsBindAddr)
if err != nil {
return iptables.Config{}, fmt.Errorf("failed parsing host and port from envoy_stats_bind_addr: %s", err)
}
cfg.ExcludeInboundPorts = append(cfg.ExcludeInboundPorts, port)
}
// Exclude the ListenerPort from Expose configs from inbound traffic redirection.
for _, exposePath := range svc.Proxy.Expose.Paths {
if exposePath.ListenerPort != 0 {
cfg.ExcludeInboundPorts = append(cfg.ExcludeInboundPorts, strconv.Itoa(exposePath.ListenerPort))
}
}
// Exclude any exposed health check ports when Proxy.Expose.Checks is true.
if svc.Proxy.Expose.Checks {
// Get the health checks of the destination service.
checks, err := c.client.Agent().ChecksWithFilter(fmt.Sprintf("ServiceName == %q", svc.Proxy.DestinationServiceName))
if err != nil {
return iptables.Config{}, err
}
for _, check := range checks {
if check.ExposedPort != 0 {
cfg.ExcludeInboundPorts = append(cfg.ExcludeInboundPorts, strconv.Itoa(check.ExposedPort))
}
}
}
}
for _, port := range c.excludeInboundPorts {
cfg.ExcludeInboundPorts = append(cfg.ExcludeInboundPorts, port)
}
for _, port := range c.excludeOutboundPorts {
cfg.ExcludeOutboundPorts = append(cfg.ExcludeOutboundPorts, port)
}
for _, cidr := range c.excludeOutboundCIDRs {
cfg.ExcludeOutboundCIDRs = append(cfg.ExcludeOutboundCIDRs, cidr)
}
for _, uid := range c.excludeUIDs {
cfg.ExcludeUIDs = append(cfg.ExcludeUIDs, uid)
}
return cfg, nil
}
const synopsis = "Applies iptables rules for traffic redirection"
const help = `
Usage: consul connect redirect-traffic [options]
Applies iptables rules for inbound and outbound traffic redirection.
Requires that the iptables command line utility is installed.
Examples:
$ consul connect redirect-traffic -proxy-uid 1234 -proxy-id web
$ consul connect redirect-traffic -proxy-uid 1234 -proxy-inbound-port 20000
`