-
Notifications
You must be signed in to change notification settings - Fork 263
/
ConscryptEngine.java
1841 lines (1646 loc) · 69.5 KB
/
ConscryptEngine.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 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.conscrypt;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.FINISHED;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_WRAP;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
import static javax.net.ssl.SSLEngineResult.Status.BUFFER_OVERFLOW;
import static javax.net.ssl.SSLEngineResult.Status.BUFFER_UNDERFLOW;
import static javax.net.ssl.SSLEngineResult.Status.CLOSED;
import static javax.net.ssl.SSLEngineResult.Status.OK;
import static org.conscrypt.NativeConstants.SSL3_RT_HEADER_LENGTH;
import static org.conscrypt.NativeConstants.SSL3_RT_MAX_PACKET_SIZE;
import static org.conscrypt.NativeConstants.SSL3_RT_MAX_PLAIN_LENGTH;
import static org.conscrypt.NativeConstants.SSL_CB_HANDSHAKE_DONE;
import static org.conscrypt.NativeConstants.SSL_CB_HANDSHAKE_START;
import static org.conscrypt.NativeConstants.SSL_ERROR_WANT_READ;
import static org.conscrypt.NativeConstants.SSL_ERROR_WANT_WRITE;
import static org.conscrypt.NativeConstants.SSL_ERROR_ZERO_RETURN;
import static org.conscrypt.Preconditions.checkArgument;
import static org.conscrypt.Preconditions.checkNotNull;
import static org.conscrypt.Preconditions.checkPositionIndexes;
import static org.conscrypt.SSLUtils.EngineStates.STATE_CLOSED;
import static org.conscrypt.SSLUtils.EngineStates.STATE_CLOSED_INBOUND;
import static org.conscrypt.SSLUtils.EngineStates.STATE_CLOSED_OUTBOUND;
import static org.conscrypt.SSLUtils.EngineStates.STATE_HANDSHAKE_COMPLETED;
import static org.conscrypt.SSLUtils.EngineStates.STATE_HANDSHAKE_STARTED;
import static org.conscrypt.SSLUtils.EngineStates.STATE_MODE_SET;
import static org.conscrypt.SSLUtils.EngineStates.STATE_NEW;
import static org.conscrypt.SSLUtils.EngineStates.STATE_READY;
import static org.conscrypt.SSLUtils.EngineStates.STATE_READY_HANDSHAKE_CUT_THROUGH;
import static org.conscrypt.SSLUtils.calculateOutNetBufSize;
import static org.conscrypt.SSLUtils.toSSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.security.InvalidKeyException;
import java.security.PrivateKey;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECKey;
import java.security.spec.ECParameterSpec;
import java.util.Arrays;
import javax.crypto.SecretKey;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509ExtendedKeyManager;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import javax.security.auth.x500.X500Principal;
import org.conscrypt.NativeRef.SSL_SESSION;
import org.conscrypt.NativeSsl.BioWrapper;
import org.conscrypt.SSLParametersImpl.AliasChooser;
/**
* Implements the {@link SSLEngine} API using OpenSSL's non-blocking interfaces.
*/
final class ConscryptEngine extends AbstractConscryptEngine implements NativeCrypto.SSLHandshakeCallbacks,
SSLParametersImpl.AliasChooser,
SSLParametersImpl.PSKCallbacks {
private static final SSLEngineResult NEED_UNWRAP_OK =
new SSLEngineResult(OK, NEED_UNWRAP, 0, 0);
private static final SSLEngineResult NEED_UNWRAP_CLOSED =
new SSLEngineResult(CLOSED, NEED_UNWRAP, 0, 0);
private static final SSLEngineResult NEED_WRAP_OK = new SSLEngineResult(OK, NEED_WRAP, 0, 0);
private static final SSLEngineResult NEED_WRAP_CLOSED =
new SSLEngineResult(CLOSED, NEED_WRAP, 0, 0);
private static final SSLEngineResult CLOSED_NOT_HANDSHAKING =
new SSLEngineResult(CLOSED, NOT_HANDSHAKING, 0, 0);
private static BufferAllocator defaultBufferAllocator = null;
private final SSLParametersImpl sslParameters;
private BufferAllocator bufferAllocator = defaultBufferAllocator;
/**
* A lazy-created direct buffer used as a bridge between heap buffers provided by the
* application and JNI. This avoids the overhead of calling JNI with heap buffers.
* Used only when no {@link #bufferAllocator} has been provided.
*/
private ByteBuffer lazyDirectBuffer;
/**
* Hostname used with the TLS extension SNI hostname.
*/
private String peerHostname;
// @GuardedBy("ssl");
private int state = STATE_NEW;
private boolean handshakeFinished;
/**
* Wrapper around the underlying SSL object.
*/
private final NativeSsl ssl;
/**
* The BIO used for reading/writing encrypted bytes.
*/
// @GuardedBy("ssl");
private final BioWrapper networkBio;
/**
* Set during startHandshake.
*/
private ActiveSession activeSession;
/**
* A snapshot of the active session when the engine was closed.
*/
private SessionSnapshot closedSession;
/**
* The session object exposed externally from this class.
*/
private final SSLSession externalSession =
Platform.wrapSSLSession(new ExternalSession(new ExternalSession.Provider() {
@Override
public ConscryptSession provideSession() {
return ConscryptEngine.this.provideSession();
}
}));
/**
* Private key for the TLS Channel ID extension. This field is client-side only. Set during
* startHandshake.
*/
private OpenSSLKey channelIdPrivateKey;
private int maxSealOverhead;
private HandshakeListener handshakeListener;
private final ByteBuffer[] singleSrcBuffer = new ByteBuffer[1];
private final ByteBuffer[] singleDstBuffer = new ByteBuffer[1];
private final PeerInfoProvider peerInfoProvider;
ConscryptEngine(SSLParametersImpl sslParameters) {
this.sslParameters = sslParameters;
peerInfoProvider = PeerInfoProvider.nullProvider();
this.ssl = newSsl(sslParameters, this, this);
this.networkBio = ssl.newBio();
}
ConscryptEngine(String host, int port, SSLParametersImpl sslParameters) {
this.sslParameters = sslParameters;
this.peerInfoProvider = PeerInfoProvider.forHostAndPort(host, port);
this.ssl = newSsl(sslParameters, this, this);
this.networkBio = ssl.newBio();
}
ConscryptEngine(SSLParametersImpl sslParameters, PeerInfoProvider peerInfoProvider,
AliasChooser aliasChooser) {
this.sslParameters = sslParameters;
this.peerInfoProvider = checkNotNull(peerInfoProvider, "peerInfoProvider");
this.ssl = newSsl(sslParameters, this, aliasChooser);
this.networkBio = ssl.newBio();
}
private static NativeSsl newSsl(SSLParametersImpl sslParameters, ConscryptEngine engine,
AliasChooser aliasChooser) {
try {
return NativeSsl.newInstance(sslParameters, engine, aliasChooser, engine);
} catch (SSLException e) {
throw new RuntimeException(e);
}
}
/**
* Configures the default {@link BufferAllocator} to be used by all future
* {@link SSLEngine} and {@link ConscryptEngineSocket} instances from this provider.
*/
static void setDefaultBufferAllocator(BufferAllocator bufferAllocator) {
defaultBufferAllocator = bufferAllocator;
}
/**
* Returns the default {@link BufferAllocator}, which may be {@code null} if no default
* has been explicitly set.
*/
static BufferAllocator getDefaultBufferAllocator() {
return defaultBufferAllocator;
}
@Override
void setBufferAllocator(BufferAllocator bufferAllocator) {
synchronized (ssl) {
if (isHandshakeStarted()) {
throw new IllegalStateException(
"Could not set buffer allocator after the initial handshake has begun.");
}
this.bufferAllocator = bufferAllocator;
}
}
/**
* Returns the maximum overhead, in bytes, of sealing a record with SSL.
*/
@Override
int maxSealOverhead() {
return maxSealOverhead;
}
/**
* Enables/disables TLS Channel ID for this server engine.
*
* <p>This method needs to be invoked before the handshake starts.
*
* @throws IllegalStateException if this is a client engine or if the handshake has already
* started.
*/
@Override
void setChannelIdEnabled(boolean enabled) {
synchronized (ssl) {
if (getUseClientMode()) {
throw new IllegalStateException("Not allowed in client mode");
}
if (isHandshakeStarted()) {
throw new IllegalStateException(
"Could not enable/disable Channel ID after the initial handshake has begun.");
}
sslParameters.channelIdEnabled = enabled;
}
}
/**
* Gets the TLS Channel ID for this server engine. Channel ID is only available once the
* handshake completes.
*
* @return channel ID or {@code null} if not available.
*
* @throws IllegalStateException if this is a client engine or if the handshake has not yet
* completed.
* @throws SSLException if channel ID is available but could not be obtained.
*/
@Override
byte[] getChannelId() throws SSLException {
synchronized (ssl) {
if (getUseClientMode()) {
throw new IllegalStateException("Not allowed in client mode");
}
if (isHandshakeStarted()) {
throw new IllegalStateException(
"Channel ID is only available after handshake completes");
}
return ssl.getTlsChannelId();
}
}
/**
* Sets the {@link PrivateKey} to be used for TLS Channel ID by this client engine.
*
* <p>This method needs to be invoked before the handshake starts.
*
* @param privateKey private key (enables TLS Channel ID) or {@code null} for no key (disables
* TLS Channel ID). The private key must be an Elliptic Curve (EC) key based on the NIST
* P-256 curve (aka SECG secp256r1 or ANSI X9.62 prime256v1).
*
* @throws IllegalStateException if this is a server engine or if the handshake has already
* started.
*/
@Override
void setChannelIdPrivateKey(PrivateKey privateKey) {
if (!getUseClientMode()) {
throw new IllegalStateException("Not allowed in server mode");
}
synchronized (ssl) {
if (isHandshakeStarted()) {
throw new IllegalStateException("Could not change Channel ID private key "
+ "after the initial handshake has begun.");
}
if (privateKey == null) {
sslParameters.channelIdEnabled = false;
channelIdPrivateKey = null;
return;
}
sslParameters.channelIdEnabled = true;
try {
ECParameterSpec ecParams = null;
if (privateKey instanceof ECKey) {
ecParams = ((ECKey) privateKey).getParams();
}
if (ecParams == null) {
// Assume this is a P-256 key, as specified in the contract of this method.
ecParams =
OpenSSLECGroupContext.getCurveByName("prime256v1").getECParameterSpec();
}
channelIdPrivateKey =
OpenSSLKey.fromECPrivateKeyForTLSStackOnly(privateKey, ecParams);
} catch (InvalidKeyException e) {
// Will have error in startHandshake
}
}
}
/**
* Sets the listener for the completion of the TLS handshake.
*/
@Override
void setHandshakeListener(HandshakeListener handshakeListener) {
synchronized (ssl) {
if (isHandshakeStarted()) {
throw new IllegalStateException(
"Handshake listener must be set before starting the handshake.");
}
this.handshakeListener = handshakeListener;
}
}
private boolean isHandshakeStarted() {
switch (state) {
case STATE_NEW:
case STATE_MODE_SET:
return false;
default:
return true;
}
}
/**
* This method enables Server Name Indication (SNI) and overrides the {@link PeerInfoProvider}
* supplied during engine creation. If the hostname is not a valid SNI hostname, the SNI
* extension will be omitted from the handshake.
*/
@Override
void setHostname(String hostname) {
sslParameters.setUseSni(hostname != null);
this.peerHostname = hostname;
}
/**
* Returns the hostname from {@link #setHostname(String)} or supplied by the
* {@link PeerInfoProvider} upon creation. No DNS resolution is attempted before
* returning the hostname.
*/
@Override
String getHostname() {
return peerHostname != null ? peerHostname : peerInfoProvider.getHostname();
}
@Override
public String getPeerHost() {
return peerHostname != null ? peerHostname : peerInfoProvider.getHostnameOrIP();
}
@Override
public int getPeerPort() {
return peerInfoProvider.getPort();
}
@Override
public void beginHandshake() throws SSLException {
synchronized (ssl) {
beginHandshakeInternal();
}
}
private void beginHandshakeInternal() throws SSLException {
switch (state) {
case STATE_NEW: {
throw new IllegalStateException("Client/server mode must be set before handshake");
}
case STATE_MODE_SET: {
// We know what mode to handshake in but have not started the handshake, proceed
break;
}
case STATE_CLOSED_INBOUND:
case STATE_CLOSED_OUTBOUND:
case STATE_CLOSED:
throw new SSLHandshakeException("Engine has already been closed");
default:
// We've already started the handshake, just return
return;
}
transitionTo(STATE_HANDSHAKE_STARTED);
boolean releaseResources = true;
try {
// Prepare the SSL object for the handshake.
ssl.initialize(getHostname(), channelIdPrivateKey);
// For clients, offer to resume a previously cached session to avoid the
// full TLS handshake.
if (getUseClientMode()) {
NativeSslSession cachedSession = clientSessionContext().getCachedSession(
getHostname(), getPeerPort(), sslParameters);
if (cachedSession != null) {
cachedSession.offerToResume(ssl);
}
}
maxSealOverhead = ssl.getMaxSealOverhead();
handshake();
releaseResources = false;
} catch (IOException e) {
closeAll();
throw SSLUtils.toSSLHandshakeException(e);
} finally {
if (releaseResources) {
closeAndFreeResources();
}
}
}
@Override
public void closeInbound() {
synchronized (ssl) {
if (state == STATE_CLOSED || state == STATE_CLOSED_INBOUND) {
return;
}
if (isHandshakeStarted()) {
if (state == STATE_CLOSED_OUTBOUND) {
transitionTo(STATE_CLOSED);
} else {
transitionTo(STATE_CLOSED_INBOUND);
}
freeIfDone();
} else {
// Never started the handshake. Just close now.
closeAndFreeResources();
}
}
}
@Override
public void closeOutbound() {
synchronized (ssl) {
if (state == STATE_CLOSED || state == STATE_CLOSED_OUTBOUND) {
return;
}
if (isHandshakeStarted()) {
if (state == STATE_CLOSED_INBOUND) {
transitionTo(STATE_CLOSED);
} else {
transitionTo(STATE_CLOSED_OUTBOUND);
}
sendSSLShutdown();
freeIfDone();
} else {
// Never started the handshake. Just close now.
closeAndFreeResources();
}
}
}
@Override
public Runnable getDelegatedTask() {
// This implementation doesn't use any delegated tasks.
return null;
}
@Override
public String[] getEnabledCipherSuites() {
return sslParameters.getEnabledCipherSuites();
}
@Override
public String[] getEnabledProtocols() {
return sslParameters.getEnabledProtocols();
}
@Override
public boolean getEnableSessionCreation() {
return sslParameters.getEnableSessionCreation();
}
@Override
public SSLParameters getSSLParameters() {
SSLParameters params = super.getSSLParameters();
Platform.getSSLParameters(params, sslParameters, this);
return params;
}
@Override
public void setSSLParameters(SSLParameters p) {
super.setSSLParameters(p);
Platform.setSSLParameters(p, sslParameters, this);
}
@Override
public HandshakeStatus getHandshakeStatus() {
synchronized (ssl) {
return getHandshakeStatusInternal();
}
}
private HandshakeStatus getHandshakeStatusInternal() {
if (handshakeFinished) {
return HandshakeStatus.NOT_HANDSHAKING;
}
switch (state) {
case STATE_HANDSHAKE_STARTED:
return pendingStatus(pendingOutboundEncryptedBytes());
case STATE_HANDSHAKE_COMPLETED:
return HandshakeStatus.NEED_WRAP;
case STATE_NEW:
case STATE_MODE_SET:
case STATE_CLOSED:
case STATE_CLOSED_INBOUND:
case STATE_CLOSED_OUTBOUND:
case STATE_READY:
case STATE_READY_HANDSHAKE_CUT_THROUGH:
return HandshakeStatus.NOT_HANDSHAKING;
default:
break;
}
throw new IllegalStateException("Unexpected engine state: " + state);
}
int pendingOutboundEncryptedBytes() {
return networkBio.getPendingWrittenBytes();
}
private int pendingInboundCleartextBytes() {
return ssl.getPendingReadableBytes();
}
private static SSLEngineResult.HandshakeStatus pendingStatus(int pendingOutboundBytes) {
// Depending on if there is something left in the BIO we need to WRAP or UNWRAP
return pendingOutboundBytes > 0 ? NEED_WRAP : NEED_UNWRAP;
}
@Override
public boolean getNeedClientAuth() {
return sslParameters.getNeedClientAuth();
}
/**
* Work-around to allow this method to be called on older versions of Android.
*/
@Override
SSLSession handshakeSession() {
synchronized (ssl) {
if (state == STATE_HANDSHAKE_STARTED) {
return Platform.wrapSSLSession(new ExternalSession(new ExternalSession.Provider() {
@Override
public ConscryptSession provideSession() {
return ConscryptEngine.this.provideHandshakeSession();
}
}));
}
return null;
}
}
@Override
public SSLSession getSession() {
return externalSession;
}
private ConscryptSession provideSession() {
synchronized (ssl) {
if (state == STATE_CLOSED) {
return closedSession != null ? closedSession : SSLNullSession.getNullSession();
}
if (state < STATE_HANDSHAKE_COMPLETED) {
// Return an invalid session with invalid cipher suite of "SSL_NULL_WITH_NULL_NULL"
return SSLNullSession.getNullSession();
}
return activeSession;
}
}
private ConscryptSession provideHandshakeSession() {
synchronized (ssl) {
return state == STATE_HANDSHAKE_STARTED ? activeSession
: SSLNullSession.getNullSession();
}
}
// After handshake has started, provide active session otherwise a null session,
// for code which needs to read session attributes without triggering the handshake.
private ConscryptSession provideAfterHandshakeSession() {
return (state < STATE_HANDSHAKE_STARTED)
? SSLNullSession.getNullSession()
: provideSession();
}
@Override
public String[] getSupportedCipherSuites() {
return NativeCrypto.getSupportedCipherSuites();
}
@Override
public String[] getSupportedProtocols() {
return NativeCrypto.getSupportedProtocols();
}
@Override
public boolean getUseClientMode() {
return sslParameters.getUseClientMode();
}
@Override
public boolean getWantClientAuth() {
return sslParameters.getWantClientAuth();
}
@Override
public boolean isInboundDone() {
synchronized (ssl) {
return (state == STATE_CLOSED
|| state == STATE_CLOSED_INBOUND
|| ssl.wasShutdownReceived())
&& (pendingInboundCleartextBytes() == 0);
}
}
@Override
public boolean isOutboundDone() {
synchronized (ssl) {
return (state == STATE_CLOSED
|| state == STATE_CLOSED_OUTBOUND
|| ssl.wasShutdownSent())
&& (pendingOutboundEncryptedBytes() == 0);
}
}
@Override
public void setEnabledCipherSuites(String[] suites) {
sslParameters.setEnabledCipherSuites(suites);
}
@Override
public void setEnabledProtocols(String[] protocols) {
sslParameters.setEnabledProtocols(protocols);
}
@Override
public void setEnableSessionCreation(boolean flag) {
sslParameters.setEnableSessionCreation(flag);
}
@Override
public void setNeedClientAuth(boolean need) {
sslParameters.setNeedClientAuth(need);
}
@Override
public void setUseClientMode(boolean mode) {
synchronized (ssl) {
if (isHandshakeStarted()) {
throw new IllegalArgumentException(
"Can not change mode after handshake: state == " + state);
}
transitionTo(STATE_MODE_SET);
sslParameters.setUseClientMode(mode);
}
}
@Override
public void setWantClientAuth(boolean want) {
sslParameters.setWantClientAuth(want);
}
@Override
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
synchronized (ssl) {
try {
return unwrap(singleSrcBuffer(src), singleDstBuffer(dst));
} finally {
resetSingleSrcBuffer();
resetSingleDstBuffer();
}
}
}
@Override
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts) throws SSLException {
synchronized (ssl) {
try {
return unwrap(singleSrcBuffer(src), dsts);
} finally {
resetSingleSrcBuffer();
}
}
}
@Override
public SSLEngineResult unwrap(final ByteBuffer src, final ByteBuffer[] dsts, final int offset,
final int length) throws SSLException {
synchronized (ssl) {
try {
return unwrap(singleSrcBuffer(src), 0, 1, dsts, offset, length);
} finally {
resetSingleSrcBuffer();
}
}
}
@Override
SSLEngineResult unwrap(final ByteBuffer[] srcs, final ByteBuffer[] dsts) throws SSLException {
checkArgument(srcs != null, "srcs is null");
checkArgument(dsts != null, "dsts is null");
return unwrap(srcs, 0, srcs.length, dsts, 0, dsts.length);
}
@Override
SSLEngineResult unwrap(final ByteBuffer[] srcs, int srcsOffset, final int srcsLength,
final ByteBuffer[] dsts, final int dstsOffset, final int dstsLength)
throws SSLException {
checkArgument(srcs != null, "srcs is null");
checkArgument(dsts != null, "dsts is null");
checkPositionIndexes(srcsOffset, srcsOffset + srcsLength, srcs.length);
checkPositionIndexes(dstsOffset, dstsOffset + dstsLength, dsts.length);
// Determine the output capacity.
final int dstLength = calcDstsLength(dsts, dstsOffset, dstsLength);
final int endOffset = dstsOffset + dstsLength;
final int srcsEndOffset = srcsOffset + srcsLength;
final long srcLength = calcSrcsLength(srcs, srcsOffset, srcsEndOffset);
synchronized (ssl) {
switch (state) {
case STATE_MODE_SET:
// Begin the handshake implicitly.
beginHandshakeInternal();
break;
case STATE_CLOSED_INBOUND:
case STATE_CLOSED:
freeIfDone();
// If the inbound direction is closed. we can't send anymore.
return new SSLEngineResult(Status.CLOSED, getHandshakeStatusInternal(), 0, 0);
case STATE_NEW:
throw new IllegalStateException(
"Client/server mode must be set before calling unwrap");
default:
break;
}
HandshakeStatus handshakeStatus = HandshakeStatus.NOT_HANDSHAKING;
if (!handshakeFinished) {
handshakeStatus = handshake();
if (handshakeStatus == NEED_WRAP) {
return NEED_WRAP_OK;
}
if (state == STATE_CLOSED) {
return NEED_WRAP_CLOSED;
}
// NEED_UNWRAP - just fall through to perform the unwrap.
}
// Consume any source data. Skip this if there are unread cleartext data.
boolean noCleartextDataAvailable = pendingInboundCleartextBytes() <= 0;
int lenRemaining = 0;
if (srcLength > 0 && noCleartextDataAvailable) {
if (srcLength < SSL3_RT_HEADER_LENGTH) {
// Need to be able to read a full TLS header.
return new SSLEngineResult(BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
}
int packetLength = SSLUtils.getEncryptedPacketLength(srcs, srcsOffset);
if (packetLength < 0) {
throw new SSLException("Unable to parse TLS packet header");
}
if (srcLength < packetLength) {
// We either have not enough data to read the packet header or not enough for
// reading the whole packet.
return new SSLEngineResult(BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
}
// Limit the amount of data to be read to a single packet.
lenRemaining = packetLength;
} else if (noCleartextDataAvailable) {
// No pending data and nothing provided as input. Need more data.
return new SSLEngineResult(BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
}
// Write all of the encrypted source data to the networkBio
int bytesConsumed = 0;
if (lenRemaining > 0 && srcsOffset < srcsEndOffset) {
do {
ByteBuffer src = srcs[srcsOffset];
int remaining = src.remaining();
if (remaining == 0) {
// We must skip empty buffers as BIO_write will return 0 if asked to
// write something with length 0.
srcsOffset++;
continue;
}
// Write the source encrypted data to the networkBio.
int written = writeEncryptedData(src, min(lenRemaining, remaining));
if (written > 0) {
bytesConsumed += written;
lenRemaining -= written;
if (lenRemaining == 0) {
// A whole packet has been consumed.
break;
}
if (written == remaining) {
srcsOffset++;
} else {
// We were not able to write everything into the BIO so break the
// write loop as otherwise we will produce an error on the next
// write attempt, which will trigger a SSL.clearError() later.
break;
}
} else {
// BIO_write returned a negative or zero number, this means we could not
// complete the write operation and should retry later.
// We ignore BIO_* errors here as we use in memory BIO anyway and will
// do another SSL_* call later on in which we will produce an exception
// in case of an error
NativeCrypto.SSL_clear_error();
break;
}
} while (srcsOffset < srcsEndOffset);
}
// Now read any available plaintext data.
int bytesProduced = 0;
try {
if (dstLength > 0) {
// Write decrypted data to dsts buffers
for (int idx = dstsOffset; idx < endOffset; ++idx) {
ByteBuffer dst = dsts[idx];
if (!dst.hasRemaining()) {
continue;
}
int bytesRead = readPlaintextData(dst);
if (bytesRead > 0) {
bytesProduced += bytesRead;
if (dst.hasRemaining()) {
// We haven't filled this buffer fully, break out of the loop
// and determine the correct response status below.
break;
}
} else {
switch (bytesRead) {
case -SSL_ERROR_WANT_READ:
case -SSL_ERROR_WANT_WRITE: {
return newResult(bytesConsumed, bytesProduced, handshakeStatus);
}
case -SSL_ERROR_ZERO_RETURN: {
// We received a close_notify from the peer, so mark the
// inbound direction as closed and shut down the SSL object
closeAll();
return new SSLEngineResult(Status.CLOSED,
pendingOutboundEncryptedBytes() > 0
? NEED_WRAP : NOT_HANDSHAKING,
bytesConsumed, bytesProduced);
}
default: {
// Should never get here.
closeAll();
throw newSslExceptionWithMessage("SSL_read");
}
}
}
}
} else {
// If the capacity of all destination buffers is 0 we need to trigger a SSL_read
// anyway to ensure everything is flushed in the BIO pair and so we can detect
// it in the pendingInboundCleartextBytes() call.
ssl.forceRead();
}
} catch (InterruptedIOException e) {
return newResult(bytesConsumed, bytesProduced, handshakeStatus);
} catch (IOException e) {
// Shut down the SSL and rethrow the exception. Users will need to drain any alerts
// from the SSL before closing.
closeAll();
throw convertException(e);
}
// There won't be any application data until we're done handshaking.
// We first check handshakeFinished to eliminate the overhead of extra JNI call if
// possible.
int pendingCleartextBytes = handshakeFinished ? pendingInboundCleartextBytes() : 0;
if (pendingCleartextBytes > 0) {
// We filled all buffers but there is still some data pending in the BIO buffer,
// return BUFFER_OVERFLOW.
return new SSLEngineResult(BUFFER_OVERFLOW,
mayFinishHandshake(handshakeStatus == FINISHED
? handshakeStatus
: getHandshakeStatusInternal()),
bytesConsumed, bytesProduced);
}
return newResult(bytesConsumed, bytesProduced, handshakeStatus);
}
}
private static int calcDstsLength(ByteBuffer[] dsts, int dstsOffset, int dstsLength) {
int capacity = 0;
for (int i = 0; i < dsts.length; i++) {
ByteBuffer dst = dsts[i];
checkArgument(dst != null, "dsts[%d] is null", i);
if (dst.isReadOnly()) {
throw new ReadOnlyBufferException();
}
if (i >= dstsOffset && i < dstsOffset + dstsLength) {
capacity += dst.remaining();
}
}
return capacity;
}
private static long calcSrcsLength(ByteBuffer[] srcs, int srcsOffset, int srcsEndOffset) {
long len = 0;
for (int i = srcsOffset; i < srcsEndOffset; i++) {
ByteBuffer src = srcs[i];
if (src == null) {
throw new IllegalArgumentException("srcs[" + i + "] is null");
}
len += src.remaining();
}
return len;
}
private SSLEngineResult.HandshakeStatus handshake() throws SSLException {
try {
// Only actually perform the handshake if we haven't already just completed it
// via BIO operations.
try {
int ssl_error_code = ssl.doHandshake();
switch (ssl_error_code) {
case SSL_ERROR_WANT_READ:
return pendingStatus(pendingOutboundEncryptedBytes());
case SSL_ERROR_WANT_WRITE: {
return NEED_WRAP;
}
default: {
// SSL_ERROR_NONE.
}
}
} catch (IOException e) {
// Shut down the SSL and rethrow the exception. Users will need to drain any alerts
// from the SSL before closing.
closeAll();
throw e;
}
// The handshake has completed successfully...
// Update the session from the current state of the SSL object.
activeSession.onPeerCertificateAvailable(getPeerHost(), getPeerPort());
finishHandshake();
return FINISHED;
} catch (Exception e) {
throw toSSLHandshakeException(e);
}
}
private void finishHandshake() throws SSLException {
handshakeFinished = true;
// Notify the listener, if provided.