-
Notifications
You must be signed in to change notification settings - Fork 361
/
DTLSConnector.java
3265 lines (3067 loc) · 125 KB
/
DTLSConnector.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, 2018 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
* Julien Vermillard - Sierra Wireless
* Kai Hudalla (Bosch Software Innovations GmbH) - add duplicate record detection
* Kai Hudalla (Bosch Software Innovations GmbH) - fix bug 462463
* Kai Hudalla (Bosch Software Innovations GmbH) - re-factor configuration
* Kai Hudalla (Bosch Software Innovations GmbH) - fix bug 464383
* Kai Hudalla (Bosch Software Innovations GmbH) - add support for stale
* session expiration (466554)
* Kai Hudalla (Bosch Software Innovations GmbH) - replace SessionStore with ConnectionStore
* keeping all information about the connection
* to a peer in a single place
* Kai Hudalla (Bosch Software Innovations GmbH) - fix bug 472196
* Achim Kraus, Kai Hudalla (Bosch Software Innovations GmbH) - fix bug 478538
* Kai Hudalla (Bosch Software Innovations GmbH) - derive max datagram size for outbound messages
* from network MTU
* Kai Hudalla (Bosch Software Innovations GmbH) - fix bug 483371
* Benjamin Cabe - fix typos in logger
* Kai Hudalla (Bosch Software Innovations GmbH) - use SessionListener to trigger sending of pending
* APPLICATION messages
* Bosch Software Innovations GmbH - set correlation context on sent/received messages
* (fix GitHub issue #1)
* Achim Kraus (Bosch Software Innovations GmbH) - use CorrelationContextMatcher
* for outgoing messages
* (fix GitHub issue #104)
* Achim Kraus (Bosch Software Innovations GmbH) - introduce synchronized getSocket()
* as pair to synchronized releaseSocket().
* Achim Kraus (Bosch Software Innovations GmbH) - restart internal executor
* Achim Kraus (Bosch Software Innovations GmbH) - processing retransmission of flight
* after last flight was sent.
* Achim Kraus (Bosch Software Innovations GmbH) - add onSent() and onError().
* issue #305
* Achim Kraus (Bosch Software Innovations GmbH) - Change RetransmitTask to
* schedule a "stripped job"
* instead of executing
* handleTimeout directly.
* cancel flight only, if they
* should not be retransmitted
* anymore.
* Achim Kraus (Bosch Software Innovations GmbH) - call handshakeFailed on
* terminateOngoingHandshake,
* processAlertRecord,
* handleTimeout,
* and add error callback in
* newDeferredMessageSender.
* Achim Kraus (Bosch Software Innovations GmbH) - reuse receive buffer and packet.
* Achim Kraus (Bosch Software Innovations GmbH) - use socket's reuseAddress only
* if bindAddress determines a port
* Achim Kraus (Bosch Software Innovations GmbH) - introduce protocol,
* remove scheme
* Achim Kraus (Bosch Software Innovations GmbH) - check for cancelled retransmission
* before sending.
* Achim Kraus (Bosch Software Innovations GmbH) - move application handler call
* out of synchronized block
* Achim Kraus (Bosch Software Innovations GmbH) - move creation of endpoint context
* to DTLSSession
* Bosch Software Innovations GmbH - migrate to SLF4J
* Achim Kraus (Bosch Software Innovations GmbH) - add automatic resumption
* Achim Kraus (Bosch Software Innovations GmbH) - change receiver thread to
* daemon
* Achim Kraus (Bosch Software Innovations GmbH) - response with alert, if
* connection store is exhausted.
* Achim Kraus (Bosch Software Innovations GmbH) - fix double incrementing
* pending outgoing message downcounter.
* Achim Kraus (Bosch Software Innovations GmbH) - update dtls session timestamp only,
* if access is validated with the MAC
* Achim Kraus (Bosch Software Innovations GmbH) - fix session resumption with session cache
* issue #712
* execute jobs after shutdown to ensure,
* onError is called for all pending messages.
* Achim Kraus (Bosch Software Innovations GmbH) - fix issues #716 and #717
* change scopes to protected to support
* subclass specific implementations.
* Achim Kraus (Bosch Software Innovations GmbH) - use session ticket when sending messages
* over a connection marked for resumption.
* Achim Kraus (Bosch Software Innovations GmbH) - issue 744: use handshaker as
* parameter for session listener.
* Move session listener callback out of sync
* block of processApplicationDataRecord.
* Achim Kraus (Bosch Software Innovations GmbH) - add handshakeFlightRetransmitted
* Achim Kraus (Bosch Software Innovations GmbH) - add onConnecting and onDtlsRetransmission
* Achim Kraus (Bosch Software Innovations GmbH) - redesign connection session listener to
* ensure, that the session listener methods
* are called via the handshaker.
* Move handshakeCompleted out on synchronized block.
* When handshaker replaced, called handshakeFailed
* on old to trigger sent error for pending messages.
* Reuse ongoing handshaker instead of creating a new
* one.
* Achim Kraus (Bosch Software Innovations GmbH) - add multiple receiver threads.
* move default thread numbers to configuration.
* Achim Kraus (Bosch Software Innovations GmbH) - add cause to handshake failure.
* Achim Kraus (Bosch Software Innovations GmbH) - remove HELLO_VERIFY_REQUEST
* from resumption handshakes
* Achim Kraus (Bosch Software Innovations GmbH) - extend deferred processed messages to
* limited number of incoming and outgoing messages
* extend executor names with specific prefix.
* Achim Kraus (Bosch Software Innovations GmbH) - fix reuse of already stopped serial
* executors.
* Achim Kraus (Bosch Software Innovations GmbH) - remove unused RecordLayer.sendRecord
* Achim Kraus (Bosch Software Innovations GmbH) - redesign DTLSFlight and RecordLayer
* add timeout for handshakes
* Achim Kraus (Bosch Software Innovations GmbH) - move serial executor into connection
* process new CLIENT_HELLOs without
* serial executor.
******************************************************************************/
package org.eclipse.californium.scandium;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.PortUnreachableException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.eclipse.californium.elements.Connector;
import org.eclipse.californium.elements.DtlsEndpointContext;
import org.eclipse.californium.elements.EndpointContext;
import org.eclipse.californium.elements.EndpointContextMatcher;
import org.eclipse.californium.elements.exception.EndpointMismatchException;
import org.eclipse.californium.elements.exception.EndpointUnconnectedException;
import org.eclipse.californium.elements.exception.MulticastNotSupportedException;
import org.eclipse.californium.elements.RawData;
import org.eclipse.californium.elements.RawDataChannel;
import org.eclipse.californium.elements.util.ClockUtil;
import org.eclipse.californium.elements.util.DaemonThreadFactory;
import org.eclipse.californium.elements.util.DatagramReader;
import org.eclipse.californium.elements.util.ExecutorsUtil;
import org.eclipse.californium.elements.util.LeastRecentlyUsedCache;
import org.eclipse.californium.elements.util.NamedThreadFactory;
import org.eclipse.californium.elements.util.NetworkInterfacesUtil;
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.config.DtlsConnectorConfig;
import org.eclipse.californium.scandium.dtls.AlertMessage;
import org.eclipse.californium.scandium.dtls.AlertMessage.AlertDescription;
import org.eclipse.californium.scandium.dtls.AlertMessage.AlertLevel;
import org.eclipse.californium.scandium.dtls.ApplicationMessage;
import org.eclipse.californium.scandium.dtls.AvailableConnections;
import org.eclipse.californium.scandium.dtls.ClientHandshaker;
import org.eclipse.californium.scandium.dtls.ClientHello;
import org.eclipse.californium.scandium.dtls.Connection;
import org.eclipse.californium.scandium.dtls.ConnectionEvictedException;
import org.eclipse.californium.scandium.dtls.ConnectionId;
import org.eclipse.californium.scandium.dtls.ConnectionIdGenerator;
import org.eclipse.californium.scandium.dtls.HandshakeResult;
import org.eclipse.californium.scandium.dtls.HandshakeResultHandler;
import org.eclipse.californium.scandium.dtls.ContentType;
import org.eclipse.californium.scandium.dtls.DTLSMessage;
import org.eclipse.californium.scandium.dtls.DTLSSession;
import org.eclipse.californium.scandium.dtls.DtlsException;
import org.eclipse.californium.scandium.dtls.DtlsHandshakeException;
import org.eclipse.californium.scandium.dtls.FragmentedHandshakeMessage;
import org.eclipse.californium.scandium.dtls.HandshakeException;
import org.eclipse.californium.scandium.dtls.HandshakeMessage;
import org.eclipse.californium.scandium.dtls.Handshaker;
import org.eclipse.californium.scandium.dtls.HelloVerifyRequest;
import org.eclipse.californium.scandium.dtls.InMemoryConnectionStore;
import org.eclipse.californium.scandium.dtls.PskSecretResult;
import org.eclipse.californium.scandium.dtls.MaxFragmentLengthExtension;
import org.eclipse.californium.scandium.dtls.ProtocolVersion;
import org.eclipse.californium.scandium.dtls.Record;
import org.eclipse.californium.scandium.dtls.RecordLayer;
import org.eclipse.californium.scandium.dtls.ResumingClientHandshaker;
import org.eclipse.californium.scandium.dtls.ResumingServerHandshaker;
import org.eclipse.californium.scandium.dtls.ResumptionSupportingConnectionStore;
import org.eclipse.californium.scandium.dtls.ServerHandshaker;
import org.eclipse.californium.scandium.dtls.ServerNameExtension;
import org.eclipse.californium.scandium.dtls.SessionAdapter;
import org.eclipse.californium.scandium.dtls.SessionCache;
import org.eclipse.californium.scandium.dtls.SessionId;
import org.eclipse.californium.scandium.dtls.SessionListener;
import org.eclipse.californium.scandium.dtls.SessionTicket;
import org.eclipse.californium.scandium.dtls.cipher.CipherSuite;
import org.eclipse.californium.scandium.dtls.pskstore.AdvancedPskStore;
import org.eclipse.californium.scandium.dtls.x509.NewAdvancedCertificateVerifier;
import org.eclipse.californium.scandium.util.SecretUtil;
import org.eclipse.californium.scandium.util.ServerNames;
/**
* A {@link Connector} using <em>Datagram TLS</em> (DTLS) as specified in
* <a href="http://tools.ietf.org/html/rfc6347">RFC 6347</a> for securing data
* exchanged between networked clients and a server application.
*
* Note: using IPv6 interfaces with multiple addresses including permanent and
* temporary (with potentially several different prefixes) currently causes
* issues on the server side. The outgoing traffic in response to incoming may
* select a different source address than the incoming destination address. To
* overcome this, please ensure that the 'any address' is not used on the server
* side and a separate Connector is created for each address to receive incoming
* traffic.
*/
public class DTLSConnector implements Connector, RecordLayer {
/**
* The {@code EndpointContext} key used to store the host name indicated by a
* client in an SNI hello extension.
*/
public static final String KEY_TLS_SERVER_HOST_NAME = "TLS_SERVER_HOST_NAME";
private static final Logger LOGGER = LoggerFactory.getLogger(DTLSConnector.class);
private static final Logger DROP_LOGGER = LoggerFactory.getLogger(LOGGER.getName() + ".drops");
private static final int MAX_PLAINTEXT_FRAGMENT_LENGTH = 16384; // max. DTLSPlaintext.length (2^14 bytes)
private static final int MAX_CIPHERTEXT_EXPANSION = CipherSuite.getOverallMaxCiphertextExpansion();
private static final int MAX_DATAGRAM_BUFFER_SIZE = MAX_PLAINTEXT_FRAGMENT_LENGTH
+ DTLSSession.DTLS_HEADER_LENGTH
+ MAX_CIPHERTEXT_EXPANSION;
/**
* Additional padding used by the new record type introduced with the
* connection id. May be randomized to obfuscate the payload length. Due to
* the ongoing discussion in draft-ietf-tls-dtls-connection-id, currently
* only a fixed value.
*/
private static final int TLS12_CID_PADDING = 0;
private static final long CLIENT_HELLO_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(60);
/**
* Indicates, that MDC support is available.
*
* @see MDC
*/
private static final boolean MDC_SUPPORT;
static {
boolean mdc = false;
try {
MDC.clear();
mdc = true;
} catch (Throwable ex) {
}
MDC_SUPPORT = mdc;
}
/** all the configuration options for the DTLS connector */
protected final DtlsConnectorConfig config;
private final ResumptionSupportingConnectionStore connectionStore;
/**
* General auto resumption timeout in milliseconds. {@code null}, if auto
* resumption is not used.
*/
private final Long autoResumptionTimeoutMillis;
private final int thresholdHandshakesWithoutVerifiedPeer;
private final AtomicInteger pendingHandshakesWithoutVerifiedPeer = new AtomicInteger();
protected final DtlsHealth health;
private final boolean serverOnly;
private final String defaultHandshakeMode;
/**
* Apply record filter only for records within the receive window.
*/
private final int useExtendedWindowFilter;
/**
* Apply record filter.
*/
private final boolean useFilter;
/**
* Apply address update only for newer records based on epoch/sequence_number.
*/
private final boolean useCidUpdateAddressOnNewerRecordFilter;
/**
* (Down-)counter for pending outbound messages. Initialized with
* {@link DtlsConnectorConfig#getOutboundMessageBufferSize()}.
*/
private final AtomicInteger pendingOutboundMessagesCountdown = new AtomicInteger();
private final List<Thread> receiverThreads = new LinkedList<Thread>();
/**
* Configure connection id generator. May be {@code null}, if connection id
* should not be supported.
*/
protected final ConnectionIdGenerator connectionIdGenerator;
/**
* Protocol version to use for sending a hello verify request. Default
* {@code null} to reply the client's version.
*
* @since 2.5
*/
private final ProtocolVersion protocolVersionForHelloVerifyRequests;
private ScheduledFuture<?> statusLogger;
private InetSocketAddress lastBindAddress;
/**
* Provided or configured maximum transmission unit.
*/
private Integer maximumTransmissionUnit;
/**
* IPv4 maximum transmission unit.
* @since 2.4
*/
private int ipv4Mtu = DEFAULT_IPV4_MTU;
/**
* IPv6 maximum transmission unit.
* @since 2.4
*/
private int ipv6Mtu = DEFAULT_IPV6_MTU;
protected int inboundDatagramBufferSize = MAX_DATAGRAM_BUFFER_SIZE;
private CookieGenerator cookieGenerator = new CookieGenerator();
private Object alertHandlerLock= new Object();
private volatile DatagramSocket socket;
/** The timer daemon to schedule retransmissions. */
protected ScheduledExecutorService timer;
/** Indicates whether the connector has started and not stopped yet */
private AtomicBoolean running = new AtomicBoolean(false);
/**
* Endpoint context matcher for outgoing messages.
*
* @see #setEndpointContextMatcher(EndpointContextMatcher)
* @see #getEndpointContextMatcher()
* @see #sendMessage(RawData, Connection)
* @see #sendMessage(RawData, Connection, DTLSSession)
*/
private volatile EndpointContextMatcher endpointContextMatcher;
private volatile RawDataChannel messageHandler;
private AlertHandler alertHandler;
private SessionListener sessionListener;
private ConnectionExecutionListener connectionExecutionListener;
private ExecutorService executorService;
private boolean hasInternalExecutor;
/**
* Creates a DTLS connector from a given configuration object using the
* standard in-memory {@code ConnectionStore}.
*
* @param configuration the configuration options
* @throws NullPointerException if the configuration is {@code null}
*/
public DTLSConnector(DtlsConnectorConfig configuration) {
this(configuration, (SessionCache) null);
}
/**
* Creates a DTLS connector for a given set of configuration options.
*
* @param configuration The configuration options.
* @param sessionCache An (optional) cache for {@code DTLSSession} objects
* that can be used for persisting and/or sharing of session
* state among multiple instances of {@code DTLSConnector}.
* Whenever a handshake with a client is finished the negotiated
* session is put to this cache. Similarly, whenever a client
* wants to perform an abbreviated handshake based on an existing
* session the connection store will try to retrieve the session
* from this cache if it is not available from the connection
* store's in-memory (first-level) cache.
* @throws NullPointerException if the configuration is {@code null}.
*/
public DTLSConnector(final DtlsConnectorConfig configuration, final SessionCache sessionCache) {
this(configuration, createConnectionStore(configuration, sessionCache));
}
/**
* Create and initialize default connection store.
*
* @param configuration configuration for initialization
* @param sessionCache An (optional) cache for {@code DTLSSession} objects
* that can be used for persisting and/or sharing of session
* state among multiple instances of {@code DTLSConnector}.
* Whenever a handshake with a client is finished the negotiated
* session is put to this cache. Similarly, whenever a client
* wants to perform an abbreviated handshake based on an existing
* session the connection store will try to retrieve the session
* from this cache if it is not available from the connection
* store's in-memory (first-level) cache.
* @return connection store
* @since 2.5
*/
protected static ResumptionSupportingConnectionStore createConnectionStore(DtlsConnectorConfig configuration,
SessionCache sessionCache) {
return new InMemoryConnectionStore(configuration.getMaxConnections(),
configuration.getStaleConnectionThreshold(), sessionCache).setTag(configuration.getLoggingTag());
}
/**
* Creates a DTLS connector for a given set of configuration options.
* <p>
* The connection store must use the same connection id generator as
* configured in the provided configuration. The current implementation synchronize on the connection store,
* therefore it is important not to use the connection store within a
* different synchronization scope.
* </p>
*
* @param configuration The configuration options.
* @param connectionStore The registry to use for managing connections to
* peers.
* @throws NullPointerException if any of the parameters is {@code null}.
* @throws IllegalArgumentException if the connection store uses a different
* cid generator than the configuration.
*/
protected DTLSConnector(final DtlsConnectorConfig configuration, final ResumptionSupportingConnectionStore connectionStore) {
if (configuration == null) {
throw new NullPointerException("Configuration must not be null");
} else if (connectionStore == null) {
throw new NullPointerException("Connection store must not be null");
} else {
this.config = configuration;
this.connectionIdGenerator = config.getConnectionIdGenerator();
this.protocolVersionForHelloVerifyRequests = config.getProtocolVersionForHelloVerifyRequests();
this.pendingOutboundMessagesCountdown.set(config.getOutboundMessageBufferSize());
this.autoResumptionTimeoutMillis = config.getAutoResumptionTimeoutMillis();
this.serverOnly = config.isServerOnly();
this.defaultHandshakeMode = config.getDefaultHandshakeMode();
this.useExtendedWindowFilter = config.useExtendedWindowFilter();
this.useFilter = config.useAntiReplayFilter() || useExtendedWindowFilter != 0;
this.useCidUpdateAddressOnNewerRecordFilter = config.useCidUpdateAddressOnNewerRecordFilter();
this.connectionStore = connectionStore;
this.connectionStore.attach(connectionIdGenerator);
this.connectionStore.setConnectionListener(config.getConnectionListener());
ConnectionListener listener = config.getConnectionListener();
if (listener instanceof ConnectionExecutionListener) {
this.connectionExecutionListener = (ConnectionExecutionListener) listener;
}
HandshakeResultHandler handler = new HandshakeResultHandler() {
@Override
public void apply(PskSecretResult secretResult) {
processAsynchronousHandshakeResult(secretResult);
}
@Override
public void apply(HandshakeResult connectionResult) {
processAsynchronousHandshakeResult(connectionResult);
}
};
AdvancedPskStore advancedPskStore = config.getAdvancedPskStore();
if (advancedPskStore != null) {
advancedPskStore.setResultHandler(handler);
}
NewAdvancedCertificateVerifier certificateVerifier = config.getAdvancedCertificateVerifier();
if (certificateVerifier != null) {
certificateVerifier.setResultHandler(handler);
}
DtlsHealth healthHandler = config.getHealthHandler();
Integer healthStatusInterval = config.getHealthStatusInterval();
// this is a useful health metric
// that could later be exported to some kind of monitoring interface
if (healthHandler == null && healthStatusInterval != null && healthStatusInterval > 0) {
healthHandler = createDefaultHealthHandler(config);
if (!healthHandler.isEnabled()) {
healthHandler = null;
}
}
this.health = healthHandler;
this.sessionListener = new SessionAdapter() {
@Override
public void sessionEstablished(Handshaker handshaker, DTLSSession establishedSession)
throws HandshakeException {
DTLSConnector.this.sessionEstablished(handshaker, establishedSession);
}
@Override
public void handshakeCompleted(final Handshaker handshaker) {
if (health != null) {
health.endHandshake(true);
}
final Connection connection = handshaker.getConnection();
ScheduledExecutorService timer = DTLSConnector.this.timer;
if (timer != null) {
try {
timer.schedule(new Runnable() {
@Override
public void run() {
connection.startByClientHello(null);
}
}, CLIENT_HELLO_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
return;
} catch (RejectedExecutionException ex) {
LOGGER.debug("stopping.");
}
}
// fallback, if execution is rejected
connection.startByClientHello(null);
}
@Override
public void handshakeFailed(Handshaker handshaker, Throwable error) {
if (health != null) {
health.endHandshake(false);
}
List<RawData> listOut = handshaker.takeDeferredApplicationData();
if (!listOut.isEmpty()) {
LOGGER.debug("Handshake with [{}] failed, report error to deferred {} messages",
handshaker.getPeerAddress(), listOut.size());
for (RawData message : listOut) {
message.onError(error);
}
}
Connection connection = handshaker.getConnection();
if (handshaker.isRemovingConnection()) {
connectionStore.remove(connection, false);
} else if (handshaker.isProbing()) {
LOGGER.debug("Handshake with [{}] failed within probe!", handshaker.getPeerAddress());
} else if (connection.getEstablishedSession() == handshaker.getSession()) {
if (error instanceof HandshakeException) {
AlertMessage alert = ((HandshakeException)error).getAlert();
if (alert != null && alert.getDescription() == AlertDescription.CLOSE_NOTIFY) {
LOGGER.debug("Handshake with [{}] closed after session was established!",
handshaker.getPeerAddress());
} else {
LOGGER.warn("Handshake with [{}] failed after session was established! {}",
handshaker.getPeerAddress(), alert);
}
} else {
// failure after established (last FINISH),
// but before completed (first data)
if (error instanceof ConnectionEvictedException) {
LOGGER.debug("Handshake with [{}] never get APPLICATION_DATA",
handshaker.getPeerAddress(), error);
} else {
LOGGER.warn("Handshake with [{}] failed after session was established!",
handshaker.getPeerAddress(), error);
}
}
} else if (connection.hasEstablishedSession()) {
LOGGER.warn("Handshake with [{}] failed, but has an established session!",
handshaker.getPeerAddress());
} else {
LOGGER.warn("Handshake with [{}] failed, connection preserved!", handshaker.getPeerAddress());
}
}
};
int maxConnections = config.getMaxConnections();
// calculate absolute threshold from relative.
long thresholdInPercent = config.getVerifyPeersOnResumptionThreshold();
long threshold = (((long) maxConnections * thresholdInPercent) + 50L) / 100L;
if (threshold == 0 && thresholdInPercent > 0) {
threshold = 1;
}
this.thresholdHandshakesWithoutVerifiedPeer = (int) threshold;
}
}
/**
* Create default health handler.
*
* @param configuration configuration
* @return default health handler.
* @since 2.5
*/
protected DtlsHealth createDefaultHealthHandler(DtlsConnectorConfig configuration) {
return new DtlsHealthLogger(configuration.getLoggingTag());
}
private final void sessionEstablished(Handshaker handshaker, final DTLSSession establishedSession)
throws HandshakeException {
try {
final Connection connection = handshaker.getConnection();
connectionStore.putEstablishedSession(establishedSession, connection);
final SerialExecutor serialExecutor = connection.getExecutor();
List<RawData> listOut = handshaker.takeDeferredApplicationData();
if (!listOut.isEmpty()) {
LOGGER.trace("Session with [{}] established, now process deferred {} messages",
establishedSession.getPeer(), listOut.size());
for (RawData message : listOut) {
final RawData rawData = message;
serialExecutor.execute(new Runnable() {
@Override
public void run() {
sendMessage(rawData, connection, establishedSession);
}
});
}
}
List<Record> listIn = handshaker.takeDeferredRecords();
if (!listIn.isEmpty()) {
LOGGER.trace("Session with [{}] established, now process deferred {} messages",
establishedSession.getPeer(), listIn.size());
for (Record message : listIn) {
final Record record = message;
serialExecutor.execute(new Runnable() {
@Override
public void run() {
processRecord(record, connection);
}
});
}
}
} catch (RejectedExecutionException ex) {
LOGGER.debug("stopping.");
}
}
/**
* Called after initialization of new create handshaker.
*
* Intended to be used for subclass specific handshaker initialization.
*
* @param handshaker new create handshaker
*/
protected void onInitializeHandshaker(final Handshaker handshaker) {
}
/**
* Initialize new create handshaker.
*
* Add {@link #sessionListener}.
*
* @param handshaker new create handshaker
*/
private final void initializeHandshaker(final Handshaker handshaker) {
if (sessionListener != null) {
handshaker.addSessionListener(sessionListener);
if (health != null) {
health.startHandshake();
}
}
onInitializeHandshaker(handshaker);
}
/**
* Sets the executor to be used for processing records.
* <p>
* If this property is not set before invoking the {@linkplain #start()
* start method}, a new {@link ExecutorService} is created with a thread
* pool of {@linkplain DtlsConnectorConfig#getConnectionThreadCount() size}.
*
* This helps with performing multiple handshakes in parallel, in particular if the key exchange
* requires a look up of identities, e.g. in a database or using a web service.
* <p>
* If this method is used to set an executor, the executor will <em>not</em> be shut down
* by the {@linkplain #stop() stop method}.
*
* @param executor The executor.
* @throws IllegalStateException if a new executor is set and this connector is already running.
*/
public final synchronized void setExecutor(ExecutorService executor) {
if (this.executorService != executor) {
if (running.get()) {
throw new IllegalStateException("cannot set new executor while connector is running");
} else {
this.executorService = executor;
}
}
}
/**
* Closes a connection with a given peer.
*
* The connection is gracefully shut down, i.e. a final
* <em>CLOSE_NOTIFY</em> alert message is sent to the peer
* prior to removing all session state.
*
* @param peerAddress the address of the peer to close the connection to
* @throws IllegalStateException if executor cache is exceeded.
*/
public final void close(InetSocketAddress peerAddress) {
final Connection connection = getConnection(peerAddress, null, false);
if (connection != null && connection.hasEstablishedSession()) {
SerialExecutor serialExecutor = connection.getExecutor();
serialExecutor.execute(new Runnable() {
@Override
public void run() {
DTLSSession session = connection.getEstablishedSession();
if (session != null) {
terminateConnection(connection, new AlertMessage(AlertLevel.WARNING,
AlertDescription.CLOSE_NOTIFY, connection.getPeerAddress()), session);
}
}
});
}
}
/**
* {@inheritDoc}
*/
@Override
public final synchronized void start() throws IOException {
start(config.getAddress());
}
/**
* Re-starts the connector binding to the same IP address and port as
* on the previous start.
*
* Note: intended for unit tests only!
*
* @throws IOException if the connector cannot be bound to the previous
* IP address and port
*/
final synchronized void restart() throws IOException {
if (lastBindAddress != null) {
start(lastBindAddress);
} else {
throw new IllegalStateException("Connector has never been started before");
}
}
private synchronized ExecutorService getExecutorService() {
return executorService;
}
/**
* Start connector.
*
* @param bindAddress address to bind socket.
* @throws IOException I/O error
*/
protected void start(InetSocketAddress bindAddress) throws IOException {
if (running.get()) {
return;
}
init(bindAddress, new DatagramSocket(null), config.getMaxTransmissionUnit());
}
/**
* Initialize socket ad start connector.
*
* @param bindAddress address to bind socket
* @param socket socket
* @param mtu mtu of socket, or {@code null}, if socket implementation
* doesn't use a special mtu.
* @throws IOException I/O error
* @since 2.1
*/
protected void init(InetSocketAddress bindAddress, DatagramSocket socket, Integer mtu) throws IOException {
this.socket = socket;
pendingOutboundMessagesCountdown.set(config.getOutboundMessageBufferSize());
if (bindAddress.getPort() != 0 && config.isAddressReuseEnabled()) {
// make it easier to stop/start a server consecutively without delays
LOGGER.info("Enable address reuse for socket!");
socket.setReuseAddress(true);
if (!socket.getReuseAddress()) {
LOGGER.warn("Enable address reuse for socket failed!");
}
}
Integer size = config.getSocketReceiveBufferSize();
try {
if (size != null && size != 0) {
socket.setReceiveBufferSize(size);
}
size = config.getSocketSendBufferSize();
if (size != null && size != 0) {
socket.setSendBufferSize(size);
}
} catch (IllegalArgumentException ex) {
LOGGER.error("failed to apply {}", size, ex);
}
// don't try to access the buffer sizes,
// when receive may already lock the socket!
int recvBuffer = socket.getReceiveBufferSize();
int sendBuffer = socket.getSendBufferSize();
if (!socket.isBound()) {
socket.bind(bindAddress);
}
if (lastBindAddress != null && (!socket.getLocalAddress().equals(lastBindAddress.getAddress()) || socket.getLocalPort() != lastBindAddress.getPort())){
if (connectionStore instanceof ResumptionSupportingConnectionStore) {
((ResumptionSupportingConnectionStore) connectionStore).markAllAsResumptionRequired();
} else {
connectionStore.clear();
}
}
if (config.getMaxFragmentLengthCode() != null) {
MaxFragmentLengthExtension.Length lengthCode = MaxFragmentLengthExtension.Length.fromCode(
config.getMaxFragmentLengthCode());
// reduce inbound buffer size accordingly
inboundDatagramBufferSize = lengthCode.length()
+ MAX_CIPHERTEXT_EXPANSION
+ DTLSSession.DTLS_HEADER_LENGTH; // 12 bytes DTLS message headers, 13 bytes DTLS record headers
}
if (config.getMaxTransmissionUnit() != null) {
this.maximumTransmissionUnit = config.getMaxTransmissionUnit();
LOGGER.info("Configured MTU [{}]", this.maximumTransmissionUnit);
} else if (mtu != null) {
this.maximumTransmissionUnit = mtu;
LOGGER.info("Forced MTU [{}]", this.maximumTransmissionUnit);
} else {
InetAddress localInterfaceAddress = bindAddress.getAddress();
if (localInterfaceAddress.isAnyLocalAddress()) {
ipv4Mtu = NetworkInterfacesUtil.getIPv4Mtu();
ipv6Mtu = NetworkInterfacesUtil.getIPv6Mtu();
LOGGER.info("multiple network interfaces, using smallest MTU [IPv4 {}, IPv6 {}]", ipv4Mtu, ipv6Mtu);
} else {
NetworkInterface ni = NetworkInterface.getByInetAddress(localInterfaceAddress);
boolean ipv6 = localInterfaceAddress instanceof Inet6Address;
if (ni != null && ni.getMTU() > 0) {
if (ipv6) {
ipv6Mtu = ni.getMTU();
} else {
ipv4Mtu = ni.getMTU();
}
} else if (ipv6) {
ipv6Mtu = NetworkInterfacesUtil.getIPv6Mtu();
LOGGER.info("Cannot determine MTU of network interface, using minimum MTU [{}] of IPv6 instead", ipv6Mtu);
} else {
ipv4Mtu = NetworkInterfacesUtil.getIPv4Mtu();
LOGGER.info("Cannot determine MTU of network interface, using minimum MTU [{}] of IPv4 instead", ipv4Mtu);
}
}
if (inboundDatagramBufferSize > config.getMaxTransmissionUnitLimit()) {
if (ipv4Mtu > config.getMaxTransmissionUnitLimit()) {
ipv4Mtu = config.getMaxTransmissionUnitLimit();
LOGGER.info("Limit MTU IPv4[{}]", ipv4Mtu);
}
if (ipv6Mtu > config.getMaxTransmissionUnitLimit()) {
ipv6Mtu = config.getMaxTransmissionUnitLimit();
LOGGER.info("Limit MTU IPv6[{}]", ipv6Mtu);
}
} else {
if (ipv4Mtu > inboundDatagramBufferSize) {
ipv4Mtu = inboundDatagramBufferSize;
LOGGER.info("Buffersize MTU IPv4[{}]", ipv4Mtu);
}
if (ipv6Mtu > inboundDatagramBufferSize) {
ipv6Mtu = inboundDatagramBufferSize;
LOGGER.info("Buffersize MTU IPv6[{}]", ipv6Mtu);
}
}
}
lastBindAddress = new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort());
if (executorService instanceof ScheduledExecutorService) {
timer = (ScheduledExecutorService) executorService;
} else {
timer = ExecutorsUtil.newSingleThreadScheduledExecutor(new DaemonThreadFactory(
"DTLS-Timer-" + lastBindAddress + "#", NamedThreadFactory.SCANDIUM_THREAD_GROUP)); //$NON-NLS-1$
}
if (executorService == null) {
int threadCount = config.getConnectionThreadCount();
if (threadCount > 1) {
executorService = ExecutorsUtil.newFixedThreadPool(threadCount - 1, new DaemonThreadFactory(
"DTLS-Worker-" + lastBindAddress + "#", NamedThreadFactory.SCANDIUM_THREAD_GROUP)); //$NON-NLS-1$
} else {
executorService = timer;
}
this.hasInternalExecutor = true;
}
running.set(true);
int receiverThreadCount = config.getReceiverThreadCount();
for (int i = 0; i < receiverThreadCount; i++) {
Worker receiver = new Worker("DTLS-Receiver-" + i + "-" + lastBindAddress) {
private final byte[] receiverBuffer = new byte[inboundDatagramBufferSize];
private final DatagramPacket packet = new DatagramPacket(receiverBuffer, inboundDatagramBufferSize);
@Override
public void doWork() throws Exception {
if (MDC_SUPPORT) {
MDC.clear();
}
packet.setData(receiverBuffer);
receiveNextDatagramFromNetwork(packet);
}
};
receiver.setDaemon(true);
receiver.start();
receiverThreads.add(receiver);
}
String mtuDescription = maximumTransmissionUnit != null ? maximumTransmissionUnit.toString() : "IPv4 " + ipv4Mtu + " / IPv6 " + ipv6Mtu;
LOGGER.info("DTLSConnector listening on {}, recv buf = {}, send buf = {}, recv packet size = {}, MTU = {}",
lastBindAddress, recvBuffer, sendBuffer, inboundDatagramBufferSize, mtuDescription);
// this is a useful health metric
// that could later be exported to some kind of monitoring interface
if (health != null && health.isEnabled()) {
final Integer healthStatusInterval = config.getHealthStatusInterval();
if (healthStatusInterval != null) {
statusLogger = timer.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
health.dump(config.getLoggingTag(), config.getMaxConnections(), connectionStore.remainingCapacity(), pendingHandshakesWithoutVerifiedPeer.get());
}
}, healthStatusInterval, healthStatusInterval, TimeUnit.SECONDS);
}
}
}
/**
* Force connector to an abbreviated handshake. See <a href="https://tools.ietf.org/html/rfc5246#section-7.3">RFC 5246</a>.
*
* The abbreviated handshake will be done next time data will be sent with {@link #send(RawData)}.
* @param peer the peer for which we will force to do an abbreviated handshake
*/
public final synchronized void forceResumeSessionFor(InetSocketAddress peer) {
Connection peerConnection = connectionStore.get(peer);
if (peerConnection != null && peerConnection.hasEstablishedSession()) {
peerConnection.setResumptionRequired(true);
}
}
/**
* Marks all established sessions currently maintained by this connector to be resumed by means
* of an <a href="https://tools.ietf.org/html/rfc5246#section-7.3">abbreviated handshake</a> the
* next time a message is being sent to the corresponding peer using {@link #send(RawData)}.
* <p>
* This method's execution time is proportional to the number of connections this connector maintains.
*/
public final synchronized void forceResumeAllSessions() {
connectionStore.markAllAsResumptionRequired();
}
/**
* Clears all connection state this connector maintains for peers.
* <p>
* After invoking this method a new connection needs to be established with a peer using a
* full handshake in order to exchange messages with it again.
*/
public final synchronized void clearConnectionState() {
connectionStore.clear();
}
private final DatagramSocket getSocket() {
return socket;
}
@Override
public void stop() {
ExecutorService shutdownTimer = null;
ExecutorService shutdown = null;
List<Runnable> pending = new ArrayList<>();
synchronized (this) {
if (running.compareAndSet(true, false)) {
if (statusLogger != null) {
statusLogger.cancel(false);
statusLogger = null;
}
LOGGER.info("Stopping DTLS connector on [{}]", lastBindAddress);
for (Thread t : receiverThreads) {
t.interrupt();
}
if (socket != null) {
socket.close();
socket = null;
}
maximumTransmissionUnit = null;
ipv4Mtu = DEFAULT_IPV4_MTU;
ipv6Mtu = DEFAULT_IPV6_MTU;
connectionStore.stop(pending);
if (executorService != timer) {
pending.addAll(timer.shutdownNow());
shutdownTimer = timer;