-
Notifications
You must be signed in to change notification settings - Fork 114
/
sessionrules_mock.go
416 lines (374 loc) · 11.3 KB
/
sessionrules_mock.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
package sessionrules
import (
"bytes"
"net"
"strings"
govppmock "git.fd.io/govpp.git/adapter/mock"
govppapi "git.fd.io/govpp.git/api"
govpp "git.fd.io/govpp.git/core"
"github.com/ligato/cn-infra/logging"
"fmt"
"git.fd.io/govpp.git/codec"
vpptcprule "github.com/contiv/vpp/plugins/policy/renderer/vpptcp/rule"
"github.com/ligato/vpp-agent/plugins/vpp/binapi/vpp1810/session"
"github.com/ligato/vpp-agent/plugins/vpp/binapi/vpp1810/vpe"
)
// MockSessionRules simulates session rules from VPPTCP stack.
// The installed rules are only stored locally and can be queried for testing
// purposes.
type MockSessionRules struct {
Log logging.Logger
tagPrefix string
vppMock *govppmock.VppAdapter
vppConn *govpp.Connection
localTable map[uint32]SessionRules // namespace index -> rules
globalTable SessionRules
errCount int
reqCount int
}
// LocalTableCheck allows to check the content of a local table.
type LocalTableCheck struct {
nsIndex uint32
session *MockSessionRules
}
// LocalTableCheck allows to check the content of the global table.
type GlobalTableCheck struct {
session *MockSessionRules
}
// SessionRules is a list of session rules.
type SessionRules []*vpptcprule.SessionRule
// NewMockSessionRules is a constructor for MockSessionRules.
// Create only one in the entire test suite.
// Clear state between tests using the Clear() method.
func NewMockSessionRules(log logging.Logger, tagPrefix string) *MockSessionRules {
var err error
mock := &MockSessionRules{
Log: log,
tagPrefix: tagPrefix,
vppMock: govppmock.NewVppAdapter(),
localTable: make(map[uint32]SessionRules),
globalTable: SessionRules{},
}
mock.vppMock.MockReplyHandler(mock.msgReplyHandler)
mock.vppMock.GetMsgID("session_rules_dump", "")
mock.vppMock.GetMsgID("session_rules_details", "")
mock.vppMock.GetMsgID("session_rule_add_del", "")
mock.vppMock.GetMsgID("session_rule_add_del_reply", "")
mock.vppConn, err = govpp.Connect(mock.vppMock)
if err != nil {
return nil
}
return mock
}
// Clear clears the state of the mocked session.
func (msr *MockSessionRules) Clear() {
msr.localTable = make(map[uint32]SessionRules)
msr.globalTable = SessionRules{}
msr.errCount = 0
msr.reqCount = 0
}
// NewVPPChan creates a new mock VPP channel.
func (msr *MockSessionRules) NewVPPChan() govppapi.Channel {
channel, _ := msr.vppConn.NewAPIChannel()
return channel
}
// GetErrCount returns the number of errors that have occurred so far.
func (msr *MockSessionRules) GetErrCount() int {
return msr.errCount
}
// GetReqCount returns the number of requests that have been received so far.
func (msr *MockSessionRules) GetReqCount() int {
return msr.reqCount
}
// LocalTable allows to access checks for a local table.
func (msr *MockSessionRules) LocalTable(nsIndex uint32) *LocalTableCheck {
return &LocalTableCheck{nsIndex: nsIndex, session: msr}
}
// GlobalTable allows to access checks for the global table.
func (msr *MockSessionRules) GlobalTable() *GlobalTableCheck {
return &GlobalTableCheck{session: msr}
}
// NumOfRules returns the number of rules in the table.
func (ltc *LocalTableCheck) NumOfRules() int {
table, exists := ltc.session.localTable[ltc.nsIndex]
if !exists {
return 0
}
return len(table)
}
// NumOfRules returns the number of rules in the table.
func (gtc *GlobalTableCheck) NumOfRules() int {
return len(gtc.session.globalTable)
}
// HasRule returns <true> if the given rule is present in the table.
func (ltc *LocalTableCheck) HasRule(lclIP string, lclPort uint16, rmtIP string, rmtPort uint16, proto string, action string) bool {
table, exists := ltc.session.localTable[ltc.nsIndex]
if !exists {
return false
}
return ltc.session.hasRule(table, vpptcprule.ScopeLocal, ltc.nsIndex, lclIP, lclPort, rmtIP, rmtPort, proto, action)
}
// HasRule returns <true> if the given rule is present in the table.
func (gtc *GlobalTableCheck) HasRule(lclIP string, lclPort uint16, rmtIP string, rmtPort uint16, proto string, action string) bool {
return gtc.session.hasRule(gtc.session.globalTable, vpptcprule.ScopeGlobal, 0, lclIP, lclPort, rmtIP, rmtPort, proto, action)
}
// hasRule returns <true> if the given rule is present in the given table.
func (msr *MockSessionRules) hasRule(table SessionRules, scope uint8, nsIndex uint32,
lclIP string, lclPort uint16, rmtIP string, rmtPort uint16, proto string, action string) bool {
var err error
// Construct SessionRule.
rule := vpptcprule.SessionRule{
LclPort: lclPort,
RmtPort: rmtPort,
AppnsIndex: nsIndex,
Scope: scope,
}
// Parse transport protocol.
var transportProto uint8
switch proto {
case "TCP":
transportProto = vpptcprule.ProtoTCP
case "UDP":
transportProto = vpptcprule.ProtoUDP
}
rule.TransportProto = transportProto
// Parse action.
var actionIndex uint32
switch action {
case "ALLOW":
actionIndex = vpptcprule.ActionAllow
case "DENY":
actionIndex = vpptcprule.ActionDeny
}
rule.ActionIndex = actionIndex
// Parse IP addresses.
isIPv4 := uint8(0)
if lclIP != "" {
var lclIPNet *net.IPNet
if !strings.Contains(lclIP, "/") {
lclIPNet = getOneHostSubnet(lclIP)
} else {
_, lclIPNet, err = net.ParseCIDR(lclIP)
if err != nil {
return false
}
}
if lclIPNet.IP.To4() != nil {
isIPv4 = 1
copy(rule.LclIP[:], lclIPNet.IP.To4())
} else {
copy(rule.LclIP[:], lclIPNet.IP.To16())
}
lclPlen, _ := lclIPNet.Mask.Size()
rule.LclPlen = uint8(lclPlen)
}
if rmtIP != "" {
var rmtIPNet *net.IPNet
if !strings.Contains(rmtIP, "/") {
rmtIPNet = getOneHostSubnet(rmtIP)
} else {
_, rmtIPNet, err = net.ParseCIDR(rmtIP)
if err != nil {
return false
}
}
if rmtIPNet.IP.To4() != nil {
isIPv4 = 1
copy(rule.RmtIP[:], rmtIPNet.IP.To4())
} else {
copy(rule.RmtIP[:], rmtIPNet.IP.To16())
}
rmtPlen, _ := rmtIPNet.Mask.Size()
rule.RmtPlen = uint8(rmtPlen)
}
if lclIP == "" && rmtIP == "" {
isIPv4 = 1
}
rule.IsIP4 = isIPv4
// Search for the rule.
for _, rule2 := range table {
if rule.Compare(rule2, false) == 0 {
return true
}
}
fmt.Printf("Rule '%s' was not found\n", rule.String())
fmt.Printf("Local table:\n")
for idx, rule2 := range table {
fmt.Printf("Rule %d: '%s'\n", idx, rule2.String())
}
return false
}
// msgReplyHandler handles binary API request.
func (msr *MockSessionRules) msgReplyHandler(request govppmock.MessageDTO) (reply []byte, msgID uint16, prepared bool) {
msr.reqCount++
reqName, found := msr.vppMock.GetMsgNameByID(request.MsgID)
if !found {
msr.errCount++
msr.Log.Error("Not existing req msg name for MsgID=", request.MsgID)
return reply, 0, false
}
msr.Log.Debug("MockSessionRules msgReplyHandler ", request.MsgID, " ", reqName)
if reqName == "session_rules_dump" {
// Session dump.
msgs := []govppapi.Message{}
for _, localTable := range msr.localTable {
for _, rule := range localTable {
msgs = append(msgs, makeSessionRuleDetails(rule))
}
}
for _, rule := range msr.globalTable {
msgs = append(msgs, makeSessionRuleDetails(rule))
}
msr.vppMock.MockReply(msgs...)
} else if reqName == "control_ping" {
// Control ping.
msgID, err := msr.vppMock.GetMsgID("control_ping_reply", "")
if err != nil {
msr.errCount++
msr.Log.Error(err)
return reply, 0, false
}
replyMsg := &vpe.ControlPingReply{}
replyMsg.Retval = 0
reply, err := msr.vppMock.ReplyBytes(request, replyMsg)
if err != nil {
msr.errCount++
msr.Log.Error(err)
return reply, 0, false
}
return reply, msgID, true
} else if reqName == "session_rule_add_del" {
// Session rule add/del.
var retval int32
// Decode rule.
codec := codec.MsgCodec{}
ruleAddDel := session.SessionRuleAddDel{}
err := codec.DecodeMsg(request.Data, &ruleAddDel)
if err != nil {
msr.errCount++
msr.Log.Error(err)
return reply, 0, false
}
msgID, err := msr.vppMock.GetMsgID("session_rule_add_del_reply", "")
if err != nil {
msr.errCount++
msr.Log.Error(err)
return reply, 0, false
}
rule := makeSessionRule(&ruleAddDel)
// Check tag
tagLen := bytes.IndexByte(rule.Tag[:], 0)
tag := string(rule.Tag[:tagLen])
if !strings.HasPrefix(tag, msr.tagPrefix) {
msr.errCount++
msr.Log.WithField("rule", rule).Warn("Invalid tag")
retval = 1
}
// Add/Delete rule.
if retval == 0 {
var ok bool
if rule.Scope == vpptcprule.ScopeLocal {
_, exists := msr.localTable[rule.AppnsIndex]
if !exists {
msr.localTable[rule.AppnsIndex] = SessionRules{}
}
msr.localTable[rule.AppnsIndex], ok = addDelRule(msr.localTable[rule.AppnsIndex], rule, ruleAddDel.IsAdd)
if !ok {
msr.errCount++
msr.Log.WithField("rule", rule).Warn("The rule cannot be added/removed to/from the table")
retval = 1
}
} else {
msr.globalTable, ok = addDelRule(msr.globalTable, rule, ruleAddDel.IsAdd)
if !ok {
msr.errCount++
msr.Log.WithField("rule", rule).Warn("The rule cannot be added/removed to/from the table")
retval = 1
}
}
}
// Send response.
replyMsg := session.SessionRuleAddDelReply{}
replyMsg.Retval = retval
reply, err := msr.vppMock.ReplyBytes(request, &replyMsg)
if err != nil {
msr.errCount++
msr.Log.Error(err)
return reply, 0, false
}
return reply, msgID, true
} else {
msr.Log.WithField("reqName", reqName).Warn("Unhandled request")
}
return reply, 0, false
}
// addDelRule adds or removes rule to/from a table.
func addDelRule(table SessionRules, rule *vpptcprule.SessionRule, isAdd uint8) (SessionRules, bool) {
compareTag := false
if isAdd == 0 {
compareTag = true /* exact match for removal */
}
for idx, rule2 := range table {
if rule.Compare(rule2, compareTag) == 0 {
if isAdd == 1 {
/* already added */
return table, false
}
return append(table[:idx], table[idx+1:]...), true
}
}
if isAdd == 1 {
return append(table, rule), true
}
/* not found */
return table, false
}
func makeSessionRuleDetails(rule *vpptcprule.SessionRule) *session.SessionRulesDetails {
details := &session.SessionRulesDetails{
TransportProto: rule.TransportProto,
IsIP4: rule.IsIP4,
LclIP: rule.LclIP[:],
LclPlen: rule.LclPlen,
RmtIP: rule.RmtIP[:],
RmtPlen: rule.RmtPlen,
LclPort: rule.LclPort,
RmtPort: rule.RmtPort,
ActionIndex: rule.ActionIndex,
AppnsIndex: rule.AppnsIndex,
Scope: rule.Scope,
Tag: rule.Tag[:],
}
return details
}
func makeSessionRule(rule *session.SessionRuleAddDel) *vpptcprule.SessionRule {
sessionRule := &vpptcprule.SessionRule{
TransportProto: rule.TransportProto,
IsIP4: rule.IsIP4,
LclPlen: rule.LclPlen,
RmtPlen: rule.RmtPlen,
LclPort: rule.LclPort,
RmtPort: rule.RmtPort,
ActionIndex: rule.ActionIndex,
AppnsIndex: rule.AppnsIndex,
Scope: rule.Scope,
}
copy(sessionRule.LclIP[:], rule.LclIP)
copy(sessionRule.RmtIP[:], rule.RmtIP)
copy(sessionRule.Tag[:], rule.Tag)
return sessionRule
}
// Function returns the IP subnet that contains only the given host
// (i.e. /32 for IPv4, /128 for IPv6).
func getOneHostSubnet(hostAddr string) *net.IPNet {
ip := net.ParseIP(hostAddr)
if ip == nil {
return nil
}
ipNet := &net.IPNet{IP: ip}
if ip.To4() != nil {
ipNet.Mask = net.CIDRMask(net.IPv4len*8, net.IPv4len*8)
} else {
ipNet.Mask = net.CIDRMask(net.IPv6len*8, net.IPv6len*8)
}
return ipNet
}