-
Notifications
You must be signed in to change notification settings - Fork 51
/
controller.go
411 lines (342 loc) · 13.3 KB
/
controller.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
package controller
import (
"context"
"fmt"
"os/exec"
"sync"
"time"
"go.aporeto.io/trireme-lib/v11/collector"
"go.aporeto.io/trireme-lib/v11/common"
"go.aporeto.io/trireme-lib/v11/controller/constants"
"go.aporeto.io/trireme-lib/v11/controller/internal/enforcer"
"go.aporeto.io/trireme-lib/v11/controller/internal/supervisor"
"go.aporeto.io/trireme-lib/v11/controller/pkg/claimsheader"
"go.aporeto.io/trireme-lib/v11/controller/pkg/dmesgparser"
"go.aporeto.io/trireme-lib/v11/controller/pkg/env"
"go.aporeto.io/trireme-lib/v11/controller/pkg/fqconfig"
"go.aporeto.io/trireme-lib/v11/controller/pkg/packettracing"
"go.aporeto.io/trireme-lib/v11/controller/pkg/secrets"
"go.aporeto.io/trireme-lib/v11/controller/runtime"
"go.aporeto.io/trireme-lib/v11/policy"
"go.uber.org/zap"
)
type traceTrigger struct {
duration time.Duration
expiry time.Time
}
// trireme contains references to all the different components of the controller.
// Depending on the configuration we might have multiple supervisor and enforcer types.
// The initialization process must provide the mode that Trireme will run in.
type trireme struct {
config *config
supervisors map[constants.ModeType]supervisor.Supervisor
enforcers map[constants.ModeType]enforcer.Enforcer
puTypeToEnforcerType map[common.PUType]constants.ModeType
enablingTrace chan *traceTrigger
locks sync.Map
}
// New returns a trireme interface implementation based on configuration provided.
func New(serverID string, mode constants.ModeType, opts ...Option) TriremeController {
c := &config{
serverID: serverID,
collector: collector.NewDefaultCollector(),
mode: mode,
fq: fqconfig.NewFilterQueueWithDefaults(),
mutualAuth: true,
validity: constants.DatapathTokenValidity,
procMountPoint: constants.DefaultProcMountPoint,
externalIPcacheTimeout: -1,
remoteParameters: &env.RemoteParameters{
LogToConsole: true,
LogFormat: "console",
LogLevel: "info",
LogWithID: false,
CompressedTags: claimsheader.CompressionTypeV1,
},
}
for _, opt := range opts {
opt(c)
}
zap.L().Debug("Trireme configuration", zap.String("configuration", fmt.Sprintf("%+v", c)))
return newTrireme(c)
}
// Run starts the supervisor and the enforcer and go routines. It doesn't try to clean
// up if something went wrong. It will be up to the caller to decide what to do.
func (t *trireme) Run(ctx context.Context) error {
// Start all the supervisors.
for _, s := range t.supervisors {
if err := s.Run(ctx); err != nil {
zap.L().Error("Error when starting the supervisor", zap.Error(err))
return fmt.Errorf("Error while starting supervisor %v", err)
}
}
// Start all the enforcers.
for _, e := range t.enforcers {
if err := e.Run(ctx); err != nil {
return fmt.Errorf("unable to start the enforcer: %s", err)
}
}
go t.runIPTraceCollector(ctx)
return nil
}
// CleanUp cleans all the acls and all the remote supervisors
func (t *trireme) CleanUp() error {
for _, s := range t.supervisors {
s.CleanUp() // nolint
}
for _, e := range t.enforcers {
e.CleanUp() // nolint
}
return nil
}
// Enforce asks the controller to enforce policy to a processing unit
func (t *trireme) Enforce(ctx context.Context, puID string, policy *policy.PUPolicy, runtime *policy.PURuntime) error {
lock, _ := t.locks.LoadOrStore(puID, &sync.Mutex{})
lock.(*sync.Mutex).Lock()
defer lock.(*sync.Mutex).Unlock()
return t.doHandleCreate(puID, policy, runtime)
}
// Enforce asks the controller to enforce policy to a processing unit
func (t *trireme) UnEnforce(ctx context.Context, puID string, policy *policy.PUPolicy, runtime *policy.PURuntime) error {
lock, _ := t.locks.LoadOrStore(puID, &sync.Mutex{})
lock.(*sync.Mutex).Lock()
defer func() {
t.locks.Delete(puID)
lock.(*sync.Mutex).Unlock()
}()
return t.doHandleDelete(puID, policy, runtime)
}
// UpdatePolicy updates a policy for an already activated PU. The PU is identified by the contextID
func (t *trireme) UpdatePolicy(ctx context.Context, puID string, plc *policy.PUPolicy, runtime *policy.PURuntime) error {
lock, _ := t.locks.LoadOrStore(puID, &sync.Mutex{})
lock.(*sync.Mutex).Lock()
defer lock.(*sync.Mutex).Unlock()
return t.doUpdatePolicy(puID, plc, runtime)
}
func (t *trireme) EnableDatapathPacketTracing(ctx context.Context, puID string, policy *policy.PUPolicy, runtime *policy.PURuntime, direction packettracing.TracingDirection, interval time.Duration) error {
lock, _ := t.locks.LoadOrStore(puID, &sync.Mutex{})
lock.(*sync.Mutex).Lock()
defer lock.(*sync.Mutex).Unlock()
return t.doHandleEnableDatapathPacketTracing(ctx, puID, policy, runtime, direction, interval)
}
func (t *trireme) EnableIPTablesPacketTracing(ctx context.Context, puID string, policy *policy.PUPolicy, runtime *policy.PURuntime, interval time.Duration) error {
lock, _ := t.locks.LoadOrStore(puID, &sync.Mutex{})
lock.(*sync.Mutex).Lock()
defer lock.(*sync.Mutex).Unlock()
return t.doHandleEnableIPTablesPacketTracing(ctx, puID, policy, runtime, interval)
}
// Ping runs ping based on the given config.
func (t *trireme) Ping(ctx context.Context, puID string, policy *policy.PUPolicy, runtime *policy.PURuntime, pingConfig *policy.PingConfig) error {
lock, _ := t.locks.LoadOrStore(puID, &sync.Mutex{})
lock.(*sync.Mutex).Lock()
defer lock.(*sync.Mutex).Unlock()
return t.enforcers[t.modeTypeFromPolicy(policy, runtime)].Ping(ctx, puID, pingConfig)
}
// UpdateSecrets updates the secrets of the controllers.
func (t *trireme) UpdateSecrets(secrets secrets.Secrets) error {
for _, enforcer := range t.enforcers {
if err := enforcer.UpdateSecrets(secrets); err != nil {
zap.L().Error("unable to update secrets", zap.Error(err))
}
}
return nil
}
// UpdateConfiguration updates the configuration of the controller. Only
// a limited number of parameters can be updated at run time.
func (t *trireme) UpdateConfiguration(cfg *runtime.Configuration) error {
failure := false
for _, s := range t.supervisors {
err := s.SetTargetNetworks(cfg)
if err != nil {
zap.L().Error("Failed to update target networks in supervisor", zap.Error(err))
failure = true
}
}
for _, e := range t.enforcers {
if cfg.LogLevel != "" {
if err := e.SetLogLevel(cfg.LogLevel); err != nil {
zap.L().Error("unable to set log level", zap.Error(err))
}
}
err := e.SetTargetNetworks(cfg)
if err != nil {
zap.L().Error("Failed to update target networks in cotnroller", zap.Error(err))
failure = true
}
}
if failure {
return fmt.Errorf("configuration update failed")
}
return nil
}
// doHandleCreate is the detailed implementation of the create event.
func (t *trireme) doHandleCreate(contextID string, policyInfo *policy.PUPolicy, runtimeInfo *policy.PURuntime) error {
containerInfo := policy.PUInfoFromPolicyAndRuntime(contextID, policyInfo, runtimeInfo)
logEvent := &collector.ContainerRecord{
ContextID: contextID,
IPAddress: policyInfo.IPAddresses(),
Tags: policyInfo.Annotations(),
Event: collector.ContainerStart,
}
defer func() {
t.config.collector.CollectContainerEvent(logEvent)
}()
addTransmitterLabel(contextID, containerInfo)
if !mustEnforce(contextID, containerInfo) {
logEvent.Event = collector.ContainerIgnored
return nil
}
modeType := t.modeTypeFromPolicy(containerInfo.Policy, containerInfo.Runtime)
if err := t.enforcers[modeType].Enforce(contextID, containerInfo); err != nil {
logEvent.Event = collector.ContainerFailed
return fmt.Errorf("unable to setup enforcer: %s", err)
}
if err := t.supervisors[modeType].Supervise(contextID, containerInfo); err != nil {
if werr := t.enforcers[modeType].Unenforce(contextID); werr != nil {
zap.L().Warn("Failed to clean up state after failures",
zap.String("contextID", contextID),
zap.Error(werr),
)
}
logEvent.Event = collector.ContainerFailed
return fmt.Errorf("unable to setup supervisor: %s", err)
}
return nil
}
// doHandleDelete is the detailed implementation of the delete event.
func (t *trireme) doHandleDelete(contextID string, policyInfo *policy.PUPolicy, runtime *policy.PURuntime) error {
modeType := t.modeTypeFromPolicy(policyInfo, runtime)
errS := t.supervisors[modeType].Unsupervise(contextID)
errE := t.enforcers[modeType].Unenforce(contextID)
t.config.collector.CollectContainerEvent(&collector.ContainerRecord{
ContextID: contextID,
IPAddress: runtime.IPAddresses(),
Tags: nil,
Event: collector.ContainerDelete,
})
if errS != nil || errE != nil {
return fmt.Errorf("unable to delete context id %s, supervisor %s, enforcer %s", contextID, errS, errE)
}
return nil
}
// doUpdatePolicy is the detailed implementation of the update policy event.
func (t *trireme) doUpdatePolicy(contextID string, newPolicy *policy.PUPolicy, runtime *policy.PURuntime) error {
containerInfo := policy.PUInfoFromPolicyAndRuntime(contextID, newPolicy, runtime)
addTransmitterLabel(contextID, containerInfo)
if !mustEnforce(contextID, containerInfo) {
return nil
}
modeType := t.modeTypeFromPolicy(containerInfo.Policy, containerInfo.Runtime)
if err := t.enforcers[modeType].Enforce(contextID, containerInfo); err != nil {
//We lost communication with the remote and killed it lets restart it here by feeding a create event in the request channel
if werr := t.supervisors[modeType].Unsupervise(contextID); werr != nil {
zap.L().Warn("Failed to clean up after enforcerments failures",
zap.String("contextID", contextID),
zap.Error(werr),
)
}
return fmt.Errorf("unable to update policy for pu %s: %s", contextID, err)
}
if err := t.supervisors[modeType].Supervise(contextID, containerInfo); err != nil {
if werr := t.enforcers[modeType].Unenforce(contextID); werr != nil {
zap.L().Warn("Failed to clean up after enforcerments failures",
zap.String("contextID", contextID),
zap.Error(werr),
)
}
return fmt.Errorf("supervisor failed to update policy for pu %s: %s", contextID, err)
}
t.config.collector.CollectContainerEvent(&collector.ContainerRecord{
ContextID: contextID,
IPAddress: runtime.IPAddresses(),
Tags: containerInfo.Runtime.Tags(),
Event: collector.ContainerUpdate,
})
return nil
}
//Debug Handlers
func (t *trireme) doHandleEnableDatapathPacketTracing(ctx context.Context, puID string, policy *policy.PUPolicy, runtime *policy.PURuntime, direction packettracing.TracingDirection, interval time.Duration) error {
return t.enforcers[t.modeTypeFromPolicy(policy, runtime)].EnableDatapathPacketTracing(ctx, puID, direction, interval)
}
func (t *trireme) doHandleEnableIPTablesPacketTracing(ctx context.Context, puID string, policy *policy.PUPolicy, runtime *policy.PURuntime, interval time.Duration) error {
modeType := t.modeTypeFromPolicy(policy, runtime)
sysctlCmd, err := exec.LookPath("sysctl")
if err != nil {
return fmt.Errorf("sysctl command not found")
}
cmd := exec.Command(sysctlCmd, "-w", "net.netfilter.nf_log_all_netns=1")
if err := cmd.Run(); err != nil {
return fmt.Errorf("remote container iptables tracing will not work %s", err)
}
t.enablingTrace <- &traceTrigger{
duration: interval,
expiry: time.Now().Add(interval),
}
if err := t.supervisors[modeType].EnableIPTablesPacketTracing(ctx, puID, interval); err != nil {
return err
}
return t.enforcers[modeType].EnableIPTablesPacketTracing(ctx, puID, interval)
}
func (t *trireme) runIPTraceCollector(ctx context.Context) {
//Run dmesg once to establish baseline
expiry := time.Now()
hdl := dmesgparser.New()
for {
select {
case <-ctx.Done():
return
case traceparams := <-t.enablingTrace:
if !traceparams.expiry.After(expiry) {
//if we already have a request expiring later drop this
continue
}
expiry = traceparams.expiry
case <-time.After(1 * time.Second):
if !time.Now().After(expiry) {
messages, err := hdl.RunDmesgCommand()
if err != nil {
zap.L().Warn("Unable to run dmesg", zap.Error(err))
continue
}
t.config.collector.CollectTraceEvent(messages)
}
}
}
}
func (t *trireme) modeTypeFromPolicy(policyInfo *policy.PUPolicy, runtime *policy.PURuntime) constants.ModeType {
if policyInfo == nil {
// there are edge cases when policyInfo really can be nil - and it is fine
// let's just fall back to the normal enforcertype mapping if this is the case
//
// Here is an example: when a PU Create event failed, but the PU gets destroyed afterwards, there is a stop
// event generated which will call UnEnforce. However, in this case there is no guarantee that PUPolicy has
// actually ever been set.
zap.L().Debug("modeTypeFromPolicy received no PU policy", zap.String("name", runtime.Name()))
return t.puTypeToEnforcerType[runtime.PUType()]
}
switch policyInfo.EnforcerType() {
case policy.EnforcerMapping:
return t.puTypeToEnforcerType[runtime.PUType()]
case policy.EnvoyAuthorizerEnforcer:
switch runtime.PUType() {
case common.KubernetesPU:
fallthrough
case common.ContainerPU:
return constants.RemoteContainerEnvoyAuthorizer
case common.UIDLoginPU:
fallthrough
case common.HostPU:
fallthrough
case common.HostNetworkPU:
fallthrough
case common.SSHSessionPU:
fallthrough
case common.LinuxProcessPU:
return constants.LocalEnvoyAuthorizer
default:
return t.puTypeToEnforcerType[runtime.PUType()]
}
default:
return t.puTypeToEnforcerType[runtime.PUType()]
}
}