-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetcode_test.go
More file actions
1318 lines (950 loc) · 36.7 KB
/
Copy pathnetcode_test.go
File metadata and controls
1318 lines (950 loc) · 36.7 KB
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
package netcode
import (
"bytes"
"errors"
"testing"
"time"
)
// This test suite is a port of the test suite in the C reference implementation.
const (
testProtocolID = 0x1122334455667788
testClientID = 0x1
testServerPort = 40000
testConnectTokenExpiry = 30
testTimeoutSeconds = 15
)
var testPrivateKey = [KeyBytes]byte{
0x60, 0x6a, 0xbe, 0x6e, 0xc9, 0x19, 0x10, 0xea,
0x9a, 0x65, 0x62, 0xf6, 0x6f, 0x2b, 0x30, 0xe4,
0x43, 0x71, 0xd6, 0x2c, 0xd1, 0x99, 0x27, 0x26,
0x6b, 0x3c, 0x60, 0xf4, 0xb7, 0x15, 0xab, 0xa1,
}
func check(t *testing.T, condition bool) {
t.Helper()
if !condition {
t.Fatal("check failed")
}
}
func TestQueue(t *testing.T) {
var queue packetQueue
check(t, queue.numPackets == 0)
check(t, queue.startIndex == 0)
// attempting to pop a packet off an empty queue should return nil
popped, _ := queue.pop()
check(t, popped == nil)
// add some packets to the queue and make sure they pop off in the correct order
{
const numPackets = 100
var packets [numPackets]*connectionPayload
for i := 0; i < numPackets; i++ {
packets[i] = &connectionPayload{payloadData: make([]byte, (i+1)*256)}
check(t, queue.push(packets[i], uint64(i)))
}
check(t, queue.numPackets == numPackets)
for i := 0; i < numPackets; i++ {
packet, sequence := queue.pop()
check(t, sequence == uint64(i))
check(t, packet == packets[i])
}
}
// after all entries are popped off, the queue is empty, so calls to pop should return nil
check(t, queue.numPackets == 0)
popped, _ = queue.pop()
check(t, popped == nil)
// test that the packet queue can be filled to max capacity
var packets [packetQueueSize]*connectionPayload
for i := 0; i < packetQueueSize; i++ {
packets[i] = &connectionPayload{}
check(t, queue.push(packets[i], uint64(i)))
}
check(t, queue.numPackets == packetQueueSize)
// when the queue is full, attempting to push a packet should fail
check(t, !queue.push(&connectionPayload{}, 0))
// make sure all packets pop off in the correct order
for i := 0; i < packetQueueSize; i++ {
packet, sequence := queue.pop()
check(t, sequence == uint64(i))
check(t, packet == packets[i])
}
// add some packets again
for i := 0; i < packetQueueSize; i++ {
check(t, queue.push(packets[i], uint64(i)))
}
// clear the queue and make sure that all packets are freed
queue.clear()
check(t, queue.startIndex == 0)
check(t, queue.numPackets == 0)
for i := 0; i < packetQueueSize; i++ {
check(t, queue.packets[i] == nil)
}
}
func TestSequence(t *testing.T) {
check(t, sequenceNumberBytesRequired(0) == 1)
check(t, sequenceNumberBytesRequired(0x11) == 1)
check(t, sequenceNumberBytesRequired(0x1122) == 2)
check(t, sequenceNumberBytesRequired(0x112233) == 3)
check(t, sequenceNumberBytesRequired(0x11223344) == 4)
check(t, sequenceNumberBytesRequired(0x1122334455) == 5)
check(t, sequenceNumberBytesRequired(0x112233445566) == 6)
check(t, sequenceNumberBytesRequired(0x11223344556677) == 7)
check(t, sequenceNumberBytesRequired(0x1122334455667788) == 8)
}
func TestAddress(t *testing.T) {
{
badAddresses := []string{
"",
"[",
"[]",
"[]:",
":",
"1",
"12",
"123",
"1234",
"1234.0.12313.0000",
"1234.0.12313.0000.0.0.0.0.0",
"1312313:123131:1312313:123131:1312313:123131:1312313:123131:1312313:123131:1312313:123131",
".",
"..",
"...",
"....",
".....",
}
for _, s := range badAddresses {
if _, err := ParseAddress(s); err == nil {
t.Fatalf("expected parse error for %q", s)
}
}
}
// ports must be all digits in [0,65535]. out of range and non-numeric ports must not silently truncate
{
address, err := ParseAddress("127.0.0.1:65535")
check(t, err == nil)
check(t, address.Type == AddressIPv4)
check(t, address.Port == 65535)
address, err = ParseAddress("[::1]:65535")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 65535)
badPorts := []string{
"127.0.0.1:65536",
"127.0.0.1:99999",
"127.0.0.1:",
"127.0.0.1:40k",
"[::1]:65536",
"[::1]:",
"[::1]:40k",
}
for _, s := range badPorts {
if _, err := ParseAddress(s); err == nil {
t.Fatalf("expected parse error for %q", s)
}
}
}
{
address, err := ParseAddress("107.77.207.77")
check(t, err == nil)
check(t, address.Type == AddressIPv4)
check(t, address.Port == 0)
check(t, address.IPv4 == [4]byte{107, 77, 207, 77})
}
{
address, err := ParseAddress("127.0.0.1")
check(t, err == nil)
check(t, address.Type == AddressIPv4)
check(t, address.Port == 0)
check(t, address.IPv4 == [4]byte{127, 0, 0, 1})
}
{
address, err := ParseAddress("107.77.207.77:40000")
check(t, err == nil)
check(t, address.Type == AddressIPv4)
check(t, address.Port == 40000)
check(t, address.IPv4 == [4]byte{107, 77, 207, 77})
}
{
address, err := ParseAddress("127.0.0.1:40000")
check(t, err == nil)
check(t, address.Type == AddressIPv4)
check(t, address.Port == 40000)
check(t, address.IPv4 == [4]byte{127, 0, 0, 1})
}
{
address, err := ParseAddress("fe80::202:b3ff:fe1e:8329")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 0)
check(t, address.IPv6 == [8]uint16{0xfe80, 0, 0, 0, 0x0202, 0xb3ff, 0xfe1e, 0x8329})
}
{
address, err := ParseAddress("::")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 0)
check(t, address.IPv6 == [8]uint16{})
}
{
address, err := ParseAddress("::1")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 0)
check(t, address.IPv6 == [8]uint16{0, 0, 0, 0, 0, 0, 0, 1})
}
{
address, err := ParseAddress("::0")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 0)
check(t, address.IPv6 == [8]uint16{})
}
{
address, err := ParseAddress("[::1]")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 0)
check(t, address.IPv6 == [8]uint16{0, 0, 0, 0, 0, 0, 0, 1})
}
{
address, err := ParseAddress("[::0]")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 0)
check(t, address.IPv6 == [8]uint16{})
}
{
address, err := ParseAddress("[fe80::1]")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 0)
check(t, address.IPv6 == [8]uint16{0xfe80, 0, 0, 0, 0, 0, 0, 1})
}
{
address, err := ParseAddress("[fe80::202:b3ff:fe1e:8329]:40000")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 40000)
check(t, address.IPv6 == [8]uint16{0xfe80, 0, 0, 0, 0x0202, 0xb3ff, 0xfe1e, 0x8329})
}
{
address, err := ParseAddress("[::]:40000")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 40000)
check(t, address.IPv6 == [8]uint16{})
}
{
address, err := ParseAddress("[::1]:5")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 5)
check(t, address.IPv6 == [8]uint16{0, 0, 0, 0, 0, 0, 0, 1})
}
{
address, err := ParseAddress("[fe80::1]:5")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 5)
check(t, address.IPv6 == [8]uint16{0xfe80, 0, 0, 0, 0, 0, 0, 1})
}
{
address, err := ParseAddress("[::1]:40000")
check(t, err == nil)
check(t, address.Type == AddressIPv6)
check(t, address.Port == 40000)
check(t, address.IPv6 == [8]uint16{0, 0, 0, 0, 0, 0, 0, 1})
}
// addresses format back to strings that parse to the same address
{
roundTrips := []string{
"107.77.207.77",
"127.0.0.1:40000",
"[::1]:40000",
"fe80::202:b3ff:fe1e:8329",
}
for _, s := range roundTrips {
address, err := ParseAddress(s)
check(t, err == nil)
parsed, err := ParseAddress(address.String())
check(t, err == nil)
check(t, address.Equal(parsed))
}
check(t, Address{}.String() == "NONE")
}
// addresses of type none are never equal to anything, including each other
{
var a, b Address
check(t, !a.Equal(b))
}
}
func testServerAddress() Address {
return Address{
Type: AddressIPv4,
IPv4: [4]byte{127, 0, 0, 1},
Port: testServerPort,
}
}
func TestConnectToken(t *testing.T) {
// generate a connect token
serverAddress := testServerAddress()
userData := make([]byte, UserDataBytes)
RandomBytes(userData)
inputToken := generateConnectTokenPrivate(testClientID, testTimeoutSeconds, []Address{serverAddress}, userData)
check(t, inputToken.clientID == testClientID)
check(t, inputToken.numServerAddresses == 1)
check(t, bytes.Equal(inputToken.userData[:], userData))
check(t, inputToken.serverAddresses[0].Equal(serverAddress))
// write it to a buffer
var buffer [connectTokenPrivateBytes]byte
inputToken.write(buffer[:])
// encrypt the buffer
expireTimestamp := uint64(time.Now().Unix()) + 30
nonce := generateNonce()
key := GenerateKey()
check(t, encryptConnectTokenPrivate(buffer[:], testProtocolID, expireTimestamp, nonce[:], key) == nil)
// decrypt the buffer
check(t, decryptConnectTokenPrivate(buffer[:], testProtocolID, expireTimestamp, nonce[:], key) == nil)
// read the connect token back in
var outputToken connectTokenPrivate
check(t, outputToken.read(buffer[:]) == nil)
// make sure that everything matches the original connect token
check(t, outputToken.clientID == inputToken.clientID)
check(t, outputToken.timeoutSeconds == inputToken.timeoutSeconds)
check(t, outputToken.numServerAddresses == inputToken.numServerAddresses)
check(t, outputToken.serverAddresses[0].Equal(inputToken.serverAddresses[0]))
check(t, outputToken.clientToServerKey == inputToken.clientToServerKey)
check(t, outputToken.serverToClientKey == inputToken.serverToClientKey)
check(t, outputToken.userData == inputToken.userData)
}
func TestChallengeToken(t *testing.T) {
// generate a challenge token
var inputToken challengeToken
inputToken.clientID = testClientID
RandomBytes(inputToken.userData[:])
// write it to a buffer
var buffer [challengeTokenBytes]byte
inputToken.write(buffer[:])
// encrypt the buffer
sequence := uint64(1000)
key := GenerateKey()
check(t, encryptChallengeToken(buffer[:], sequence, key) == nil)
// decrypt the buffer
check(t, decryptChallengeToken(buffer[:], sequence, key) == nil)
// read the challenge token back in
var outputToken challengeToken
check(t, outputToken.read(buffer[:]) == nil)
// make sure that everything matches the original challenge token
check(t, outputToken.clientID == inputToken.clientID)
check(t, outputToken.userData == inputToken.userData)
}
func allPacketsAllowed() [connectionNumPackets]bool {
var allowed [connectionNumPackets]bool
for i := range allowed {
allowed[i] = true
}
return allowed
}
func TestConnectionRequestPacket(t *testing.T) {
// generate a connect token
serverAddress := testServerAddress()
userData := make([]byte, UserDataBytes)
RandomBytes(userData)
inputToken := generateConnectTokenPrivate(testClientID, testTimeoutSeconds, []Address{serverAddress}, userData)
check(t, inputToken.clientID == testClientID)
check(t, inputToken.numServerAddresses == 1)
check(t, bytes.Equal(inputToken.userData[:], userData))
check(t, inputToken.serverAddresses[0].Equal(serverAddress))
// write the connect token to a buffer (non-encrypted)
var connectTokenData [connectTokenPrivateBytes]byte
inputToken.write(connectTokenData[:])
// copy to a second buffer then encrypt it in place (we need the unencrypted token for verification later on)
encryptedConnectTokenData := connectTokenData
connectTokenExpireTimestamp := uint64(time.Now().Unix()) + 30
connectTokenNonce := generateNonce()
connectTokenKey := GenerateKey()
check(t, encryptConnectTokenPrivate(encryptedConnectTokenData[:], testProtocolID, connectTokenExpireTimestamp, connectTokenNonce[:], connectTokenKey) == nil)
// setup a connection request packet wrapping the encrypted connect token
inputPacket := &connectionRequest{
versionInfo: versionInfo,
protocolID: testProtocolID,
connectTokenExpireTimestamp: connectTokenExpireTimestamp,
connectTokenNonce: connectTokenNonce,
connectTokenData: encryptedConnectTokenData,
}
// write the connection request packet to a buffer
var buffer [2048]byte
packetKey := GenerateKey()
bytesWritten := writePacket(inputPacket, buffer[:], 1000, packetKey, testProtocolID)
check(t, bytesWritten > 0)
// read the connection request packet back in from the buffer (the connect token data is decrypted as part of the read packet validation)
var sequence uint64
allowedPackets := allPacketsAllowed()
outputPacket, ok := readPacket(buffer[:bytesWritten], &sequence, packetKey, testProtocolID, uint64(time.Now().Unix()), connectTokenKey, &allowedPackets, nil).(*connectionRequest)
check(t, ok)
// make sure the read packet matches what was written
check(t, outputPacket.versionInfo == inputPacket.versionInfo)
check(t, outputPacket.protocolID == inputPacket.protocolID)
check(t, outputPacket.connectTokenExpireTimestamp == inputPacket.connectTokenExpireTimestamp)
check(t, outputPacket.connectTokenNonce == inputPacket.connectTokenNonce)
check(t, bytes.Equal(outputPacket.connectTokenData[:connectTokenPrivateBytes-MacBytes], connectTokenData[:connectTokenPrivateBytes-MacBytes]))
}
func TestConnectionDeniedPacket(t *testing.T) {
// setup a connection denied packet
inputPacket := &connectionDenied{}
// write the packet to a buffer
var buffer [maxPacketBytes]byte
packetKey := GenerateKey()
bytesWritten := writePacket(inputPacket, buffer[:], 1000, packetKey, testProtocolID)
check(t, bytesWritten > 0)
// read the packet back in from the buffer
var sequence uint64
allowedPackets := allPacketsAllowed()
outputPacket, ok := readPacket(buffer[:bytesWritten], &sequence, packetKey, testProtocolID, uint64(time.Now().Unix()), nil, &allowedPackets, nil).(*connectionDenied)
check(t, ok)
check(t, outputPacket != nil)
check(t, sequence == 1000)
}
func TestConnectionChallengePacket(t *testing.T) {
// setup a connection challenge packet
inputPacket := &connectionChallenge{}
inputPacket.challengeTokenSequence = 0
RandomBytes(inputPacket.challengeTokenData[:])
// write the packet to a buffer
var buffer [maxPacketBytes]byte
packetKey := GenerateKey()
bytesWritten := writePacket(inputPacket, buffer[:], 1000, packetKey, testProtocolID)
check(t, bytesWritten > 0)
// read the packet back in from the buffer
var sequence uint64
allowedPackets := allPacketsAllowed()
outputPacket, ok := readPacket(buffer[:bytesWritten], &sequence, packetKey, testProtocolID, uint64(time.Now().Unix()), nil, &allowedPackets, nil).(*connectionChallenge)
check(t, ok)
// make sure the read packet matches what was written
check(t, outputPacket.challengeTokenSequence == inputPacket.challengeTokenSequence)
check(t, outputPacket.challengeTokenData == inputPacket.challengeTokenData)
}
func TestConnectionResponsePacket(t *testing.T) {
// setup a connection response packet
inputPacket := &connectionResponse{}
inputPacket.challengeTokenSequence = 0
RandomBytes(inputPacket.challengeTokenData[:])
// write the packet to a buffer
var buffer [maxPacketBytes]byte
packetKey := GenerateKey()
bytesWritten := writePacket(inputPacket, buffer[:], 1000, packetKey, testProtocolID)
check(t, bytesWritten > 0)
// read the packet back in from the buffer
var sequence uint64
allowedPackets := allPacketsAllowed()
outputPacket, ok := readPacket(buffer[:bytesWritten], &sequence, packetKey, testProtocolID, uint64(time.Now().Unix()), nil, &allowedPackets, nil).(*connectionResponse)
check(t, ok)
// make sure the read packet matches what was written
check(t, outputPacket.challengeTokenSequence == inputPacket.challengeTokenSequence)
check(t, outputPacket.challengeTokenData == inputPacket.challengeTokenData)
}
func TestConnectionKeepAlivePacket(t *testing.T) {
// setup a connection keep alive packet
inputPacket := &connectionKeepAlive{
clientIndex: 10,
maxClients: 16,
}
// write the packet to a buffer
var buffer [maxPacketBytes]byte
packetKey := GenerateKey()
bytesWritten := writePacket(inputPacket, buffer[:], 1000, packetKey, testProtocolID)
check(t, bytesWritten > 0)
// read the packet back in from the buffer
var sequence uint64
allowedPackets := allPacketsAllowed()
outputPacket, ok := readPacket(buffer[:bytesWritten], &sequence, packetKey, testProtocolID, uint64(time.Now().Unix()), nil, &allowedPackets, nil).(*connectionKeepAlive)
check(t, ok)
// make sure the read packet matches what was written
check(t, outputPacket.clientIndex == inputPacket.clientIndex)
check(t, outputPacket.maxClients == inputPacket.maxClients)
}
func TestConnectionPayloadPacket(t *testing.T) {
// setup a connection payload packet
inputPacket := &connectionPayload{payloadData: make([]byte, maxPayloadBytes)}
RandomBytes(inputPacket.payloadData)
// write the packet to a buffer
var buffer [maxPacketBytes]byte
packetKey := GenerateKey()
bytesWritten := writePacket(inputPacket, buffer[:], 1000, packetKey, testProtocolID)
check(t, bytesWritten > 0)
// read the packet back in from the buffer
var sequence uint64
allowedPackets := allPacketsAllowed()
outputPacket, ok := readPacket(buffer[:bytesWritten], &sequence, packetKey, testProtocolID, uint64(time.Now().Unix()), nil, &allowedPackets, nil).(*connectionPayload)
check(t, ok)
// make sure the read packet matches what was written
check(t, bytes.Equal(outputPacket.payloadData, inputPacket.payloadData))
}
func TestConnectionDisconnectPacket(t *testing.T) {
// setup a connection disconnect packet
inputPacket := &connectionDisconnect{}
// write the packet to a buffer
var buffer [maxPacketBytes]byte
packetKey := GenerateKey()
bytesWritten := writePacket(inputPacket, buffer[:], 1000, packetKey, testProtocolID)
check(t, bytesWritten > 0)
// read the packet back in from the buffer
var sequence uint64
allowedPackets := allPacketsAllowed()
outputPacket, ok := readPacket(buffer[:bytesWritten], &sequence, packetKey, testProtocolID, uint64(time.Now().Unix()), nil, &allowedPackets, nil).(*connectionDisconnect)
check(t, ok)
check(t, outputPacket != nil)
}
func TestConnectTokenPublic(t *testing.T) {
// generate a private connect token
serverAddress := testServerAddress()
userData := make([]byte, UserDataBytes)
RandomBytes(userData)
connectTokenPrivateStruct := generateConnectTokenPrivate(testClientID, testTimeoutSeconds, []Address{serverAddress}, userData)
check(t, connectTokenPrivateStruct.clientID == testClientID)
check(t, connectTokenPrivateStruct.numServerAddresses == 1)
check(t, bytes.Equal(connectTokenPrivateStruct.userData[:], userData))
check(t, connectTokenPrivateStruct.serverAddresses[0].Equal(serverAddress))
// write it to a buffer
var connectTokenPrivateData [connectTokenPrivateBytes]byte
connectTokenPrivateStruct.write(connectTokenPrivateData[:])
// encrypt the buffer
createTimestamp := uint64(time.Now().Unix())
expireTimestamp := createTimestamp + 30
connectTokenNonce := generateNonce()
key := GenerateKey()
check(t, encryptConnectTokenPrivate(connectTokenPrivateData[:], testProtocolID, expireTimestamp, connectTokenNonce[:], key) == nil)
// wrap a public connect token around the private connect token data
var inputConnectToken connectToken
inputConnectToken.protocolID = testProtocolID
inputConnectToken.createTimestamp = createTimestamp
inputConnectToken.expireTimestamp = expireTimestamp
inputConnectToken.nonce = connectTokenNonce
inputConnectToken.privateData = connectTokenPrivateData
inputConnectToken.numServerAddresses = 1
inputConnectToken.serverAddresses[0] = serverAddress
inputConnectToken.clientToServerKey = connectTokenPrivateStruct.clientToServerKey
inputConnectToken.serverToClientKey = connectTokenPrivateStruct.serverToClientKey
inputConnectToken.timeoutSeconds = testTimeoutSeconds
// write the connect token to a buffer
var buffer [ConnectTokenBytes]byte
inputConnectToken.write(buffer[:])
// read the buffer back in
var outputConnectToken connectToken
check(t, outputConnectToken.read(buffer[:]) == nil)
// make sure the public connect token matches what was written
check(t, outputConnectToken.protocolID == inputConnectToken.protocolID)
check(t, outputConnectToken.createTimestamp == inputConnectToken.createTimestamp)
check(t, outputConnectToken.expireTimestamp == inputConnectToken.expireTimestamp)
check(t, outputConnectToken.nonce == inputConnectToken.nonce)
check(t, outputConnectToken.privateData == inputConnectToken.privateData)
check(t, outputConnectToken.numServerAddresses == inputConnectToken.numServerAddresses)
check(t, outputConnectToken.serverAddresses[0].Equal(inputConnectToken.serverAddresses[0]))
check(t, outputConnectToken.clientToServerKey == inputConnectToken.clientToServerKey)
check(t, outputConnectToken.serverToClientKey == inputConnectToken.serverToClientKey)
check(t, outputConnectToken.timeoutSeconds == inputConnectToken.timeoutSeconds)
}
func TestEncryptionManager(t *testing.T) {
var manager encryptionManager
manager.reset()
currentTime := 100.0
// generate some test encryption mappings
type encryptionMapping struct {
address Address
sendKey []byte
receiveKey []byte
}
const numEncryptionMappings = 5
var mappings [numEncryptionMappings]encryptionMapping
for i := 0; i < numEncryptionMappings; i++ {
mappings[i].address = Address{Type: AddressIPv6, IPv6: [8]uint16{0, 0, 0, 0, 0, 0, 0, 1}, Port: uint16(20000 + i)}
mappings[i].sendKey = GenerateKey()
mappings[i].receiveKey = GenerateKey()
}
// add the encryption mappings to the manager and make sure they can be looked up by address
for i := 0; i < numEncryptionMappings; i++ {
encryptionIndex := manager.findEncryptionMapping(&mappings[i].address, currentTime)
check(t, encryptionIndex == -1)
check(t, manager.getSendKey(encryptionIndex) == nil)
check(t, manager.getReceiveKey(encryptionIndex) == nil)
check(t, manager.addEncryptionMapping(&mappings[i].address, mappings[i].sendKey, mappings[i].receiveKey, currentTime, -1.0, testTimeoutSeconds))
encryptionIndex = manager.findEncryptionMapping(&mappings[i].address, currentTime)
sendKey := manager.getSendKey(encryptionIndex)
receiveKey := manager.getReceiveKey(encryptionIndex)
check(t, sendKey != nil)
check(t, receiveKey != nil)
check(t, bytes.Equal(sendKey, mappings[i].sendKey))
check(t, bytes.Equal(receiveKey, mappings[i].receiveKey))
}
// removing an encryption mapping that doesn't exist should return false
{
address := Address{Type: AddressIPv6, IPv6: [8]uint16{0, 0, 0, 0, 0, 0, 0, 1}, Port: 50000}
check(t, !manager.removeEncryptionMapping(&address, currentTime))
}
// remove the first and last encryption mappings
check(t, manager.removeEncryptionMapping(&mappings[0].address, currentTime))
check(t, manager.removeEncryptionMapping(&mappings[numEncryptionMappings-1].address, currentTime))
// make sure the encryption mappings that were removed can no longer be looked up by address
for i := 0; i < numEncryptionMappings; i++ {
encryptionIndex := manager.findEncryptionMapping(&mappings[i].address, currentTime)
sendKey := manager.getSendKey(encryptionIndex)
receiveKey := manager.getReceiveKey(encryptionIndex)
if i != 0 && i != numEncryptionMappings-1 {
check(t, sendKey != nil)
check(t, receiveKey != nil)
check(t, bytes.Equal(sendKey, mappings[i].sendKey))
check(t, bytes.Equal(receiveKey, mappings[i].receiveKey))
} else {
check(t, sendKey == nil)
check(t, receiveKey == nil)
}
}
// add the encryption mappings back in
check(t, manager.addEncryptionMapping(&mappings[0].address, mappings[0].sendKey, mappings[0].receiveKey, currentTime, -1.0, testTimeoutSeconds))
check(t, manager.addEncryptionMapping(&mappings[numEncryptionMappings-1].address, mappings[numEncryptionMappings-1].sendKey, mappings[numEncryptionMappings-1].receiveKey, currentTime, -1.0, testTimeoutSeconds))
// all encryption mappings should be able to be looked up by address again
for i := 0; i < numEncryptionMappings; i++ {
encryptionIndex := manager.findEncryptionMapping(&mappings[i].address, currentTime)
sendKey := manager.getSendKey(encryptionIndex)
receiveKey := manager.getReceiveKey(encryptionIndex)
check(t, sendKey != nil)
check(t, receiveKey != nil)
check(t, bytes.Equal(sendKey, mappings[i].sendKey))
check(t, bytes.Equal(receiveKey, mappings[i].receiveKey))
}
// check that encryption mappings time out properly
currentTime += testTimeoutSeconds * 2
for i := 0; i < numEncryptionMappings; i++ {
encryptionIndex := manager.findEncryptionMapping(&mappings[i].address, currentTime)
sendKey := manager.getSendKey(encryptionIndex)
receiveKey := manager.getReceiveKey(encryptionIndex)
check(t, sendKey == nil)
check(t, receiveKey == nil)
}
// add the same encryption mappings after timeout
for i := 0; i < numEncryptionMappings; i++ {
encryptionIndex := manager.findEncryptionMapping(&mappings[i].address, currentTime)
check(t, encryptionIndex == -1)
check(t, manager.getSendKey(encryptionIndex) == nil)
check(t, manager.getReceiveKey(encryptionIndex) == nil)
check(t, manager.addEncryptionMapping(&mappings[i].address, mappings[i].sendKey, mappings[i].receiveKey, currentTime, -1.0, testTimeoutSeconds))
encryptionIndex = manager.findEncryptionMapping(&mappings[i].address, currentTime)
sendKey := manager.getSendKey(encryptionIndex)
receiveKey := manager.getReceiveKey(encryptionIndex)
check(t, sendKey != nil)
check(t, receiveKey != nil)
check(t, bytes.Equal(sendKey, mappings[i].sendKey))
check(t, bytes.Equal(receiveKey, mappings[i].receiveKey))
}
// reset the encryption manager and verify that all encryption mappings have been removed
manager.reset()
for i := 0; i < numEncryptionMappings; i++ {
encryptionIndex := manager.findEncryptionMapping(&mappings[i].address, currentTime)
check(t, manager.getSendKey(encryptionIndex) == nil)
check(t, manager.getReceiveKey(encryptionIndex) == nil)
}
// test the expire time for encryption mapping works as expected
check(t, manager.addEncryptionMapping(&mappings[0].address, mappings[0].sendKey, mappings[0].receiveKey, currentTime, currentTime+1.0, testTimeoutSeconds))
encryptionIndex := manager.findEncryptionMapping(&mappings[0].address, currentTime)
check(t, encryptionIndex != -1)
check(t, manager.findEncryptionMapping(&mappings[0].address, currentTime+1.1) == -1)
manager.setExpireTime(encryptionIndex, -1.0)
check(t, manager.findEncryptionMapping(&mappings[0].address, currentTime) == encryptionIndex)
}
func TestReplayProtection(t *testing.T) {
var replay replayProtection
for i := 0; i < 2; i++ {
replay.reset()
check(t, replay.mostRecentSequence == 0)
// the first time we receive packets, they should not be already received
const maxSequence = replayProtectionBufferSize * 4
for sequence := uint64(0); sequence < maxSequence; sequence++ {
check(t, !replay.alreadyReceived(sequence))
replay.advanceSequence(sequence)
}
// old packets outside buffer should be considered already received
check(t, replay.alreadyReceived(0))
// packets received a second time should be flagged already received
for sequence := uint64(maxSequence - 10); sequence < maxSequence; sequence++ {
check(t, replay.alreadyReceived(sequence))
}
// jumping ahead to a much higher sequence should be considered not already received
check(t, !replay.alreadyReceived(maxSequence+replayProtectionBufferSize))
// old packets should be considered already received
for sequence := uint64(0); sequence < maxSequence; sequence++ {
check(t, replay.alreadyReceived(sequence))
}
}
// sequence numbers near the top of the sequence space must not be falsely rejected
// as replays. "sequence + buffer size" overflowed in the already received check and
// treated the top of the sequence space as ancient packets.
replay.reset()
const maxUint64 = uint64(0xFFFFFFFFFFFFFFFF)
check(t, !replay.alreadyReceived(maxUint64-replayProtectionBufferSize))
replay.advanceSequence(maxUint64 - replayProtectionBufferSize)
check(t, !replay.alreadyReceived(maxUint64-1))
replay.advanceSequence(maxUint64 - 1)
// and a replayed packet up there is still caught
check(t, replay.alreadyReceived(maxUint64-1))
// while packets that fell out of the window are rejected as before
check(t, replay.alreadyReceived(maxUint64-1-replayProtectionBufferSize))
}
func TestRuntimeGuards(t *testing.T) {
// out of range arguments to public entry points must not crash or corrupt state
// no private key needed: nothing in this test decrypts anything
serverConfig := &ServerConfig{ProtocolID: testProtocolID}
server, err := NewServer("127.0.0.1:40000", serverConfig, 0.0)
check(t, err == nil)
defer server.Close()
// starting with an out of range number of clients must not start the server
server.Start(0)
check(t, !server.Running())
server.Start(-1)
check(t, !server.Running())
server.Start(MaxClients + 1)
check(t, !server.Running())
server.Start(1)
check(t, server.Running())
check(t, server.MaxClients() == 1)
// out of range client indices must return cleanly. max clients is 1, so 1 is out of range
check(t, server.ClientUserData(-1) == nil)
check(t, server.ClientUserData(1) == nil)
check(t, server.ClientUserData(MaxClients) == nil)
check(t, server.NextPacketSequence(-1) == 0)
check(t, server.NextPacketSequence(1) == 0)
check(t, !server.ClientLoopback(-1))
check(t, !server.ClientLoopback(1))
packetData, _ := server.ReceivePacket(-1)
check(t, packetData == nil)