File: iptables.go

package info (click to toggle)
golang-github-containernetworking-plugins 0.9.1%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 1,512 kB
  • sloc: sh: 124; makefile: 18
file content (266 lines) | stat: -rw-r--r-- 7,520 bytes parent folder | download | duplicates (2)
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
// Copyright 2016 CNI authors
//
// 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.

// This is a "meta-plugin". It reads in its own netconf, it does not create
// any network interface but just changes the network sysctl.

package main

import (
	"fmt"
	"net"

	"github.com/containernetworking/cni/pkg/types/current"
	"github.com/containernetworking/plugins/pkg/utils"
	"github.com/coreos/go-iptables/iptables"
)

func getPrivChainRules(ip string) [][]string {
	var rules [][]string
	rules = append(rules, []string{"-d", ip, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"})
	rules = append(rules, []string{"-s", ip, "-j", "ACCEPT"})
	return rules
}

func generateFilterRule(privChainName string) []string {
	return []string{"-m", "comment", "--comment", "CNI firewall plugin rules", "-j", privChainName}
}

func generateAdminRule(adminChainName string) []string {
	return []string{"-m", "comment", "--comment", "CNI firewall plugin admin overrides", "-j", adminChainName}
}

func cleanupRules(ipt *iptables.IPTables, privChainName string, rules [][]string) {
	for _, rule := range rules {
		ipt.Delete("filter", privChainName, rule...)
	}
}

func ensureFirstChainRule(ipt *iptables.IPTables, chain string, rule []string) error {
	exists, err := ipt.Exists("filter", chain, rule...)
	if !exists && err == nil {
		err = ipt.Insert("filter", chain, 1, rule...)
	}
	return err
}

func (ib *iptablesBackend) setupChains(ipt *iptables.IPTables) error {
	privRule := generateFilterRule(ib.privChainName)
	adminRule := generateAdminRule(ib.adminChainName)

	// Ensure our private chains exist
	if err := utils.EnsureChain(ipt, "filter", ib.privChainName); err != nil {
		return err
	}
	if err := utils.EnsureChain(ipt, "filter", ib.adminChainName); err != nil {
		return err
	}

	// Ensure our filter rule exists in the forward chain
	if err := ensureFirstChainRule(ipt, "FORWARD", privRule); err != nil {
		return err
	}

	// Ensure our admin override chain rule exists in our private chain
	if err := ensureFirstChainRule(ipt, ib.privChainName, adminRule); err != nil {
		return err
	}

	return nil
}

func protoForIP(ip net.IPNet) iptables.Protocol {
	if ip.IP.To4() != nil {
		return iptables.ProtocolIPv4
	}
	return iptables.ProtocolIPv6
}

func (ib *iptablesBackend) addRules(conf *FirewallNetConf, result *current.Result, ipt *iptables.IPTables, proto iptables.Protocol) error {
	rules := make([][]string, 0)
	for _, ip := range result.IPs {
		if protoForIP(ip.Address) == proto {
			rules = append(rules, getPrivChainRules(ipString(ip.Address))...)
		}
	}

	if len(rules) > 0 {
		if err := ib.setupChains(ipt); err != nil {
			return err
		}

		// Clean up on any errors
		var err error
		defer func() {
			if err != nil {
				cleanupRules(ipt, ib.privChainName, rules)
			}
		}()

		for _, rule := range rules {
			err = ipt.AppendUnique("filter", ib.privChainName, rule...)
			if err != nil {
				return err
			}
		}
	}

	return nil
}

func (ib *iptablesBackend) delRules(conf *FirewallNetConf, result *current.Result, ipt *iptables.IPTables, proto iptables.Protocol) error {
	rules := make([][]string, 0)
	for _, ip := range result.IPs {
		if protoForIP(ip.Address) == proto {
			rules = append(rules, getPrivChainRules(ipString(ip.Address))...)
		}
	}

	if len(rules) > 0 {
		cleanupRules(ipt, ib.privChainName, rules)
	}

	return nil
}

func (ib *iptablesBackend) checkRules(conf *FirewallNetConf, result *current.Result, ipt *iptables.IPTables, proto iptables.Protocol) error {
	rules := make([][]string, 0)
	for _, ip := range result.IPs {
		if protoForIP(ip.Address) == proto {
			rules = append(rules, getPrivChainRules(ipString(ip.Address))...)
		}
	}

	if len(rules) <= 0 {
		return nil
	}

	// Ensure our private chains exist
	if err := utils.EnsureChain(ipt, "filter", ib.privChainName); err != nil {
		return err
	}
	if err := utils.EnsureChain(ipt, "filter", ib.adminChainName); err != nil {
		return err
	}

	// Ensure our filter rule exists in the forward chain
	privRule := generateFilterRule(ib.privChainName)
	privExists, err := ipt.Exists("filter", "FORWARD", privRule...)
	if err != nil {
		return err
	}
	if !privExists {
		return fmt.Errorf("expected %v rule %v not found", "FORWARD", privRule)
	}

	// Ensure our admin override chain rule exists in our private chain
	adminRule := generateAdminRule(ib.adminChainName)
	adminExists, err := ipt.Exists("filter", ib.privChainName, adminRule...)
	if err != nil {
		return err
	}
	if !adminExists {
		return fmt.Errorf("expected %v rule %v not found", ib.privChainName, adminRule)
	}

	// ensure rules for this IP address exist
	for _, rule := range rules {
		// Ensure our rule exists in our private chain
		exists, err := ipt.Exists("filter", ib.privChainName, rule...)
		if err != nil {
			return err
		}
		if !exists {
			return fmt.Errorf("expected rule %v not found", rule)
		}
	}

	return nil
}

func findProtos(conf *FirewallNetConf) []iptables.Protocol {
	protos := []iptables.Protocol{iptables.ProtocolIPv4, iptables.ProtocolIPv6}
	if conf.PrevResult != nil {
		// If PrevResult is given, scan all IP addresses to figure out
		// which IP versions to use
		protos = []iptables.Protocol{}
		result, _ := current.NewResultFromResult(conf.PrevResult)
		for _, addr := range result.IPs {
			if addr.Address.IP.To4() != nil {
				protos = append(protos, iptables.ProtocolIPv4)
			} else {
				protos = append(protos, iptables.ProtocolIPv6)
			}
		}
	}
	return protos
}

type iptablesBackend struct {
	protos         map[iptables.Protocol]*iptables.IPTables
	privChainName  string
	adminChainName string
	ifName         string
}

// iptablesBackend implements the FirewallBackend interface
var _ FirewallBackend = &iptablesBackend{}

func newIptablesBackend(conf *FirewallNetConf) (FirewallBackend, error) {
	adminChainName := conf.IptablesAdminChainName
	if adminChainName == "" {
		adminChainName = "CNI-ADMIN"
	}

	backend := &iptablesBackend{
		privChainName:  "CNI-FORWARD",
		adminChainName: adminChainName,
		protos:         make(map[iptables.Protocol]*iptables.IPTables),
	}

	for _, proto := range []iptables.Protocol{iptables.ProtocolIPv4, iptables.ProtocolIPv6} {
		ipt, err := iptables.NewWithProtocol(proto)
		if err != nil {
			return nil, fmt.Errorf("could not initialize iptables protocol %v: %v", proto, err)
		}
		backend.protos[proto] = ipt
	}

	return backend, nil
}

func (ib *iptablesBackend) Add(conf *FirewallNetConf, result *current.Result) error {
	for proto, ipt := range ib.protos {
		if err := ib.addRules(conf, result, ipt, proto); err != nil {
			return err
		}
	}
	return nil
}

func (ib *iptablesBackend) Del(conf *FirewallNetConf, result *current.Result) error {
	for proto, ipt := range ib.protos {
		ib.delRules(conf, result, ipt, proto)
	}
	return nil
}

func (ib *iptablesBackend) Check(conf *FirewallNetConf, result *current.Result) error {
	for proto, ipt := range ib.protos {
		if err := ib.checkRules(conf, result, ipt, proto); err != nil {
			return err
		}
	}
	return nil
}