forked from concourse/concourse
/
cni_network.go
321 lines (270 loc) · 7.51 KB
/
cni_network.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
package runtime
import (
"context"
"fmt"
"path/filepath"
"github.com/chenbh/concourse/v6/worker/runtime/iptables"
"github.com/containerd/containerd"
"github.com/containerd/go-cni"
"github.com/opencontainers/runtime-spec/specs-go"
)
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 github.com/containerd/go-cni.CNI
// CNINetworkConfig provides configuration for CNINetwork to override the
// defaults.
//
type CNINetworkConfig struct {
// BridgeName is the name that the bridge set up in the current network
// namespace to connect the veth's to.
//
BridgeName string
// NetworkName is the virtual name used to identify the managed network.
//
NetworkName string
// Subnet is the subnet (in CIDR notation) which the veths should be
// added to.
//
Subnet string
}
const (
// fileStoreWorkDir is a default directory used for storing
// container-related files
//
fileStoreWorkDir = "/tmp"
// binariesDir corresponds to the directory where CNI plugins have their
// binaries in.
//
binariesDir = "/usr/local/concourse/bin"
ipTablesAdminChainName = "CONCOURSE-OPERATOR"
)
var (
// defaultNameServers is the default set of nameservers used.
//
defaultNameServers = []string{"8.8.8.8"}
// defaultCNINetworkConfig is the default configuration for the CNI network
// created to put concourse containers into.
//
defaultCNINetworkConfig = CNINetworkConfig{
BridgeName: "concourse0",
NetworkName: "concourse",
Subnet: "10.80.0.0/16",
}
)
func (c CNINetworkConfig) ToJSON() string {
const networksConfListFormat = `{
"cniVersion": "0.4.0",
"name": "%s",
"plugins": [
{
"type": "bridge",
"bridge": "%s",
"isGateway": true,
"ipMasq": true,
"ipam": {
"type": "host-local",
"subnet": "%s",
"routes": [
{
"dst": "0.0.0.0/0"
}
]
}
},
{
"type": "firewall",
"iptablesAdminChainName": "%s"
}
]
}`
return fmt.Sprintf(networksConfListFormat,
c.NetworkName, c.BridgeName, c.Subnet, ipTablesAdminChainName,
)
}
// CNINetworkOpt defines a functional option that when applied, modifies the
// configuration of a CNINetwork.
//
type CNINetworkOpt func(n *cniNetwork)
// WithCNIBinariesDir is the directory where the binaries necessary for setting
// up the network live.
//
func WithCNIBinariesDir(dir string) CNINetworkOpt {
return func(n *cniNetwork) {
n.binariesDir = dir
}
}
// WithNameServers sets the set of nameservers to be configured for the
// /etc/resolv.conf inside the containers.
//
func WithNameServers(nameservers []string) CNINetworkOpt {
return func(n *cniNetwork) {
n.nameServers = nameservers
}
}
// WithCNIClient is an implementor of the CNI interface for reaching out to CNI
// plugins.
//
func WithCNIClient(c cni.CNI) CNINetworkOpt {
return func(n *cniNetwork) {
n.client = c
}
}
// WithCNINetworkConfig provides a custom CNINetworkConfig to be used by the CNI
// client at startup time.
//
func WithCNINetworkConfig(c CNINetworkConfig) CNINetworkOpt {
return func(n *cniNetwork) {
n.config = c
}
}
// WithCNIFileStore changes the default FileStore used to store files that
// belong to network configurations for containers.
//
func WithCNIFileStore(f FileStore) CNINetworkOpt {
return func(n *cniNetwork) {
n.store = f
}
}
// WithRestrictedNetworks defines the network ranges that containers will be restricted
// from accessing.
func WithRestrictedNetworks(restrictedNetworks []string) CNINetworkOpt {
return func(n *cniNetwork) {
n.restrictedNetworks = restrictedNetworks
}
}
// WithIptables allows for a custom implementation of the iptables.Iptables interface
// to be provided.
func WithIptables(ipt iptables.Iptables) CNINetworkOpt {
return func(n *cniNetwork) {
n.ipt = ipt
}
}
type cniNetwork struct {
client cni.CNI
store FileStore
config CNINetworkConfig
nameServers []string
binariesDir string
restrictedNetworks []string
ipt iptables.Iptables
}
var _ Network = (*cniNetwork)(nil)
func NewCNINetwork(opts ...CNINetworkOpt) (*cniNetwork, error) {
var err error
n := &cniNetwork{
binariesDir: binariesDir,
config: defaultCNINetworkConfig,
nameServers: defaultNameServers,
}
for _, opt := range opts {
opt(n)
}
if n.store == nil {
n.store = NewFileStore(fileStoreWorkDir)
}
if n.client == nil {
n.client, err = cni.New(cni.WithPluginDir([]string{n.binariesDir}))
if err != nil {
return nil, fmt.Errorf("cni init: %w", err)
}
err = n.client.Load(
cni.WithConfListBytes([]byte(n.config.ToJSON())),
cni.WithLoNetwork,
)
if err != nil {
return nil, fmt.Errorf("cni configuration loading: %w", err)
}
}
if n.ipt == nil {
n.ipt, err = iptables.New()
if err != nil {
return nil, fmt.Errorf("failed to initialized iptables")
}
}
return n, nil
}
func (n cniNetwork) SetupMounts(handle string) ([]specs.Mount, error) {
if handle == "" {
return nil, ErrInvalidInput("empty handle")
}
etcHosts, err := n.store.Create(
filepath.Join(handle, "/hosts"),
[]byte("127.0.0.1 localhost"),
)
if err != nil {
return nil, fmt.Errorf("creating /etc/hosts: %w", err)
}
resolvConf, err := n.store.Create(
filepath.Join(handle, "/resolv.conf"),
n.generateResolvConfContents(),
)
if err != nil {
return nil, fmt.Errorf("creating /etc/resolv.conf: %w", err)
}
return []specs.Mount{
{
Destination: "/etc/hosts",
Type: "bind",
Source: etcHosts,
Options: []string{"bind", "rw"},
}, {
Destination: "/etc/resolv.conf",
Type: "bind",
Source: resolvConf,
Options: []string{"bind", "rw"},
},
}, nil
}
func (n cniNetwork) SetupRestrictedNetworks() error {
const tableName = "filter"
err := n.ipt.CreateChainOrFlushIfExists(tableName, ipTablesAdminChainName)
if err != nil {
return fmt.Errorf("create chain or flush if exists failed: %w", err)
}
// Optimization that allows packets of ESTABLISHED and RELATED connections to go through without further rule matching
err = n.ipt.AppendRule(tableName, ipTablesAdminChainName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT")
if err != nil {
return fmt.Errorf("appending accept rule for RELATED & ESTABLISHED connections failed: %w", err)
}
for _, restrictedNetwork := range n.restrictedNetworks {
// Create REJECT rule in admin chain
err = n.ipt.AppendRule(tableName, ipTablesAdminChainName, "-d", restrictedNetwork, "-j", "REJECT")
if err != nil {
return fmt.Errorf("appending reject rule for restricted network %s failed: %w", restrictedNetwork, err)
}
}
return nil
}
func (n cniNetwork) generateResolvConfContents() []byte {
contents := ""
for _, n := range n.nameServers {
contents = contents + "nameserver " + n + "\n"
}
return []byte(contents)
}
func (n cniNetwork) Add(ctx context.Context, task containerd.Task) error {
if task == nil {
return ErrInvalidInput("nil task")
}
id, netns := netId(task), netNsPath(task)
_, err := n.client.Setup(ctx, id, netns)
if err != nil {
return fmt.Errorf("cni net setup: %w", err)
}
return nil
}
func (n cniNetwork) Remove(ctx context.Context, task containerd.Task) error {
if task == nil {
return ErrInvalidInput("nil task")
}
id, netns := netId(task), netNsPath(task)
err := n.client.Remove(ctx, id, netns)
if err != nil {
return fmt.Errorf("cni net teardown: %w", err)
}
return nil
}
func netId(task containerd.Task) string {
return task.ID()
}
func netNsPath(task containerd.Task) string {
return fmt.Sprintf("/proc/%d/ns/net", task.Pid())
}