/
packetin.go
407 lines (381 loc) · 13.7 KB
/
packetin.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
// Copyright 2020 Antrea Authors
//
// 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 traceflow
import (
"context"
"errors"
"fmt"
"net"
"time"
"antrea.io/libOpenflow/openflow13"
"antrea.io/libOpenflow/protocol"
"antrea.io/ofnet/ofctrl"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/util/retry"
"k8s.io/klog/v2"
"antrea.io/antrea/pkg/agent/openflow"
crdv1alpha1 "antrea.io/antrea/pkg/apis/crd/v1alpha1"
binding "antrea.io/antrea/pkg/ovs/openflow"
)
func (c *Controller) HandlePacketIn(pktIn *ofctrl.PacketIn) error {
if !c.traceflowListerSynced() {
return errors.New("traceflow controller is not started")
}
oldTf, nodeResult, packet, err := c.parsePacketIn(pktIn)
if err != nil {
klog.Errorf("parsePacketIn error: %+v", err)
return err
}
// Retry when update CRD conflict which caused by multiple agents updating one CRD at same time.
err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
tf, err := c.traceflowInformer.Lister().Get(oldTf.Name)
if err != nil {
klog.Warningf("Get traceflow failed: %+v", err)
return err
}
update := tf.DeepCopy()
update.Status.Results = append(update.Status.Results, *nodeResult)
if packet != nil {
update.Status.CapturedPacket = packet
}
_, err = c.traceflowClient.CrdV1alpha1().Traceflows().UpdateStatus(context.TODO(), update, v1.UpdateOptions{})
if err != nil {
klog.Warningf("Update traceflow failed: %+v", err)
return err
}
klog.Infof("Updated traceflow %s: %+v", tf.Name, update.Status)
return nil
})
if err != nil {
klog.Errorf("Update traceflow error: %+v", err)
}
return err
}
func (c *Controller) parsePacketIn(pktIn *ofctrl.PacketIn) (*crdv1alpha1.Traceflow, *crdv1alpha1.NodeResult, *crdv1alpha1.Packet, error) {
matchers := pktIn.GetMatches()
// Get data plane tag.
// Directly read data plane tag from packet.
var err error
var tag uint8
var ctNwDst, ctNwSrc, ipDst, ipSrc string
if pktIn.Data.Ethertype == protocol.IPv4_MSG {
ipPacket, ok := pktIn.Data.Data.(*protocol.IPv4)
if !ok {
return nil, nil, nil, errors.New("invalid traceflow IPv4 packet")
}
tag = ipPacket.DSCP
ctNwDst, err = getCTDstValue(matchers, false)
if err != nil {
return nil, nil, nil, err
}
ctNwSrc, err = getCTSrcValue(matchers, false)
if err != nil {
return nil, nil, nil, err
}
ipDst = ipPacket.NWDst.String()
ipSrc = ipPacket.NWSrc.String()
} else if pktIn.Data.Ethertype == protocol.IPv6_MSG {
ipv6Packet, ok := pktIn.Data.Data.(*protocol.IPv6)
if !ok {
return nil, nil, nil, errors.New("invalid traceflow IPv6 packet")
}
tag = ipv6Packet.TrafficClass >> 2
ctNwDst, err = getCTDstValue(matchers, true)
if err != nil {
return nil, nil, nil, err
}
ctNwSrc, err = getCTSrcValue(matchers, true)
if err != nil {
return nil, nil, nil, err
}
ipDst = ipv6Packet.NWDst.String()
ipSrc = ipv6Packet.NWSrc.String()
} else {
return nil, nil, nil, fmt.Errorf("unsupported traceflow packet Ethertype: %d", pktIn.Data.Ethertype)
}
firstPacket := false
c.runningTraceflowsMutex.RLock()
tfState, exists := c.runningTraceflows[tag]
if exists {
firstPacket = !tfState.receivedPacket
tfState.receivedPacket = true
}
c.runningTraceflowsMutex.RUnlock()
if !exists {
return nil, nil, nil, fmt.Errorf("Traceflow for dataplane tag %d not found in cache", tag)
}
var capturedPacket *crdv1alpha1.Packet
if tfState.liveTraffic && firstPacket {
// Uninstall the OVS flows after receiving the first packet, to
// avoid capturing too many matched packets.
c.ofClient.UninstallTraceflowFlows(tag)
// Report the captured dropped packet, if the Traceflow is for
// the dropped packet only; report too if only the receiver
// captures packets in the Traceflow (live-traffic Traceflow
// that has only destination Pod set); otherwise only the sender
// should report the first captured packet.
if tfState.isSender || tfState.receiverOnly || tfState.droppedOnly {
capturedPacket = parseCapturedPacket(pktIn)
}
}
tf, err := c.traceflowLister.Get(tfState.name)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to get Traceflow %s CRD: %v", tfState.name, err)
}
obs := []crdv1alpha1.Observation{}
tableID := pktIn.TableId
if tfState.isSender {
ob := new(crdv1alpha1.Observation)
ob.Component = crdv1alpha1.ComponentSpoofGuard
ob.Action = crdv1alpha1.ActionForwarded
obs = append(obs, *ob)
} else {
ob := new(crdv1alpha1.Observation)
ob.Component = crdv1alpha1.ComponentForwarding
ob.Action = crdv1alpha1.ActionReceived
obs = append(obs, *ob)
}
// Collect Service connections.
// - For packet is DNATed only, the final state is that ipDst != ctNwDst (in DNAT CT zone).
// - For packet is both DNATed and SNATed, the first state is also ipDst != ctNwDst (in DNAT CT zone), but the final
// state is that ipSrc != ctNwSrc (in SNAT CT zone). The state in DNAT CT zone cannot be recognized in SNAT CT zone.
if !tfState.receiverOnly {
if isValidCtNw(ctNwDst) && ipDst != ctNwDst || isValidCtNw(ctNwSrc) && ipSrc != ctNwSrc {
ob := &crdv1alpha1.Observation{
Component: crdv1alpha1.ComponentLB,
Action: crdv1alpha1.ActionForwarded,
TranslatedDstIP: ipDst,
}
if isValidCtNw(ctNwSrc) && ipSrc != ctNwSrc {
ob.TranslatedSrcIP = ipSrc
}
obs = append(obs, *ob)
}
// Collect egress conjunctionID and get NetworkPolicy from cache.
if match := getMatchRegField(matchers, openflow.TFEgressConjIDField); match != nil {
egressInfo, err := getRegValue(match, nil)
if err != nil {
return nil, nil, nil, err
}
ob := getNetworkPolicyObservation(tableID, false)
npRef := c.networkPolicyQuerier.GetNetworkPolicyByRuleFlowID(egressInfo)
if npRef != nil {
ob.NetworkPolicy = npRef.ToString()
}
obs = append(obs, *ob)
}
}
// Collect ingress conjunctionID and get NetworkPolicy from cache.
if match := getMatchRegField(matchers, openflow.TFIngressConjIDField); match != nil {
ingressInfo, err := getRegValue(match, nil)
if err != nil {
return nil, nil, nil, err
}
ob := getNetworkPolicyObservation(tableID, true)
npRef := c.networkPolicyQuerier.GetNetworkPolicyByRuleFlowID(ingressInfo)
if npRef != nil {
ob.NetworkPolicy = npRef.ToString()
}
obs = append(obs, *ob)
}
// Get drop table.
if tableID == openflow.EgressMetricTable.GetID() || tableID == openflow.IngressMetricTable.GetID() {
ob := getNetworkPolicyObservation(tableID, tableID == openflow.IngressMetricTable.GetID())
if match := getMatchRegField(matchers, openflow.CNPConjIDField); match != nil {
notAllowConjInfo, err := getRegValue(match, nil)
if err != nil {
return nil, nil, nil, err
}
if ruleRef := c.networkPolicyQuerier.GetRuleByFlowID(notAllowConjInfo); ruleRef != nil {
if npRef := ruleRef.PolicyRef; npRef != nil {
ob.NetworkPolicy = npRef.ToString()
}
if ruleRef.Action != nil && *ruleRef.Action == crdv1alpha1.RuleActionReject {
ob.Action = crdv1alpha1.ActionRejected
}
}
}
obs = append(obs, *ob)
} else if tableID == openflow.EgressDefaultTable.GetID() || tableID == openflow.IngressDefaultTable.GetID() {
ob := getNetworkPolicyObservation(tableID, tableID == openflow.IngressDefaultTable.GetID())
obs = append(obs, *ob)
}
// Get output table.
if tableID == openflow.L2ForwardingOutTable.GetID() {
ob := new(crdv1alpha1.Observation)
tunnelDstIP := ""
isIPv6 := c.nodeConfig.NodeIPv6Addr != nil
if match := getMatchTunnelDstField(matchers, isIPv6); match != nil {
tunnelDstIP, err = getTunnelDstValue(match)
if err != nil {
return nil, nil, nil, err
}
}
var outputPort uint32
if match := getMatchRegField(matchers, openflow.TargetOFPortField); match != nil {
outputPort, err = getRegValue(match, nil)
if err != nil {
return nil, nil, nil, err
}
}
gatewayIP := c.nodeConfig.GatewayConfig.IPv4
if pktIn.Data.Ethertype == protocol.IPv6_MSG {
gatewayIP = c.nodeConfig.GatewayConfig.IPv6
}
gwPort := c.nodeConfig.GatewayConfig.OFPort
tunPort := c.nodeConfig.TunnelOFPort
if c.networkConfig.TrafficEncapMode.SupportsEncap() && outputPort == tunPort {
ob.TunnelDstIP = tunnelDstIP
ob.Action = crdv1alpha1.ActionForwarded
} else if ipDst == gatewayIP.String() && outputPort == gwPort {
ob.Action = crdv1alpha1.ActionDelivered
} else if c.networkConfig.TrafficEncapMode.SupportsEncap() && outputPort == gwPort {
ob.Action = crdv1alpha1.ActionForwardedOutOfOverlay
} else if outputPort == gwPort { // noEncap
ob.Action = crdv1alpha1.ActionForwarded
} else {
// Output port is Pod port, packet is delivered.
ob.Action = crdv1alpha1.ActionDelivered
}
ob.ComponentInfo = openflow.L2ForwardingOutTable.GetName()
ob.Component = crdv1alpha1.ComponentForwarding
obs = append(obs, *ob)
}
nodeResult := crdv1alpha1.NodeResult{Node: c.nodeConfig.Name, Timestamp: time.Now().Unix(), Observations: obs}
return tf, &nodeResult, capturedPacket, nil
}
func getMatchRegField(matchers *ofctrl.Matchers, field *binding.RegField) *ofctrl.MatchField {
return matchers.GetMatchByName(field.GetNXFieldName())
}
func getMatchTunnelDstField(matchers *ofctrl.Matchers, isIPv6 bool) *ofctrl.MatchField {
if isIPv6 {
return matchers.GetMatchByName("NXM_NX_TUN_IPV6_DST")
}
return matchers.GetMatchByName("NXM_NX_TUN_IPV4_DST")
}
func getRegValue(regMatch *ofctrl.MatchField, rng *openflow13.NXRange) (uint32, error) {
regValue, ok := regMatch.GetValue().(*ofctrl.NXRegister)
if !ok {
return 0, errors.New("register value cannot be got")
}
if rng != nil {
return ofctrl.GetUint32ValueWithRange(regValue.Data, rng), nil
}
return regValue.Data, nil
}
func getTunnelDstValue(regMatch *ofctrl.MatchField) (string, error) {
regValue, ok := regMatch.GetValue().(net.IP)
if !ok {
return "", errors.New("tunnel destination value cannot be got")
}
return regValue.String(), nil
}
func getCTDstValue(matchers *ofctrl.Matchers, isIPv6 bool) (string, error) {
var match *ofctrl.MatchField
if isIPv6 {
match = matchers.GetMatchByName("NXM_NX_CT_IPV6_DST")
} else {
match = matchers.GetMatchByName("NXM_NX_CT_NW_DST")
}
if match == nil {
return "", nil
}
regValue, ok := match.GetValue().(net.IP)
if !ok {
return "", errors.New("packet-in conntrack destination value cannot be retrieved from metadata")
}
return regValue.String(), nil
}
func getCTSrcValue(matchers *ofctrl.Matchers, isIPv6 bool) (string, error) {
var match *ofctrl.MatchField
if isIPv6 {
match = matchers.GetMatchByName("NXM_NX_CT_IPV6_SRC")
} else {
match = matchers.GetMatchByName("NXM_NX_CT_NW_SRC")
}
if match == nil {
return "", nil
}
regValue, ok := match.GetValue().(net.IP)
if !ok {
return "", errors.New("packet-in conntrack source value cannot be retrieved from metadata")
}
return regValue.String(), nil
}
func getNetworkPolicyObservation(tableID uint8, ingress bool) *crdv1alpha1.Observation {
ob := new(crdv1alpha1.Observation)
ob.Component = crdv1alpha1.ComponentNetworkPolicy
if ingress {
switch tableID {
case openflow.IngressMetricTable.GetID():
// Packet dropped by ANP/default drop rule
ob.ComponentInfo = openflow.IngressMetricTable.GetName()
ob.Action = crdv1alpha1.ActionDropped
case openflow.IngressDefaultTable.GetID():
// Packet dropped by ANP/default drop rule
ob.ComponentInfo = openflow.IngressDefaultTable.GetName()
ob.Action = crdv1alpha1.ActionDropped
default:
ob.ComponentInfo = openflow.IngressRuleTable.GetName()
ob.Action = crdv1alpha1.ActionForwarded
}
} else {
switch tableID {
case openflow.EgressMetricTable.GetID():
// Packet dropped by ANP/default drop rule
ob.ComponentInfo = openflow.EgressMetricTable.GetName()
ob.Action = crdv1alpha1.ActionDropped
case openflow.EgressDefaultTable.GetID():
// Packet dropped by ANP/default drop rule
ob.ComponentInfo = openflow.EgressDefaultTable.GetName()
ob.Action = crdv1alpha1.ActionDropped
default:
ob.ComponentInfo = openflow.EgressRuleTable.GetName()
ob.Action = crdv1alpha1.ActionForwarded
}
}
return ob
}
func isValidCtNw(ipStr string) bool {
ip := net.ParseIP(ipStr)
if ip == nil {
return false
}
// Reserved by IETF [RFC3513][RFC4291]
_, cidr, _ := net.ParseCIDR("0000::/8")
if cidr.Contains(ip) {
return false
}
return true
}
func parseCapturedPacket(pktIn *ofctrl.PacketIn) *crdv1alpha1.Packet {
pkt, _ := binding.ParsePacketIn(pktIn)
capturedPacket := crdv1alpha1.Packet{SrcIP: pkt.SourceIP.String(), DstIP: pkt.DestinationIP.String(), Length: pkt.IPLength}
if pkt.IsIPv6 {
ipProto := int32(pkt.IPProto)
capturedPacket.IPv6Header = &crdv1alpha1.IPv6Header{NextHeader: &ipProto, HopLimit: int32(pkt.TTL)}
} else {
capturedPacket.IPHeader.Protocol = int32(pkt.IPProto)
capturedPacket.IPHeader.TTL = int32(pkt.TTL)
capturedPacket.IPHeader.Flags = int32(pkt.IPFlags)
}
if pkt.IPProto == protocol.Type_TCP {
capturedPacket.TransportHeader.TCP = &crdv1alpha1.TCPHeader{SrcPort: int32(pkt.SourcePort), DstPort: int32(pkt.DestinationPort), Flags: int32(pkt.TCPFlags)}
} else if pkt.IPProto == protocol.Type_UDP {
capturedPacket.TransportHeader.UDP = &crdv1alpha1.UDPHeader{SrcPort: int32(pkt.SourcePort), DstPort: int32(pkt.DestinationPort)}
} else if pkt.IPProto == protocol.Type_ICMP || pkt.IPProto == protocol.Type_IPv6ICMP {
capturedPacket.TransportHeader.ICMP = &crdv1alpha1.ICMPEchoRequestHeader{ID: int32(pkt.ICMPEchoID), Sequence: int32(pkt.ICMPEchoSeq)}
}
return &capturedPacket
}