forked from contiv/vpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iptables_renderer.go
315 lines (279 loc) · 9.5 KB
/
iptables_renderer.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
// Copyright (c) 2019 Cisco and/or its affiliates.
//
// 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 iptables
import (
"fmt"
controller "github.com/contiv/vpp/plugins/controller/api"
"github.com/contiv/vpp/plugins/ipam"
"github.com/contiv/vpp/plugins/ipnet"
podmodel "github.com/contiv/vpp/plugins/ksr/model/pod"
"github.com/contiv/vpp/plugins/podmanager"
"github.com/contiv/vpp/plugins/policy/renderer"
"github.com/contiv/vpp/plugins/policy/renderer/cache"
"github.com/gogo/protobuf/proto"
"github.com/ligato/cn-infra/logging"
"github.com/ligato/vpp-agent/api/models/linux/iptables"
"github.com/ligato/vpp-agent/api/models/linux/namespace"
"net"
"strings"
)
const (
reflexiveRule = "-m state --state RELATED,ESTABLISHED -j ACCEPT"
allowSvcRule = "-d %v -j ACCEPT"
)
// Renderer renders Contiv Rules into iptables rules.
// The configuration changes are transported into iptables plugin via localclient.
type Renderer struct {
Deps
cache *cache.RendererCache
}
// Deps lists dependencies of Renderer.
type Deps struct {
Log logging.Logger
LogFactory logging.LoggerFactory /* optional */
PodManager podmanager.API
IPNet ipnet.API
IPAM ipam.API
UpdateTxn func() (txn controller.UpdateOperations)
ResyncTxn func() (txn controller.ResyncOperations)
}
// RendererTxn represents a single transaction of Renderer.
type RendererTxn struct {
Log logging.Logger
renderer *Renderer
cacheTxn cache.Txn
resync bool
}
// Init initializes the ACL Renderer.
func (r *Renderer) Init() error {
r.cache = &cache.RendererCache{}
if r.LogFactory != nil {
r.cache.Log = r.LogFactory.NewLogger("-iptablesCache")
} else {
r.cache.Log = r.Log
}
r.cache.Init(cache.EgressOrientation)
return nil
}
// NewTxn starts a new transaction. The rendering executes only after Commit()
// is called. Rollback is not yet supported however.
// If <resync> is enabled, the supplied configuration will completely
// replace the existing one. Otherwise, the change is performed incrementally,
// i.e. interfaces not mentioned in the transaction are left unaffected.
func (r *Renderer) NewTxn(resync bool) renderer.Txn {
txn := &RendererTxn{
Log: r.Log,
cacheTxn: r.cache.NewTxn(),
renderer: r,
resync: resync,
}
return txn
}
// Render applies the set of ingress & egress rules for a given pod.
// The existing rules are replaced. It adds rendered config for iptables into
// the current transaction.
func (rt *RendererTxn) Render(pod podmodel.ID, podIP *net.IPNet, ingress []*renderer.ContivRule, egress []*renderer.ContivRule, removed bool) renderer.Txn {
rt.renderer.Log.WithFields(logging.Fields{
"pod": pod,
"ingress-count": len(ingress),
"egress-count": len(egress),
"removed": removed,
}).Debug("iptables RendererTxn Render()")
rt.cacheTxn.Update(pod, &cache.PodConfig{PodIP: podIP, Ingress: ingress, Egress: egress, Removed: removed})
// ingress rule is applied AS-IS with additional rule allowing services
// all the other rules are re-calculated to egress direction only (applied in commit)
ruleChains := rt.renderRuleChains(pod, podIP, ingress, nil)
if rt.resync {
txn := rt.renderer.ResyncTxn()
controller.PutAll(txn, ruleChains)
} else {
txn := rt.renderer.UpdateTxn()
txn.Delete(linux_iptables.RuleChainKey(rt.chainName(pod, podIP, true)))
controller.PutAll(txn, ruleChains)
}
return rt
}
// Commit is currently NOOP since the config was added into the event transaction in render phase,
// it will be committed as a part of the event transaction.
func (rt *RendererTxn) Commit() error {
if rt.resync {
return rt.commitResync()
}
pods := make(cache.PodSet)
for _, change := range rt.cacheTxn.GetChanges() {
// re-render rules for pods that is either only in prevPods or only in pods set
symDiff := change.PreviousPods.SymDiff(change.Table.Pods)
pods.Join(symDiff)
}
hostIPs := rt.renderer.IPNet.GetHostIPs()
for podID := range pods {
var ruleChains controller.KeyValuePairs
_, found := rt.renderer.PodManager.GetLocalPods()[podID]
if !found {
// skip pods on other nodes
continue
}
pod := rt.cacheTxn.GetPodConfig(podID)
if isInIPlist(pod.PodIP.IP, hostIPs) {
continue
}
localTable := rt.cacheTxn.GetLocalTableByPod(podID)
if localTable != nil {
rules := localTable.Rules[:localTable.NumOfRules]
ruleChains = rt.renderRuleChains(podID, pod.PodIP, nil, rules)
}
txn := rt.renderer.UpdateTxn()
// remove old config
txn.Delete(linux_iptables.RuleChainKey(rt.chainName(podID, pod.PodIP, false)))
controller.PutAll(txn, ruleChains)
}
// Save changes into the cache.
return rt.cacheTxn.Commit()
}
// commitResync commits full iptables configuration for re-synchronization.
func (rt *RendererTxn) commitResync() error {
txn := rt.renderer.ResyncTxn()
// reset the cache and the renderer internal state first
rt.renderer.cache.Flush()
pods := make(cache.PodSet)
for _, change := range rt.cacheTxn.GetChanges() {
symDiff := change.PreviousPods.SymDiff(change.Table.Pods)
pods.Join(symDiff)
}
hostIPs := rt.renderer.IPNet.GetHostIPs()
// after the flush, changes == all newly created
for podID := range pods {
_, found := rt.renderer.PodManager.GetLocalPods()[podID]
if !found {
// skip pods on other nodes
continue
}
table := rt.cacheTxn.GetLocalTableByPod(podID)
if table == nil {
continue
}
rules := table.Rules[:table.NumOfRules]
pod := rt.cacheTxn.GetPodConfig(podID)
if isInIPlist(pod.PodIP.IP, hostIPs) {
continue
}
chains := rt.renderRuleChains(podID, pod.PodIP, nil, rules)
controller.PutAll(txn, chains)
}
// save changes into the cache.
return rt.cacheTxn.Commit()
}
// renderRuleChains transform set of rules for a given pod into iptables rule
func (rt *RendererTxn) renderRuleChains(podID podmodel.ID, podIP *net.IPNet, ingress []*renderer.ContivRule, egress []*renderer.ContivRule) controller.KeyValuePairs {
res := make(map[string]proto.Message)
pod, exists := rt.renderer.PodManager.GetLocalPods()[podID]
if !exists {
rt.Log.Warnf("pod %v not found in local pods list", podID)
return res
}
if len(ingress) > 0 {
c := &linux_iptables.RuleChain{}
c.Name = rt.chainName(podID, podIP, true)
c.Namespace = &linux_namespace.NetNamespace{
Type: linux_namespace.NetNamespace_FD,
Reference: pod.NetworkNamespace,
}
c.Protocol = rt.ruleChainProtocolForIP(podIP)
c.Table = linux_iptables.RuleChain_FILTER
c.ChainType = linux_iptables.RuleChain_OUTPUT
c.Rules = append(c.Rules, reflexiveRule)
c.Rules = append(c.Rules, fmt.Sprintf(allowSvcRule, rt.renderer.IPAM.ServiceNetwork().String()))
for _, i := range ingress {
c.Rules = append(c.Rules, rt.contivRuleToIPtables(i))
}
res[linux_iptables.RuleChainKey(c.Name)] = c
}
if len(egress) > 0 {
c := &linux_iptables.RuleChain{}
c.Name = rt.chainName(podID, podIP, false)
c.Namespace = &linux_namespace.NetNamespace{
Type: linux_namespace.NetNamespace_FD,
Reference: pod.NetworkNamespace,
}
c.Protocol = rt.ruleChainProtocolForIP(podIP)
c.Table = linux_iptables.RuleChain_FILTER
c.ChainType = linux_iptables.RuleChain_INPUT
c.Rules = append(c.Rules, reflexiveRule)
for _, e := range egress {
c.Rules = append(c.Rules, rt.contivRuleToIPtables(e))
}
res[linux_iptables.RuleChainKey(c.Name)] = c
}
return res
}
// contivRuleToIPtables transforms single ContiveRule to iptables rule
func (rt *RendererTxn) contivRuleToIPtables(rule *renderer.ContivRule) string {
var parts []string
// protocol must listed before --dport argument
parts = append(parts, fmt.Sprintf("-p %v", rt.protocolToStr(rule.Protocol)))
if rule.SrcNetwork != nil && len(rule.SrcNetwork.IP) > 0 {
parts = append(parts, fmt.Sprintf("-s %v", rule.SrcNetwork.String()))
}
if rule.SrcPort != 0 {
parts = append(parts, fmt.Sprintf("--sport %v", rule.SrcPort))
}
if rule.DestNetwork != nil && len(rule.DestNetwork.IP) > 0 {
parts = append(parts, fmt.Sprintf("-d %v", rule.DestNetwork.String()))
}
if rule.DestPort != 0 {
parts = append(parts, fmt.Sprintf("--dport %v", rule.DestPort))
}
parts = append(parts, fmt.Sprintf("-j %v", rt.actionToStr(rule.Action)))
return strings.Join(parts, " ")
}
// chainName returns name of the NB chain for a given pod
func (rt *RendererTxn) chainName(pod podmodel.ID, podIP *net.IPNet, isIngress bool) string {
name := "rule-"
if isIngress {
name += "ingress-"
} else {
name += "egress-"
}
name += pod.Namespace + "-" + pod.Name
return name
}
func (rt *RendererTxn) protocolToStr(p renderer.ProtocolType) string {
if p == renderer.TCP {
return "tcp"
}
if p == renderer.UDP {
return "udp"
}
return "all"
}
func (rt *RendererTxn) actionToStr(a renderer.ActionType) string {
if a == renderer.ActionPermit {
return "ACCEPT"
}
return "DROP"
}
func (rt *RendererTxn) ruleChainProtocolForIP(ipNet *net.IPNet) linux_iptables.RuleChain_Protocol {
if strings.Contains(ipNet.String(), ":") {
return linux_iptables.RuleChain_IPv6
}
return linux_iptables.RuleChain_IPv4
}
func isInIPlist(ip net.IP, ips []net.IP) bool {
for _, i := range ips {
if i.Equal(ip) {
return true
}
}
return false
}