-
Notifications
You must be signed in to change notification settings - Fork 51
/
datapath_udp.go
679 lines (555 loc) · 24.1 KB
/
datapath_udp.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
package nfqdatapath
// Go libraries
import (
"fmt"
"strconv"
"time"
"go.aporeto.io/trireme-lib/collector"
"go.aporeto.io/trireme-lib/controller/constants"
enforcerconstants "go.aporeto.io/trireme-lib/controller/internal/enforcer/constants"
"go.aporeto.io/trireme-lib/controller/pkg/claimsheader"
"go.aporeto.io/trireme-lib/controller/pkg/connection"
"go.aporeto.io/trireme-lib/controller/pkg/packet"
"go.aporeto.io/trireme-lib/controller/pkg/pucontext"
"go.aporeto.io/trireme-lib/controller/pkg/tokens"
"go.uber.org/zap"
)
const (
// Default retransmit delay for first packet
retransmitDelay = 200
// rentrasmitRetries is the number of times we will retry
retransmitRetries = 3
)
// ProcessNetworkUDPPacket processes packets arriving from network and are destined to the application.
func (d *Datapath) ProcessNetworkUDPPacket(p *packet.Packet) (conn *connection.UDPConnection, err error) {
if d.PacketLogsEnabled() {
zap.L().Debug("Processing network packet ",
zap.String("flow", p.L4FlowHash()),
)
defer zap.L().Debug("Finished Processing network packet ",
zap.String("flow", p.L4FlowHash()),
zap.Error(err),
)
}
udpPacketType := p.GetUDPType()
zap.L().Debug("Got packet of type:", zap.Reflect("Type", udpPacketType), zap.Reflect("Len", len(p.GetBuffer(0))))
switch udpPacketType {
case packet.UDPSynMask:
conn, err = d.netSynUDPRetrieveState(p)
if err != nil {
if d.PacketLogsEnabled() {
zap.L().Debug("Packet rejected",
zap.String("flow", p.L4FlowHash()),
zap.Error(err),
)
}
return nil, err
}
case packet.UDPSynAckMask:
conn, err = d.netSynAckUDPRetrieveState(p)
if err != nil {
if d.PacketLogsEnabled() {
zap.L().Debug("Syn ack Packet Rejected/ignored",
zap.String("flow", p.L4FlowHash()),
)
}
return nil, err
}
case packet.UDPFinAckMask:
if err := d.processUDPFinPacket(p); err != nil {
zap.L().Debug("unable to process udp fin ack",
zap.String("flowhash", p.L4FlowHash()), zap.Error(err))
return nil, err
}
// drop control packets
return conn, fmt.Errorf("dropping udp fin ack control packet")
default:
// Process packets that don't have the control header. These are data packets.
conn, err = d.netUDPAckRetrieveState(p)
if err != nil {
if d.PacketLogsEnabled() {
zap.L().Debug("No connection found for the flow, Dropping it",
zap.String("flow", p.L4FlowHash()),
zap.Error(err),
)
}
return nil, err
}
}
// We are processing only one connection at a time.
conn.Lock()
defer conn.Unlock()
p.Print(packet.PacketStageIncoming, d.PacketLogsEnabled())
if d.service != nil {
if !d.service.PreProcessUDPNetPacket(p, conn.Context, conn) {
p.Print(packet.PacketFailureService, d.PacketLogsEnabled())
return conn, conn.Context.PuContextError(pucontext.ErrUDPPreProcessingFailed, "pre processing failed for network packet")
}
}
// handle handshake packets and do not deliver to application.
action, claims, err := d.processNetUDPPacket(p, conn.Context, conn)
if err != nil {
zap.L().Debug("Rejecting packet because of policy decision",
zap.String("flow", p.L4FlowHash()),
zap.Error(err),
)
return conn, fmt.Errorf("packet processing failed for network packet: %s", err)
}
// Process the packet by any external services.
if d.service != nil {
if !d.service.PostProcessUDPNetPacket(p, action, claims, conn.Context, conn) {
p.Print(packet.PacketFailureService, d.PacketLogsEnabled())
return conn, conn.Context.PuContextError(pucontext.ErrUDPPostProcessingFailed, "post service processing failed for network packet")
}
}
// If reached the final state, drain the queue.
if conn.GetState() == connection.UDPClientSendAck {
conn.SetState(connection.UDPData)
zap.L().Debug("Draining the queue of application packets")
for udpPacket := conn.ReadPacket(); udpPacket != nil; udpPacket = conn.ReadPacket() {
if d.service != nil {
// PostProcessServiceInterface
// We call it for all outgoing packets.
if !d.service.PostProcessUDPAppPacket(udpPacket, nil, conn.Context, conn) {
udpPacket.Print(packet.PacketFailureService, d.PacketLogsEnabled())
zap.L().Error("Failed to encrypt queued packet")
}
}
err = d.udpSocketWriter.WriteSocket(udpPacket.GetBuffer(0), udpPacket.IPversion())
if err != nil {
zap.L().Error("Unable to transmit Queued UDP packets", zap.Error(err))
}
}
return conn, fmt.Errorf("Drop the packet")
}
if conn.GetState() != connection.UDPData {
// handshake packets are not to be delivered to application.
return conn, fmt.Errorf("Drop net hanshake packets (udp)")
}
return conn, nil
}
func (d *Datapath) netSynUDPRetrieveState(p *packet.Packet) (*connection.UDPConnection, error) {
// Retrieve the context from the packet information.
context, err := d.contextFromIP(false, p.Mark, p.DestPort(), packet.IPProtocolUDP)
if err != nil {
return nil, pucontext.PuContextError(pucontext.ErrNonPUTraffic, "traffic for unknown context")
}
// Check if a connection already exists for this flow. This can happen
// in the case of retransmissions. If there is no connection, create
// a new one.
conn, cerr := d.udpNetOrigConnectionTracker.Get(p.L4FlowHash())
if cerr != nil {
return connection.NewUDPConnection(context, d.udpSocketWriter), nil
}
return conn.(*connection.UDPConnection), nil
}
func (d *Datapath) netSynAckUDPRetrieveState(p *packet.Packet) (*connection.UDPConnection, error) {
conn, err := d.udpSourcePortConnectionCache.GetReset(p.SourcePortHash(packet.PacketTypeNetwork), 0)
if err != nil {
return nil, pucontext.PuContextError(pucontext.ErrUDPNoConnection, "No connection.Drop the syn ack packet")
}
return conn.(*connection.UDPConnection), nil
}
func (d *Datapath) netUDPAckRetrieveState(p *packet.Packet) (*connection.UDPConnection, error) {
hash := p.L4FlowHash()
conn, err := d.udpNetReplyConnectionTracker.GetReset(hash, 0)
if err != nil {
conn, err = d.udpNetOrigConnectionTracker.GetReset(hash, 0)
if err != nil {
// This might be an existing udp connection.
// Send FinAck to reauthorize the connection.
if err := d.sendUDPFinPacket(p); err != nil {
return nil, fmt.Errorf("net state not found, unable to send fin ack packets: %s", err)
}
return nil, fmt.Errorf("net state not found: %s", err)
}
}
return conn.(*connection.UDPConnection), nil
}
// processNetUDPPacket processes a network UDP packet and dispatches it to different methods based on the flags.
// This applies only to control packets.
func (d *Datapath) processNetUDPPacket(udpPacket *packet.Packet, context *pucontext.PUContext, conn *connection.UDPConnection) (action interface{}, claims *tokens.ConnectionClaims, err error) {
// Extra check, just in case the caller didn't provide a connection.
if conn == nil {
return nil, nil, fmt.Errorf("no connection provided")
}
udpPacketType := udpPacket.GetUDPType()
// Update connection state in the internal state machine tracker
switch udpPacketType {
case packet.UDPSynMask:
// Parse the packet for the identity information.
action, claims, err = d.processNetworkUDPSynPacket(context, conn, udpPacket)
if err != nil {
return nil, nil, err
}
// Send the return packet.
if err = d.sendUDPSynAckPacket(udpPacket, context, conn); err != nil {
return nil, nil, err
}
// Mark the state that we have transmitted a SynAck packet.
conn.SetState(connection.UDPReceiverSendSynAck)
return action, claims, nil
case packet.UDPAckMask:
// Retrieve the header and parse the signatures.
if err = d.processNetworkUDPAckPacket(udpPacket, context, conn); err != nil {
zap.L().Error("Error during authorization", zap.Error(err))
return nil, nil, err
}
// Set the connection to
conn.SetState(connection.UDPReceiverProcessedAck)
return nil, nil, nil
case packet.UDPSynAckMask:
// Process the synack header and claims of the other side.
action, claims, err = d.processNetworkUDPSynAckPacket(udpPacket, context, conn)
if err != nil {
zap.L().Error("UDP Syn ack failed with", zap.Error(err))
return nil, nil, err
}
// Send back the acknowledgement.
err = d.sendUDPAckPacket(udpPacket, context, conn)
if err != nil {
zap.L().Error("Unable to send udp Syn ack failed", zap.Error(err))
return nil, nil, err
}
conn.SetState(connection.UDPClientSendAck)
return action, claims, nil
default:
state := conn.GetState()
if state == connection.UDPReceiverProcessedAck || state == connection.UDPClientSendAck || state == connection.UDPData {
conn.SetState(connection.UDPData)
return nil, nil, nil
}
return nil, nil, fmt.Errorf("invalid packet at state: %d", state)
}
}
// ProcessApplicationUDPPacket processes packets arriving from an application and are destined to the network
func (d *Datapath) ProcessApplicationUDPPacket(p *packet.Packet) (conn *connection.UDPConnection, err error) {
if d.PacketLogsEnabled() {
zap.L().Debug("Processing application UDP packet ",
zap.String("flow", p.L4FlowHash()),
)
defer zap.L().Debug("Finished Processing UDP application packet ",
zap.String("flow", p.L4FlowHash()),
zap.Error(err),
)
}
// First retrieve the connection state.
conn, err = d.appUDPRetrieveState(p)
if err != nil {
zap.L().Debug("Connection not found", zap.Error(err))
return nil, pucontext.PuContextError(pucontext.ErrNonPUTraffic, fmt.Sprintf("Received packet from unenforced process: %s", err))
}
// We are processing only one packet from a given connection at a time.
conn.Lock()
defer conn.Unlock()
// do some pre processing.
if d.service != nil {
// PreProcessServiceInterface
if !d.service.PreProcessUDPAppPacket(p, conn.Context, conn, packet.UDPSynMask) {
p.Print(packet.PacketFailureService, d.PacketLogsEnabled())
return nil, conn.Context.PuContextError(pucontext.ErrUDPPreProcessingFailed, "pre service processing failed for UDP application packet")
}
}
triggerControlProtocol := false
switch conn.GetState() {
case connection.UDPStart:
// Queue the packet. We will send it after we authorize the session.
if err = conn.QueuePackets(p); err != nil {
// unable to queue packets, perhaps queue is full. if start
// machine is still in start state, we can start authorisation
// again. A drop counter is incremented.
zap.L().Debug("udp queue full for connection", zap.String("flow", p.L4FlowHash()))
}
// Set the state indicating that we send out a Syn packet
conn.SetState(connection.UDPClientSendSyn)
// Drop the packet. We stored it in the queue.
triggerControlProtocol = true
case connection.UDPReceiverProcessedAck, connection.UDPClientSendAck, connection.UDPData:
conn.SetState(connection.UDPData)
default:
zap.L().Debug("Packet is added to the queue", zap.String("flow", p.L4FlowHash()))
if err = conn.QueuePackets(p); err != nil {
return conn, conn.Context.PuContextError(pucontext.ErrUDPDropQueueFull, fmt.Sprintf("Unable to queue packets:%s", err))
}
return conn, conn.Context.PuContextError(pucontext.ErrUDPDropInNfQueue, "Drop in nfq - buffered")
}
if d.service != nil {
// PostProcessServiceInterface
if !d.service.PostProcessUDPAppPacket(p, nil, conn.Context, conn) {
p.Print(packet.PacketFailureService, d.PacketLogsEnabled())
return conn, conn.Context.PuContextError(pucontext.ErrUDPPostProcessingFailed, "Encryption failed for application packet")
}
}
if triggerControlProtocol {
err = d.triggerNegotiation(p, conn.Context, conn)
if err != nil {
return conn, err
}
return conn, conn.Context.PuContextError(pucontext.ErrUDPDropInNfQueue, "Drop in nfq - buffered")
}
return conn, nil
}
func (d *Datapath) appUDPRetrieveState(p *packet.Packet) (*connection.UDPConnection, error) {
hash := p.L4FlowHash()
if conn, err := d.udpAppReplyConnectionTracker.GetReset(hash, 0); err == nil {
return conn.(*connection.UDPConnection), nil
}
if conn, err := d.udpAppOrigConnectionTracker.GetReset(hash, 0); err == nil {
return conn.(*connection.UDPConnection), nil
}
context, err := d.contextFromIP(true, p.Mark, p.SourcePort(), packet.IPProtocolUDP)
if err != nil {
return nil, pucontext.PuContextError(pucontext.ErrNonPUTraffic, "No context in app processing")
}
return connection.NewUDPConnection(context, d.udpSocketWriter), nil
}
// processApplicationUDPSynPacket processes a single Syn Packet
func (d *Datapath) triggerNegotiation(udpPacket *packet.Packet, context *pucontext.PUContext, conn *connection.UDPConnection) (err error) {
udpOptions := packet.CreateUDPAuthMarker(packet.UDPSynMask)
udpData, err := d.tokenAccessor.CreateSynPacketToken(context, &conn.Auth)
if err != nil {
return err
}
newPacket, err := d.clonePacketHeaders(udpPacket)
if err != nil {
return fmt.Errorf("Unable to clone packet: %s", err)
}
// Attach the UDP data and token
newPacket.UDPTokenAttach(udpOptions, udpData)
// send packet
err = d.writeWithRetransmit(newPacket, conn, conn.SynChannel())
if err != nil {
zap.L().Error("Unable to send syn token on raw socket", zap.Error(err))
return fmt.Errorf("unable to transmit syn packet")
}
// Populate the caches to track the connection
hash := udpPacket.L4FlowHash()
d.udpAppOrigConnectionTracker.AddOrUpdate(hash, conn)
d.udpSourcePortConnectionCache.AddOrUpdate(newPacket.SourcePortHash(packet.PacketTypeApplication), conn)
return nil
}
func (d *Datapath) writeWithRetransmit(udpPacket *packet.Packet, conn *connection.UDPConnection, stop chan bool) error {
buffer := udpPacket.GetBuffer(0)
localBuffer := make([]byte, len(buffer))
copy(localBuffer, buffer)
if err := d.udpSocketWriter.WriteSocket(localBuffer, udpPacket.IPversion()); err != nil {
zap.L().Error("Failed to write control packet to socket", zap.Error(err))
return err
}
go func() {
for retries := 0; retries < retransmitRetries; retries++ {
delay := time.Millisecond * time.Duration((retransmitDelay * (retries + 1)))
select {
case <-stop:
return
case <-time.After(delay):
if err := d.udpSocketWriter.WriteSocket(localBuffer, udpPacket.IPversion()); err != nil {
zap.L().Error("Failed to write control packet to socket", zap.Error(err))
}
}
}
// retransmits did not succeed. Reset the state machine so that
// next packet can try again.
conn.SetState(connection.UDPStart)
}()
return nil
}
func (d *Datapath) clonePacketHeaders(p *packet.Packet) (*packet.Packet, error) {
// copy the ip and udp headers.
newSize := uint16(p.IPHeaderLen() + packet.UDPDataPos)
newPacket := make([]byte, newSize)
p.FixupIPHdrOnDataModify(p.IPTotalLen(), newSize)
origBuffer := p.GetBuffer(0)
_ = copy(newPacket, origBuffer[:newSize])
return packet.New(packet.PacketTypeApplication, newPacket, p.Mark, true)
}
// sendUDPSynAckPacket processes a UDP SynAck packet
func (d *Datapath) sendUDPSynAckPacket(udpPacket *packet.Packet, context *pucontext.PUContext, conn *connection.UDPConnection) (err error) {
// Create UDP Option
udpOptions := packet.CreateUDPAuthMarker(packet.UDPSynAckMask)
udpData, err := d.tokenAccessor.CreateSynAckPacketToken(context, &conn.Auth, claimsheader.NewClaimsHeader())
if err != nil {
return err
}
udpPacket.CreateReverseFlowPacket()
// Attach the UDP data and token
udpPacket.UDPTokenAttach(udpOptions, udpData)
// If we have already a backgroun re-transmit session, stop it at this point. We will
// start from the beginning.
if conn.GetState() == connection.UDPReceiverSendSynAck {
conn.SynAckStop()
}
// Only start the retransmission timer once. Not on every packet.
if err := d.writeWithRetransmit(udpPacket, conn, conn.SynAckChannel()); err != nil {
zap.L().Debug("Unable to send synack token on raw socket", zap.Error(err))
return err
}
return nil
}
func (d *Datapath) sendUDPAckPacket(udpPacket *packet.Packet, context *pucontext.PUContext, conn *connection.UDPConnection) (err error) {
// Create UDP Option
zap.L().Debug("Sending UDP Ack packet", zap.String("flow", udpPacket.L4ReverseFlowHash()))
udpOptions := packet.CreateUDPAuthMarker(packet.UDPAckMask)
udpData, err := d.tokenAccessor.CreateAckPacketToken(context, &conn.Auth)
if err != nil {
return err
}
udpPacket.CreateReverseFlowPacket()
// Attach the UDP data and token
udpPacket.UDPTokenAttach(udpOptions, udpData)
// send packet
err = d.udpSocketWriter.WriteSocket(udpPacket.GetBuffer(0), udpPacket.IPversion())
if err != nil {
zap.L().Debug("Unable to send ack token on raw socket", zap.Error(err))
return err
}
if !conn.ServiceConnection {
zap.L().Debug("Plumbing the conntrack (app) rule for flow", zap.String("flow", udpPacket.L4FlowHash()))
if err = d.conntrack.UpdateApplicationFlowMark(
udpPacket.SourceAddress(),
udpPacket.DestinationAddress(),
udpPacket.IPProto(),
udpPacket.SourcePort(),
udpPacket.DestPort(),
constants.DefaultConnMark,
); err != nil {
zap.L().Error("Failed to update conntrack table for UDP flow at transmitter",
zap.String("context", string(conn.Auth.LocalContext)),
zap.String("app-conn", udpPacket.L4FlowHash()),
zap.String("state", fmt.Sprintf("%d", conn.GetState())),
zap.Error(err),
)
return err
}
}
zap.L().Debug("Clearing fin packet entry in cache", zap.String("flowhash", udpPacket.L4FlowHash()))
if err := d.udpFinPacketTracker.Remove(udpPacket.L4FlowHash()); err != nil {
zap.L().Debug("Unable to remove entry from udp finack cache")
}
return nil
}
// processNetworkUDPSynPacket processes a syn packet arriving from the network
func (d *Datapath) processNetworkUDPSynPacket(context *pucontext.PUContext, conn *connection.UDPConnection, udpPacket *packet.Packet) (action interface{}, claims *tokens.ConnectionClaims, err error) {
claims, err = d.tokenAccessor.ParsePacketToken(&conn.Auth, udpPacket.ReadUDPToken())
if err != nil {
d.reportUDPRejectedFlow(udpPacket, conn, collector.DefaultEndPoint, context.ManagementID(), context, tokens.CodeFromErr(err), nil, nil, false)
return nil, nil, conn.Context.PuContextError(pucontext.ErrSynDroppedInvalidToken, fmt.Sprintf("UDP Syn packet dropped because of invalid token: %s", err))
}
// if there are no claims we must drop the connection and we drop the Syn
// packet. The source will retry but we have no state to maintain here.
if claims == nil {
d.reportUDPRejectedFlow(udpPacket, conn, collector.DefaultEndPoint, context.ManagementID(), context, collector.InvalidToken, nil, nil, false)
return nil, nil, conn.Context.PuContextError(pucontext.ErrUDPSynMissingClaims, "UDP Syn packet dropped because of no claims")
}
// Why is this required. Take a look.
txLabel, _ := claims.T.Get(enforcerconstants.TransmitterLabel)
// Add the port as a label with an @ prefix. These labels are invalid otherwise
// If all policies are restricted by port numbers this will allow port-specific policies
claims.T.AppendKeyValue(constants.PortNumberLabelString, fmt.Sprintf("%s/%s", constants.UDPProtoString, strconv.Itoa(int(udpPacket.DestPort()))))
report, pkt := context.SearchRcvRules(claims.T)
if pkt.Action.Rejected() {
d.reportUDPRejectedFlow(udpPacket, conn, txLabel, context.ManagementID(), context, collector.PolicyDrop, report, pkt, false)
return nil, nil, conn.Context.PuContextError(pucontext.ErrUDPSynDroppedPolicy, fmt.Sprintf("connection rejected because of policy: %s", claims.T.String()))
}
hash := udpPacket.L4FlowHash()
// conntrack
d.udpNetOrigConnectionTracker.AddOrUpdate(hash, conn)
d.udpAppReplyConnectionTracker.AddOrUpdate(udpPacket.L4ReverseFlowHash(), conn)
// Record actions
conn.ReportFlowPolicy = report
conn.PacketFlowPolicy = pkt
return pkt, claims, nil
}
func (d *Datapath) processNetworkUDPSynAckPacket(udpPacket *packet.Packet, context *pucontext.PUContext, conn *connection.UDPConnection) (action interface{}, claims *tokens.ConnectionClaims, err error) {
conn.SynStop()
// Packets that have authorization information go through the auth path
// Decode the JWT token using the context key
claims, err = d.tokenAccessor.ParsePacketToken(&conn.Auth, udpPacket.ReadUDPToken())
if err != nil {
d.reportUDPRejectedFlow(udpPacket, nil, context.ManagementID(), collector.DefaultEndPoint, context, collector.MissingToken, nil, nil, true)
return nil, nil, conn.Context.PuContextError(pucontext.ErrSynAckMissingClaims, "SynAck packet dropped because of bad claims")
}
if claims == nil {
d.reportUDPRejectedFlow(udpPacket, nil, context.ManagementID(), collector.DefaultEndPoint, context, collector.MissingToken, nil, nil, true)
return nil, nil, conn.Context.PuContextError(pucontext.ErrSynAckMissingClaims, fmt.Sprintf("SynAck packet dropped because of no claims"))
}
report, pkt := context.SearchTxtRules(claims.T, !d.mutualAuthorization)
if pkt.Action.Rejected() {
d.reportUDPRejectedFlow(udpPacket, conn, conn.Auth.RemoteContextID, context.ManagementID(), context, collector.PolicyDrop, report, pkt, true)
return nil, nil, conn.Context.PuContextError(pucontext.ErrUDPSynAckPolicy, fmt.Sprintf("dropping because of reject rule on transmitter: %s", claims.T.String()))
}
// conntrack
d.udpNetReplyConnectionTracker.AddOrUpdate(udpPacket.L4FlowHash(), conn)
return pkt, claims, nil
}
func (d *Datapath) processNetworkUDPAckPacket(udpPacket *packet.Packet, context *pucontext.PUContext, conn *connection.UDPConnection) (err error) {
conn.SynAckStop()
_, err = d.tokenAccessor.ParseAckToken(&conn.Auth, udpPacket.ReadUDPToken())
if err != nil {
d.reportUDPRejectedFlow(udpPacket, conn, conn.Auth.RemoteContextID, context.ManagementID(), context, collector.PolicyDrop, conn.ReportFlowPolicy, conn.PacketFlowPolicy, false)
return conn.Context.PuContextError(pucontext.ErrUDPInvalidSignature, fmt.Sprintf("ack packet dropped because signature validation failed: %s", err))
}
if !conn.ServiceConnection {
zap.L().Debug("Plumb conntrack rule for flow:", zap.String("flow", udpPacket.L4FlowHash()))
// Plumb connmark rule here.
if err := d.conntrack.UpdateNetworkFlowMark(
udpPacket.SourceAddress(),
udpPacket.DestinationAddress(),
udpPacket.IPProto(),
udpPacket.SourcePort(),
udpPacket.DestPort(),
constants.DefaultConnMark,
); err != nil {
zap.L().Error("Failed to update conntrack table after ack packet")
}
}
d.reportUDPAcceptedFlow(udpPacket, conn, conn.Auth.RemoteContextID, context.ManagementID(), context, conn.ReportFlowPolicy, conn.PacketFlowPolicy, false)
conn.Context.PuContextError(pucontext.ErrUDPConnectionsProcessed, "") // nolint
return nil
}
// sendUDPFinPacket sends a Fin packet to Peer.
func (d *Datapath) sendUDPFinPacket(udpPacket *packet.Packet) (err error) {
// Create UDP Option
udpOptions := packet.CreateUDPAuthMarker(packet.UDPFinAckMask)
udpPacket.CreateReverseFlowPacket()
// Attach the UDP data and token
udpPacket.UDPTokenAttach(udpOptions, []byte{})
zap.L().Info("Sending udp fin ack packet", zap.String("packet", udpPacket.L4FlowHash()))
// no need for retransmits here.
err = d.udpSocketWriter.WriteSocket(udpPacket.GetBuffer(0), udpPacket.IPversion())
if err != nil {
zap.L().Debug("Unable to send fin packet on raw socket", zap.Error(err))
return pucontext.PuContextError(pucontext.ErrUDPDropFin, "Unable to send fin packet on raw socket"+err.Error())
}
return nil
}
// Update the udp fin cache and delete the connmark.
func (d *Datapath) processUDPFinPacket(udpPacket *packet.Packet) (err error) { // nolint
// add it to the udp fin cache. If we have already received the fin packet
// for this flow. There is no need to change the connmark label again.
if d.udpFinPacketTracker.AddOrUpdate(udpPacket.L4ReverseFlowHash(), true) {
return nil
}
// clear cache entries.
if err := d.udpAppOrigConnectionTracker.Remove(udpPacket.L4ReverseFlowHash()); err != nil {
zap.L().Debug("Failed to clean cache udpappOrigConnectionTracker", zap.Error(err))
}
if err := d.udpSourcePortConnectionCache.Remove(udpPacket.SourcePortHash(packet.PacketTypeNetwork)); err != nil {
zap.L().Debug("Failed to clean cache udpsourcePortConnectionCache", zap.Error(err))
}
zap.L().Debug("Updating the connmark label", zap.String("flow", udpPacket.L4FlowHash()))
if err = d.conntrack.UpdateNetworkFlowMark(
udpPacket.SourceAddress(),
udpPacket.DestinationAddress(),
udpPacket.IPProto(),
udpPacket.SourcePort(),
udpPacket.DestPort(),
constants.DeleteConnmark,
); err != nil {
zap.L().Error("Failed to update conntrack table for flow to terminate connection",
zap.String("app-conn", udpPacket.L4FlowHash()),
zap.Error(err),
)
}
return nil
}