-
Notifications
You must be signed in to change notification settings - Fork 158
/
conn.go
1257 lines (1096 loc) · 34.5 KB
/
conn.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
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package dtls
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/pion/dtls/v3/internal/closer"
"github.com/pion/dtls/v3/pkg/crypto/elliptic"
"github.com/pion/dtls/v3/pkg/crypto/signaturehash"
"github.com/pion/dtls/v3/pkg/protocol"
"github.com/pion/dtls/v3/pkg/protocol/alert"
"github.com/pion/dtls/v3/pkg/protocol/handshake"
"github.com/pion/dtls/v3/pkg/protocol/recordlayer"
"github.com/pion/logging"
"github.com/pion/transport/v3/deadline"
"github.com/pion/transport/v3/netctx"
"github.com/pion/transport/v3/replaydetector"
)
const (
initialTickerInterval = time.Second
cookieLength = 20
sessionLength = 32
defaultNamedCurve = elliptic.X25519
inboundBufferSize = 8192
// Default replay protection window is specified by RFC 6347 Section 4.1.2.6
defaultReplayProtectionWindow = 64
// maxAppDataPacketQueueSize is the maximum number of app data packets we will
// enqueue before the handshake is completed
maxAppDataPacketQueueSize = 100
)
func invalidKeyingLabels() map[string]bool {
return map[string]bool{
"client finished": true,
"server finished": true,
"master secret": true,
"key expansion": true,
}
}
type addrPkt struct {
rAddr net.Addr
data []byte
}
type recvHandshakeState struct {
done chan struct{}
isRetransmit bool
}
// Conn represents a DTLS connection
type Conn struct {
lock sync.RWMutex // Internal lock (must not be public)
nextConn netctx.PacketConn // Embedded Conn, typically a udpconn we read/write from
fragmentBuffer *fragmentBuffer // out-of-order and missing fragment handling
handshakeCache *handshakeCache // caching of handshake messages for verifyData generation
decrypted chan interface{} // Decrypted Application Data or error, pull by calling `Read`
rAddr net.Addr
state State // Internal state
maximumTransmissionUnit int
paddingLengthGenerator func(uint) uint
handshakeCompletedSuccessfully atomic.Value
handshakeMutex sync.Mutex
handshakeDone chan struct{}
encryptedPackets []addrPkt
connectionClosedByUser bool
closeLock sync.Mutex
closed *closer.Closer
readDeadline *deadline.Deadline
writeDeadline *deadline.Deadline
log logging.LeveledLogger
reading chan struct{}
handshakeRecv chan recvHandshakeState
cancelHandshaker func()
cancelHandshakeReader func()
fsm *handshakeFSM
replayProtectionWindow uint
handshakeConfig *handshakeConfig
}
func createConn(nextConn net.PacketConn, rAddr net.Addr, config *Config, isClient bool, resumeState *State) (*Conn, error) {
if err := validateConfig(config); err != nil {
return nil, err
}
if nextConn == nil {
return nil, errNilNextConn
}
loggerFactory := config.LoggerFactory
if loggerFactory == nil {
loggerFactory = logging.NewDefaultLoggerFactory()
}
logger := loggerFactory.NewLogger("dtls")
mtu := config.MTU
if mtu <= 0 {
mtu = defaultMTU
}
replayProtectionWindow := config.ReplayProtectionWindow
if replayProtectionWindow <= 0 {
replayProtectionWindow = defaultReplayProtectionWindow
}
paddingLengthGenerator := config.PaddingLengthGenerator
if paddingLengthGenerator == nil {
paddingLengthGenerator = func(uint) uint { return 0 }
}
cipherSuites, err := parseCipherSuites(config.CipherSuites, config.CustomCipherSuites, config.includeCertificateSuites(), config.PSK != nil)
if err != nil {
return nil, err
}
signatureSchemes, err := signaturehash.ParseSignatureSchemes(config.SignatureSchemes, config.InsecureHashes)
if err != nil {
return nil, err
}
workerInterval := initialTickerInterval
if config.FlightInterval != 0 {
workerInterval = config.FlightInterval
}
serverName := config.ServerName
// Do not allow the use of an IP address literal as an SNI value.
// See RFC 6066, Section 3.
if net.ParseIP(serverName) != nil {
serverName = ""
}
curves := config.EllipticCurves
if len(curves) == 0 {
curves = defaultCurves
}
handshakeConfig := &handshakeConfig{
localPSKCallback: config.PSK,
localPSKIdentityHint: config.PSKIdentityHint,
localCipherSuites: cipherSuites,
localSignatureSchemes: signatureSchemes,
extendedMasterSecret: config.ExtendedMasterSecret,
localSRTPProtectionProfiles: config.SRTPProtectionProfiles,
localSRTPMasterKeyIdentifier: config.SRTPMasterKeyIdentifier,
serverName: serverName,
supportedProtocols: config.SupportedProtocols,
clientAuth: config.ClientAuth,
localCertificates: config.Certificates,
insecureSkipVerify: config.InsecureSkipVerify,
verifyPeerCertificate: config.VerifyPeerCertificate,
verifyConnection: config.VerifyConnection,
rootCAs: config.RootCAs,
clientCAs: config.ClientCAs,
customCipherSuites: config.CustomCipherSuites,
initialRetransmitInterval: workerInterval,
disableRetransmitBackoff: config.DisableRetransmitBackoff,
log: logger,
initialEpoch: 0,
keyLogWriter: config.KeyLogWriter,
sessionStore: config.SessionStore,
ellipticCurves: curves,
localGetCertificate: config.GetCertificate,
localGetClientCertificate: config.GetClientCertificate,
insecureSkipHelloVerify: config.InsecureSkipVerifyHello,
connectionIDGenerator: config.ConnectionIDGenerator,
helloRandomBytesGenerator: config.HelloRandomBytesGenerator,
clientHelloMessageHook: config.ClientHelloMessageHook,
serverHelloMessageHook: config.ServerHelloMessageHook,
certificateRequestMessageHook: config.CertificateRequestMessageHook,
resumeState: resumeState,
}
c := &Conn{
rAddr: rAddr,
nextConn: netctx.NewPacketConn(nextConn),
handshakeConfig: handshakeConfig,
fragmentBuffer: newFragmentBuffer(),
handshakeCache: newHandshakeCache(),
maximumTransmissionUnit: mtu,
paddingLengthGenerator: paddingLengthGenerator,
decrypted: make(chan interface{}, 1),
log: logger,
readDeadline: deadline.New(),
writeDeadline: deadline.New(),
reading: make(chan struct{}, 1),
handshakeRecv: make(chan recvHandshakeState),
closed: closer.NewCloser(),
cancelHandshaker: func() {},
cancelHandshakeReader: func() {},
replayProtectionWindow: uint(replayProtectionWindow),
state: State{
isClient: isClient,
},
}
c.setRemoteEpoch(0)
c.setLocalEpoch(0)
return c, nil
}
// Handshake runs the client or server DTLS handshake
// protocol if it has not yet been run.
//
// Most uses of this package need not call Handshake explicitly: the
// first [Conn.Read] or [Conn.Write] will call it automatically.
//
// For control over canceling or setting a timeout on a handshake, use
// [Conn.HandshakeContext].
func (c *Conn) Handshake() error {
return c.HandshakeContext(context.Background())
}
// HandshakeContext runs the client or server DTLS handshake
// protocol if it has not yet been run.
//
// The provided Context must be non-nil. If the context is canceled before
// the handshake is complete, the handshake is interrupted and an error is returned.
// Once the handshake has completed, cancellation of the context will not affect the
// connection.
//
// Most uses of this package need not call HandshakeContext explicitly: the
// first [Conn.Read] or [Conn.Write] will call it automatically.
func (c *Conn) HandshakeContext(ctx context.Context) error {
c.handshakeMutex.Lock()
defer c.handshakeMutex.Unlock()
if c.isHandshakeCompletedSuccessfully() {
return nil
}
handshakeDone := make(chan struct{})
defer close(handshakeDone)
c.closeLock.Lock()
c.handshakeDone = handshakeDone
c.closeLock.Unlock()
// rfc5246#section-7.4.3
// In addition, the hash and signature algorithms MUST be compatible
// with the key in the server's end-entity certificate.
if !c.state.isClient {
cert, err := c.handshakeConfig.getCertificate(&ClientHelloInfo{})
if err != nil && !errors.Is(err, errNoCertificates) {
return err
}
c.handshakeConfig.localCipherSuites = filterCipherSuitesForCertificate(cert, c.handshakeConfig.localCipherSuites)
}
var initialFlight flightVal
var initialFSMState handshakeState
if c.handshakeConfig.resumeState != nil {
if c.state.isClient {
initialFlight = flight5
} else {
initialFlight = flight6
}
initialFSMState = handshakeFinished
c.state = *c.handshakeConfig.resumeState
} else {
if c.state.isClient {
initialFlight = flight1
} else {
initialFlight = flight0
}
initialFSMState = handshakePreparing
}
// Do handshake
if err := c.handshake(ctx, c.handshakeConfig, initialFlight, initialFSMState); err != nil {
return err
}
c.log.Trace("Handshake Completed")
return nil
}
// Dial connects to the given network address and establishes a DTLS connection on top.
func Dial(network string, rAddr *net.UDPAddr, config *Config) (*Conn, error) {
// net.ListenUDP is used rather than net.DialUDP as the latter prevents the
// use of net.PacketConn.WriteTo.
// https://github.com/golang/go/blob/ce5e37ec21442c6eb13a43e68ca20129102ebac0/src/net/udpsock_posix.go#L115
pConn, err := net.ListenUDP(network, nil)
if err != nil {
return nil, err
}
return Client(pConn, rAddr, config)
}
// Client establishes a DTLS connection over an existing connection.
func Client(conn net.PacketConn, rAddr net.Addr, config *Config) (*Conn, error) {
switch {
case config == nil:
return nil, errNoConfigProvided
case config.PSK != nil && config.PSKIdentityHint == nil:
return nil, errPSKAndIdentityMustBeSetForClient
}
return createConn(conn, rAddr, config, true, nil)
}
// Server listens for incoming DTLS connections.
func Server(conn net.PacketConn, rAddr net.Addr, config *Config) (*Conn, error) {
if config == nil {
return nil, errNoConfigProvided
}
if config.OnConnectionAttempt != nil {
if err := config.OnConnectionAttempt(rAddr); err != nil {
return nil, err
}
}
return createConn(conn, rAddr, config, false, nil)
}
// Read reads data from the connection.
func (c *Conn) Read(p []byte) (n int, err error) {
if err := c.Handshake(); err != nil {
return 0, err
}
select {
case <-c.readDeadline.Done():
return 0, errDeadlineExceeded
default:
}
for {
select {
case <-c.readDeadline.Done():
return 0, errDeadlineExceeded
case out, ok := <-c.decrypted:
if !ok {
return 0, io.EOF
}
switch val := out.(type) {
case ([]byte):
if len(p) < len(val) {
return 0, errBufferTooSmall
}
copy(p, val)
return len(val), nil
case (error):
return 0, val
}
}
}
}
// Write writes len(p) bytes from p to the DTLS connection
func (c *Conn) Write(p []byte) (int, error) {
if c.isConnectionClosed() {
return 0, ErrConnClosed
}
select {
case <-c.writeDeadline.Done():
return 0, errDeadlineExceeded
default:
}
if err := c.Handshake(); err != nil {
return 0, err
}
return len(p), c.writePackets(c.writeDeadline, []*packet{
{
record: &recordlayer.RecordLayer{
Header: recordlayer.Header{
Epoch: c.state.getLocalEpoch(),
Version: protocol.Version1_2,
},
Content: &protocol.ApplicationData{
Data: p,
},
},
shouldWrapCID: len(c.state.remoteConnectionID) > 0,
shouldEncrypt: true,
},
})
}
// Close closes the connection.
func (c *Conn) Close() error {
err := c.close(true) //nolint:contextcheck
c.closeLock.Lock()
handshakeDone := c.handshakeDone
c.closeLock.Unlock()
if handshakeDone != nil {
<-handshakeDone
}
return err
}
// ConnectionState returns basic DTLS details about the connection.
// Note that this replaced the `Export` function of v1.
func (c *Conn) ConnectionState() (State, bool) {
c.lock.RLock()
defer c.lock.RUnlock()
stateClone, err := c.state.clone()
if err != nil {
return State{}, false
}
return *stateClone, true
}
// SelectedSRTPProtectionProfile returns the selected SRTPProtectionProfile
func (c *Conn) SelectedSRTPProtectionProfile() (SRTPProtectionProfile, bool) {
profile := c.state.getSRTPProtectionProfile()
if profile == 0 {
return 0, false
}
return profile, true
}
// RemoteSRTPMasterKeyIdentifier returns the MasterKeyIdentifier value from the use_srtp
func (c *Conn) RemoteSRTPMasterKeyIdentifier() ([]byte, bool) {
if profile := c.state.getSRTPProtectionProfile(); profile == 0 {
return nil, false
}
return c.state.remoteSRTPMasterKeyIdentifier, true
}
func (c *Conn) writePackets(ctx context.Context, pkts []*packet) error {
c.lock.Lock()
defer c.lock.Unlock()
var rawPackets [][]byte
for _, p := range pkts {
if h, ok := p.record.Content.(*handshake.Handshake); ok {
handshakeRaw, err := p.record.Marshal()
if err != nil {
return err
}
c.log.Tracef("[handshake:%v] -> %s (epoch: %d, seq: %d)",
srvCliStr(c.state.isClient), h.Header.Type.String(),
p.record.Header.Epoch, h.Header.MessageSequence)
c.handshakeCache.push(handshakeRaw[recordlayer.FixedHeaderSize:], p.record.Header.Epoch, h.Header.MessageSequence, h.Header.Type, c.state.isClient)
rawHandshakePackets, err := c.processHandshakePacket(p, h)
if err != nil {
return err
}
rawPackets = append(rawPackets, rawHandshakePackets...)
} else {
rawPacket, err := c.processPacket(p)
if err != nil {
return err
}
rawPackets = append(rawPackets, rawPacket)
}
}
if len(rawPackets) == 0 {
return nil
}
compactedRawPackets := c.compactRawPackets(rawPackets)
for _, compactedRawPackets := range compactedRawPackets {
if _, err := c.nextConn.WriteToContext(ctx, compactedRawPackets, c.rAddr); err != nil {
return netError(err)
}
}
return nil
}
func (c *Conn) compactRawPackets(rawPackets [][]byte) [][]byte {
// avoid a useless copy in the common case
if len(rawPackets) == 1 {
return rawPackets
}
combinedRawPackets := make([][]byte, 0)
currentCombinedRawPacket := make([]byte, 0)
for _, rawPacket := range rawPackets {
if len(currentCombinedRawPacket) > 0 && len(currentCombinedRawPacket)+len(rawPacket) >= c.maximumTransmissionUnit {
combinedRawPackets = append(combinedRawPackets, currentCombinedRawPacket)
currentCombinedRawPacket = []byte{}
}
currentCombinedRawPacket = append(currentCombinedRawPacket, rawPacket...)
}
combinedRawPackets = append(combinedRawPackets, currentCombinedRawPacket)
return combinedRawPackets
}
func (c *Conn) processPacket(p *packet) ([]byte, error) {
epoch := p.record.Header.Epoch
for len(c.state.localSequenceNumber) <= int(epoch) {
c.state.localSequenceNumber = append(c.state.localSequenceNumber, uint64(0))
}
seq := atomic.AddUint64(&c.state.localSequenceNumber[epoch], 1) - 1
if seq > recordlayer.MaxSequenceNumber {
// RFC 6347 Section 4.1.0
// The implementation must either abandon an association or rehandshake
// prior to allowing the sequence number to wrap.
return nil, errSequenceNumberOverflow
}
p.record.Header.SequenceNumber = seq
var rawPacket []byte
if p.shouldWrapCID {
// Record must be marshaled to populate fields used in inner plaintext.
if _, err := p.record.Marshal(); err != nil {
return nil, err
}
content, err := p.record.Content.Marshal()
if err != nil {
return nil, err
}
inner := &recordlayer.InnerPlaintext{
Content: content,
RealType: p.record.Header.ContentType,
}
rawInner, err := inner.Marshal() //nolint:govet
if err != nil {
return nil, err
}
cidHeader := &recordlayer.Header{
Version: p.record.Header.Version,
ContentType: protocol.ContentTypeConnectionID,
Epoch: p.record.Header.Epoch,
ContentLen: uint16(len(rawInner)),
ConnectionID: c.state.remoteConnectionID,
SequenceNumber: p.record.Header.SequenceNumber,
}
rawPacket, err = cidHeader.Marshal()
if err != nil {
return nil, err
}
p.record.Header = *cidHeader
rawPacket = append(rawPacket, rawInner...)
} else {
var err error
rawPacket, err = p.record.Marshal()
if err != nil {
return nil, err
}
}
if p.shouldEncrypt {
var err error
rawPacket, err = c.state.cipherSuite.Encrypt(p.record, rawPacket)
if err != nil {
return nil, err
}
}
return rawPacket, nil
}
func (c *Conn) processHandshakePacket(p *packet, h *handshake.Handshake) ([][]byte, error) {
rawPackets := make([][]byte, 0)
handshakeFragments, err := c.fragmentHandshake(h)
if err != nil {
return nil, err
}
epoch := p.record.Header.Epoch
for len(c.state.localSequenceNumber) <= int(epoch) {
c.state.localSequenceNumber = append(c.state.localSequenceNumber, uint64(0))
}
for _, handshakeFragment := range handshakeFragments {
seq := atomic.AddUint64(&c.state.localSequenceNumber[epoch], 1) - 1
if seq > recordlayer.MaxSequenceNumber {
return nil, errSequenceNumberOverflow
}
var rawPacket []byte
if p.shouldWrapCID {
inner := &recordlayer.InnerPlaintext{
Content: handshakeFragment,
RealType: protocol.ContentTypeHandshake,
Zeros: c.paddingLengthGenerator(uint(len(handshakeFragment))),
}
rawInner, err := inner.Marshal() //nolint:govet
if err != nil {
return nil, err
}
cidHeader := &recordlayer.Header{
Version: p.record.Header.Version,
ContentType: protocol.ContentTypeConnectionID,
Epoch: p.record.Header.Epoch,
ContentLen: uint16(len(rawInner)),
ConnectionID: c.state.remoteConnectionID,
SequenceNumber: p.record.Header.SequenceNumber,
}
rawPacket, err = cidHeader.Marshal()
if err != nil {
return nil, err
}
p.record.Header = *cidHeader
rawPacket = append(rawPacket, rawInner...)
} else {
recordlayerHeader := &recordlayer.Header{
Version: p.record.Header.Version,
ContentType: p.record.Header.ContentType,
ContentLen: uint16(len(handshakeFragment)),
Epoch: p.record.Header.Epoch,
SequenceNumber: seq,
}
rawPacket, err = recordlayerHeader.Marshal()
if err != nil {
return nil, err
}
p.record.Header = *recordlayerHeader
rawPacket = append(rawPacket, handshakeFragment...)
}
if p.shouldEncrypt {
var err error
rawPacket, err = c.state.cipherSuite.Encrypt(p.record, rawPacket)
if err != nil {
return nil, err
}
}
rawPackets = append(rawPackets, rawPacket)
}
return rawPackets, nil
}
func (c *Conn) fragmentHandshake(h *handshake.Handshake) ([][]byte, error) {
content, err := h.Message.Marshal()
if err != nil {
return nil, err
}
fragmentedHandshakes := make([][]byte, 0)
contentFragments := splitBytes(content, c.maximumTransmissionUnit)
if len(contentFragments) == 0 {
contentFragments = [][]byte{
{},
}
}
offset := 0
for _, contentFragment := range contentFragments {
contentFragmentLen := len(contentFragment)
headerFragment := &handshake.Header{
Type: h.Header.Type,
Length: h.Header.Length,
MessageSequence: h.Header.MessageSequence,
FragmentOffset: uint32(offset),
FragmentLength: uint32(contentFragmentLen),
}
offset += contentFragmentLen
fragmentedHandshake, err := headerFragment.Marshal()
if err != nil {
return nil, err
}
fragmentedHandshake = append(fragmentedHandshake, contentFragment...)
fragmentedHandshakes = append(fragmentedHandshakes, fragmentedHandshake)
}
return fragmentedHandshakes, nil
}
var poolReadBuffer = sync.Pool{ //nolint:gochecknoglobals
New: func() interface{} {
b := make([]byte, inboundBufferSize)
return &b
},
}
func (c *Conn) readAndBuffer(ctx context.Context) error {
bufptr, ok := poolReadBuffer.Get().(*[]byte)
if !ok {
return errFailedToAccessPoolReadBuffer
}
defer poolReadBuffer.Put(bufptr)
b := *bufptr
i, rAddr, err := c.nextConn.ReadFromContext(ctx, b)
if err != nil {
return netError(err)
}
pkts, err := recordlayer.ContentAwareUnpackDatagram(b[:i], len(c.state.getLocalConnectionID()))
if err != nil {
return err
}
var hasHandshake, isRetransmit bool
for _, p := range pkts {
hs, rtx, alert, err := c.handleIncomingPacket(ctx, p, rAddr, true)
if alert != nil {
if alertErr := c.notify(ctx, alert.Level, alert.Description); alertErr != nil {
if err == nil {
err = alertErr
}
}
}
var e *alertError
if errors.As(err, &e) && e.IsFatalOrCloseNotify() {
return e
}
if err != nil {
return err
}
if hs {
hasHandshake = true
}
if rtx {
isRetransmit = true
}
}
if hasHandshake {
s := recvHandshakeState{
done: make(chan struct{}),
isRetransmit: isRetransmit,
}
select {
case c.handshakeRecv <- s:
// If the other party may retransmit the flight,
// we should respond even if it not a new message.
<-s.done
case <-c.fsm.Done():
}
}
return nil
}
func (c *Conn) handleQueuedPackets(ctx context.Context) error {
pkts := c.encryptedPackets
c.encryptedPackets = nil
for _, p := range pkts {
_, _, alert, err := c.handleIncomingPacket(ctx, p.data, p.rAddr, false) // don't re-enqueue
if alert != nil {
if alertErr := c.notify(ctx, alert.Level, alert.Description); alertErr != nil {
if err == nil {
err = alertErr
}
}
}
var e *alertError
if errors.As(err, &e) && e.IsFatalOrCloseNotify() {
return e
}
if err != nil {
return err
}
}
return nil
}
func (c *Conn) enqueueEncryptedPackets(packet addrPkt) bool {
if len(c.encryptedPackets) < maxAppDataPacketQueueSize {
c.encryptedPackets = append(c.encryptedPackets, packet)
return true
}
return false
}
func (c *Conn) handleIncomingPacket(ctx context.Context, buf []byte, rAddr net.Addr, enqueue bool) (bool, bool, *alert.Alert, error) { //nolint:gocognit
h := &recordlayer.Header{}
// Set connection ID size so that records of content type tls12_cid will
// be parsed correctly.
if len(c.state.getLocalConnectionID()) > 0 {
h.ConnectionID = make([]byte, len(c.state.getLocalConnectionID()))
}
if err := h.Unmarshal(buf); err != nil {
// Decode error must be silently discarded
// [RFC6347 Section-4.1.2.7]
c.log.Debugf("discarded broken packet: %v", err)
return false, false, nil, nil
}
// Validate epoch
remoteEpoch := c.state.getRemoteEpoch()
if h.Epoch > remoteEpoch {
if h.Epoch > remoteEpoch+1 {
c.log.Debugf("discarded future packet (epoch: %d, seq: %d)",
h.Epoch, h.SequenceNumber,
)
return false, false, nil, nil
}
if enqueue {
if ok := c.enqueueEncryptedPackets(addrPkt{rAddr, buf}); ok {
c.log.Debug("received packet of next epoch, queuing packet")
}
}
return false, false, nil, nil
}
// Anti-replay protection
for len(c.state.replayDetector) <= int(h.Epoch) {
c.state.replayDetector = append(c.state.replayDetector,
replaydetector.New(c.replayProtectionWindow, recordlayer.MaxSequenceNumber),
)
}
markPacketAsValid, ok := c.state.replayDetector[int(h.Epoch)].Check(h.SequenceNumber)
if !ok {
c.log.Debugf("discarded duplicated packet (epoch: %d, seq: %d)",
h.Epoch, h.SequenceNumber,
)
return false, false, nil, nil
}
// originalCID indicates whether the original record had content type
// Connection ID.
originalCID := false
// Decrypt
if h.Epoch != 0 {
if c.state.cipherSuite == nil || !c.state.cipherSuite.IsInitialized() {
if enqueue {
if ok := c.enqueueEncryptedPackets(addrPkt{rAddr, buf}); ok {
c.log.Debug("handshake not finished, queuing packet")
}
}
return false, false, nil, nil
}
// If a connection identifier had been negotiated and encryption is
// enabled, the connection identifier MUST be sent.
if len(c.state.getLocalConnectionID()) > 0 && h.ContentType != protocol.ContentTypeConnectionID {
c.log.Debug("discarded packet missing connection ID after value negotiated")
return false, false, nil, nil
}
var err error
var hdr recordlayer.Header
if h.ContentType == protocol.ContentTypeConnectionID {
hdr.ConnectionID = make([]byte, len(c.state.getLocalConnectionID()))
}
buf, err = c.state.cipherSuite.Decrypt(hdr, buf)
if err != nil {
c.log.Debugf("%s: decrypt failed: %s", srvCliStr(c.state.isClient), err)
return false, false, nil, nil
}
// If this is a connection ID record, make it look like a normal record for
// further processing.
if h.ContentType == protocol.ContentTypeConnectionID {
originalCID = true
ip := &recordlayer.InnerPlaintext{}
if err := ip.Unmarshal(buf[h.Size():]); err != nil { //nolint:govet
c.log.Debugf("unpacking inner plaintext failed: %s", err)
return false, false, nil, nil
}
unpacked := &recordlayer.Header{
ContentType: ip.RealType,
ContentLen: uint16(len(ip.Content)),
Version: h.Version,
Epoch: h.Epoch,
SequenceNumber: h.SequenceNumber,
}
buf, err = unpacked.Marshal()
if err != nil {
c.log.Debugf("converting CID record to inner plaintext failed: %s", err)
return false, false, nil, nil
}
buf = append(buf, ip.Content...)
}
// If connection ID does not match discard the packet.
if !bytes.Equal(c.state.getLocalConnectionID(), h.ConnectionID) {
c.log.Debug("unexpected connection ID")
return false, false, nil, nil
}
}
isHandshake, isRetransmit, err := c.fragmentBuffer.push(append([]byte{}, buf...))
if err != nil {
// Decode error must be silently discarded
// [RFC6347 Section-4.1.2.7]
c.log.Debugf("defragment failed: %s", err)
return false, false, nil, nil
} else if isHandshake {
markPacketAsValid()
for out, epoch := c.fragmentBuffer.pop(); out != nil; out, epoch = c.fragmentBuffer.pop() {
header := &handshake.Header{}
if err := header.Unmarshal(out); err != nil {
c.log.Debugf("%s: handshake parse failed: %s", srvCliStr(c.state.isClient), err)
continue
}
c.handshakeCache.push(out, epoch, header.MessageSequence, header.Type, !c.state.isClient)
}
return true, isRetransmit, nil, nil
}
r := &recordlayer.RecordLayer{}
if err := r.Unmarshal(buf); err != nil {
return false, false, &alert.Alert{Level: alert.Fatal, Description: alert.DecodeError}, err
}
isLatestSeqNum := false
switch content := r.Content.(type) {
case *alert.Alert:
c.log.Tracef("%s: <- %s", srvCliStr(c.state.isClient), content.String())
var a *alert.Alert
if content.Description == alert.CloseNotify {
// Respond with a close_notify [RFC5246 Section 7.2.1]
a = &alert.Alert{Level: alert.Warning, Description: alert.CloseNotify}
}
_ = markPacketAsValid()
return false, false, a, &alertError{content}
case *protocol.ChangeCipherSpec:
if c.state.cipherSuite == nil || !c.state.cipherSuite.IsInitialized() {
if enqueue {
if ok := c.enqueueEncryptedPackets(addrPkt{rAddr, buf}); ok {
c.log.Debugf("CipherSuite not initialized, queuing packet")
}
}
return false, false, nil, nil
}
newRemoteEpoch := h.Epoch + 1
c.log.Tracef("%s: <- ChangeCipherSpec (epoch: %d)", srvCliStr(c.state.isClient), newRemoteEpoch)
if c.state.getRemoteEpoch()+1 == newRemoteEpoch {
c.setRemoteEpoch(newRemoteEpoch)
isLatestSeqNum = markPacketAsValid()
}
case *protocol.ApplicationData:
if h.Epoch == 0 {
return false, false, &alert.Alert{Level: alert.Fatal, Description: alert.UnexpectedMessage}, errApplicationDataEpochZero
}
isLatestSeqNum = markPacketAsValid()
select {
case c.decrypted <- content.Data:
case <-c.closed.Done():
case <-ctx.Done():
}
default:
return false, false, &alert.Alert{Level: alert.Fatal, Description: alert.UnexpectedMessage}, fmt.Errorf("%w: %d", errUnhandledContextType, content.ContentType())
}
// Any valid connection ID record is a candidate for updating the remote
// address if it is the latest record received.
// https://datatracker.ietf.org/doc/html/rfc9146#peer-address-update
if originalCID && isLatestSeqNum {
if rAddr != c.RemoteAddr() {
c.lock.Lock()
c.rAddr = rAddr
c.lock.Unlock()
}
}
return false, false, nil, nil
}
func (c *Conn) recvHandshake() <-chan recvHandshakeState {
return c.handshakeRecv
}
func (c *Conn) notify(ctx context.Context, level alert.Level, desc alert.Description) error {
if level == alert.Fatal && len(c.state.SessionID) > 0 {
// According to the RFC, we need to delete the stored session.
// https://datatracker.ietf.org/doc/html/rfc5246#section-7.2