-
Notifications
You must be signed in to change notification settings - Fork 51
/
datapath.go
360 lines (283 loc) · 9.36 KB
/
datapath.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
package enforcer
// Go libraries
import (
"fmt"
"os/exec"
"strings"
"time"
"go.uber.org/zap"
"github.com/aporeto-inc/netlink-go/conntrack"
"github.com/aporeto-inc/trireme/cache"
"github.com/aporeto-inc/trireme/collector"
"github.com/aporeto-inc/trireme/constants"
"github.com/aporeto-inc/trireme/enforcer/acls"
"github.com/aporeto-inc/trireme/enforcer/utils/fqconfig"
"github.com/aporeto-inc/trireme/enforcer/utils/secrets"
"github.com/aporeto-inc/trireme/enforcer/utils/tokens"
"github.com/aporeto-inc/trireme/monitor/linuxmonitor/cgnetcls"
"github.com/aporeto-inc/trireme/policy"
)
// Datapath is the structure holding all information about a connection filter
type Datapath struct {
// Configuration parameters
filterQueue *fqconfig.FilterQueue
tokenEngine tokens.TokenEngine
collector collector.EventCollector
service PacketProcessor
secrets secrets.Secrets
nflogger nfLogger
procMountPoint string
// Internal structures and caches
// Key=ContextId Value=ContainerIP
contextTracker cache.DataStore
puFromIP cache.DataStore
puFromMark cache.DataStore
puFromPort cache.DataStore
// Hash based on source IP/Port to capture SynAck packets with possible NAT.
// When a new connection is created, we has the source IP/port. A return
// poacket might come with a different source IP NAT is done later.
// If we don't receife a return SynAck in 20 seconds, it expires
sourcePortConnectionCache cache.DataStore
// Hash on full five-tuple and return the connection
// These are auto-expired connections after 60 seconds of inactivity.
appOrigConnectionTracker cache.DataStore
appReplyConnectionTracker cache.DataStore
netOrigConnectionTracker cache.DataStore
netReplyConnectionTracker cache.DataStore
// connctrack handle
conntrackHdl conntrack.Conntrack
// mode captures the mode of the enforcer
mode constants.ModeType
// stop signals
netStop []chan bool
appStop []chan bool
// ack size
ackSize uint32
mutualAuthorization bool
}
// New will create a new data path structure. It instantiates the data stores
// needed to track sessions. The data path is started with a different call.
// Only required parameters must be provided. Rest a pre-populated with defaults.
func New(
mutualAuth bool,
filterQueue *fqconfig.FilterQueue,
collector collector.EventCollector,
service PacketProcessor,
secrets secrets.Secrets,
serverID string,
validity time.Duration,
mode constants.ModeType,
procMountPoint string,
) PolicyEnforcer {
if mode == constants.RemoteContainer || mode == constants.LocalServer {
// Make conntrack liberal for TCP
sysctlCmd, err := exec.LookPath("sysctl")
if err != nil {
zap.L().Fatal("sysctl command must be installed", zap.Error(err))
}
cmd := exec.Command(sysctlCmd, "-w", "net.netfilter.nf_conntrack_tcp_be_liberal=1")
if err := cmd.Run(); err != nil {
zap.L().Fatal("Failed to set conntrack options", zap.Error(err))
}
}
tokenEngine, err := tokens.NewJWT(validity, serverID, secrets)
if err != nil {
zap.L().Fatal("Unable to create TokenEngine in enforcer", zap.Error(err))
}
d := &Datapath{
puFromIP: cache.NewCache(),
puFromMark: cache.NewCache(),
puFromPort: cache.NewCache(),
contextTracker: cache.NewCache(),
sourcePortConnectionCache: cache.NewCacheWithExpiration(time.Second * 24),
appOrigConnectionTracker: cache.NewCacheWithExpiration(time.Second * 24),
appReplyConnectionTracker: cache.NewCacheWithExpiration(time.Second * 24),
netOrigConnectionTracker: cache.NewCacheWithExpiration(time.Second * 24),
netReplyConnectionTracker: cache.NewCacheWithExpiration(time.Second * 24),
filterQueue: filterQueue,
mutualAuthorization: mutualAuth,
service: service,
collector: collector,
tokenEngine: tokenEngine,
secrets: secrets,
ackSize: secrets.AckSize(),
mode: mode,
procMountPoint: procMountPoint,
conntrackHdl: conntrack.NewHandle(),
}
if d.tokenEngine == nil {
zap.L().Fatal("Unable to create enforcer")
}
d.nflogger = newNFLogger(11, 10, d.puInfoDelegate, collector)
return d
}
// NewWithDefaults create a new data path with most things used by default
func NewWithDefaults(
serverID string,
collector collector.EventCollector,
service PacketProcessor,
secrets secrets.Secrets,
mode constants.ModeType,
procMountPoint string,
) PolicyEnforcer {
if collector == nil {
zap.L().Fatal("Collector must be given to NewDefaultDatapathEnforcer")
}
mutualAuthorization := false
fqConfig := fqconfig.NewFilterQueueWithDefaults()
validity := time.Hour * 8760
return New(
mutualAuthorization,
fqConfig,
collector,
service,
secrets,
serverID,
validity,
mode,
procMountPoint,
)
}
// Enforce implements the Enforce interface method and configures the data path for a new PU
func (d *Datapath) Enforce(contextID string, puInfo *policy.PUInfo) error {
puContext, err := d.contextTracker.Get(contextID)
if err != nil {
return d.doCreatePU(contextID, puInfo)
}
return d.doUpdatePU(puContext.(*PUContext), puInfo)
}
// Unenforce removes the configuration for the given PU
func (d *Datapath) Unenforce(contextID string) error {
puContext, err := d.contextTracker.Get(contextID)
if err != nil {
return fmt.Errorf("ContextID not found in Enforcer")
}
puContext.(*PUContext).Lock()
defer puContext.(*PUContext).Unlock()
pu := puContext.(*PUContext)
if err := d.puFromIP.Remove(pu.IP); err != nil {
zap.L().Warn("Unable to remove cache entry during unenforcement",
zap.String("IP", pu.IP),
zap.Error(err),
)
}
if err := d.puFromIP.Remove(pu.Mark); err != nil {
zap.L().Warn("Unable to remove cache entry during unenforcement",
zap.String("Mark", pu.Mark),
zap.Error(err),
)
}
for _, port := range pu.Ports {
if err := d.puFromIP.Remove(port); err != nil {
zap.L().Warn("Unable to remove cache entry during unenforcement",
zap.String("Port", port),
zap.Error(err),
)
}
}
if err := d.contextTracker.Remove(contextID); err != nil {
zap.L().Warn("Unable to remove context from cache",
zap.String("contextID", contextID),
zap.Error(err),
)
}
return nil
}
// GetFilterQueue returns the filter queues used by the data path
func (d *Datapath) GetFilterQueue() *fqconfig.FilterQueue {
return d.filterQueue
}
// Start starts the application and network interceptors
func (d *Datapath) Start() error {
zap.L().Debug("Start enforcer", zap.Int("mode", int(d.mode)))
if d.service != nil {
d.service.Initialize(d.secrets, d.filterQueue)
}
d.startApplicationInterceptor()
d.startNetworkInterceptor()
go d.nflogger.start()
return nil
}
// Stop stops the enforcer
func (d *Datapath) Stop() error {
zap.L().Debug("Stoping enforcer")
for i := uint16(0); i < d.filterQueue.GetNumApplicationQueues(); i++ {
d.appStop[i] <- true
}
for i := uint16(0); i < d.filterQueue.GetNumNetworkQueues(); i++ {
d.netStop[i] <- true
}
d.nflogger.stop()
return nil
}
func (d *Datapath) getProcessKeys(puInfo *policy.PUInfo) (string, []string) {
mark, ok := puInfo.Runtime.Options().Get(cgnetcls.CgroupMarkTag)
if !ok {
mark = ""
}
ports, ok := puInfo.Runtime.Options().Get(cgnetcls.PortTag)
if !ok {
ports = "0"
}
portlist := strings.Split(ports, ",")
return mark, portlist
}
func (d *Datapath) doCreatePU(contextID string, puInfo *policy.PUInfo) error {
ip, ok := puInfo.Runtime.DefaultIPAddress()
if !ok {
if d.mode == constants.LocalContainer {
return fmt.Errorf("No IP provided for Local Container")
}
ip = DefaultNetwork
}
pu := &PUContext{
ID: contextID,
ManagementID: puInfo.Policy.ManagementID(),
PUType: puInfo.Runtime.PUType(),
IP: ip,
externalIPCache: cache.NewCacheWithExpiration(time.Second * 900),
}
// Cache PUs for retrieval based on packet information
if pu.PUType == constants.LinuxProcessPU {
pu.Mark, pu.Ports = d.getProcessKeys(puInfo)
d.puFromMark.AddOrUpdate(pu.Mark, pu)
for _, port := range pu.Ports {
d.puFromPort.AddOrUpdate(port, pu)
}
} else {
if ip, ok := puInfo.Runtime.DefaultIPAddress(); ok {
d.puFromIP.AddOrUpdate(ip, pu)
} else {
d.puFromIP.AddOrUpdate(DefaultNetwork, pu)
}
}
// Cache PU from contextID for management and policy updates
d.contextTracker.AddOrUpdate(contextID, pu)
return d.doUpdatePU(pu, puInfo)
}
func (d *Datapath) doUpdatePU(puContext *PUContext, containerInfo *policy.PUInfo) error {
puContext.Lock()
defer puContext.Unlock()
puContext.AcceptRcvRules, puContext.RejectRcvRules = createRuleDBs(containerInfo.Policy.ReceiverRules())
puContext.AcceptTxtRules, puContext.RejectTxtRules = createRuleDBs(containerInfo.Policy.TransmitterRules())
puContext.Identity = containerInfo.Policy.Identity()
puContext.Annotations = containerInfo.Policy.Annotations()
puContext.ApplicationACLs = acls.NewACLCache()
if err := puContext.ApplicationACLs.AddRuleList(containerInfo.Policy.ApplicationACLs()); err != nil {
return err
}
puContext.NetworkACLS = acls.NewACLCache()
return puContext.NetworkACLS.AddRuleList(containerInfo.Policy.NetworkACLs())
}
func (d *Datapath) puInfoDelegate(contextID string) (ID string, tags *policy.TagStore) {
item, err := d.contextTracker.Get(contextID)
if err != nil {
return
}
ctx := item.(*PUContext)
ctx.Lock()
ID = ctx.ManagementID
tags = ctx.Annotations.Copy()
ctx.Unlock()
return
}