forked from projectcalico/felix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rule_defs.go
327 lines (278 loc) · 11.4 KB
/
rule_defs.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
// Copyright (c) 2016-2018 Tigera, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rules
import (
"net"
"reflect"
"strings"
log "github.com/sirupsen/logrus"
"github.com/projectcalico/felix/config"
"github.com/projectcalico/felix/ipsets"
"github.com/projectcalico/felix/iptables"
"github.com/projectcalico/felix/proto"
"github.com/projectcalico/libcalico-go/lib/numorstring"
)
const (
// ChainNamePrefix is a prefix used for all our iptables chain names. We include a '-' at
// the end to reduce clashes with other apps. Our OpenStack DHCP agent uses prefix
// 'calico-dhcp-', for example.
ChainNamePrefix = "cali-"
// IPSetNamePrefix: similarly for IP sets, we use the following prefix; the IP sets layer
// adds its own "-" so it isn't included here.
IPSetNamePrefix = "cali"
ChainFilterInput = ChainNamePrefix + "INPUT"
ChainFilterForward = ChainNamePrefix + "FORWARD"
ChainFilterOutput = ChainNamePrefix + "OUTPUT"
ChainRawPrerouting = ChainNamePrefix + "PREROUTING"
ChainRawOutput = ChainNamePrefix + "OUTPUT"
ChainFailsafeIn = ChainNamePrefix + "failsafe-in"
ChainFailsafeOut = ChainNamePrefix + "failsafe-out"
ChainNATPrerouting = ChainNamePrefix + "PREROUTING"
ChainNATPostrouting = ChainNamePrefix + "POSTROUTING"
ChainNATOutput = ChainNamePrefix + "OUTPUT"
ChainNATOutgoing = ChainNamePrefix + "nat-outgoing"
ChainManglePrerouting = ChainNamePrefix + "PREROUTING"
IPSetIDNATOutgoingAllPools = "all-ipam-pools"
IPSetIDNATOutgoingMasqPools = "masq-ipam-pools"
IPSetIDAllHostNets = "all-hosts-net"
IPSetIDThisHostIPs = "this-host"
ChainFIPDnat = ChainNamePrefix + "fip-dnat"
ChainFIPSnat = ChainNamePrefix + "fip-snat"
PolicyInboundPfx PolicyChainNamePrefix = ChainNamePrefix + "pi-"
PolicyOutboundPfx PolicyChainNamePrefix = ChainNamePrefix + "po-"
ProfileInboundPfx ProfileChainNamePrefix = ChainNamePrefix + "pri-"
ProfileOutboundPfx ProfileChainNamePrefix = ChainNamePrefix + "pro-"
ChainWorkloadToHost = ChainNamePrefix + "wl-to-host"
ChainFromWorkloadDispatch = ChainNamePrefix + "from-wl-dispatch"
ChainToWorkloadDispatch = ChainNamePrefix + "to-wl-dispatch"
ChainDispatchToHostEndpoint = ChainNamePrefix + "to-host-endpoint"
ChainDispatchFromHostEndpoint = ChainNamePrefix + "from-host-endpoint"
ChainDispatchToHostEndpointForward = ChainNamePrefix + "to-hep-forward"
ChainDispatchFromHostEndPointForward = ChainNamePrefix + "from-hep-forward"
ChainDispatchSetEndPointMark = ChainNamePrefix + "set-endpoint-mark"
ChainDispatchFromEndPointMark = ChainNamePrefix + "from-endpoint-mark"
ChainForwardCheck = ChainNamePrefix + "forward-check"
ChainForwardEndpointMark = ChainNamePrefix + "forward-endpoint-mark"
WorkloadToEndpointPfx = ChainNamePrefix + "tw-"
WorkloadFromEndpointPfx = ChainNamePrefix + "fw-"
SetEndPointMarkPfx = ChainNamePrefix + "sm-"
HostToEndpointPfx = ChainNamePrefix + "th-"
HostFromEndpointPfx = ChainNamePrefix + "fh-"
HostToEndpointForwardPfx = ChainNamePrefix + "thfw-"
HostFromEndpointForwardPfx = ChainNamePrefix + "fhfw-"
RuleHashPrefix = "cali:"
// HistoricNATRuleInsertRegex is a regex pattern to match to match
// special-case rules inserted by old versions of felix. Specifically,
// Python felix used to insert a masquerade rule directly into the
// POSTROUTING chain.
//
// Note: this regex depends on the output format of iptables-save so,
// where possible, it's best to match only on part of the rule that
// we're sure can't change (such as the ipset name in the masquerade
// rule).
HistoricInsertedNATRuleRegex = `-A POSTROUTING .* felix-masq-ipam-pools .*|` +
`-A POSTROUTING -o tunl0 -m addrtype ! --src-type LOCAL --limit-iface-out -m addrtype --src-type LOCAL -j MASQUERADE`
)
// Typedefs to prevent accidentally passing the wrong prefix to the Policy/ProfileChainName()
type PolicyChainNamePrefix string
type ProfileChainNamePrefix string
var (
// AllHistoricChainNamePrefixes lists all the prefixes that we've used for chains. Keeping
// track of the old names lets us clean them up.
AllHistoricChainNamePrefixes = []string{
// Current.
"cali-",
// Early RCs of Felix 2.1 used "cali" as the prefix for some chains rather than
// "cali-". This led to name clashes with the DHCP agent, which uses "calico-" as
// its prefix. We need to explicitly list these exceptions.
"califw-",
"calitw-",
"califh-",
"calith-",
"calipi-",
"calipo-",
// Pre Felix v2.1.
"felix-",
}
// AllHistoricIPSetNamePrefixes, similarly contains all the prefixes we've ever used for IP
// sets.
AllHistoricIPSetNamePrefixes = []string{"felix-", "cali"}
// LegacyV4IPSetNames contains some extra IP set names that were used in older versions of
// Felix and don't fit our versioned pattern.
LegacyV4IPSetNames = []string{"felix-masq-ipam-pools", "felix-all-ipam-pools"}
)
type RuleRenderer interface {
StaticFilterTableChains(ipVersion uint8) []*iptables.Chain
StaticNATTableChains(ipVersion uint8) []*iptables.Chain
StaticRawTableChains(ipVersion uint8) []*iptables.Chain
StaticMangleTableChains(ipVersion uint8) []*iptables.Chain
WorkloadDispatchChains(map[proto.WorkloadEndpointID]*proto.WorkloadEndpoint) []*iptables.Chain
WorkloadEndpointToIptablesChains(
ifaceName string,
epMarkMapper EndpointMarkMapper,
adminUp bool,
ingressPolicies []string,
egressPolicies []string,
profileIDs []string,
) []*iptables.Chain
EndpointMarkDispatchChains(
epMarkMapper EndpointMarkMapper,
wlEndpoints map[proto.WorkloadEndpointID]*proto.WorkloadEndpoint,
hepEndpoints map[string]proto.HostEndpointID,
) []*iptables.Chain
HostDispatchChains(map[string]proto.HostEndpointID, bool) []*iptables.Chain
FromHostDispatchChains(map[string]proto.HostEndpointID, string) []*iptables.Chain
HostEndpointToFilterChains(
ifaceName string,
epMarkMapper EndpointMarkMapper,
ingressPolicyNames []string,
egressPolicyNames []string,
ingressForwardPolicyNames []string,
egressForwardPolicyNames []string,
profileIDs []string,
) []*iptables.Chain
HostEndpointToRawChains(
ifaceName string,
ingressPolicyNames []string,
egressPolicyNames []string,
) []*iptables.Chain
HostEndpointToMangleChains(
ifaceName string,
preDNATPolicyNames []string,
) []*iptables.Chain
PolicyToIptablesChains(policyID *proto.PolicyID, policy *proto.Policy, ipVersion uint8) []*iptables.Chain
ProfileToIptablesChains(profileID *proto.ProfileID, policy *proto.Profile, ipVersion uint8) []*iptables.Chain
ProtoRuleToIptablesRules(pRule *proto.Rule, ipVersion uint8) []iptables.Rule
MakeNatOutgoingRule(protocol string, action iptables.Action, ipVersion uint8) iptables.Rule
NATOutgoingChain(active bool, ipVersion uint8) *iptables.Chain
DNATsToIptablesChains(dnats map[string]string) []*iptables.Chain
SNATsToIptablesChains(snats map[string]string) []*iptables.Chain
}
type DefaultRuleRenderer struct {
Config
inputAcceptActions []iptables.Action
filterAllowAction iptables.Action
mangleAllowAction iptables.Action
}
func (r *DefaultRuleRenderer) ipSetConfig(ipVersion uint8) *ipsets.IPVersionConfig {
if ipVersion == 4 {
return r.IPSetConfigV4
} else if ipVersion == 6 {
return r.IPSetConfigV6
} else {
log.WithField("version", ipVersion).Panic("Unknown IP version")
return nil
}
}
type Config struct {
IPSetConfigV4 *ipsets.IPVersionConfig
IPSetConfigV6 *ipsets.IPVersionConfig
WorkloadIfacePrefixes []string
IptablesMarkAccept uint32
IptablesMarkPass uint32
IptablesMarkScratch0 uint32
IptablesMarkScratch1 uint32
IptablesMarkEndpoint uint32
// IptablesMarkNonCaliEndpoint is an endpoint mark which is reserved
// to mark non-calico (workload or host) endpoint.
IptablesMarkNonCaliEndpoint uint32
KubeNodePortRanges []numorstring.Port
KubeIPVSSupportEnabled bool
OpenStackMetadataIP net.IP
OpenStackMetadataPort uint16
OpenStackSpecialCasesEnabled bool
IPIPEnabled bool
// IPIPTunnelAddress is an address chosen from an IPAM pool, used as a source address
// by the host when sending traffic to a workload over IPIP.
IPIPTunnelAddress net.IP
IptablesLogPrefix string
EndpointToHostAction string
IptablesFilterAllowAction string
IptablesMangleAllowAction string
FailsafeInboundHostPorts []config.ProtoPort
FailsafeOutboundHostPorts []config.ProtoPort
DisableConntrackInvalid bool
NATPortRange numorstring.Port
IptablesNATOutgoingInterfaceFilter string
}
func (c *Config) validate() {
// Scan for unset iptables mark bits. We use reflection so that we have a hope of catching
// newly-added fields.
myValue := reflect.ValueOf(c).Elem()
myType := myValue.Type()
found := 0
usedBits := uint32(0)
for i := 0; i < myValue.NumField(); i++ {
fieldName := myType.Field(i).Name
if strings.HasPrefix(fieldName, "IptablesMark") && fieldName != "IptablesMarkNonCaliEndpoint" {
bits := myValue.Field(i).Interface().(uint32)
if bits == 0 {
log.WithField("field", fieldName).Panic(
"IptablesMarkXXX field not set.")
}
if usedBits&bits > 0 {
log.WithField("field", fieldName).Panic(
"IptablesMarkXXX field overlapped with another's bits.")
}
usedBits |= bits
found++
}
}
if found == 0 {
// Check the reflection found something we were expecting.
log.Panic("Didn't find any IptablesMarkXXX fields.")
}
}
func NewRenderer(config Config) RuleRenderer {
log.WithField("config", config).Info("Creating rule renderer.")
config.validate()
// Convert configured actions to rule slices.
// First, what should we do with packets that come from workloads to the host itself.
var inputAcceptActions []iptables.Action
switch config.EndpointToHostAction {
case "DROP":
log.Info("Workload to host packets will be dropped.")
inputAcceptActions = []iptables.Action{iptables.DropAction{}}
case "ACCEPT":
log.Info("Workload to host packets will be accepted.")
inputAcceptActions = []iptables.Action{iptables.AcceptAction{}}
default:
log.Info("Workload to host packets will be returned to INPUT chain.")
inputAcceptActions = []iptables.Action{iptables.ReturnAction{}}
}
//What should we do with packets that are accepted in the forwarding chain
var filterAllowAction, mangleAllowAction iptables.Action
switch config.IptablesFilterAllowAction {
case "RETURN":
log.Info("filter table allowed packets will be returned to FORWARD chain.")
filterAllowAction = iptables.ReturnAction{}
default:
log.Info("filter table allowed packets will be accepted immediately.")
filterAllowAction = iptables.AcceptAction{}
}
switch config.IptablesMangleAllowAction {
case "RETURN":
log.Info("mangle table allowed packets will be returned to PREROUTING chain.")
mangleAllowAction = iptables.ReturnAction{}
default:
log.Info("mangle table allowed packets will be accepted immediately.")
mangleAllowAction = iptables.AcceptAction{}
}
return &DefaultRuleRenderer{
Config: config,
inputAcceptActions: inputAcceptActions,
filterAllowAction: filterAllowAction,
mangleAllowAction: mangleAllowAction,
}
}