forked from vmware/vic
/
ops_linux.go
490 lines (414 loc) · 13.9 KB
/
ops_linux.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
// Copyright 2016-2017 VMware, 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 main
import (
"context"
"errors"
"fmt"
"io"
"math"
"os"
"path"
"strconv"
"strings"
"syscall"
log "github.com/Sirupsen/logrus"
"golang.org/x/crypto/ssh/terminal"
"golang.org/x/sys/unix"
"github.com/vmware/vic/lib/config/executor"
"github.com/vmware/vic/lib/constants"
"github.com/vmware/vic/lib/iolog"
"github.com/vmware/vic/lib/tether"
"github.com/vmware/vic/lib/tether/netfilter"
"github.com/vmware/vic/pkg/dio"
"github.com/vmware/vic/pkg/trace"
)
const (
runMountPoint = "/run"
// default values to set for ulimit fields
defaultNOFILE = 1024 * 1024
defaultULimit = math.MaxUint64
)
type operations struct {
tether.BaseOperations
logging bool
}
func (t *operations) Log() (io.Writer, error) {
defer trace.End(trace.Begin("operations.Log"))
// redirect logging to the serial log
log.Infof("opening %s/ttyS1 for debug log", pathPrefix)
f, err := os.OpenFile(path.Join(pathPrefix, "ttyS1"), os.O_RDWR|os.O_SYNC|syscall.O_NOCTTY, 0)
if err != nil {
detail := fmt.Sprintf("failed to open serial port for debug log: %s", err)
log.Error(detail)
return nil, errors.New(detail)
}
if err := setTerminalSpeed(f.Fd()); err != nil {
log.Errorf("Setting terminal speed failed with %s", err)
}
// enable raw mode
_, err = terminal.MakeRaw(int(f.Fd()))
if err != nil {
detail := fmt.Sprintf("Making ttyS1 raw failed with %s", err)
log.Error(detail)
return nil, errors.New(detail)
}
return io.MultiWriter(f, os.Stdout), nil
}
// sessionLogWriter returns a writer that will persist the session output
func (t *operations) SessionLog(session *tether.SessionConfig) (dio.DynamicMultiWriter, dio.DynamicMultiWriter, error) {
defer trace.End(trace.Begin("configure session log writer"))
if t.logging {
detail := "unable to log more than one session concurrently to persistent logging"
log.Warn(detail)
// use multi-writer so it's still viable for attach
return dio.MultiWriter(), dio.MultiWriter(), nil
}
t.logging = true
// open SttyS2 for session logging
log.Info("opening ttyS2 for session logging")
f, err := os.OpenFile(path.Join(pathPrefix, "ttyS2"), os.O_RDWR|os.O_SYNC|syscall.O_NOCTTY, 0)
if err != nil {
detail := fmt.Sprintf("failed to open serial port for session log: %s", err)
log.Error(detail)
return nil, nil, errors.New(detail)
}
if err := setTerminalSpeed(f.Fd()); err != nil {
log.Errorf("Setting terminal speed failed with %s", err)
}
// enable raw mode
_, err = terminal.MakeRaw(int(f.Fd()))
if err != nil {
detail := fmt.Sprintf("Making ttyS2 raw failed with %s", err)
log.Error(detail)
return nil, nil, errors.New(detail)
}
// wrap output in a LogWriter to serialize it into our persisted
// containerVM output format, using iolog.LogClock for timestamps
lw := iolog.NewLogWriter(f, iolog.LogClock{})
// use multi-writer so it goes to both screen and session log
return dio.MultiWriter(lw, os.Stdout), dio.MultiWriter(lw, os.Stderr), nil
}
func (t *operations) Setup(sink tether.Config) error {
if err := t.BaseOperations.Setup(sink); err != nil {
return err
}
// unmount /run - https://github.com/vmware/vic/issues/1643
if err := tether.Sys.Syscall.Unmount(runMountPoint, syscall.MNT_DETACH); err != nil {
if errno, ok := err.(syscall.Errno); !ok || errno != syscall.EINVAL {
return err
}
}
// NOTE: ulimit default values should change when we support ulimit configuration
ApplyDefaultULimit()
return nil
}
// ApplyDefaultULimit sets ulimit fields to their defined default value
func ApplyDefaultULimit() {
var rLimit syscall.Rlimit
// NOFILE does not support defaultULimit as a value due to kernel restriction on number of open files
rLimit.Max = defaultNOFILE
rLimit.Cur = rLimit.Max
if err := syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit); err != nil {
log.Errorf("Cannot set ulimit for nofile: %s", err.Error())
}
rLimit.Max = defaultULimit
rLimit.Cur = rLimit.Max
if err := syscall.Setrlimit(syscall.RLIMIT_STACK, &rLimit); err != nil {
log.Errorf("Cannot set ulimit for stack: %s ", err.Error())
}
if err := syscall.Setrlimit(syscall.RLIMIT_CORE, &rLimit); err != nil {
log.Errorf("Cannot set ulimit for core blocks: %s", err.Error())
}
if err := syscall.Setrlimit(unix.RLIMIT_MEMLOCK, &rLimit); err != nil {
log.Errorf("Cannot set ulimit for memlock: %s", err.Error())
}
if err := syscall.Setrlimit(unix.RLIMIT_NPROC, &rLimit); err != nil {
log.Errorf("Cannot set ulimit for nproc: %s", err.Error())
}
}
// invoke will invoke the closure returned from the tether netfilter prep and
// block until complete. It handles both potential preparation errors and invocation
// errors.
// the 'task' specified is used to construct error messages with the specific operation
// embedded
func invoke(t *tether.BaseOperations, fn tether.UtilityFn, task string) error {
exitChan, err := t.LaunchUtility(fn)
if err != nil {
return fmt.Errorf("%s failed: %s", task, err)
}
exitCode := <-exitChan
if exitCode != 0 {
return fmt.Errorf("%s returned non-zero: %d", task, exitCode)
}
return nil
}
// SetupFirewall sets up firewall rules on the external scope only. Any
// portmaps are honored as are port exposes.
func (t *operations) SetupFirewall(ctx context.Context, config *tether.ExecutorConfig) error {
return setupFirewall(ctx, &t.BaseOperations, config)
}
// setupFirewall is broken out from SetupFirewall so that it can be referenced from the test code
func setupFirewall(ctx context.Context, t *tether.BaseOperations, config *tether.ExecutorConfig) error {
fn := netfilter.Flush(ctx, "VIC")
if err := invoke(t, fn, "flush"); err != nil {
return err
}
for _, endpoint := range config.Networks {
switch endpoint.Network.Type {
case constants.ExternalScopeType:
id, err := strconv.Atoi(endpoint.ID)
if err != nil {
log.Errorf("can't apply port rules: %s", err.Error())
continue
}
iface, err := t.LinkBySlot(int32(id))
if err != nil {
log.Errorf("can't apply rules: %s", err.Error())
continue
}
ifaceName := iface.Attrs().Name
log.Debugf("slot %d -> %s", endpoint.ID, ifaceName)
// ensure that we can pass DHCP traffic if it's necessary
if endpoint.Network.TrustLevel != executor.Open && endpoint.IsDynamic() {
allowDHCPTraffic(ctx, t, ifaceName)
}
switch endpoint.Network.TrustLevel {
case executor.Open:
// Configure port redirect in Open deployment
if err := setupPorts(ctx, t, endpoint, ifaceName, true); err != nil {
return err
}
// Accept all incoming and outgoing traffic
for _, chain := range []netfilter.Chain{netfilter.Input, netfilter.Output, netfilter.Forward} {
fn := (&netfilter.Rule{
Chain: chain,
Target: netfilter.Accept,
Interface: ifaceName,
}).Commit(ctx)
if err := invoke(t, fn, "accept all"); err != nil {
return err
}
}
case executor.Closed:
// Reject all incoming and outgoing traffic
// Since our default policy is to drop traffic, nothing is needed here.
case executor.Outbound:
// Reject all incoming traffic, but allow outgoing
if err := setupOutboundFirewall(ctx, t, ifaceName); err != nil {
return err
}
case executor.Peers:
// Outbound + all ports open to source addresses in --container-network-ip-range
if err := setupOutboundFirewall(ctx, t, ifaceName); err != nil {
return err
}
// Configure port redirect in Peer deployment
if err := setupPorts(ctx, t, endpoint, ifaceName, true); err != nil {
return err
}
sourceAddresses := make([]string, len(endpoint.Network.Pools))
for i, v := range endpoint.Network.Pools {
sourceAddresses[i] = v.String()
}
fn := (&netfilter.Rule{
Chain: netfilter.Input,
Target: netfilter.Accept,
SourceAddresses: sourceAddresses,
Interface: ifaceName,
}).Commit(ctx)
if err := invoke(t, fn, "allow outbound and peers"); err != nil {
return err
}
if err := allowPingTraffic(ctx, t, ifaceName, sourceAddresses); err != nil {
return err
}
default:
// covers executor.Published and executor.Unspecified as well as invalid values
log.Infof("Applying published rules for configuration %v", endpoint.Network.TrustLevel)
if err := setupOutboundFirewall(ctx, t, ifaceName); err != nil {
return err
}
if err := allowPingTraffic(ctx, t, ifaceName, nil); err != nil {
return err
}
if err := setupPorts(ctx, t, endpoint, ifaceName, false); err != nil {
return err
}
}
case constants.BridgeScopeType:
id, err := strconv.Atoi(endpoint.ID)
if err != nil {
log.Errorf("can't apply port rules: %s", err.Error())
continue
}
iface, err := t.LinkBySlot(int32(id))
if err != nil {
log.Errorf("can't apply rules: %s", err.Error())
continue
}
ifaceName := iface.Attrs().Name
log.Debugf("slot %d -> %s", endpoint.ID, ifaceName)
// Traffic over container bridge network should be peers+outbound.
if err := setupOutboundFirewall(ctx, t, ifaceName); err != nil {
return err
}
sourceAddresses := make([]string, len(endpoint.Network.Pools))
for i, v := range endpoint.Network.Pools {
sourceAddresses[i] = v.String()
}
fn := (&netfilter.Rule{
Chain: netfilter.Input,
Target: netfilter.Accept,
SourceAddresses: sourceAddresses,
Interface: ifaceName,
}).Commit(ctx)
if err := invoke(t, fn, "configure for bridge scope"); err != nil {
return err
}
}
}
return invoke(t, netfilter.Return(ctx, "VIC"), "return from VIC chain")
}
func setupOutboundFirewall(ctx context.Context, t *tether.BaseOperations, ifaceName string) error {
// All already established inputs are accepted
fn := (&netfilter.Rule{
Chain: netfilter.Input,
States: []netfilter.State{netfilter.Established, netfilter.Related},
Target: netfilter.Accept,
Interface: ifaceName,
}).Commit(ctx)
if err := invoke(t, fn, "permit established inbound"); err != nil {
return err
}
// All output is accepted
fn = (&netfilter.Rule{
Chain: netfilter.Output,
Target: netfilter.Accept,
Interface: ifaceName,
}).Commit(ctx)
return invoke(t, fn, "permit all outbound")
}
func setupPorts(ctx context.Context, t *tether.BaseOperations, endpoint *tether.NetworkEndpoint, ifaceName string, redirectOnly bool) error {
// handle the ports
for _, p := range endpoint.Ports {
// parse the port maps
rules, err := portToRule(p, redirectOnly)
if err != nil {
log.Errorf("can't apply port rule (%s): %s", p, err.Error())
continue
}
log.Infof("Applying %d rules for port %s", len(rules), p)
for _, r := range rules {
r.Interface = ifaceName
fn := r.Commit(ctx)
if err := invoke(t, fn, "allow incoming on published port"); err != nil {
return err
}
}
}
return nil
}
func allowPingTraffic(ctx context.Context, t *tether.BaseOperations, ifaceName string, sourceAddresses []string) error {
fn := (&netfilter.Rule{
Chain: netfilter.Input,
Target: netfilter.Accept,
Interface: ifaceName,
Protocol: netfilter.ICMP,
ICMPType: netfilter.EchoRequest,
SourceAddresses: sourceAddresses,
}).Commit(ctx)
if err := invoke(t, fn, "allow ping inbound"); err != nil {
return err
}
fn = (&netfilter.Rule{
Chain: netfilter.Output,
Target: netfilter.Accept,
Interface: ifaceName,
Protocol: netfilter.ICMP,
ICMPType: netfilter.EchoReply,
SourceAddresses: sourceAddresses,
}).Commit(ctx)
return invoke(t, fn, "allow ping outbound")
}
func allowDHCPTraffic(ctx context.Context, t *tether.BaseOperations, ifaceName string) error {
fn := (&netfilter.Rule{
Chain: netfilter.Input,
Target: netfilter.Accept,
Interface: ifaceName,
Protocol: netfilter.UDP,
FromPort: "67:68",
SrcPort: "67:68",
}).Commit(ctx)
if err := invoke(t, fn, "allow dhcp inbound"); err != nil {
return err
}
fn = (&netfilter.Rule{
Chain: netfilter.Output,
Target: netfilter.Accept,
Interface: ifaceName,
Protocol: netfilter.UDP,
FromPort: "67:68",
SrcPort: "67:68",
}).Commit(ctx)
return invoke(t, fn, "allow dhcp outbound")
}
func portToRule(p string, redirectOnly bool) ([]*netfilter.Rule, error) {
// 9999/tcp
s := strings.Split(p, "/")
if len(s) != 2 {
return nil, errors.New("can't parse port spec: " + p)
}
proto := netfilter.Protocol(s[1])
switch proto {
case netfilter.UDP:
case netfilter.TCP:
default:
return nil, errors.New("unknown protocol")
}
mapping := strings.Split(s[0], ":")
directPort := mapping[len(mapping)-1]
// publish the actual port directly
var rules []*netfilter.Rule
expose := &netfilter.Rule{
Chain: netfilter.Input,
Interface: "external",
Target: netfilter.Accept,
Protocol: proto,
// ranges are specified using a hyphen in docker
FromPort: strings.Replace(directPort, "-", ":", -1),
}
if !redirectOnly {
rules = append(rules, expose)
}
// if there's no redirection we're done
if len(mapping) == 1 || mapping[0] == mapping[1] {
return rules, nil
}
// redirect port
// https://wiki.debian.org/Firewalls-local-port-redirection contains a useful reference
if strings.Contains(s[0], "-") {
return nil, errors.New("cannot port forward a range")
}
rules = append(rules, &netfilter.Rule{
Table: netfilter.Nat,
Chain: netfilter.Prerouting,
Interface: "external",
Target: netfilter.Redirect,
Protocol: proto,
FromPort: mapping[0],
ToPort: mapping[1],
})
return rules, nil
}