-
Notifications
You must be signed in to change notification settings - Fork 51
/
enforcerproxy.go
408 lines (336 loc) · 11.6 KB
/
enforcerproxy.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
// Package enforcerproxy :: This is the implementation of the RPC client
// It implements the interface of Trireme Enforcer and forwards these
// requests to the actual remote enforcer instead of implementing locally
package enforcerproxy
import (
"context"
"fmt"
"strconv"
"sync"
"time"
"go.aporeto.io/trireme-lib/collector"
"go.aporeto.io/trireme-lib/common"
"go.aporeto.io/trireme-lib/controller/constants"
"go.aporeto.io/trireme-lib/controller/internal/enforcer"
"go.aporeto.io/trireme-lib/controller/internal/enforcer/utils/rpcwrapper"
"go.aporeto.io/trireme-lib/controller/internal/processmon"
"go.aporeto.io/trireme-lib/controller/pkg/ebpf"
"go.aporeto.io/trireme-lib/controller/pkg/env"
"go.aporeto.io/trireme-lib/controller/pkg/fqconfig"
"go.aporeto.io/trireme-lib/controller/pkg/packettracing"
"go.aporeto.io/trireme-lib/controller/pkg/remoteenforcer"
"go.aporeto.io/trireme-lib/controller/pkg/secrets"
"go.aporeto.io/trireme-lib/controller/runtime"
"go.aporeto.io/trireme-lib/policy"
"go.aporeto.io/trireme-lib/utils/crypto"
"go.uber.org/zap"
)
// ProxyInfo is the struct used to hold state about active enforcers in the system
type ProxyInfo struct {
mutualAuth bool
packetLogs bool
Secrets secrets.Secrets
serverID string
validity time.Duration
prochdl processmon.ProcessManager
rpchdl rpcwrapper.RPCClient
filterQueue *fqconfig.FilterQueue
commandArg string
statsServerSecret string
procMountPoint string
ExternalIPCacheTimeout time.Duration
collector collector.EventCollector
cfg *runtime.Configuration
tokenIssuer common.ServiceTokenIssuer
binaryTokens bool
isBPFEnabled bool
ipv6Enabled bool
rpcServer rpcwrapper.RPCServer
sync.RWMutex
}
// Enforce method makes a RPC call for the remote enforcer enforce method
func (s *ProxyInfo) Enforce(contextID string, puInfo *policy.PUInfo) error {
initEnforcer, err := s.prochdl.LaunchRemoteEnforcer(
contextID,
puInfo.Runtime.Pid(),
puInfo.Runtime.NSPath(),
s.commandArg,
s.statsServerSecret,
s.procMountPoint,
puInfo.Policy.EnforcerType(),
)
if err != nil {
return err
}
zap.L().Debug("Called enforce and launched process", zap.String("contextID", contextID),
zap.Reflect("Policy Object", puInfo))
if initEnforcer {
if err := s.initRemoteEnforcer(contextID); err != nil {
s.prochdl.KillRemoteEnforcer(contextID, true) // nolint errcheck
return err
}
}
enforcerPayload := &rpcwrapper.EnforcePayload{
ContextID: contextID,
Policy: puInfo.Policy.ToPublicPolicy(),
}
//Only the secrets need to be under lock. They can change async to the enforce call from Updatesecrets
s.RLock()
enforcerPayload.Secrets = s.Secrets.PublicSecrets()
s.RUnlock()
request := &rpcwrapper.Request{
Payload: enforcerPayload,
}
if err := s.rpchdl.RemoteCall(contextID, remoteenforcer.Enforce, request, &rpcwrapper.Response{}); err != nil {
s.prochdl.KillRemoteEnforcer(contextID, true) // nolint errcheck
return fmt.Errorf("failed to send message to remote enforcer: %s", err)
}
return nil
}
// Unenforce stops enforcing policy for the given contextID.
func (s *ProxyInfo) Unenforce(contextID string) error {
request := &rpcwrapper.Request{
Payload: &rpcwrapper.UnEnforcePayload{
ContextID: contextID,
},
}
if err := s.rpchdl.RemoteCall(contextID, remoteenforcer.Unenforce, request, &rpcwrapper.Response{}); err != nil {
zap.L().Error("failed to send message to remote enforcer", zap.Error(err))
}
return s.prochdl.KillRemoteEnforcer(contextID, true)
}
// UpdateSecrets updates the secrets used for signing communication between trireme instances
func (s *ProxyInfo) UpdateSecrets(token secrets.Secrets) error {
s.Lock()
s.Secrets = token
s.Unlock()
var allErrors string
resp := &rpcwrapper.Response{}
request := &rpcwrapper.Request{
Payload: &rpcwrapper.UpdateSecretsPayload{
Secrets: s.Secrets.PublicSecrets(),
},
}
for _, contextID := range s.rpchdl.ContextList() {
if err := s.rpchdl.RemoteCall(contextID, remoteenforcer.UpdateSecrets, request, resp); err != nil {
allErrors = allErrors + " contextID " + contextID + ":" + err.Error()
}
}
if len(allErrors) > 0 {
return fmt.Errorf("unable to update secrets for some remotes: %s", allErrors)
}
return nil
}
// SetLogLevel sets log level.
func (s *ProxyInfo) SetLogLevel(level constants.LogLevel) error {
resp := &rpcwrapper.Response{}
request := &rpcwrapper.Request{
Payload: &rpcwrapper.SetLogLevelPayload{
Level: level,
},
}
var allErrors string
for _, contextID := range s.rpchdl.ContextList() {
if err := s.rpchdl.RemoteCall(contextID, remoteenforcer.SetLogLevel, request, resp); err != nil {
allErrors = allErrors + " contextID " + contextID + ":" + err.Error()
}
}
if len(allErrors) > 0 {
return fmt.Errorf("unable to set log level: %s", allErrors)
}
return nil
}
// CleanUp sends a cleanup command to all the remotes forcing them to exit and clean their state.
func (s *ProxyInfo) CleanUp() error {
var synch sync.Mutex
var wg sync.WaitGroup
contextList := s.rpchdl.ContextList()
lenCids := len(contextList)
if lenCids == 0 {
return nil
}
zap.L().Info(strconv.Itoa(lenCids) + " remote enforcers waiting to be exited")
var chs []chan string
wg.Add(lenCids)
for i := 0; i < 4; i++ {
ch := make(chan string)
chs = append(chs, ch)
go func(ch chan string) {
var cid string
for {
cid = <-ch
if err := s.prochdl.KillRemoteEnforcer(cid, false); err != nil {
zap.L().Error("enforcer with contextID "+cid+"failed to exit", zap.Error(err))
}
synch.Lock()
lenCids = lenCids - 1
zap.L().Info(strconv.Itoa(lenCids) + " remote enforcers waiting to be exited")
synch.Unlock()
wg.Done()
}
}(ch)
}
for i, contextID := range contextList {
chs[i%4] <- contextID
}
wg.Wait()
zap.L().Info("All remote enforcers have exited...")
return nil
}
// EnableDatapathPacketTracing enable nfq packet tracing in remote container
func (s *ProxyInfo) EnableDatapathPacketTracing(ctx context.Context, contextID string, direction packettracing.TracingDirection, interval time.Duration) error {
resp := &rpcwrapper.Response{}
request := &rpcwrapper.Request{
Payload: &rpcwrapper.EnableDatapathPacketTracingPayLoad{
Direction: direction,
Interval: interval,
ContextID: contextID,
},
}
if err := s.rpchdl.RemoteCall(contextID, remoteenforcer.EnableDatapathPacketTracing, request, resp); err != nil {
return fmt.Errorf("unable to enable datapath packet tracing %s -- %s", err, resp.Status)
}
return nil
}
// EnableIPTablesPacketTracing enable iptables tracing
func (s *ProxyInfo) EnableIPTablesPacketTracing(ctx context.Context, contextID string, interval time.Duration) error {
request := &rpcwrapper.Request{
Payload: &rpcwrapper.EnableIPTablesPacketTracingPayLoad{
IPTablesPacketTracing: true,
Interval: interval,
ContextID: contextID,
},
}
if err := s.rpchdl.RemoteCall(contextID, remoteenforcer.EnableIPTablesPacketTracing, request, &rpcwrapper.Response{}); err != nil {
return fmt.Errorf("Unable to enable iptables tracing for contextID %s: %s", contextID, err)
}
return nil
}
// SetTargetNetworks does the RPC call for SetTargetNetworks to the corresponding
// remote enforcers
func (s *ProxyInfo) SetTargetNetworks(cfg *runtime.Configuration) error {
resp := &rpcwrapper.Response{}
request := &rpcwrapper.Request{
Payload: &rpcwrapper.SetTargetNetworksPayload{
Configuration: cfg,
},
}
var allErrors string
for _, contextID := range s.rpchdl.ContextList() {
if err := s.rpchdl.RemoteCall(contextID, remoteenforcer.SetTargetNetworks, request, resp); err != nil {
allErrors = allErrors + " contextID " + contextID + ":" + err.Error()
}
}
s.Lock()
s.cfg = cfg
s.Unlock()
if len(allErrors) > 0 {
return fmt.Errorf("Remote enforcers failed: %s", allErrors)
}
return nil
}
// GetBPFObject returns the bpf object
func (s *ProxyInfo) GetBPFObject() ebpf.BPFModule {
return nil
}
// GetFilterQueue returns the current FilterQueueConfig.
func (s *ProxyInfo) GetFilterQueue() *fqconfig.FilterQueue {
return s.filterQueue
}
// Run starts the the remote enforcer proxy.
func (s *ProxyInfo) Run(ctx context.Context) error {
handler := &ProxyRPCServer{
rpchdl: s.rpcServer,
collector: s.collector,
secret: s.statsServerSecret,
tokenIssuer: s.tokenIssuer,
}
// Start the server for statistics collection.
go s.rpcServer.StartServer(ctx, "unix", constants.StatsChannel, handler) // nolint
return nil
}
// Ping runs ping from the given config.
func (s *ProxyInfo) Ping(ctx context.Context, contextID string, pingConfig *policy.PingConfig) error {
resp := &rpcwrapper.Response{}
request := &rpcwrapper.Request{
Payload: &rpcwrapper.PingPayload{
ContextID: contextID,
PingConfig: pingConfig,
},
}
if err := s.rpchdl.RemoteCall(contextID, remoteenforcer.Ping, request, resp); err != nil {
return fmt.Errorf("unable to run ping %s -- %s", err, resp.Status)
}
return nil
}
// initRemoteEnforcer method makes a RPC call to the remote enforcer
func (s *ProxyInfo) initRemoteEnforcer(contextID string) error {
resp := &rpcwrapper.Response{}
request := &rpcwrapper.Request{
Payload: &rpcwrapper.InitRequestPayload{
FqConfig: s.filterQueue,
MutualAuth: s.mutualAuth,
Validity: s.validity,
ServerID: s.serverID,
ExternalIPCacheTimeout: s.ExternalIPCacheTimeout,
PacketLogs: s.packetLogs,
Secrets: s.Secrets.PublicSecrets(),
Configuration: s.cfg,
BinaryTokens: s.binaryTokens,
IsBPFEnabled: s.isBPFEnabled,
IPv6Enabled: s.ipv6Enabled,
},
}
return s.rpchdl.RemoteCall(contextID, remoteenforcer.InitEnforcer, request, resp)
}
// NewProxyEnforcer creates a new proxy to remote enforcers.
func NewProxyEnforcer(
mutualAuth bool,
filterQueue *fqconfig.FilterQueue,
collector collector.EventCollector,
secrets secrets.Secrets,
serverID string,
validity time.Duration,
cmdArg string,
procMountPoint string,
ExternalIPCacheTimeout time.Duration,
packetLogs bool,
cfg *runtime.Configuration,
runtimeError chan *policy.RuntimeError,
remoteParameters *env.RemoteParameters,
tokenIssuer common.ServiceTokenIssuer,
binaryTokens bool,
isBPFEnabled bool,
ipv6Enabled bool,
rpcServer rpcwrapper.RPCServer,
) enforcer.Enforcer {
statsServersecret, err := crypto.GenerateRandomString(32)
if err != nil {
// There is a very small chance of this happening we will log an error here.
zap.L().Error("Failed to generate random secret for stats reporting", zap.Error(err))
// We will use current time as the secret
statsServersecret = time.Now().String()
}
rpcClient := rpcwrapper.NewRPCWrapper()
return &ProxyInfo{
mutualAuth: mutualAuth,
Secrets: secrets,
serverID: serverID,
validity: validity,
prochdl: processmon.New(context.Background(), remoteParameters, runtimeError, rpcClient),
rpchdl: rpcClient,
filterQueue: filterQueue,
commandArg: cmdArg,
statsServerSecret: statsServersecret,
procMountPoint: procMountPoint,
ExternalIPCacheTimeout: ExternalIPCacheTimeout,
packetLogs: packetLogs,
collector: collector,
cfg: cfg,
tokenIssuer: tokenIssuer,
binaryTokens: binaryTokens,
isBPFEnabled: isBPFEnabled,
ipv6Enabled: ipv6Enabled,
rpcServer: rpcServer,
}
}