-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathDtlsEndpoint.cs
More file actions
1547 lines (1258 loc) · 42.5 KB
/
DtlsEndpoint.cs
File metadata and controls
1547 lines (1258 loc) · 42.5 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Waher.Events;
using Waher.Networking;
using Waher.Networking.Sniffers;
using Waher.Runtime.Cache;
using Waher.Runtime.Inventory;
using Waher.Runtime.Timing;
namespace Waher.Security.DTLS
{
/// <summary>
/// DTLS endpoint class. Manages a client or server DTLS endpoint connection, as defined
/// in RFC 6347: https://tools.ietf.org/html/rfc6347.
/// </summary>
public class DtlsEndpoint : CommunicationLayer, IDisposable
{
private static ICipher[] ciphers = null;
private static Dictionary<ushort, ICipher> ciphersPerCode = null;
private Cache<object, EndpointState> states;
private Scheduler timeouts;
internal readonly DtlsMode mode;
private RandomNumberGenerator rnd;
private ICommunicationLayer comLayer;
private readonly IUserSource users;
private readonly string requiredPrivilege;
private double probabilityPacketLoss = 0;
static DtlsEndpoint()
{
InitCiphers();
Types.OnInvalidated += (Sender, e) => InitCiphers();
}
private static void InitCiphers()
{
List<ICipher> Ciphers = new List<ICipher>();
Dictionary<ushort, ICipher> PerCode = new Dictionary<ushort, ICipher>();
foreach (Type T in Types.GetTypesImplementingInterface(typeof(ICipher)))
{
ConstructorInfo CI = Types.GetDefaultConstructor(T);
if (CI is null)
continue;
try
{
ICipher Cipher = (ICipher)CI.Invoke(Types.NoParameters);
Ciphers.Add(Cipher);
PerCode[Cipher.IanaCipherSuite] = Cipher;
}
catch (Exception ex)
{
Log.Exception(ex);
}
}
Ciphers.Sort((x, y) => y.Priority - x.Priority);
ciphers = Ciphers.ToArray();
ciphersPerCode = PerCode;
}
/// <summary>
/// DTLS endpoint class. Manages a client or server DTLS endpoint connection, as defined
/// in RFC 6347: https://tools.ietf.org/html/rfc6347.
/// </summary>
/// <param name="Mode">DTLS Mode of operation.</param>
/// <param name="ComLayer">Communication layer.</param>
/// <param name="Sniffers">Sniffers.</param>
public DtlsEndpoint(DtlsMode Mode, ICommunicationLayer ComLayer, params ISniffer[] Sniffers)
: this(Mode, ComLayer, null, null, Sniffers)
{
}
/// <summary>
/// DTLS endpoint class. Manages a client or server DTLS endpoint connection, as defined
/// in RFC 6347: https://tools.ietf.org/html/rfc6347.
/// </summary>
/// <param name="Mode">DTLS Mode of operation.</param>
/// <param name="ComLayer">Communication layer.</param>
/// <param name="Users">User data source, if pre-shared keys should be allowed by a DTLS server endpoint.</param>
/// <param name="Sniffers">Sniffers.</param>
public DtlsEndpoint(DtlsMode Mode, ICommunicationLayer ComLayer, IUserSource Users,
params ISniffer[] Sniffers)
: this(Mode, ComLayer, Users, null, Sniffers)
{
}
/// <summary>
/// DTLS endpoint class. Manages a client or server DTLS endpoint connection, as defined
/// in RFC 6347: https://tools.ietf.org/html/rfc6347.
/// </summary>
/// <param name="Mode">DTLS Mode of operation.</param>
/// <param name="ComLayer">Communication layer.</param>
/// <param name="Users">User data source, if pre-shared keys should be allowed by a DTLS server endpoint.</param>
/// <param name="RequiredPrivilege">Required privilege, for the user to be acceptable
/// in PSK handshakes.</param>
/// <param name="Sniffers">Sniffers.</param>
public DtlsEndpoint(DtlsMode Mode, ICommunicationLayer ComLayer, IUserSource Users,
string RequiredPrivilege, params ISniffer[] Sniffers)
: base(false, Sniffers)
{
this.mode = Mode;
this.users = Users;
this.requiredPrivilege = RequiredPrivilege;
this.rnd = RandomNumberGenerator.Create();
this.timeouts = new Scheduler();
this.states = new Cache<object, EndpointState>(int.MaxValue, TimeSpan.MaxValue, TimeSpan.FromHours(1), true);
this.states.Removed += this.States_Removed;
this.comLayer = ComLayer;
this.comLayer.PacketReceived += this.DataReceived;
}
private async Task States_Removed(object Sender, CacheItemEventArgs<object, EndpointState> e)
{
if (e.Value.state == DtlsState.SessionEstablished ||
e.Value.state == DtlsState.Handshake)
{
await e.Value.SetState(DtlsState.Closed);
await this.SendAlert(AlertLevel.fatal, AlertDescription.close_notify, e.Value);
}
e.Value.Dispose();
}
/// <summary>
/// User data source, if pre-shared keys should be allowed by a DTLS server endpoint.
/// </summary>
public IUserSource Users => this.users;
/// <summary>
/// Required privilege, for the user to be acceptable in PSK handshakes.
/// </summary>
public string RequiredPrivilege => this.requiredPrivilege;
/// <summary>
/// Probability of packet loss. Is by default 0.
/// Can be used to simulate lossy network.
/// </summary>
public double ProbabilityPacketLoss
{
get { return this.probabilityPacketLoss; }
set
{
if (value < 0 || value > 1)
{
throw new ArgumentOutOfRangeException("Valid probabilities lie between 0 and 1.",
nameof(this.ProbabilityPacketLoss));
}
this.probabilityPacketLoss = value;
}
}
/// <summary>
/// <see cref="IDisposable.Dispose"/>
/// </summary>
public void Dispose()
{
if (!(this.timeouts is null))
{
this.timeouts.Dispose();
this.timeouts = null;
}
if (!(this.states is null))
{
this.states.Clear();
this.states.Dispose();
this.states = null;
}
if (!(this.comLayer is null))
{
this.comLayer.PacketReceived -= this.DataReceived;
this.comLayer = null;
}
if (!(this.rnd is null))
{
this.rnd.Dispose();
this.rnd = null;
}
}
private double NextDouble()
{
byte[] A = new byte[4];
lock (this.rnd)
{
this.rnd.GetBytes(A);
}
double d = BitConverter.ToUInt32(A, 0);
d /= uint.MaxValue;
return d;
}
private bool PacketLost()
{
return (this.NextDouble() <= this.probabilityPacketLoss);
}
private async Task DataReceived(bool ConstantBuffer, byte[] Data, object RemoteEndpoint)
{
try
{
int Pos = 0;
int Len = Data.Length;
int Start;
if (this.probabilityPacketLoss > 0 && this.PacketLost())
{
if (this.HasSniffers)
this.Warning(DateTime.Now.ToString("T") + " Received packet lost.");
return;
}
this.ReceiveBinary(ConstantBuffer, Data);
EndpointState State = this.GetState(RemoteEndpoint, false);
bool First = true;
while (Pos + 13 <= Len)
{
Start = Pos;
DTLSPlaintext Rec = new DTLSPlaintext()
{
type = (ContentType)Data[Pos],
version = new ProtocolVersion()
{
major = Data[Pos + 1],
minor = Data[Pos + 2]
},
epoch = GetUInt16(Data, Pos + 3),
sequence_number = GetUInt48(Data, Pos + 5),
length = GetUInt16(Data, Pos + 11),
fragment = null,
datagram = Data,
recordOffset = Pos
};
Pos += 13;
if (Pos + Rec.length > Len)
break;
Rec.fragment = new byte[Rec.length];
Buffer.BlockCopy(Data, Pos, Rec.fragment, 0, Rec.length);
Pos += Rec.length;
if (!await this.RecordReceived(Rec, Data, Start, State, First))
break;
First = false;
}
}
catch (Exception ex)
{
this.Exception(ex);
}
}
private async Task<bool> RecordReceived(DTLSPlaintext Record, byte[] RecordData, int Start,
EndpointState State, bool StartOfFlight)
{
if (Record.version.major != 254)
{
this.Error(DateTime.Now.ToString("T") + " Packet dropped. Protocol version not recognized.");
return false; // Not DTLS 1.x
}
// Anti-replay §4.1.2.6
bool ValidEpoch = Record.epoch == State.currentEpoch;
if (State.acceptRollbackPrevEpoch)
{
if (Record.epoch == State.currentEpoch - 1)
{
if (Record.type != ContentType.change_cipher_spec)
{
State.currentEpoch--;
State.currentCipher = State.previousCipher;
State.leftEdgeSeqNr = State.previousLeftEdgeSeqNr;
State.receivedPacketsWindow = State.previousReceivedPacketsWindow;
State.currentSeqNr = State.previousSeqNr;
State.next_receive_seq = State.flightRxSeq = State.previousFlightRxSeq;
State.message_seq = State.flightTxSeq = State.previousFlightTxSeq;
}
ValidEpoch = true;
}
State.acceptRollbackPrevEpoch = false;
}
if (!ValidEpoch)
{
this.Error(DateTime.Now.ToString("T") + " Packet dropped. Unexpected epoch (" +
Record.epoch + ", expected " + State.currentEpoch.ToString() + ").");
return false;
}
long Offset = (long)(Record.sequence_number - State.leftEdgeSeqNr);
if (Offset < 0)
{
this.Error(DateTime.Now.ToString("T") + " Packet dropped. Old sequence number.");
return false;
}
if (Offset < 64 && (State.receivedPacketsWindow & (1UL << (int)Offset)) != 0)
{
this.Error(DateTime.Now.ToString("T") + " Packet dropped. Sequence number already processed.");
return false;
}
if (Record.epoch > 0 && !(State.currentCipher is null))
{
try
{
Record.fragment = State.currentCipher.Decrypt(Record.fragment, RecordData, Start, State);
}
catch (Exception ex)
{
this.Exception(ex);
Record.fragment = null;
}
if (Record.fragment is null)
{
this.Error(DateTime.Now.ToString("T") + " Packet dropped. Decryption failed.");
State.acceptRollbackPrevEpoch = true;
return false;
}
Record.length = (ushort)Record.fragment.Length;
if (this.HasSniffers)
{
byte[] NewRecord = new byte[13 + Record.length];
Buffer.BlockCopy(Record.datagram, Record.recordOffset, NewRecord, 0, 13);
Buffer.BlockCopy(Record.fragment, 0, NewRecord, 13, Record.length);
Record.datagram = NewRecord;
Record.recordOffset = 0;
}
}
// TODO: Queue future sequence numbers, is handshake. These must be processed in order.
if (!await this.ProcessRecord(Record, State, StartOfFlight))
return false;
// Update receive window
if (Offset >= 64)
{
ulong Diff = (ulong)(Offset - 63);
if (Diff >= 64)
State.receivedPacketsWindow = 0;
else
State.receivedPacketsWindow >>= (int)Diff;
State.leftEdgeSeqNr += Diff;
Offset -= (long)Diff;
}
State.receivedPacketsWindow |= 1UL << (int)Offset;
return true;
}
private string TlsVersion(byte[] Data, int Offset)
{
StringBuilder Version = new StringBuilder();
byte Major = Data[Offset++];
byte Minor = Data[Offset++];
if (Major >= 128)
{
Version.Append('D');
Major ^= 255;
Minor ^= 255;
}
Version.Append("TLS ");
Version.Append(Major.ToString());
Version.Append('.');
Version.Append(Minor.ToString());
return Version.ToString();
}
private void SniffMsg(byte[] Data, int Offset, bool Rx)
{
StringBuilder Msg = new StringBuilder();
Msg.Append(DateTime.Now.ToString("T"));
if (Rx)
Msg.Append(" RX: ");
else
Msg.Append(" TX: ");
ContentType ContentType = (ContentType)Data[Offset];
string Ver = this.TlsVersion(Data, Offset + 1);
ushort Epoch = GetUInt16(Data, Offset + 3);
ulong SeqNr = GetUInt48(Data, Offset + 5);
uint? MsgNr = null;
int? Len = null;
int? FOffset = null;
int? FLen = null;
Msg.Append(ContentType.ToString());
Msg.Append(", ");
switch (ContentType)
{
case ContentType.handshake:
HandshakeType HandshakeType = (HandshakeType)Data[Offset + 13];
Len = GetUInt24(Data, Offset + 14);
MsgNr = GetUInt16(Data, Offset + 17);
FOffset = GetUInt24(Data, Offset + 19);
FLen = GetUInt24(Data, Offset + 22);
Msg.Append(HandshakeType.ToString());
break;
case ContentType.alert:
AlertLevel AlertLevel = (AlertLevel)Data[Offset + 13];
AlertDescription AlertDescription = (AlertDescription)Data[Offset + 14];
Msg.Append(AlertLevel.ToString());
Msg.Append(", ");
Msg.Append(AlertDescription.ToString());
break;
}
Msg.Append(" (");
Msg.Append(Ver);
Msg.Append(", Epoch: ");
Msg.Append(Epoch.ToString());
Msg.Append(", seq: ");
Msg.Append(SeqNr.ToString());
if (MsgNr.HasValue)
{
Msg.Append(", msg: ");
Msg.Append(MsgNr.Value.ToString());
Msg.Append(", len: ");
Msg.Append(Len.Value.ToString());
Msg.Append(", foffs: ");
Msg.Append(FOffset.Value.ToString());
Msg.Append(", flen: ");
Msg.Append(FLen.Value.ToString());
}
Msg.Append(')');
this.Information(Msg.ToString());
}
private async Task<bool> ProcessRecord(DTLSPlaintext Record, EndpointState State, bool StartOfFlight)
{
try
{
if (this.HasSniffers)
this.SniffMsg(Record.datagram, Record.recordOffset, true);
switch (Record.type)
{
case ContentType.handshake:
HandshakeType HandshakeType = (HandshakeType)Record.fragment[0];
int PayloadLen = Record.fragment[1];
PayloadLen <<= 8;
PayloadLen |= Record.fragment[2];
PayloadLen <<= 8;
PayloadLen |= Record.fragment[3];
int MessageSeqNr = Record.fragment[4];
MessageSeqNr <<= 8;
MessageSeqNr |= Record.fragment[5];
if (MessageSeqNr != State.next_receive_seq)
{
if (MessageSeqNr != 0)
{
this.Error(DateTime.Now.ToString("T") +
" Packet dropped. Expected message number " +
State.next_receive_seq.ToString() + ", but was " +
MessageSeqNr.ToString() + ".");
return false; // Not the expected handshake sequence number.
}
else if (HandshakeType == HandshakeType.client_hello ||
HandshakeType == HandshakeType.hello_request)
{
State.message_seq = 0;
State.next_receive_seq = 0;
}
else
{
this.Error(DateTime.Now.ToString("T") +
" Packet dropped. Expected message number " +
State.next_receive_seq.ToString() + ", but was " +
MessageSeqNr.ToString() + ".");
return false; // Not the expected handshake sequence number.
}
}
if (StartOfFlight)
{
lock (State.lastFlight)
{
State.flightNr++;
State.lastFlight.Clear();
State.timeoutSeconds = 1;
State.flightTxSeq = State.message_seq;
State.flightRxSeq = State.next_receive_seq;
}
}
State.next_receive_seq++;
int FragmentOffset = GetUInt24(Record.fragment, 6);
int FragmentLength = GetUInt24(Record.fragment, 9);
if (FragmentOffset > 0 || FragmentLength != PayloadLen)
{
this.Error(DateTime.Now.ToString("T") +
" Packet dropped. Fragmented messages not supported.");
return false; // TODO: Reassembly of fragmented messages.
}
int Pos = 12;
this.AddHandshakeMessageToHash(HandshakeType, Record.fragment, 0,
Record.fragment.Length, State, false);
switch (HandshakeType)
{
case HandshakeType.hello_verify_request:
if (this.mode == DtlsMode.Server)
break;
if (Record.fragment[Pos++] != 254) // Major version.
await this.HandshakeFailure(State, "DTLS version mismatch.", AlertDescription.protocol_version);
else
{
Pos++; // Minor version.
int Len = Record.fragment[Pos++];
State.cookie = new byte[Len + 1];
Buffer.BlockCopy(Record.fragment, Pos - 1, State.cookie, 0, Len + 1);
Pos += Len;
await this.SendClientHello(State);
}
break;
case HandshakeType.server_hello:
if (this.mode == DtlsMode.Server)
break;
if (Record.fragment[Pos++] != 254 || Record.fragment[Pos++] != 253) // Protocol version.
await this.HandshakeFailure(State, "DTLS version mismatch.", AlertDescription.protocol_version);
else
{
State.serverRandom = new byte[32];
Buffer.BlockCopy(Record.fragment, Pos, State.serverRandom, 0, 32);
Pos += 32;
byte[] PrevSessionId = State.sessionId;
int Len = Record.fragment[Pos++];
State.sessionId = new byte[Len];
Buffer.BlockCopy(Record.fragment, Pos, State.sessionId, 0, Len);
Pos += Len;
ushort CipherSuite = Record.fragment[Pos++];
CipherSuite <<= 8;
CipherSuite |= Record.fragment[Pos++];
byte CompressionMethod = Record.fragment[Pos++];
// TODO: Compression methods.
// TODO: Extensions
State.pendingCipher = null;
if (!ciphersPerCode.TryGetValue(CipherSuite, out State.pendingCipher))
State.pendingCipher = null;
if (State.pendingCipher is null || CompressionMethod != 0)
{
await this.HandshakeFailure(State, "Cipher and compression mode agreement not reached.",
AlertDescription.handshake_failure);
}
}
break;
case HandshakeType.server_hello_done:
if (this.mode == DtlsMode.Server)
break;
await State.pendingCipher.SendClientKeyExchange(this, State);
break;
case HandshakeType.server_key_exchange:
if (this.mode == DtlsMode.Server)
break;
State.pendingCipher?.ServerKeyExchange(Record.fragment, ref Pos, State);
break;
case HandshakeType.client_hello:
if (this.mode == DtlsMode.Client)
break;
if (Record.fragment[Pos++] != 254) // Major version.
break;
Pos++; // Minor version.
byte[] ClientRandom = new byte[32];
Buffer.BlockCopy(Record.fragment, Pos, ClientRandom, 0, 32);
Pos += 32;
byte SessionIdLen = Record.fragment[Pos++];
byte[] SessionId = new byte[SessionIdLen];
Buffer.BlockCopy(Record.fragment, Pos, SessionId, 0, SessionIdLen);
Pos += SessionIdLen;
byte CookieLen = Record.fragment[Pos++];
byte[] Cookie = new byte[CookieLen];
Buffer.BlockCopy(Record.fragment, Pos, Cookie, 0, CookieLen);
Pos += CookieLen;
int CipherPos = Pos;
ushort NrCiphers = Record.fragment[Pos++];
NrCiphers <<= 1;
NrCiphers |= Record.fragment[Pos++];
if ((NrCiphers & 1) != 0)
break;
NrCiphers >>= 1;
int i;
ushort CipherCode = 0;
ICipher Cipher = null;
for (i = 0; i < NrCiphers; i++)
{
CipherCode = Record.fragment[Pos++];
CipherCode <<= 8;
CipherCode |= Record.fragment[Pos++];
if (ciphersPerCode.TryGetValue(CipherCode, out Cipher))
{
Pos += (NrCiphers - i - 1) << 1;
break;
}
}
int CompressionPos = Pos;
byte NrCompressionMethods = Record.fragment[Pos++];
bool NullCompression = false;
for (i = 0; i < NrCompressionMethods; i++)
{
if (Record.fragment[Pos++] == 0)
{
NullCompression = true;
Pos += (NrCompressionMethods - i - 1);
break;
}
}
if (Cipher is null || !NullCompression)
{
await this.SendAlert(AlertLevel.warning, AlertDescription.handshake_failure, State);
break;
}
// TODO: Extensions.
// TODO: Session resumption (RFC 6347, § 4.2.4, Figure 2).
using (IncrementalHash CookieHash = IncrementalHash.CreateHMAC(
HashAlgorithmName.SHA256, State.cookieRandom))
{
CookieHash.AppendData(Encoding.UTF8.GetBytes(State.remoteEndpoint.ToString()));
CookieHash.AppendData(Record.fragment, 0, 2); // Version.
CookieHash.AppendData(ClientRandom);
CookieHash.AppendData(Record.fragment, CipherPos, 2 + (NrCiphers << 1));
CookieHash.AppendData(Record.fragment, CompressionPos, 1 + NrCompressionMethods);
byte[] Cookie2 = CookieHash.GetHashAndReset();
byte CookieLen2 = (byte)Cookie2.Length;
if (CookieLen == 0 || !AreEqual(Cookie, Cookie2))
{
byte[] HelloVerifyRequest = new byte[3 + CookieLen2];
HelloVerifyRequest[0] = 254;
HelloVerifyRequest[1] = 253;
HelloVerifyRequest[2] = (byte)CookieLen2;
Buffer.BlockCopy(Cookie2, 0, HelloVerifyRequest, 3, CookieLen2);
await this.SendHandshake(HandshakeType.hello_verify_request,
HelloVerifyRequest, false, true, State);
break;
}
}
SessionIdLen = 32;
SessionId = new byte[32];
State.serverRandom = new byte[32];
lock (this.rnd)
{
this.rnd.GetBytes(SessionId);
this.rnd.GetBytes(State.serverRandom);
}
await this.OnIncomingHandshakeStarted.Raise(this, new RemoteEndpointEventArgs(State), false);
this.SetUnixTime(State.serverRandom, 0);
byte[] ServerHello = new byte[70];
State.sessionId = SessionId;
State.clientRandom = ClientRandom;
ServerHello[0] = 254;
ServerHello[1] = 253;
Buffer.BlockCopy(State.serverRandom, 0, ServerHello, 2, 32);
ServerHello[34] = 32;
Buffer.BlockCopy(SessionId, 0, ServerHello, 35, 32);
ServerHello[67] = (byte)(CipherCode >> 8);
ServerHello[68] = (byte)CipherCode;
ServerHello[69] = 0;
State.pendingCipher = Cipher;
State.clientFinished = false;
State.serverFinished = false;
await this.SendHandshake(HandshakeType.server_hello, ServerHello,
true, true, State);
await Cipher.SendServerKeyExchange(this, State);
break;
case HandshakeType.client_key_exchange:
if (this.mode == DtlsMode.Client)
break;
if (!(State.pendingCipher is null))
Pos = await State.pendingCipher.ClientKeyExchange(Record.fragment, Pos, State);
break;
case HandshakeType.finished:
if (State.currentCipher is null)
break;
byte[] VerifyData = new byte[12];
Buffer.BlockCopy(Record.fragment, Pos, VerifyData, 0, 12);
Pos += 12;
if (!State.currentCipher.VerifyFinished(VerifyData, State))
{
await this.HandshakeFailure(State, "Verify data not valid.", AlertDescription.decrypt_error);
break;
}
if (State.isClient)
State.serverFinished = true;
else
State.clientFinished = true;
if (State.clientFinished && State.serverFinished)
await this.HandshakeSuccess(State);
else
{
ulong Temp = State.currentSeqNr;
try
{
State.currentSeqNr = State.previousSeqNr;
State.currentEpoch--;
await this.SendRecord(ContentType.change_cipher_spec,
new byte[] { 1 }, true, false, State);
}
finally
{
State.currentSeqNr = Temp;
State.currentEpoch++;
}
await State.currentCipher.SendFinished(this, State, false);
}
break;
case HandshakeType.hello_request:
if (this.mode == DtlsMode.Server)
break;
if (State.state == DtlsState.SessionEstablished)
{
await State.SetState(DtlsState.Handshake);
await this.StartHandshake(State.remoteEndpoint);
}
break;
case HandshakeType.certificate: // TODO
case HandshakeType.certificate_request: // TODO
case HandshakeType.certificate_verify: // TODO
break;
}
break;
case ContentType.change_cipher_spec:
// Make sure the hash of the other side is calculated before
// the finished message is received.
if (StartOfFlight)
{
lock (State.lastFlight)
{
State.flightNr++;
State.lastFlight.Clear();
State.timeoutSeconds = 1;
State.flightTxSeq = State.message_seq;
State.flightRxSeq = State.next_receive_seq;
}
}
if (State.isClient)
State.CalcServerHandshakeHash();
else
State.CalcClientHandshakeHash();
this.ChangeCipherSpec(State, State.isClient);
break;
case ContentType.alert:
if (Record.fragment.Length >= 2)
{
AlertLevel Level = (AlertLevel)Record.fragment[0];
AlertDescription Description = (AlertDescription)Record.fragment[1];
if (Description == AlertDescription.close_notify)
{
if (this.HasSniffers)
this.Information(DateTime.Now.ToString("T") + " Session closed.");
if (State.state == DtlsState.Handshake ||
State.state == DtlsState.SessionEstablished)
{
await this.SendAlert(Level, Description, State); // Send close notification back.
}
await State.SetState(DtlsState.Closed);
this.states.Remove(State.remoteEndpoint);
}
else if (Description == AlertDescription.handshake_failure)
{
await this.HandshakeFailure(State, "Handshake failed.", Description);
}
else if (Level == AlertLevel.fatal)
{
if (State.state == DtlsState.Handshake)
await this.HandshakeFailure(State, "Fatal error.", Description);
else
await this.SessionFailure(State, "Fatal error.", Description);
}
else if (this.HasSniffers)
{
this.Warning(DateTime.Now.ToString("T") + " Non-fatal alert received: " +
Description.ToString());
}
}
break;
case ContentType.application_data:
if (State.State != DtlsState.SessionEstablished)
break;
await this.OnApplicationDataReceived.Raise(this, new ApplicationDataEventArgs(State, Record.fragment));
break;
default:
break;
}
return true;
}
catch (Exception ex)
{
Log.Exception(ex);
await this.HandshakeFailure(State, "Unexpected error: " + ex.Message, AlertDescription.internal_error);
return false;
}
}
/// <summary>
/// Event raised when application data has been received.
/// </summary>
public event EventHandlerAsync<ApplicationDataEventArgs> OnApplicationDataReceived = null;
internal Task SendAlert(AlertLevel Level, AlertDescription Description, EndpointState State)
{
return this.SendRecord(ContentType.alert, new byte[] { (byte)Level, (byte)Description }, false, false, State);
}
internal static bool AreEqual(byte[] A1, byte[] A2)
{
if ((A1 is null) ^ (A2 is null))
return false;
if (A1 is null)
return true;
int i, c = A1.Length;
if (c != A2.Length)
return false;
for (i = 0; i < c; i++)
{
if (A1[i] != A2[i])
return false;
}
return true;
}
internal async Task HandshakeSuccess(EndpointState State)
{
await State.SetState(DtlsState.SessionEstablished);
await this.OnHandshakeSuccessful.Raise(this, new RemoteEndpointEventArgs(State));
}
/// <summary>
/// Event raised when handshake has been successful.
/// </summary>
public event EventHandlerAsync<RemoteEndpointEventArgs> OnHandshakeSuccessful = null;
/// <summary>
/// Event raised when an incoming handshake has begun.
/// </summary>
public event EventHandlerAsync<RemoteEndpointEventArgs> OnIncomingHandshakeStarted = null;
private async Task HandshakeFailure(EndpointState State, string Reason, AlertDescription Descripton)
{
await State.SetState(DtlsState.Failed);
await this.OnHandshakeFailed.Raise(this, new FailureEventArgs(State, Reason, Descripton));
this.states?.Remove(State.remoteEndpoint);
}
/// <summary>
/// Event raised when handshake fails.
/// </summary>
public event EventHandlerAsync<FailureEventArgs> OnHandshakeFailed = null;
private async Task SessionFailure(EndpointState State, string Reason, AlertDescription Descripton)
{
await State.SetState(DtlsState.Failed);
await this.OnSessionFailed.Raise(this, new FailureEventArgs(State, Reason, Descripton));
this.states?.Remove(State.remoteEndpoint);
}
/// <summary>
/// Event raised when session fails.
/// </summary>
public event EventHandlerAsync<FailureEventArgs> OnSessionFailed = null;