-
Notifications
You must be signed in to change notification settings - Fork 361
/
Handshaker.java
2609 lines (2453 loc) · 92 KB
/
Handshaker.java
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
/*******************************************************************************
* Copyright (c) 2015, 2019 Institute for Pervasive Computing, ETH Zurich and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* Matthias Kovatsch - creator and main architect
* Stefan Jucker - DTLS implementation
* Kai Hudalla (Bosch Software Innovations GmbH) - fix bug 464383
* Kai Hudalla (Bosch Software Innovations GmbH) - replace custom HMAC implementation
* with standard algorithm
* Kai Hudalla (Bosch Software Innovations GmbH) - retrieve security parameters from cipher suite only
* Kai Hudalla (Bosch Software Innovations GmbH) - add support for notifying a SessionListener about
* life-cycle events
* Kai Hudalla (Bosch Software Innovations GmbH) - use SortedSet for buffering fragmented messages in order
* to avoid repetitive sorting
* Kai Hudalla (Bosch Software Innovations GmbH) - consolidate and fix record buffering and message re-assembly
* Kai Hudalla (Bosch Software Innovations GmbH) - replace local compressionMethod and cipherSuite properties
* with corresponding properties in DTLSSession
* Kai Hudalla (Bosch Software Innovations GmbH) - derive max fragment length from network MTU
* Kai Hudalla (Bosch Software Innovations GmbH) - use SessionListener to trigger sending of pending
* APPLICATION messages
* Bosch Software Innovations GmbH - move PRF code to separate PseudoRandomFunction class
* Achim Kraus (Bosch Software Innovations GmbH) - add handshakeFailed to report
* handshake errors.
* Achim Kraus (Bosch Software Innovations GmbH) - use LinkedHashSet to order listeners
* see issue #406
* Ludwig Seitz (RISE SICS) - Moved certificate validation here from CertificateMessage
* Ludwig Seitz (RISE SICS) - Added support for raw public key validation
* Bosch Software Innovations GmbH - migrate to SLF4J
* Achim Kraus (Bosch Software Innovations GmbH) - issue #549
* trustStore := null, disable x.509
* trustStore := [], enable x.509, trust all
* Vikram (University of Rostock) - generatePremasterSecertFromPSK with otherSecret from ECDHE_PSK
* Achim Kraus (Bosch Software Innovations GmbH) - use handshake parameter and
* generic handshake messages to
* process reordered handshake messages
* and create the specific, when the parameters
* are available.
* Achim Kraus (Bosch Software Innovations GmbH) - issue 744: use handshaker as
* parameter for session listener.
* Achim Kraus (Bosch Software Innovations GmbH) - add handshakeFlightRetransmitted
* Achim Kraus (Bosch Software Innovations GmbH) - redesign connection session listener to
* ensure, that the session listener methods
* are called via the handshaker.
* Achim Kraus (Bosch Software Innovations GmbH) - suppress duplicates only from
* the same epoch
* Achim Kraus (Bosch Software Innovations GmbH) - redesign DTLSFlight and RecordLayer
* Achim Kraus (Bosch Software Innovations GmbH) - remove copy of master secret
* Achim Kraus (Bosch Software Innovations GmbH) - redesign wrapMessage
******************************************************************************/
package org.eclipse.californium.scandium.dtls;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.Inet6Address;
import java.net.InetSocketAddress;
import java.security.MessageDigest;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertPath;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.security.auth.DestroyFailedException;
import javax.security.auth.Destroyable;
import javax.security.auth.x500.X500Principal;
import org.eclipse.californium.elements.RawData;
import org.eclipse.californium.elements.auth.AdditionalInfo;
import org.eclipse.californium.elements.auth.ExtensiblePrincipal;
import org.eclipse.californium.elements.auth.PreSharedKeyIdentity;
import org.eclipse.californium.elements.auth.RawPublicKeyIdentity;
import org.eclipse.californium.elements.auth.X509CertPath;
import org.eclipse.californium.elements.util.Bytes;
import org.eclipse.californium.elements.util.ClockUtil;
import org.eclipse.californium.elements.util.NoPublicAPI;
import org.eclipse.californium.elements.util.SerialExecutor;
import org.eclipse.californium.elements.util.StringUtil;
import org.eclipse.californium.scandium.auth.ApplicationLevelInfoSupplier;
import org.eclipse.californium.scandium.config.DtlsConfig;
import org.eclipse.californium.scandium.config.DtlsConnectorConfig;
import org.eclipse.californium.scandium.dtls.AlertMessage.AlertDescription;
import org.eclipse.californium.scandium.dtls.AlertMessage.AlertLevel;
import org.eclipse.californium.scandium.dtls.cipher.CipherSuite;
import org.eclipse.californium.scandium.dtls.cipher.CipherSuite.CertificateKeyAlgorithm;
import org.eclipse.californium.scandium.dtls.cipher.PseudoRandomFunction;
import org.eclipse.californium.scandium.dtls.cipher.PseudoRandomFunction.Label;
import org.eclipse.californium.scandium.dtls.cipher.RandomManager;
import org.eclipse.californium.scandium.dtls.cipher.XECDHECryptography.SupportedGroup;
import org.eclipse.californium.scandium.dtls.pskstore.AdvancedPskStore;
import org.eclipse.californium.scandium.dtls.x509.CertificateProvider;
import org.eclipse.californium.scandium.dtls.x509.NewAdvancedCertificateVerifier;
import org.eclipse.californium.scandium.util.SecretIvParameterSpec;
import org.eclipse.californium.scandium.util.SecretUtil;
import org.eclipse.californium.scandium.util.ServerNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A base class for the DTLS handshake protocol.
*
* Contains functionality and fields needed by all types of handshakers.
*/
public abstract class Handshaker implements Destroyable {
/**
* The logger.
*
* @deprecated scope will change to private.
*/
@Deprecated
protected final Logger LOGGER = LoggerFactory.getLogger(getClass());
protected Random clientRandom;
protected Random serverRandom;
/**
* Seed for master secret.
*
* @since 3.0
*/
private byte[] masterSecretSeed;
/**
* The master secret for this handshake.
*/
private SecretKey masterSecret;
private SecretKey clientWriteMACKey;
private SecretKey serverWriteMACKey;
private SecretKey clientWriteKey;
private SecretKey serverWriteKey;
private SecretIvParameterSpec clientWriteIV;
private SecretIvParameterSpec serverWriteIV;
private volatile boolean generateClusterMacKeys;
private boolean destroyed;
private final ReentrantLock recursionProtection = new ReentrantLock();
/**
* Communication over IPv6.
*
* @since 2.4
*/
private final boolean ipv6;
/**
* DTLS context of handshaker.
*/
private final DTLSContext context;
/**
* The logic in charge of verifying the chain of certificates asserting this
* handshaker's identity
*/
protected final NewAdvancedCertificateVerifier certificateVerifier;
/** Used to retrieve identity/pre-shared-key for a given destination */
protected final AdvancedPskStore advancedPskStore;
/**
* The configured connection id length. {@code null}, not supported,
* {@code 0} supported but not used.
*/
protected final ConnectionIdGenerator connectionIdGenerator;
/**
* The current handshake message sequence number (in the handshake message
* called message_seq) for outgoing messages of this handshake.
*/
private int sendMessageSequence = 0;
/**
* The next expected handshake message sequence number (in the handshake
* message called message_seq) for incoming messages of this handshake.
*/
private int nextReceiveMessageSequence = 0;
/** Realtime nanoseconds of last sending a flight */
private long flightSendNanos;
/** Realtime nanoseconds when handshakes get's expired. */
private long nanosExpireTime;
/** Timeout in nanoseconds to expire handshakes. */
private final long nanosExpireTimeout;
/** The current flight number. */
protected int flightNumber = 0;
/**
* Record size limit. {@code null}, if not used.
* @since 2.4
*/
protected Integer recordSizeLimit;
/**
* Accumulated record size of deferred incoming records.
*
* @see #addDeferredProcessedRecord(Record, Collection)
* @see #removeDeferredProcessedRecord(Record, Collection)
*/
private int deferredIncomingRecordsSize;
/** Maximum length of reassembled fragmented handshake messages */
private final int maxFragmentedHandshakeMessageLength;
/** Maximum number of outgoing application data messages, which may be processed deferred after the handshake */
private final int maxDeferredProcessedOutgoingApplicationDataMessages;
/** Maximum number of bytes of deferred processed incoming records */
private final int maxDeferredProcessedIncomingRecordsSize;
/** List of application data messages, which are send deferred after the handshake */
private final List<RawData> deferredApplicationData = new ArrayList<RawData>();
/**
* List of received records of next epoch.
*
* Records are processed deferred after the epoch changed or the handshake
* failed.
*
* @since 3.0 (renamed, was deferredRecords)
*/
private final List<Record> nextEpochDeferredRecords = new ArrayList<Record>();
/** Currently pending flight */
private final AtomicReference<DTLSFlight> pendingFlight = new AtomicReference<DTLSFlight>();
/**
* Task to retransmit flight.
*
* @since 2.4
*/
private Runnable retransmitFlight;
/**
* Future of completion timeout of the last flight.
*
* This future indicates, that the last flight of the handshake is pending.
* The last flight is not retransmitted by the retransmission timeout, it's
* retransmitted, if the other peer retransmits the flight before this.
*
* If no data is received within that completion timeout, the handshake is
* completed without. The last flight is not longer kept, because the other
* peer is not longer considered to retransmit its flight before this.
*
* @since 3.0
*/
private ScheduledFuture<?> timeoutLastFlight;
/**
* Scheduler for flight timeout and retransmission.
*
* @since 2.4
*/
private final ScheduledExecutorService timer;
/**
* Record layer to send messages.
*/
private final RecordLayer recordLayer;
/**
* Associated connection for this handshaker.
*/
private final Connection connection;
/**
* Associated peer for this handshaker.
* @since 3.2
*/
private final InetSocketAddress peer;
protected final Object peerToLog;
/** Buffer for received records that can not be processed immediately. */
private InboundMessageBuffer inboundMessageBuffer;
/** List of handshake messages */
protected final List<HandshakeMessage> handshakeMessages = new ArrayList<HandshakeMessage>();
/**
* Current partial reassembled handshake message.
*/
private ReassemblingHandshakeMessage reassembledMessage;
/**
* The handshaker's certificate identity provider.
*
* @since 3.0
*/
protected final CertificateProvider certificateIdentityProvider;
/**
* The handshaker's private key.
*
* Only available after certificate identity is provided. May be
* {@code null}, if no matching identity is available.
*/
protected PrivateKey privateKey;
/**
* The handshaker's public key.
*
* Only available after certificate identity is provided. May be
* {@code null}, if no matching identity is available.
*/
protected PublicKey publicKey;
/**
* The chain of certificates asserting this handshaker's identity.
*
* Only available after certificate identity is provided. May be
* {@code null}, if no matching identity is available.
*/
protected List<X509Certificate> certificateChain;
/**
* The certificate path of the other peer.
*
* Only available after certificate verification. Optionally truncated to
* trusted issuer.
*
* @since 3.0 (renamed, was peerCertPath)
*/
private CertPath otherPeersCertPath;
/**
* The public key of the other peer
*
* May be {@code null}, if other peer sends a empty certificate.
*
* @since 3.0
*/
protected PublicKey otherPeersPublicKey;
/**
* Indicates, that the verification of the other peer's certificate chain public key has finished.
*
* @since 3.0 (renamed certificateVerfied)
*/
protected boolean otherPeersCertificateVerified;
/**
* Indicates, that the signature of the other peers is verified.
*
* That signature is contained in the SERVER_KEY_EXCHANGE or CERTIFICATE_VERIFY.
*
* @since 3.0
*/
private boolean otherPeersSignatureVerified;
/**
* Support Server Name Indication TLS extension.
*/
protected final boolean sniEnabled;
/**
* Send the extended master secret extension.
*
* @since 3.0
*/
protected final ExtendedMasterSecretMode extendedMasterSecretMode;
/**
* Truncate certificate path for validation.
*/
protected final boolean useTruncatedCertificatePathForVerification;
/**
* Stop retransmission with receiving the first record of the answer flight.
*
* @since 2.4
*/
private final boolean useEarlyStopRetransmission;
/**
* Use datagrams with multiple dtls records.
*
* @since 2.4
*/
private Boolean useMultiRecordMessages;
/**
* Use dtls records with multiple handshake messages.
*
* @since 2.4
*/
private Boolean useMultiHandshakeMessagesRecord;
/**
* Back-off retransmission.
*
* @since 2.4
*/
private final int backOffRetransmission;
/**
* Maximum number of retransmissions.
*
* @since 2.4
*/
private final int maxRetransmissions;
/**
* Retransmission timeout.
*
* @since 2.4
*/
private final int retransmissionTimeout;
/**
* Maximum retransmission timeout.
*
* @since 3.0
*/
private final int maxRetransmissionTimeout;
private final float retransmissionRandomFactor;
private final float retransmissionTimeoutScale;
/**
* Additional timeout for ECC.
*
* @since 3.0
*/
private final int additionalTimeoutForEcc;
/**
* Session listeners.
*
* @see #addSessionListener(SessionListener)
*/
private final Set<SessionListener> sessionListeners = new LinkedHashSet<>();
/**
* Indicates, that {@link #setExpectedStates(HandshakeState[])} has been called
* during the last processing of {@link #processNextHandshakeMessages}.
*
* @since 3.0
*/
private boolean statesChanged;
/**
* Current index of {@link #expectedStates}.
*/
private int statesIndex;
/**
* Currently expected states.
*
* @see #statesIndex
* @see #setExpectedStates(HandshakeState[])
* @since 3.0 (renamed, was states)
*/
private HandshakeState[] expectedStates;
private boolean eccExpected;
private boolean changeCipherSuiteMessageExpected;
private boolean contextEstablished;
private boolean handshakeCompleted;
private boolean handshakeAborted;
private boolean handshakeFailed;
private boolean pskRequestPending;
private boolean certificateVerificationPending;
private boolean certificateIdentityPending;
/**
* {@code true}, if the certificate identity request has completed,
* {@code false}, otherwise. Gets {@code true}, even if no matching identity
* is available.
*
* @since 3.0
*/
protected boolean certificateIdentityAvailable;
/**
* Other secret for ECDHE-PSK cipher suites.
* <a href="https://tools.ietf.org/html/rfc5489#page-4" target="_blank"> RFC 5489, other
* secret</a>
*/
private SecretKey otherSecret;
/**
* Cause for handshake failure.
*
* @see #setFailureCause(Throwable)
*/
private Throwable cause;
/**
* Custom argument for {@link ApplicationLevelInfoSupplier#getInfo(Principal, Object)}.
*
* @since 2.3
*/
private Object customArgument;
/**
* Application level info supplier. May be {@code null}.
*/
private ApplicationLevelInfoSupplier applicationLevelInfoSupplier;
/**
* Creates a new handshaker for negotiating a DTLS session with a given
* peer.
*
* @param initialRecordSequenceNo the initial record sequence number (since 3.0).
* @param initialMessageSeq the initial message sequence number to use and
* expect in the exchange of handshake messages with the peer.
* This parameter can be used to initialize the
* <em>message_seq</em> and <em>receive_next_seq</em> counters to
* a value larger than 0, e.g. if one or more cookie exchange
* round-trips have been performed with the peer before the
* handshake starts.
* @param recordLayer the object to use for sending flights to the peer.
* @param timer scheduled executor for flight retransmission (since 2.4).
* @param connection the connection related to this handshaker.
* @param config the dtls configuration
* @throws NullPointerException if any of the provided parameter is
* {@code null}
* @throws IllegalArgumentException if the initial record or message sequence number
* is negative
*/
@NoPublicAPI
protected Handshaker(long initialRecordSequenceNo, int initialMessageSeq, RecordLayer recordLayer,
ScheduledExecutorService timer, Connection connection, DtlsConnectorConfig config) {
if (recordLayer == null) {
throw new NullPointerException("Record layer must not be null");
} else if (timer == null) {
throw new NullPointerException("Timer must not be null");
} else if (connection == null) {
throw new NullPointerException("Connection must not be null");
} else if (config == null) {
throw new NullPointerException("Dtls Connector Config must not be null");
} else if (initialMessageSeq < 0) {
throw new IllegalArgumentException("Initial message sequence number must not be negative");
} else if (initialRecordSequenceNo < 0) {
throw new IllegalArgumentException("Initial record sequence number must not be negative");
}
this.sendMessageSequence = initialMessageSeq;
this.nextReceiveMessageSequence = initialMessageSeq;
this.context = new DTLSContext(initialRecordSequenceNo, config.get(DtlsConfig.DTLS_SUPPORT_KEY_MATERIAL_EXPORT));
this.recordLayer = recordLayer;
this.timer = timer;
this.connection = connection;
this.peer = connection.getPeerAddress();
this.peerToLog = StringUtil.toLog(this.peer);
this.connectionIdGenerator = config.getConnectionIdGenerator();
this.retransmissionTimeout = config.getTimeAsInt(DtlsConfig.DTLS_RETRANSMISSION_TIMEOUT, TimeUnit.MILLISECONDS);
this.maxRetransmissionTimeout = config.getTimeAsInt(DtlsConfig.DTLS_MAX_RETRANSMISSION_TIMEOUT, TimeUnit.MILLISECONDS);
this.additionalTimeoutForEcc = config.getTimeAsInt(DtlsConfig.DTLS_ADDITIONAL_ECC_TIMEOUT, TimeUnit.MILLISECONDS);
this.retransmissionRandomFactor = config.get(DtlsConfig.DTLS_RETRANSMISSION_INIT_RANDOM);
this.retransmissionTimeoutScale = config.get(DtlsConfig.DTLS_RETRANSMISSION_TIMEOUT_SCALE);
this.backOffRetransmission = config.getBackOffRetransmission();
this.maxRetransmissions = config.get(DtlsConfig.DTLS_MAX_RETRANSMISSIONS);
this.recordSizeLimit = config.get(DtlsConfig.DTLS_RECORD_SIZE_LIMIT);
this.maxFragmentedHandshakeMessageLength = config.get(DtlsConfig.DTLS_MAX_FRAGMENTED_HANDSHAKE_MESSAGE_LENGTH);
this.useMultiRecordMessages = config.get(DtlsConfig.DTLS_USE_MULTI_RECORD_MESSAGES);
this.useMultiHandshakeMessagesRecord = config.get(DtlsConfig.DTLS_USE_MULTI_HANDSHAKE_MESSAGE_RECORDS);
this.maxDeferredProcessedOutgoingApplicationDataMessages = config.get(DtlsConfig.DTLS_MAX_DEFERRED_OUTBOUND_APPLICATION_MESSAGES);
this.maxDeferredProcessedIncomingRecordsSize = config.get(DtlsConfig.DTLS_MAX_DEFERRED_INBOUND_RECORDS_SIZE);
this.sniEnabled = config.get(DtlsConfig.DTLS_USE_SERVER_NAME_INDICATION);
this.extendedMasterSecretMode = config.get(DtlsConfig.DTLS_EXTENDED_MASTER_SECRET_MODE);
this.useTruncatedCertificatePathForVerification = config.get(DtlsConfig.DTLS_TRUNCATE_CERTIFICATE_PATH_FOR_VALIDATION);
this.useEarlyStopRetransmission = config.get(DtlsConfig.DTLS_USE_EARLY_STOP_RETRANSMISSION);
this.certificateIdentityProvider = config.getCertificateIdentityProvider();
this.certificateVerifier = config.getAdvancedCertificateVerifier();
this.advancedPskStore = config.getAdvancedPskStore();
this.applicationLevelInfoSupplier = config.getApplicationLevelInfoSupplier();
this.inboundMessageBuffer = new InboundMessageBuffer();
this.ipv6 = connection.getPeerAddress().getAddress() instanceof Inet6Address;
// add all timeouts for retries and the initial timeout twice
// to get a short extra timespan for regular handshake timeouts
int timeoutMillis = Math.round(retransmissionTimeout * retransmissionRandomFactor);
if (CipherSuite.containsEccBasedCipherSuite(config.getSupportedCipherSuites())) {
timeoutMillis += additionalTimeoutForEcc;
}
timeoutMillis = Math.min(timeoutMillis, maxRetransmissionTimeout);
int expireTimeoutMillis = Math.min(Math.round(timeoutMillis * retransmissionTimeoutScale),
maxRetransmissionTimeout);
for (int retry = 0; retry < maxRetransmissions; ++retry) {
timeoutMillis = DTLSFlight.incrementTimeout(timeoutMillis, retransmissionTimeoutScale,
maxRetransmissionTimeout);
expireTimeoutMillis += timeoutMillis;
}
this.nanosExpireTimeout = TimeUnit.MILLISECONDS.toNanos(expireTimeoutMillis);
addSessionListener(connection.getSessionListener());
}
/**
* A queue for buffering inbound handshake records.
*/
private class InboundMessageBuffer {
private Record changeCipherSpec = null;
private SortedSet<Record> queue = new TreeSet<>(new Comparator<Record>() {
@Override
public int compare(Record r1, Record r2) {
return compareRecords(r1, r2);
}
});
boolean isEmpty() {
return queue.isEmpty();
}
/**
* Gets (and removes from the queue) the next record of the handshake
* message with this handshake's next expected message sequence number.
*
* @return the record or {@code null} if the queue does not contain the
* next expected message (yet)
*/
Record getNextRecord() {
if (isChangeCipherSpecMessageExpected() && changeCipherSpec != null) {
Record result = changeCipherSpec;
changeCipherSpec = null;
return result;
} else {
while (!queue.isEmpty()) {
Record record = queue.first();
int messageSeq = ((HandshakeMessage) record.getFragment()).getMessageSeq();
if (messageSeq > nextReceiveMessageSequence) {
break;
}
removeDeferredProcessedRecord(record, queue);
if (messageSeq == nextReceiveMessageSequence) {
return record;
}
}
}
return null;
}
/**
* Checks if a given record contains a message that can be processed
* immediately as part of the ongoing handshake.
* <p>
* This is the case, if the record is from the <em>current read
* epoch</em> and the contained message is either a
* <em>CHANGE_CIPHER_SPEC</em> message or a <em>HANDSHAKE</em> message
* with the next expected sequence number.
* <p>
* If the record contains a message having a sequence number that is
* higher than the next expected one, the record is put into a buffer
* for later processing when the message's sequence number becomes the
* next expected one.
*
* @param candidate the candidate record containing the message to check
* @return the record containing a message if the message is up for
* immediate processing or {@code null}, if the message cannot
* be processed immediately
* @throws IllegalArgumentException if the record's epoch differs from
* the session's read epoch
*/
Record getNextRecord(Record candidate) {
int recordEpoch = candidate.getEpoch();
int contextEpoch = context.getReadEpoch();
if (recordEpoch == contextEpoch) {
DTLSMessage fragment = candidate.getFragment();
switch (fragment.getContentType()) {
case CHANGE_CIPHER_SPEC:
// the following cases are possible:
// 1. the CCS message is the one we currently expect
// -> process it immediately
// 2. the CCS message is NOT YET expected, i.e. we are still missing one of the
// messages that logically need to be processed BEFORE the CCS message
// -> stash the CCS message and process it immediately once the missing messages
// have been processed
// 3. the FINISHED message is received BEFORE the CCS message
// -> stash the FINISHED message (note that the FINISHED message's epoch is
// current read epoch + 1 and thus will have been queued by the
// "else" branch below
if (isChangeCipherSpecMessageExpected()) {
return candidate;
} else if (changeCipherSpec == null) {
// store message for later processing
LOGGER.debug("Change Cipher Spec is not expected and therefore kept for later processing!");
changeCipherSpec = candidate;
return null;
} else {
// already stored message for later processing
LOGGER.debug("Change Cipher Spec is received again!");
return null;
}
case HANDSHAKE:
HandshakeMessage handshakeMessage = (HandshakeMessage) fragment;
int messageSeq = handshakeMessage.getMessageSeq();
if (messageSeq == nextReceiveMessageSequence) {
return candidate;
} else if (messageSeq > nextReceiveMessageSequence) {
LOGGER.debug(
"Queued newer {} message from current epoch, message_seq [{}] > next_receive_seq [{}]",
handshakeMessage.getMessageType(),
messageSeq,
nextReceiveMessageSequence);
addDeferredProcessedRecord(candidate, queue);
return null;
} else {
LOGGER.debug("Discarding old {} message_seq [{}] < next_receive_seq [{}]",
handshakeMessage.getMessageType(),
messageSeq,
nextReceiveMessageSequence);
return null;
}
default:
LOGGER.info("Cannot process message of type [{}], discarding...", fragment.getContentType());
return null;
}
} else {
throw new IllegalArgumentException("record epoch " + recordEpoch + " doesn't match dtls context " + contextEpoch);
}
}
}
/**
* Compare records by the handshake message sequence number and record
* sequence number
*
* @param r1 first record to be compared
* @param r2 second record to be compared
* @return a negative integer, zero, or a positive integer as the first
* record is before, equal to, or after the second.
*/
private static int compareRecords(Record r1, Record r2) {
if (r1.getEpoch() != r2.getEpoch()) {
throw new IllegalArgumentException(
"records with different epoch! " + r1.getEpoch() + " != " + r2.getEpoch());
}
HandshakeMessage h1 = (HandshakeMessage) r1.getFragment();
HandshakeMessage h2 = (HandshakeMessage) r2.getFragment();
if (h1.getMessageSeq() < h2.getMessageSeq()) {
return -1;
} else if (h1.getMessageSeq() > h2.getMessageSeq()) {
return 1;
}
if (r1.getSequenceNumber() < r2.getSequenceNumber()) {
return -1;
} else if (r1.getSequenceNumber() > r2.getSequenceNumber()) {
return 1;
}
return 0;
}
/**
* Check, if inbound messages are all processed.
*
* @return {@code true}, all inbound messages are processed, {@code false},
* some inbound messages are pending.
* @since 2.1
*/
public boolean isInboundMessageProcessed() {
return inboundMessageBuffer.isEmpty();
}
/**
* Processes a handshake record received from a peer based on the
* handshake's current state.
*
* This method passes the messages into the {@link #inboundMessageBuffer} and
* delegates processing of the ordered messages to the
* {@link #doProcessMessage(HandshakeMessage)} method. If
* {@link ChangeCipherSpecMessage} is processed, the
* {@link #nextEpochDeferredRecords} are passed again to the {@link RecordLayer} to
* get decrypted and processed.
*
* @param record the handshake record
* @throws HandshakeException if the record's plaintext fragment cannot be
* parsed into a handshake message or cannot be processed
* properly
* @throws IllegalArgumentException if the record's epoch differs from the
* DTLS context's read epoch
*/
public final void processMessage(Record record) throws HandshakeException {
int epoch = context.getReadEpoch();
if (epoch != record.getEpoch()) {
LOGGER.debug("Discarding {} message with wrong epoch received from peer [{}]:{}{}",
record.getType(), record.getPeerAddress(), StringUtil.lineSeparator(), record);
throw new IllegalArgumentException("processing record with wrong epoch! " + record.getEpoch() + " expected " + epoch);
}
if (pendingFlight.get() != null && (flightSendNanos - record.getReceiveNanos()) > 0) {
// (see https://github.com/eclipse/californium/issues/1034#issuecomment-526656943)
LOGGER.debug("Discarding {} message received from peer [{}] before last flight was sent:{}{}",
record.getType(), record.getPeerAddress(), StringUtil.lineSeparator(), record);
return;
}
Record recordToProcess = inboundMessageBuffer.getNextRecord(record);
if (recordToProcess != null) {
processNextMessages(recordToProcess);
}
}
/**
* Process next messages.
*
* Read next messages also from inbound message buffer. To protect against
* recursion, returns immediately, if called from
* {@link #doProcessMessage(HandshakeMessage)}.
*
* @param record message to process. Maybe {@code null} to start with the
* first message from inbound message buffer.
* @throws HandshakeException if an error occurs processing a message
* @since 2.3
*/
private void processNextMessages(Record record) throws HandshakeException {
if (recursionProtection.isHeldByCurrentThread()) {
LOGGER.warn("Called from doProcessMessage, return immediately to process next message!",
new Throwable("recursion-protection"));
return;
}
try {
final int epoch = context.getReadEpoch();
int bufferIndex = 0;
Record recordToProcess = record != null ? record : inboundMessageBuffer.getNextRecord();
while (recordToProcess != null) {
if (useMultiRecordMessages == null && recordToProcess.isFollowUpRecord()) {
useMultiRecordMessages = true;
}
DTLSMessage messageToProcess = recordToProcess.getFragment();
if (messageToProcess.getContentType() == ContentType.CHANGE_CIPHER_SPEC) {
expectMessage(messageToProcess);
// is thrown during processing
LOGGER.debug("Processing {} message from peer [{}]", messageToProcess.getContentType(),
peerToLog);
setCurrentReadState();
++statesIndex;
LOGGER.debug("Processed {} message from peer [{}]", messageToProcess.getContentType(),
peerToLog);
} else if (messageToProcess.getContentType() == ContentType.HANDSHAKE) {
boolean more = processNextHandshakeMessages(recordToProcess.getEpoch(), bufferIndex, (HandshakeMessage) messageToProcess);
context.markRecordAsRead(recordToProcess.getEpoch(), recordToProcess.getSequenceNumber());
if (!more) {
break;
}
} else {
throw new HandshakeException(
String.format("Received unexpected message type [%s], epoch %d from peer %s",
messageToProcess.getContentType(), recordToProcess.getEpoch(), peerToLog),
new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE));
}
recordToProcess = inboundMessageBuffer.getNextRecord();
if (epoch < context.getReadEpoch()) {
if (recordToProcess == null && !inboundMessageBuffer.isEmpty()) {
recordToProcess = inboundMessageBuffer.queue.first();
}
if (recordToProcess != null) {
HandshakeMessage left = (HandshakeMessage) recordToProcess.getFragment();
throw new HandshakeException(
String.format("Unexpected %s handshake message, epoch %d.%d/%d left from peer %s",
left.getMessageType(), recordToProcess.getEpoch(),
recordToProcess.getSequenceNumber(), left.getMessageSeq(), peerToLog),
new AlertMessage(AlertLevel.FATAL, AlertDescription.HANDSHAKE_FAILURE));
}
}
++bufferIndex;
}
if (epoch < context.getReadEpoch()) {
final SerialExecutor serialExecutor = connection.getExecutor();
final List<Record> records = takeDeferredRecordsOfNextEpoch();
if (deferredIncomingRecordsSize > 0) {
throw new HandshakeException(
String.format("Received message of next epoch left from peer %s", peerToLog),
new AlertMessage(AlertLevel.FATAL, AlertDescription.INTERNAL_ERROR));
}
for (Record deferredRecord : records) {
if (serialExecutor != null && !serialExecutor.isShutdown()) {
try {
final Record dRecord = deferredRecord;
serialExecutor.execute(new Runnable() {
@Override
public void run() {
recordLayer.processRecord(dRecord, connection);
}
});
continue;
} catch (RejectedExecutionException ex) {
LOGGER.debug("Execution rejected while processing record [type: {}, peer: {}]",
deferredRecord.getType(), deferredRecord.getPeerAddress(), ex);
}
}
// shutdown or rejected
recordLayer.processRecord(deferredRecord, connection);
}
}
} catch (RuntimeException e) {
LOGGER.warn("Cannot process handshake message from peer [{}] due to [{}]", peerToLog,
e.getMessage(), e);
AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.INTERNAL_ERROR);
throw new HandshakeException("Cannot process handshake message, caused by " + e.getMessage(), alert, e);
}
}
/**
* Process next {@link HandshakeMessage}.
*
* When {@link HandshakeMessage}s are chained, process all. To protected
* against recursion, returns immediately, if called from
* {@link #doProcessMessage(HandshakeMessage)}.
*
* @param epoch epoch of the based record
* @param bufferIndex index within buffered handshake message. Used only for
* logging.
* @param handshakeMessage the handshake message.
* @return {@code true}, continue processing record, {@code false}, stop
* processing records.
* @throws HandshakeException if an error occurs processing a message
* @since 2.4
*/
private boolean processNextHandshakeMessages(int epoch, int bufferIndex, HandshakeMessage handshakeMessage)
throws HandshakeException {
if (recursionProtection.isHeldByCurrentThread()) {
LOGGER.warn("Called from doProcessMessage, return immediately to process next message!",
new Throwable("recursion-protection"));
return false;
}
// only cancel on HANDSHAKE messages
// the very last flight CCS + FINISH
// must not be canceled before the FINISH
DTLSFlight flight = pendingFlight.get();
if (flight != null) {
LOGGER.debug("response for flight {} started", flight.getFlightNumber());
flight.setResponseStarted();
}
while (handshakeMessage != null) {
expectMessage(handshakeMessage);
if (handshakeMessage.getMessageType() == HandshakeType.FINISHED && epoch == 0) {
LOGGER.debug("FINISH with epoch 0 from peer [{}]!", peerToLog);
AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.UNEXPECTED_MESSAGE);
throw new HandshakeException("FINISH with epoch 0!", alert);
}
if (handshakeMessage instanceof FragmentedHandshakeMessage) {
handshakeMessage = reassembleFragment((FragmentedHandshakeMessage) handshakeMessage);
if (handshakeMessage == null) {
break;
}
}
if (handshakeMessage instanceof GenericHandshakeMessage) {
GenericHandshakeMessage genericMessage = (GenericHandshakeMessage) handshakeMessage;
handshakeMessage = HandshakeMessage.fromGenericHandshakeMessage(genericMessage, getParameter());
}
if (timeoutLastFlight != null) {
if (flight == null) {
if (cause != null) {
LOGGER.error("last flight missing, handshake already failed! {}", handshakeMessage, cause);
} else if (bufferIndex == 0) {
LOGGER.error("last flight missing, resend failed! {}", handshakeMessage);
} else {
LOGGER.error("last flight missing, resend for buffered message {} failed! {}", bufferIndex,
handshakeMessage);
}
return false;
}
// we already sent the last flight (including our FINISHED
// message), but the other peer does not seem to have received
// it because we received its finished message again, so we
// simply retransmit our last flight
LOGGER.debug("Received ({}) FINISHED message again, retransmitting last flight...", peerToLog);
flight.incrementTries();
// retransmit CCS and FINISH, back-off not required!
sendFlight(flight);
return false;
} else {
// is thrown during processing
if (LOGGER.isDebugEnabled()) {
StringBuilder msg = new StringBuilder();
msg.append(String.format("Processing %s message from peer [%s], seqn: [%d]",
handshakeMessage.getMessageType(), peerToLog,
handshakeMessage.getMessageSeq()));
if (LOGGER.isTraceEnabled()) {
msg.append(":").append(StringUtil.lineSeparator()).append(handshakeMessage);
}
LOGGER.debug(msg.toString());
}
if (epoch == 0) {
handshakeMessages.add(handshakeMessage);
}
statesChanged = false;
recursionProtection.lock();
try {
doProcessMessage(handshakeMessage);
} finally {
recursionProtection.unlock();
}
LOGGER.debug("Processed {} message from peer [{}]", handshakeMessage.getMessageType(),
peerToLog);
if (timeoutLastFlight == null) {
// last Flight may have changed processing
// the handshake message
++nextReceiveMessageSequence;
if (!statesChanged) {
++statesIndex;
}
}
handshakeMessage = handshakeMessage.getNextHandshakeMessage();
if (useMultiHandshakeMessagesRecord == null && handshakeMessage != null) {
useMultiHandshakeMessagesRecord = true;
}
}
}