1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.ssl;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.ByteBufAllocator;
20 import io.netty.handler.ssl.util.LazyJavaxX509Certificate;
21 import io.netty.handler.ssl.util.LazyX509Certificate;
22 import io.netty.internal.tcnative.AsyncTask;
23 import io.netty.internal.tcnative.Buffer;
24 import io.netty.internal.tcnative.SSL;
25 import io.netty.util.AbstractReferenceCounted;
26 import io.netty.util.CharsetUtil;
27 import io.netty.util.ReferenceCounted;
28 import io.netty.util.ResourceLeakDetector;
29 import io.netty.util.ResourceLeakDetectorFactory;
30 import io.netty.util.ResourceLeakTracker;
31 import io.netty.util.internal.EmptyArrays;
32 import io.netty.util.internal.PlatformDependent;
33 import io.netty.util.internal.StringUtil;
34 import io.netty.util.internal.SuppressJava6Requirement;
35 import io.netty.util.internal.ThrowableUtil;
36 import io.netty.util.internal.UnstableApi;
37 import io.netty.util.internal.logging.InternalLogger;
38 import io.netty.util.internal.logging.InternalLoggerFactory;
39
40 import java.nio.ByteBuffer;
41 import java.nio.ReadOnlyBufferException;
42 import java.security.Principal;
43 import java.security.cert.Certificate;
44 import java.util.Arrays;
45 import java.util.Collection;
46 import java.util.Collections;
47 import java.util.HashSet;
48 import java.util.LinkedHashSet;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Set;
52 import java.util.concurrent.ConcurrentHashMap;
53 import java.util.concurrent.locks.Lock;
54
55 import javax.crypto.spec.SecretKeySpec;
56 import javax.net.ssl.SSLEngine;
57 import javax.net.ssl.SSLEngineResult;
58 import javax.net.ssl.SSLException;
59 import javax.net.ssl.SSLHandshakeException;
60 import javax.net.ssl.SSLParameters;
61 import javax.net.ssl.SSLPeerUnverifiedException;
62 import javax.net.ssl.SSLSession;
63 import javax.net.ssl.SSLSessionBindingEvent;
64 import javax.net.ssl.SSLSessionBindingListener;
65 import javax.security.cert.X509Certificate;
66
67 import static io.netty.handler.ssl.OpenSsl.memoryAddress;
68 import static io.netty.handler.ssl.SslUtils.SSL_RECORD_HEADER_LENGTH;
69 import static io.netty.util.internal.EmptyArrays.EMPTY_STRINGS;
70 import static io.netty.util.internal.ObjectUtil.checkNotNull;
71 import static io.netty.util.internal.ObjectUtil.checkNotNullArrayParam;
72 import static io.netty.util.internal.ObjectUtil.checkNotNullWithIAE;
73 import static java.lang.Integer.MAX_VALUE;
74 import static java.lang.Math.min;
75 import static javax.net.ssl.SSLEngineResult.HandshakeStatus.FINISHED;
76 import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_TASK;
77 import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
78 import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_WRAP;
79 import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
80 import static javax.net.ssl.SSLEngineResult.Status.BUFFER_OVERFLOW;
81 import static javax.net.ssl.SSLEngineResult.Status.BUFFER_UNDERFLOW;
82 import static javax.net.ssl.SSLEngineResult.Status.CLOSED;
83 import static javax.net.ssl.SSLEngineResult.Status.OK;
84
85
86
87
88
89
90
91
92
93
94 public class ReferenceCountedOpenSslEngine extends SSLEngine implements ReferenceCounted, ApplicationProtocolAccessor {
95
96 private static final InternalLogger logger = InternalLoggerFactory.getInstance(ReferenceCountedOpenSslEngine.class);
97
98 private static final ResourceLeakDetector<ReferenceCountedOpenSslEngine> leakDetector =
99 ResourceLeakDetectorFactory.instance().newResourceLeakDetector(ReferenceCountedOpenSslEngine.class);
100 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV2 = 0;
101 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV3 = 1;
102 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1 = 2;
103 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_1 = 3;
104 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_2 = 4;
105 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_3 = 5;
106 private static final int[] OPENSSL_OP_NO_PROTOCOLS = {
107 SSL.SSL_OP_NO_SSLv2,
108 SSL.SSL_OP_NO_SSLv3,
109 SSL.SSL_OP_NO_TLSv1,
110 SSL.SSL_OP_NO_TLSv1_1,
111 SSL.SSL_OP_NO_TLSv1_2,
112 SSL.SSL_OP_NO_TLSv1_3
113 };
114
115
116
117
118 static final int MAX_PLAINTEXT_LENGTH = SSL.SSL_MAX_PLAINTEXT_LENGTH;
119
120
121
122 static final int MAX_RECORD_SIZE = SSL.SSL_MAX_RECORD_LENGTH;
123
124 private static final SSLEngineResult NEED_UNWRAP_OK = new SSLEngineResult(OK, NEED_UNWRAP, 0, 0);
125 private static final SSLEngineResult NEED_UNWRAP_CLOSED = new SSLEngineResult(CLOSED, NEED_UNWRAP, 0, 0);
126 private static final SSLEngineResult NEED_WRAP_OK = new SSLEngineResult(OK, NEED_WRAP, 0, 0);
127 private static final SSLEngineResult NEED_WRAP_CLOSED = new SSLEngineResult(CLOSED, NEED_WRAP, 0, 0);
128 private static final SSLEngineResult CLOSED_NOT_HANDSHAKING = new SSLEngineResult(CLOSED, NOT_HANDSHAKING, 0, 0);
129
130
131 private long ssl;
132 private long networkBIO;
133
134 private enum HandshakeState {
135
136
137
138 NOT_STARTED,
139
140
141
142 STARTED_IMPLICITLY,
143
144
145
146 STARTED_EXPLICITLY,
147
148
149
150 FINISHED
151 }
152
153 private HandshakeState handshakeState = HandshakeState.NOT_STARTED;
154 private boolean receivedShutdown;
155 private volatile boolean destroyed;
156 private volatile String applicationProtocol;
157 private volatile boolean needTask;
158 private boolean hasTLSv13Cipher;
159 private boolean sessionSet;
160
161
162 private final ResourceLeakTracker<ReferenceCountedOpenSslEngine> leak;
163 private final AbstractReferenceCounted refCnt = new AbstractReferenceCounted() {
164 @Override
165 public ReferenceCounted touch(Object hint) {
166 if (leak != null) {
167 leak.record(hint);
168 }
169
170 return ReferenceCountedOpenSslEngine.this;
171 }
172
173 @Override
174 protected void deallocate() {
175 shutdown();
176 if (leak != null) {
177 boolean closed = leak.close(ReferenceCountedOpenSslEngine.this);
178 assert closed;
179 }
180 parentContext.release();
181 }
182 };
183
184 private final Set<String> enabledProtocols = new LinkedHashSet<String>();
185
186 private volatile ClientAuth clientAuth = ClientAuth.NONE;
187
188 private String endpointIdentificationAlgorithm;
189
190 private Object algorithmConstraints;
191 private List<String> sniHostNames;
192
193
194
195 private volatile Collection<?> matchers;
196
197
198 private boolean isInboundDone;
199 private boolean outboundClosed;
200
201 final boolean jdkCompatibilityMode;
202 private final boolean clientMode;
203 final ByteBufAllocator alloc;
204 private final OpenSslEngineMap engineMap;
205 private final OpenSslApplicationProtocolNegotiator apn;
206 private final ReferenceCountedOpenSslContext parentContext;
207 private final OpenSslInternalSession session;
208 private final ByteBuffer[] singleSrcBuffer = new ByteBuffer[1];
209 private final ByteBuffer[] singleDstBuffer = new ByteBuffer[1];
210 private final boolean enableOcsp;
211 private int maxWrapOverhead;
212 private int maxWrapBufferSize;
213 private Throwable pendingException;
214
215
216
217
218
219
220
221
222
223
224
225
226
227 ReferenceCountedOpenSslEngine(ReferenceCountedOpenSslContext context, final ByteBufAllocator alloc, String peerHost,
228 int peerPort, boolean jdkCompatibilityMode, boolean leakDetection,
229 String endpointIdentificationAlgorithm) {
230 super(peerHost, peerPort);
231 OpenSsl.ensureAvailability();
232 engineMap = context.engineMap;
233 enableOcsp = context.enableOcsp;
234 this.jdkCompatibilityMode = jdkCompatibilityMode;
235 this.alloc = checkNotNull(alloc, "alloc");
236 apn = (OpenSslApplicationProtocolNegotiator) context.applicationProtocolNegotiator();
237 clientMode = context.isClient();
238 this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm;
239
240 if (PlatformDependent.javaVersion() >= 7) {
241 session = new ExtendedOpenSslSession(new DefaultOpenSslSession(context.sessionContext())) {
242 private String[] peerSupportedSignatureAlgorithms;
243 private List requestedServerNames;
244
245 @Override
246 public List getRequestedServerNames() {
247 if (clientMode) {
248 return Java8SslUtils.getSniHostNames(sniHostNames);
249 } else {
250 synchronized (ReferenceCountedOpenSslEngine.this) {
251 if (requestedServerNames == null) {
252 if (isDestroyed()) {
253 requestedServerNames = Collections.emptyList();
254 } else {
255 String name = SSL.getSniHostname(ssl);
256 if (name == null) {
257 requestedServerNames = Collections.emptyList();
258 } else {
259
260
261 requestedServerNames =
262 Java8SslUtils.getSniHostName(
263 SSL.getSniHostname(ssl).getBytes(CharsetUtil.UTF_8));
264 }
265 }
266 }
267 return requestedServerNames;
268 }
269 }
270 }
271
272 @Override
273 public String[] getPeerSupportedSignatureAlgorithms() {
274 synchronized (ReferenceCountedOpenSslEngine.this) {
275 if (peerSupportedSignatureAlgorithms == null) {
276 if (isDestroyed()) {
277 peerSupportedSignatureAlgorithms = EMPTY_STRINGS;
278 } else {
279 String[] algs = SSL.getSigAlgs(ssl);
280 if (algs == null) {
281 peerSupportedSignatureAlgorithms = EMPTY_STRINGS;
282 } else {
283 Set<String> algorithmList = new LinkedHashSet<String>(algs.length);
284 for (String alg: algs) {
285 String converted = SignatureAlgorithmConverter.toJavaName(alg);
286
287 if (converted != null) {
288 algorithmList.add(converted);
289 }
290 }
291 peerSupportedSignatureAlgorithms = algorithmList.toArray(EMPTY_STRINGS);
292 }
293 }
294 }
295 return peerSupportedSignatureAlgorithms.clone();
296 }
297 }
298
299 @Override
300 public List<byte[]> getStatusResponses() {
301 byte[] ocspResponse = null;
302 if (enableOcsp && clientMode) {
303 synchronized (ReferenceCountedOpenSslEngine.this) {
304 if (!isDestroyed()) {
305 ocspResponse = SSL.getOcspResponse(ssl);
306 }
307 }
308 }
309 return ocspResponse == null ?
310 Collections.<byte[]>emptyList() : Collections.singletonList(ocspResponse);
311 }
312 };
313 } else {
314 session = new DefaultOpenSslSession(context.sessionContext());
315 }
316
317 if (!context.sessionContext().useKeyManager()) {
318 session.setLocalCertificate(context.keyCertChain);
319 }
320
321 Lock readerLock = context.ctxLock.readLock();
322 readerLock.lock();
323 final long finalSsl;
324 try {
325 finalSsl = SSL.newSSL(context.ctx, !context.isClient());
326 } finally {
327 readerLock.unlock();
328 }
329 synchronized (this) {
330 ssl = finalSsl;
331 try {
332 networkBIO = SSL.bioNewByteBuffer(ssl, context.getBioNonApplicationBufferSize());
333
334
335
336 setClientAuth(clientMode ? ClientAuth.NONE : context.clientAuth);
337
338 assert context.protocols != null;
339 this.hasTLSv13Cipher = context.hasTLSv13Cipher;
340
341 setEnabledProtocols(context.protocols);
342
343
344
345 if (clientMode && SslUtils.isValidHostNameForSNI(peerHost)) {
346
347
348 if (PlatformDependent.javaVersion() >= 8) {
349 if (Java8SslUtils.isValidHostNameForSNI(peerHost)) {
350 SSL.setTlsExtHostName(ssl, peerHost);
351 sniHostNames = Collections.singletonList(peerHost);
352 }
353 } else {
354 SSL.setTlsExtHostName(ssl, peerHost);
355 sniHostNames = Collections.singletonList(peerHost);
356 }
357 }
358
359 if (enableOcsp) {
360 SSL.enableOcsp(ssl);
361 }
362
363 if (!jdkCompatibilityMode) {
364 SSL.setMode(ssl, SSL.getMode(ssl) | SSL.SSL_MODE_ENABLE_PARTIAL_WRITE);
365 }
366
367 if (isProtocolEnabled(SSL.getOptions(ssl), SSL.SSL_OP_NO_TLSv1_3, SslProtocols.TLS_v1_3)) {
368 final boolean enableTickets = clientMode ?
369 ReferenceCountedOpenSslContext.CLIENT_ENABLE_SESSION_TICKET_TLSV13 :
370 ReferenceCountedOpenSslContext.SERVER_ENABLE_SESSION_TICKET_TLSV13;
371 if (enableTickets) {
372
373
374
375
376
377
378
379 SSL.clearOptions(ssl, SSL.SSL_OP_NO_TICKET);
380 }
381 }
382
383 if (OpenSsl.isBoringSSL() && clientMode) {
384
385
386
387
388 SSL.setRenegotiateMode(ssl, SSL.SSL_RENEGOTIATE_ONCE);
389 }
390
391 calculateMaxWrapOverhead();
392
393
394 configureEndpointVerification(endpointIdentificationAlgorithm);
395 } catch (Throwable cause) {
396
397
398 shutdown();
399
400 PlatformDependent.throwException(cause);
401 }
402 }
403
404
405
406 parentContext = context;
407 parentContext.retain();
408
409
410
411 leak = leakDetection ? leakDetector.track(this) : null;
412 }
413
414 final synchronized String[] authMethods() {
415 if (isDestroyed()) {
416 return EMPTY_STRINGS;
417 }
418 return SSL.authenticationMethods(ssl);
419 }
420
421 final boolean setKeyMaterial(OpenSslKeyMaterial keyMaterial) throws Exception {
422 synchronized (this) {
423 if (isDestroyed()) {
424 return false;
425 }
426 SSL.setKeyMaterial(ssl, keyMaterial.certificateChainAddress(), keyMaterial.privateKeyAddress());
427 }
428 session.setLocalCertificate(keyMaterial.certificateChain());
429 return true;
430 }
431
432 final synchronized SecretKeySpec masterKey() {
433 if (isDestroyed()) {
434 return null;
435 }
436 return new SecretKeySpec(SSL.getMasterKey(ssl), "AES");
437 }
438
439 synchronized boolean isSessionReused() {
440 if (isDestroyed()) {
441 return false;
442 }
443 return SSL.isSessionReused(ssl);
444 }
445
446
447
448
449 @UnstableApi
450 public void setOcspResponse(byte[] response) {
451 if (!enableOcsp) {
452 throw new IllegalStateException("OCSP stapling is not enabled");
453 }
454
455 if (clientMode) {
456 throw new IllegalStateException("Not a server SSLEngine");
457 }
458
459 synchronized (this) {
460 if (!isDestroyed()) {
461 SSL.setOcspResponse(ssl, response);
462 }
463 }
464 }
465
466
467
468
469 @UnstableApi
470 public byte[] getOcspResponse() {
471 if (!enableOcsp) {
472 throw new IllegalStateException("OCSP stapling is not enabled");
473 }
474
475 if (!clientMode) {
476 throw new IllegalStateException("Not a client SSLEngine");
477 }
478
479 synchronized (this) {
480 if (isDestroyed()) {
481 return EmptyArrays.EMPTY_BYTES;
482 }
483 return SSL.getOcspResponse(ssl);
484 }
485 }
486
487 @Override
488 public final int refCnt() {
489 return refCnt.refCnt();
490 }
491
492 @Override
493 public final ReferenceCounted retain() {
494 refCnt.retain();
495 return this;
496 }
497
498 @Override
499 public final ReferenceCounted retain(int increment) {
500 refCnt.retain(increment);
501 return this;
502 }
503
504 @Override
505 public final ReferenceCounted touch() {
506 refCnt.touch();
507 return this;
508 }
509
510 @Override
511 public final ReferenceCounted touch(Object hint) {
512 refCnt.touch(hint);
513 return this;
514 }
515
516 @Override
517 public final boolean release() {
518 return refCnt.release();
519 }
520
521 @Override
522 public final boolean release(int decrement) {
523 return refCnt.release(decrement);
524 }
525
526
527
528 public String getApplicationProtocol() {
529 return applicationProtocol;
530 }
531
532
533
534 public String getHandshakeApplicationProtocol() {
535 return applicationProtocol;
536 }
537
538 @Override
539 public final synchronized SSLSession getHandshakeSession() {
540
541
542
543
544 switch(handshakeState) {
545 case NOT_STARTED:
546 case FINISHED:
547 return null;
548 default:
549 return session;
550 }
551 }
552
553
554
555
556
557
558 public final synchronized long sslPointer() {
559 return ssl;
560 }
561
562
563
564
565 public final synchronized void shutdown() {
566 if (!destroyed) {
567 destroyed = true;
568
569
570
571 if (engineMap != null) {
572 engineMap.remove(ssl);
573 }
574 SSL.freeSSL(ssl);
575 ssl = networkBIO = 0;
576
577 isInboundDone = outboundClosed = true;
578 }
579
580
581 SSL.clearError();
582 }
583
584
585
586
587
588
589 private int writePlaintextData(final ByteBuffer src, int len) {
590 final int pos = src.position();
591 final int limit = src.limit();
592 final int sslWrote;
593
594 if (src.isDirect()) {
595 sslWrote = SSL.writeToSSL(ssl, bufferAddress(src) + pos, len);
596 if (sslWrote > 0) {
597 src.position(pos + sslWrote);
598 }
599 } else {
600 ByteBuf buf = alloc.directBuffer(len);
601 try {
602 src.limit(pos + len);
603
604 buf.setBytes(0, src);
605 src.limit(limit);
606
607 sslWrote = SSL.writeToSSL(ssl, memoryAddress(buf), len);
608 if (sslWrote > 0) {
609 src.position(pos + sslWrote);
610 } else {
611 src.position(pos);
612 }
613 } finally {
614 buf.release();
615 }
616 }
617 return sslWrote;
618 }
619
620 synchronized void bioSetFd(int fd) {
621 if (!isDestroyed()) {
622 SSL.bioSetFd(this.ssl, fd);
623 }
624 }
625
626
627
628
629 private ByteBuf writeEncryptedData(final ByteBuffer src, int len) throws SSLException {
630 final int pos = src.position();
631 if (src.isDirect()) {
632 SSL.bioSetByteBuffer(networkBIO, bufferAddress(src) + pos, len, false);
633 } else {
634 final ByteBuf buf = alloc.directBuffer(len);
635 try {
636 final int limit = src.limit();
637 src.limit(pos + len);
638 buf.writeBytes(src);
639
640 src.position(pos);
641 src.limit(limit);
642
643 SSL.bioSetByteBuffer(networkBIO, memoryAddress(buf), len, false);
644 return buf;
645 } catch (Throwable cause) {
646 buf.release();
647 PlatformDependent.throwException(cause);
648 }
649 }
650 return null;
651 }
652
653
654
655
656 private int readPlaintextData(final ByteBuffer dst) throws SSLException {
657 final int sslRead;
658 final int pos = dst.position();
659 if (dst.isDirect()) {
660 sslRead = SSL.readFromSSL(ssl, bufferAddress(dst) + pos, dst.limit() - pos);
661 if (sslRead > 0) {
662 dst.position(pos + sslRead);
663 }
664 } else {
665 final int limit = dst.limit();
666 final int len = min(maxEncryptedPacketLength0(), limit - pos);
667 final ByteBuf buf = alloc.directBuffer(len);
668 try {
669 sslRead = SSL.readFromSSL(ssl, memoryAddress(buf), len);
670 if (sslRead > 0) {
671 dst.limit(pos + sslRead);
672 buf.getBytes(buf.readerIndex(), dst);
673 dst.limit(limit);
674 }
675 } finally {
676 buf.release();
677 }
678 }
679
680 return sslRead;
681 }
682
683
684
685
686 final synchronized int maxWrapOverhead() {
687 return maxWrapOverhead;
688 }
689
690
691
692
693 final synchronized int maxEncryptedPacketLength() {
694 return maxEncryptedPacketLength0();
695 }
696
697
698
699
700
701 final int maxEncryptedPacketLength0() {
702 return maxWrapOverhead + MAX_PLAINTEXT_LENGTH;
703 }
704
705
706
707
708
709
710
711
712
713 final int calculateMaxLengthForWrap(int plaintextLength, int numComponents) {
714 return (int) min(maxWrapBufferSize, plaintextLength + (long) maxWrapOverhead * numComponents);
715 }
716
717
718
719
720
721
722
723
724 final int calculateOutNetBufSize(int plaintextLength, int numComponents) {
725 return (int) min(MAX_VALUE, plaintextLength + (long) maxWrapOverhead * numComponents);
726 }
727
728 final synchronized int sslPending() {
729 return sslPending0();
730 }
731
732
733
734
735 private void calculateMaxWrapOverhead() {
736 maxWrapOverhead = SSL.getMaxWrapOverhead(ssl);
737
738
739
740
741 maxWrapBufferSize = jdkCompatibilityMode ? maxEncryptedPacketLength0() : maxEncryptedPacketLength0() << 4;
742 }
743
744 private int sslPending0() {
745
746
747
748
749 return handshakeState != HandshakeState.FINISHED ? 0 : SSL.sslPending(ssl);
750 }
751
752 private boolean isBytesAvailableEnoughForWrap(int bytesAvailable, int plaintextLength, int numComponents) {
753 return bytesAvailable - (long) maxWrapOverhead * numComponents >= plaintextLength;
754 }
755
756 @Override
757 public final SSLEngineResult wrap(
758 final ByteBuffer[] srcs, int offset, final int length, final ByteBuffer dst) throws SSLException {
759
760 checkNotNullWithIAE(srcs, "srcs");
761 checkNotNullWithIAE(dst, "dst");
762
763 if (offset >= srcs.length || offset + length > srcs.length) {
764 throw new IndexOutOfBoundsException(
765 "offset: " + offset + ", length: " + length +
766 " (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
767 }
768
769 if (dst.isReadOnly()) {
770 throw new ReadOnlyBufferException();
771 }
772
773 synchronized (this) {
774 if (isOutboundDone()) {
775
776 return isInboundDone() || isDestroyed() ? CLOSED_NOT_HANDSHAKING : NEED_UNWRAP_CLOSED;
777 }
778
779 int bytesProduced = 0;
780 ByteBuf bioReadCopyBuf = null;
781 try {
782
783 if (dst.isDirect()) {
784 SSL.bioSetByteBuffer(networkBIO, bufferAddress(dst) + dst.position(), dst.remaining(),
785 true);
786 } else {
787 bioReadCopyBuf = alloc.directBuffer(dst.remaining());
788 SSL.bioSetByteBuffer(networkBIO, memoryAddress(bioReadCopyBuf), bioReadCopyBuf.writableBytes(),
789 true);
790 }
791
792 int bioLengthBefore = SSL.bioLengthByteBuffer(networkBIO);
793
794
795 if (outboundClosed) {
796
797
798
799
800
801 if (!isBytesAvailableEnoughForWrap(dst.remaining(), 2, 1)) {
802 return new SSLEngineResult(BUFFER_OVERFLOW, getHandshakeStatus(), 0, 0);
803 }
804
805
806
807 bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
808 if (bytesProduced <= 0) {
809 return newResultMayFinishHandshake(NOT_HANDSHAKING, 0, 0);
810 }
811
812
813
814 if (!doSSLShutdown()) {
815 return newResultMayFinishHandshake(NOT_HANDSHAKING, 0, bytesProduced);
816 }
817 bytesProduced = bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
818 return newResultMayFinishHandshake(NEED_WRAP, 0, bytesProduced);
819 }
820
821
822 SSLEngineResult.HandshakeStatus status = NOT_HANDSHAKING;
823 HandshakeState oldHandshakeState = handshakeState;
824
825
826 if (handshakeState != HandshakeState.FINISHED) {
827 if (handshakeState != HandshakeState.STARTED_EXPLICITLY) {
828
829 handshakeState = HandshakeState.STARTED_IMPLICITLY;
830 }
831
832
833 bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
834
835 if (pendingException != null) {
836
837
838
839
840
841
842
843
844
845
846
847 if (bytesProduced > 0) {
848 return newResult(NEED_WRAP, 0, bytesProduced);
849 }
850
851
852
853 return newResult(handshakeException(), 0, 0);
854 }
855
856 status = handshake();
857
858
859
860 bytesProduced = bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
861
862 if (status == NEED_TASK) {
863 return newResult(status, 0, bytesProduced);
864 }
865
866 if (bytesProduced > 0) {
867
868
869
870 return newResult(mayFinishHandshake(status != FINISHED ?
871 bytesProduced == bioLengthBefore ? NEED_WRAP :
872 getHandshakeStatus(SSL.bioLengthNonApplication(networkBIO)) : FINISHED),
873 0, bytesProduced);
874 }
875
876 if (status == NEED_UNWRAP) {
877
878 return isOutboundDone() ? NEED_UNWRAP_CLOSED : NEED_UNWRAP_OK;
879 }
880
881
882
883 if (outboundClosed) {
884 bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
885 return newResultMayFinishHandshake(status, 0, bytesProduced);
886 }
887 }
888
889 final int endOffset = offset + length;
890 if (jdkCompatibilityMode ||
891
892
893
894 oldHandshakeState != HandshakeState.FINISHED) {
895 int srcsLen = 0;
896 for (int i = offset; i < endOffset; ++i) {
897 final ByteBuffer src = srcs[i];
898 if (src == null) {
899 throw new IllegalArgumentException("srcs[" + i + "] is null");
900 }
901 if (srcsLen == MAX_PLAINTEXT_LENGTH) {
902 continue;
903 }
904
905 srcsLen += src.remaining();
906 if (srcsLen > MAX_PLAINTEXT_LENGTH || srcsLen < 0) {
907
908
909
910 srcsLen = MAX_PLAINTEXT_LENGTH;
911 }
912 }
913
914
915
916 if (!isBytesAvailableEnoughForWrap(dst.remaining(), srcsLen, 1)) {
917 return new SSLEngineResult(BUFFER_OVERFLOW, getHandshakeStatus(), 0, 0);
918 }
919 }
920
921
922 int bytesConsumed = 0;
923 assert bytesProduced == 0;
924
925
926 bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
927
928 if (bytesProduced > 0) {
929 return newResultMayFinishHandshake(status, bytesConsumed, bytesProduced);
930 }
931
932
933 if (pendingException != null) {
934 Throwable error = pendingException;
935 pendingException = null;
936 shutdown();
937
938
939 throw new SSLException(error);
940 }
941
942 for (; offset < endOffset; ++offset) {
943 final ByteBuffer src = srcs[offset];
944 final int remaining = src.remaining();
945 if (remaining == 0) {
946 continue;
947 }
948
949 final int bytesWritten;
950 if (jdkCompatibilityMode) {
951
952
953
954 bytesWritten = writePlaintextData(src, min(remaining, MAX_PLAINTEXT_LENGTH - bytesConsumed));
955 } else {
956
957
958
959 final int availableCapacityForWrap = dst.remaining() - bytesProduced - maxWrapOverhead;
960 if (availableCapacityForWrap <= 0) {
961 return new SSLEngineResult(BUFFER_OVERFLOW, getHandshakeStatus(), bytesConsumed,
962 bytesProduced);
963 }
964 bytesWritten = writePlaintextData(src, min(remaining, availableCapacityForWrap));
965 }
966
967
968
969
970
971
972 final int pendingNow = SSL.bioLengthByteBuffer(networkBIO);
973 bytesProduced += bioLengthBefore - pendingNow;
974 bioLengthBefore = pendingNow;
975
976 if (bytesWritten > 0) {
977 bytesConsumed += bytesWritten;
978
979 if (jdkCompatibilityMode || bytesProduced == dst.remaining()) {
980 return newResultMayFinishHandshake(status, bytesConsumed, bytesProduced);
981 }
982 } else {
983 int sslError = SSL.getError(ssl, bytesWritten);
984 if (sslError == SSL.SSL_ERROR_ZERO_RETURN) {
985
986 if (!receivedShutdown) {
987 closeAll();
988
989 bytesProduced += bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
990
991
992
993
994 SSLEngineResult.HandshakeStatus hs = mayFinishHandshake(
995 status != FINISHED ? bytesProduced == dst.remaining() ? NEED_WRAP
996 : getHandshakeStatus(SSL.bioLengthNonApplication(networkBIO))
997 : FINISHED);
998 return newResult(hs, bytesConsumed, bytesProduced);
999 }
1000
1001 return newResult(NOT_HANDSHAKING, bytesConsumed, bytesProduced);
1002 } else if (sslError == SSL.SSL_ERROR_WANT_READ) {
1003
1004
1005
1006 return newResult(NEED_UNWRAP, bytesConsumed, bytesProduced);
1007 } else if (sslError == SSL.SSL_ERROR_WANT_WRITE) {
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020 if (bytesProduced > 0) {
1021
1022
1023 return newResult(NEED_WRAP, bytesConsumed, bytesProduced);
1024 }
1025 return newResult(BUFFER_OVERFLOW, status, bytesConsumed, bytesProduced);
1026 } else if (sslError == SSL.SSL_ERROR_WANT_X509_LOOKUP ||
1027 sslError == SSL.SSL_ERROR_WANT_CERTIFICATE_VERIFY ||
1028 sslError == SSL.SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1029
1030 return newResult(NEED_TASK, bytesConsumed, bytesProduced);
1031 } else {
1032
1033 throw shutdownWithError("SSL_write", sslError, SSL.getLastErrorNumber());
1034 }
1035 }
1036 }
1037 return newResultMayFinishHandshake(status, bytesConsumed, bytesProduced);
1038 } finally {
1039 SSL.bioClearByteBuffer(networkBIO);
1040 if (bioReadCopyBuf == null) {
1041 dst.position(dst.position() + bytesProduced);
1042 } else {
1043 assert bioReadCopyBuf.readableBytes() <= dst.remaining() : "The destination buffer " + dst +
1044 " didn't have enough remaining space to hold the encrypted content in " + bioReadCopyBuf;
1045 dst.put(bioReadCopyBuf.internalNioBuffer(bioReadCopyBuf.readerIndex(), bytesProduced));
1046 bioReadCopyBuf.release();
1047 }
1048 }
1049 }
1050 }
1051
1052 private SSLEngineResult newResult(SSLEngineResult.HandshakeStatus hs, int bytesConsumed, int bytesProduced) {
1053 return newResult(OK, hs, bytesConsumed, bytesProduced);
1054 }
1055
1056 private SSLEngineResult newResult(SSLEngineResult.Status status, SSLEngineResult.HandshakeStatus hs,
1057 int bytesConsumed, int bytesProduced) {
1058
1059
1060
1061 if (isOutboundDone()) {
1062 if (isInboundDone()) {
1063
1064 hs = NOT_HANDSHAKING;
1065
1066
1067 shutdown();
1068 }
1069 return new SSLEngineResult(CLOSED, hs, bytesConsumed, bytesProduced);
1070 }
1071 if (hs == NEED_TASK) {
1072
1073 needTask = true;
1074 }
1075 return new SSLEngineResult(status, hs, bytesConsumed, bytesProduced);
1076 }
1077
1078 private SSLEngineResult newResultMayFinishHandshake(SSLEngineResult.HandshakeStatus hs,
1079 int bytesConsumed, int bytesProduced) throws SSLException {
1080 return newResult(mayFinishHandshake(hs, bytesConsumed, bytesProduced), bytesConsumed, bytesProduced);
1081 }
1082
1083 private SSLEngineResult newResultMayFinishHandshake(SSLEngineResult.Status status,
1084 SSLEngineResult.HandshakeStatus hs,
1085 int bytesConsumed, int bytesProduced) throws SSLException {
1086 return newResult(status, mayFinishHandshake(hs, bytesConsumed, bytesProduced), bytesConsumed, bytesProduced);
1087 }
1088
1089
1090
1091
1092 private SSLException shutdownWithError(String operation, int sslError, int error) {
1093 if (logger.isDebugEnabled()) {
1094 String errorString = SSL.getErrorString(error);
1095 logger.debug("{} failed with {}: OpenSSL error: {} {}",
1096 operation, sslError, error, errorString);
1097 }
1098
1099
1100 shutdown();
1101
1102 SSLException exception = newSSLExceptionForError(error);
1103
1104 if (pendingException != null) {
1105 exception.initCause(pendingException);
1106 pendingException = null;
1107 }
1108 return exception;
1109 }
1110
1111 private SSLEngineResult handleUnwrapException(int bytesConsumed, int bytesProduced, SSLException e)
1112 throws SSLException {
1113 int lastError = SSL.getLastErrorNumber();
1114 if (lastError != 0) {
1115 return sslReadErrorResult(SSL.SSL_ERROR_SSL, lastError, bytesConsumed,
1116 bytesProduced);
1117 }
1118 throw e;
1119 }
1120
1121 public final SSLEngineResult unwrap(
1122 final ByteBuffer[] srcs, int srcsOffset, final int srcsLength,
1123 final ByteBuffer[] dsts, int dstsOffset, final int dstsLength) throws SSLException {
1124
1125
1126 checkNotNullWithIAE(srcs, "srcs");
1127 if (srcsOffset >= srcs.length
1128 || srcsOffset + srcsLength > srcs.length) {
1129 throw new IndexOutOfBoundsException(
1130 "offset: " + srcsOffset + ", length: " + srcsLength +
1131 " (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
1132 }
1133 checkNotNullWithIAE(dsts, "dsts");
1134 if (dstsOffset >= dsts.length || dstsOffset + dstsLength > dsts.length) {
1135 throw new IndexOutOfBoundsException(
1136 "offset: " + dstsOffset + ", length: " + dstsLength +
1137 " (expected: offset <= offset + length <= dsts.length (" + dsts.length + "))");
1138 }
1139 long capacity = 0;
1140 final int dstsEndOffset = dstsOffset + dstsLength;
1141 for (int i = dstsOffset; i < dstsEndOffset; i ++) {
1142 ByteBuffer dst = checkNotNullArrayParam(dsts[i], i, "dsts");
1143 if (dst.isReadOnly()) {
1144 throw new ReadOnlyBufferException();
1145 }
1146 capacity += dst.remaining();
1147 }
1148
1149 final int srcsEndOffset = srcsOffset + srcsLength;
1150 long len = 0;
1151 for (int i = srcsOffset; i < srcsEndOffset; i++) {
1152 ByteBuffer src = checkNotNullArrayParam(srcs[i], i, "srcs");
1153 len += src.remaining();
1154 }
1155
1156 synchronized (this) {
1157 if (isInboundDone()) {
1158 return isOutboundDone() || isDestroyed() ? CLOSED_NOT_HANDSHAKING : NEED_WRAP_CLOSED;
1159 }
1160
1161 SSLEngineResult.HandshakeStatus status = NOT_HANDSHAKING;
1162 HandshakeState oldHandshakeState = handshakeState;
1163
1164 if (handshakeState != HandshakeState.FINISHED) {
1165 if (handshakeState != HandshakeState.STARTED_EXPLICITLY) {
1166
1167 handshakeState = HandshakeState.STARTED_IMPLICITLY;
1168 }
1169
1170 status = handshake();
1171
1172 if (status == NEED_TASK) {
1173 return newResult(status, 0, 0);
1174 }
1175
1176 if (status == NEED_WRAP) {
1177 return NEED_WRAP_OK;
1178 }
1179
1180 if (isInboundDone) {
1181 return NEED_WRAP_CLOSED;
1182 }
1183 }
1184
1185 int sslPending = sslPending0();
1186 int packetLength;
1187
1188
1189
1190
1191 if (jdkCompatibilityMode ||
1192
1193
1194
1195 oldHandshakeState != HandshakeState.FINISHED) {
1196 if (len < SSL_RECORD_HEADER_LENGTH) {
1197 return newResultMayFinishHandshake(BUFFER_UNDERFLOW, status, 0, 0);
1198 }
1199
1200 packetLength = SslUtils.getEncryptedPacketLength(srcs, srcsOffset);
1201 if (packetLength == SslUtils.NOT_ENCRYPTED) {
1202 throw new NotSslRecordException("not an SSL/TLS record");
1203 }
1204
1205 assert packetLength >= 0;
1206
1207 final int packetLengthDataOnly = packetLength - SSL_RECORD_HEADER_LENGTH;
1208 if (packetLengthDataOnly > capacity) {
1209
1210
1211 if (packetLengthDataOnly > MAX_RECORD_SIZE) {
1212
1213
1214
1215
1216
1217 throw new SSLException("Illegal packet length: " + packetLengthDataOnly + " > " +
1218 session.getApplicationBufferSize());
1219 } else {
1220 session.tryExpandApplicationBufferSize(packetLengthDataOnly);
1221 }
1222 return newResultMayFinishHandshake(BUFFER_OVERFLOW, status, 0, 0);
1223 }
1224
1225 if (len < packetLength) {
1226
1227
1228 return newResultMayFinishHandshake(BUFFER_UNDERFLOW, status, 0, 0);
1229 }
1230 } else if (len == 0 && sslPending <= 0) {
1231 return newResultMayFinishHandshake(BUFFER_UNDERFLOW, status, 0, 0);
1232 } else if (capacity == 0) {
1233 return newResultMayFinishHandshake(BUFFER_OVERFLOW, status, 0, 0);
1234 } else {
1235 packetLength = (int) min(MAX_VALUE, len);
1236 }
1237
1238
1239 assert srcsOffset < srcsEndOffset;
1240
1241
1242 assert capacity > 0;
1243
1244
1245 int bytesProduced = 0;
1246 int bytesConsumed = 0;
1247 try {
1248 srcLoop:
1249 for (;;) {
1250 ByteBuffer src = srcs[srcsOffset];
1251 int remaining = src.remaining();
1252 final ByteBuf bioWriteCopyBuf;
1253 int pendingEncryptedBytes;
1254 if (remaining == 0) {
1255 if (sslPending <= 0) {
1256
1257
1258 if (++srcsOffset >= srcsEndOffset) {
1259 break;
1260 }
1261 continue;
1262 } else {
1263 bioWriteCopyBuf = null;
1264 pendingEncryptedBytes = SSL.bioLengthByteBuffer(networkBIO);
1265 }
1266 } else {
1267
1268
1269 pendingEncryptedBytes = min(packetLength, remaining);
1270 try {
1271 bioWriteCopyBuf = writeEncryptedData(src, pendingEncryptedBytes);
1272 } catch (SSLException e) {
1273
1274 return handleUnwrapException(bytesConsumed, bytesProduced, e);
1275 }
1276 }
1277 try {
1278 for (;;) {
1279 ByteBuffer dst = dsts[dstsOffset];
1280 if (!dst.hasRemaining()) {
1281
1282 if (++dstsOffset >= dstsEndOffset) {
1283 break srcLoop;
1284 }
1285 continue;
1286 }
1287
1288 int bytesRead;
1289 try {
1290 bytesRead = readPlaintextData(dst);
1291 } catch (SSLException e) {
1292
1293 return handleUnwrapException(bytesConsumed, bytesProduced, e);
1294 }
1295
1296
1297
1298 int localBytesConsumed = pendingEncryptedBytes - SSL.bioLengthByteBuffer(networkBIO);
1299 bytesConsumed += localBytesConsumed;
1300 packetLength -= localBytesConsumed;
1301 pendingEncryptedBytes -= localBytesConsumed;
1302 src.position(src.position() + localBytesConsumed);
1303
1304 if (bytesRead > 0) {
1305 bytesProduced += bytesRead;
1306
1307 if (!dst.hasRemaining()) {
1308 sslPending = sslPending0();
1309
1310 if (++dstsOffset >= dstsEndOffset) {
1311 return sslPending > 0 ?
1312 newResult(BUFFER_OVERFLOW, status, bytesConsumed, bytesProduced) :
1313 newResultMayFinishHandshake(isInboundDone() ? CLOSED : OK, status,
1314 bytesConsumed, bytesProduced);
1315 }
1316 } else if (packetLength == 0 || jdkCompatibilityMode) {
1317
1318
1319 break srcLoop;
1320 }
1321 } else {
1322 int sslError = SSL.getError(ssl, bytesRead);
1323 if (sslError == SSL.SSL_ERROR_WANT_READ || sslError == SSL.SSL_ERROR_WANT_WRITE) {
1324
1325
1326 break;
1327 } else if (sslError == SSL.SSL_ERROR_ZERO_RETURN) {
1328
1329 if (!receivedShutdown) {
1330 closeAll();
1331 }
1332 return newResultMayFinishHandshake(isInboundDone() ? CLOSED : OK, status,
1333 bytesConsumed, bytesProduced);
1334 } else if (sslError == SSL.SSL_ERROR_WANT_X509_LOOKUP ||
1335 sslError == SSL.SSL_ERROR_WANT_CERTIFICATE_VERIFY ||
1336 sslError == SSL.SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1337 return newResult(isInboundDone() ? CLOSED : OK,
1338 NEED_TASK, bytesConsumed, bytesProduced);
1339 } else {
1340 return sslReadErrorResult(sslError, SSL.getLastErrorNumber(), bytesConsumed,
1341 bytesProduced);
1342 }
1343 }
1344 }
1345
1346 if (++srcsOffset >= srcsEndOffset) {
1347 break;
1348 }
1349 } finally {
1350 if (bioWriteCopyBuf != null) {
1351 bioWriteCopyBuf.release();
1352 }
1353 }
1354 }
1355 } finally {
1356 SSL.bioClearByteBuffer(networkBIO);
1357 rejectRemoteInitiatedRenegotiation();
1358 }
1359
1360
1361 if (!receivedShutdown && (SSL.getShutdown(ssl) & SSL.SSL_RECEIVED_SHUTDOWN) == SSL.SSL_RECEIVED_SHUTDOWN) {
1362 closeAll();
1363 }
1364
1365 return newResultMayFinishHandshake(isInboundDone() ? CLOSED : OK, status, bytesConsumed, bytesProduced);
1366 }
1367 }
1368
1369 private boolean needWrapAgain(int stackError) {
1370
1371
1372
1373
1374 if (SSL.bioLengthNonApplication(networkBIO) > 0) {
1375
1376
1377 if (pendingException == null) {
1378 pendingException = newSSLExceptionForError(stackError);
1379 } else if (shouldAddSuppressed(pendingException, stackError)) {
1380 ThrowableUtil.addSuppressed(pendingException, newSSLExceptionForError(stackError));
1381 }
1382
1383
1384 SSL.clearError();
1385 return true;
1386 }
1387 return false;
1388 }
1389
1390 private SSLException newSSLExceptionForError(int stackError) {
1391 String message = SSL.getErrorString(stackError);
1392 return handshakeState == HandshakeState.FINISHED ?
1393 new OpenSslException(message, stackError) : new OpenSslHandshakeException(message, stackError);
1394 }
1395
1396 private static boolean shouldAddSuppressed(Throwable target, int errorCode) {
1397 for (Throwable suppressed: ThrowableUtil.getSuppressed(target)) {
1398 if (suppressed instanceof NativeSslException &&
1399 ((NativeSslException) suppressed).errorCode() == errorCode) {
1400
1401 return false;
1402 }
1403 }
1404 return true;
1405 }
1406
1407 private SSLEngineResult sslReadErrorResult(int error, int stackError, int bytesConsumed, int bytesProduced)
1408 throws SSLException {
1409 if (needWrapAgain(stackError)) {
1410
1411
1412 return new SSLEngineResult(OK, NEED_WRAP, bytesConsumed, bytesProduced);
1413 }
1414 throw shutdownWithError("SSL_read", error, stackError);
1415 }
1416
1417 private void closeAll() throws SSLException {
1418 receivedShutdown = true;
1419 closeOutbound();
1420 closeInbound();
1421 }
1422
1423 private void rejectRemoteInitiatedRenegotiation() throws SSLHandshakeException {
1424
1425
1426
1427 if (!isDestroyed() && (!clientMode && SSL.getHandshakeCount(ssl) > 1 ||
1428
1429 clientMode && SSL.getHandshakeCount(ssl) > 2) &&
1430
1431
1432 !SslProtocols.TLS_v1_3.equals(session.getProtocol()) && handshakeState == HandshakeState.FINISHED) {
1433
1434
1435 shutdown();
1436 throw new SSLHandshakeException("remote-initiated renegotiation not allowed");
1437 }
1438 }
1439
1440 public final SSLEngineResult unwrap(final ByteBuffer[] srcs, final ByteBuffer[] dsts) throws SSLException {
1441 return unwrap(srcs, 0, srcs.length, dsts, 0, dsts.length);
1442 }
1443
1444 private ByteBuffer[] singleSrcBuffer(ByteBuffer src) {
1445 singleSrcBuffer[0] = src;
1446 return singleSrcBuffer;
1447 }
1448
1449 private void resetSingleSrcBuffer() {
1450 singleSrcBuffer[0] = null;
1451 }
1452
1453 private ByteBuffer[] singleDstBuffer(ByteBuffer src) {
1454 singleDstBuffer[0] = src;
1455 return singleDstBuffer;
1456 }
1457
1458 private void resetSingleDstBuffer() {
1459 singleDstBuffer[0] = null;
1460 }
1461
1462 @Override
1463 public final synchronized SSLEngineResult unwrap(
1464 final ByteBuffer src, final ByteBuffer[] dsts, final int offset, final int length) throws SSLException {
1465 try {
1466 return unwrap(singleSrcBuffer(src), 0, 1, dsts, offset, length);
1467 } finally {
1468 resetSingleSrcBuffer();
1469 }
1470 }
1471
1472 @Override
1473 public final synchronized SSLEngineResult wrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
1474 try {
1475 return wrap(singleSrcBuffer(src), dst);
1476 } finally {
1477 resetSingleSrcBuffer();
1478 }
1479 }
1480
1481 @Override
1482 public final synchronized SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
1483 try {
1484 return unwrap(singleSrcBuffer(src), singleDstBuffer(dst));
1485 } finally {
1486 resetSingleSrcBuffer();
1487 resetSingleDstBuffer();
1488 }
1489 }
1490
1491 @Override
1492 public final synchronized SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts) throws SSLException {
1493 try {
1494 return unwrap(singleSrcBuffer(src), dsts);
1495 } finally {
1496 resetSingleSrcBuffer();
1497 }
1498 }
1499
1500 private class TaskDecorator<R extends Runnable> implements Runnable {
1501 protected final R task;
1502 TaskDecorator(R task) {
1503 this.task = task;
1504 }
1505
1506 @Override
1507 public void run() {
1508 runAndResetNeedTask(task);
1509 }
1510 }
1511
1512 private final class AsyncTaskDecorator extends TaskDecorator<AsyncTask> implements AsyncRunnable {
1513 AsyncTaskDecorator(AsyncTask task) {
1514 super(task);
1515 }
1516
1517 @Override
1518 public void run(final Runnable runnable) {
1519 if (isDestroyed()) {
1520
1521 return;
1522 }
1523 task.runAsync(new TaskDecorator<Runnable>(runnable));
1524 }
1525 }
1526
1527 private void runAndResetNeedTask(Runnable task) {
1528
1529
1530 synchronized (ReferenceCountedOpenSslEngine.this) {
1531 try {
1532 if (isDestroyed()) {
1533
1534 return;
1535 }
1536 task.run();
1537 if (handshakeState != HandshakeState.FINISHED && !isDestroyed()) {
1538
1539
1540
1541 if (SSL.doHandshake(ssl) <= 0) {
1542 SSL.clearError();
1543 }
1544 }
1545 } finally {
1546
1547 needTask = false;
1548 }
1549 }
1550 }
1551
1552 @Override
1553 public final synchronized Runnable getDelegatedTask() {
1554 if (isDestroyed()) {
1555 return null;
1556 }
1557 final Runnable task = SSL.getTask(ssl);
1558 if (task == null) {
1559 return null;
1560 }
1561 if (task instanceof AsyncTask) {
1562 return new AsyncTaskDecorator((AsyncTask) task);
1563 }
1564 return new TaskDecorator<Runnable>(task);
1565 }
1566
1567 @Override
1568 public final synchronized void closeInbound() throws SSLException {
1569 if (isInboundDone) {
1570 return;
1571 }
1572
1573 isInboundDone = true;
1574
1575 if (isOutboundDone()) {
1576
1577
1578 shutdown();
1579 }
1580
1581 if (handshakeState != HandshakeState.NOT_STARTED && !receivedShutdown) {
1582 throw new SSLException(
1583 "Inbound closed before receiving peer's close_notify: possible truncation attack?");
1584 }
1585 }
1586
1587 @Override
1588 public final synchronized boolean isInboundDone() {
1589 return isInboundDone;
1590 }
1591
1592 @Override
1593 public final synchronized void closeOutbound() {
1594 if (outboundClosed) {
1595 return;
1596 }
1597
1598 outboundClosed = true;
1599
1600 if (handshakeState != HandshakeState.NOT_STARTED && !isDestroyed()) {
1601 int mode = SSL.getShutdown(ssl);
1602 if ((mode & SSL.SSL_SENT_SHUTDOWN) != SSL.SSL_SENT_SHUTDOWN) {
1603 doSSLShutdown();
1604 }
1605 } else {
1606
1607 shutdown();
1608 }
1609 }
1610
1611
1612
1613
1614
1615 private boolean doSSLShutdown() {
1616 if (SSL.isInInit(ssl) != 0) {
1617
1618
1619
1620
1621 return false;
1622 }
1623 int err = SSL.shutdownSSL(ssl);
1624 if (err < 0) {
1625 int sslErr = SSL.getError(ssl, err);
1626 if (sslErr == SSL.SSL_ERROR_SYSCALL || sslErr == SSL.SSL_ERROR_SSL) {
1627 if (logger.isDebugEnabled()) {
1628 int error = SSL.getLastErrorNumber();
1629 logger.debug("SSL_shutdown failed: OpenSSL error: {} {}", error, SSL.getErrorString(error));
1630 }
1631
1632 shutdown();
1633 return false;
1634 }
1635 SSL.clearError();
1636 }
1637 return true;
1638 }
1639
1640 @Override
1641 public final synchronized boolean isOutboundDone() {
1642
1643
1644 return outboundClosed && (networkBIO == 0 || SSL.bioLengthNonApplication(networkBIO) == 0);
1645 }
1646
1647 @Override
1648 public final String[] getSupportedCipherSuites() {
1649 return OpenSsl.AVAILABLE_CIPHER_SUITES.toArray(EMPTY_STRINGS);
1650 }
1651
1652 @Override
1653 public final String[] getEnabledCipherSuites() {
1654 final String[] extraCiphers;
1655 final String[] enabled;
1656 final boolean tls13Enabled;
1657 synchronized (this) {
1658 if (!isDestroyed()) {
1659 enabled = SSL.getCiphers(ssl);
1660 int opts = SSL.getOptions(ssl);
1661 if (isProtocolEnabled(opts, SSL.SSL_OP_NO_TLSv1_3, SslProtocols.TLS_v1_3)) {
1662 extraCiphers = OpenSsl.EXTRA_SUPPORTED_TLS_1_3_CIPHERS;
1663 tls13Enabled = true;
1664 } else {
1665 extraCiphers = EMPTY_STRINGS;
1666 tls13Enabled = false;
1667 }
1668 } else {
1669 return EMPTY_STRINGS;
1670 }
1671 }
1672 if (enabled == null) {
1673 return EMPTY_STRINGS;
1674 } else {
1675 Set<String> enabledSet = new LinkedHashSet<String>(enabled.length + extraCiphers.length);
1676 synchronized (this) {
1677 for (int i = 0; i < enabled.length; i++) {
1678 String mapped = toJavaCipherSuite(enabled[i]);
1679 final String cipher = mapped == null ? enabled[i] : mapped;
1680 if ((!tls13Enabled || !OpenSsl.isTlsv13Supported()) && SslUtils.isTLSv13Cipher(cipher)) {
1681 continue;
1682 }
1683 enabledSet.add(cipher);
1684 }
1685 Collections.addAll(enabledSet, extraCiphers);
1686 }
1687 return enabledSet.toArray(EMPTY_STRINGS);
1688 }
1689 }
1690
1691 @Override
1692 public final void setEnabledCipherSuites(String[] cipherSuites) {
1693 checkNotNull(cipherSuites, "cipherSuites");
1694
1695 final StringBuilder buf = new StringBuilder();
1696 final StringBuilder bufTLSv13 = new StringBuilder();
1697
1698 CipherSuiteConverter.convertToCipherStrings(Arrays.asList(cipherSuites), buf, bufTLSv13, OpenSsl.isBoringSSL());
1699 final String cipherSuiteSpec = buf.toString();
1700 final String cipherSuiteSpecTLSv13 = bufTLSv13.toString();
1701
1702 if (!OpenSsl.isTlsv13Supported() && !cipherSuiteSpecTLSv13.isEmpty()) {
1703 throw new IllegalArgumentException("TLSv1.3 is not supported by this java version.");
1704 }
1705 synchronized (this) {
1706 hasTLSv13Cipher = !cipherSuiteSpecTLSv13.isEmpty();
1707 if (!isDestroyed()) {
1708 try {
1709
1710 SSL.setCipherSuites(ssl, cipherSuiteSpec, false);
1711 if (OpenSsl.isTlsv13Supported()) {
1712
1713 SSL.setCipherSuites(ssl, OpenSsl.checkTls13Ciphers(logger, cipherSuiteSpecTLSv13), true);
1714 }
1715
1716
1717
1718 Set<String> protocols = new HashSet<String>(enabledProtocols);
1719
1720
1721
1722 if (cipherSuiteSpec.isEmpty()) {
1723 protocols.remove(SslProtocols.TLS_v1);
1724 protocols.remove(SslProtocols.TLS_v1_1);
1725 protocols.remove(SslProtocols.TLS_v1_2);
1726 protocols.remove(SslProtocols.SSL_v3);
1727 protocols.remove(SslProtocols.SSL_v2);
1728 protocols.remove(SslProtocols.SSL_v2_HELLO);
1729 }
1730
1731 if (cipherSuiteSpecTLSv13.isEmpty()) {
1732 protocols.remove(SslProtocols.TLS_v1_3);
1733 }
1734
1735
1736 setEnabledProtocols0(protocols.toArray(EMPTY_STRINGS), !hasTLSv13Cipher);
1737 } catch (Exception e) {
1738 throw new IllegalStateException("failed to enable cipher suites: " + cipherSuiteSpec, e);
1739 }
1740 } else {
1741 throw new IllegalStateException("failed to enable cipher suites: " + cipherSuiteSpec);
1742 }
1743 }
1744 }
1745
1746 @Override
1747 public final String[] getSupportedProtocols() {
1748 return OpenSsl.SUPPORTED_PROTOCOLS_SET.toArray(EMPTY_STRINGS);
1749 }
1750
1751 @Override
1752 public final String[] getEnabledProtocols() {
1753 return enabledProtocols.toArray(EMPTY_STRINGS);
1754 }
1755
1756 private static boolean isProtocolEnabled(int opts, int disableMask, String protocolString) {
1757
1758
1759 return (opts & disableMask) == 0 && OpenSsl.SUPPORTED_PROTOCOLS_SET.contains(protocolString);
1760 }
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771 @Override
1772 public final void setEnabledProtocols(String[] protocols) {
1773 checkNotNullWithIAE(protocols, "protocols");
1774 synchronized (this) {
1775 enabledProtocols.clear();
1776
1777 enabledProtocols.add(SslProtocols.SSL_v2_HELLO);
1778
1779 Collections.addAll(enabledProtocols, protocols);
1780
1781 setEnabledProtocols0(protocols, !hasTLSv13Cipher);
1782 }
1783 }
1784
1785 private void setEnabledProtocols0(String[] protocols, boolean explicitDisableTLSv13) {
1786 assert Thread.holdsLock(this);
1787
1788 int minProtocolIndex = OPENSSL_OP_NO_PROTOCOLS.length;
1789 int maxProtocolIndex = 0;
1790 for (String p: protocols) {
1791 if (!OpenSsl.SUPPORTED_PROTOCOLS_SET.contains(p)) {
1792 throw new IllegalArgumentException("Protocol " + p + " is not supported.");
1793 }
1794 if (p.equals(SslProtocols.SSL_v2)) {
1795 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV2) {
1796 minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV2;
1797 }
1798 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV2) {
1799 maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV2;
1800 }
1801 } else if (p.equals(SslProtocols.SSL_v3)) {
1802 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV3) {
1803 minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV3;
1804 }
1805 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV3) {
1806 maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV3;
1807 }
1808 } else if (p.equals(SslProtocols.TLS_v1)) {
1809 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1) {
1810 minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1;
1811 }
1812 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1) {
1813 maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1;
1814 }
1815 } else if (p.equals(SslProtocols.TLS_v1_1)) {
1816 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_1) {
1817 minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_1;
1818 }
1819 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_1) {
1820 maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_1;
1821 }
1822 } else if (p.equals(SslProtocols.TLS_v1_2)) {
1823 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_2) {
1824 minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_2;
1825 }
1826 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_2) {
1827 maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_2;
1828 }
1829 } else if (!explicitDisableTLSv13 && p.equals(SslProtocols.TLS_v1_3)) {
1830 if (minProtocolIndex > OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_3) {
1831 minProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_3;
1832 }
1833 if (maxProtocolIndex < OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_3) {
1834 maxProtocolIndex = OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_3;
1835 }
1836 }
1837 }
1838 if (!isDestroyed()) {
1839
1840 SSL.clearOptions(ssl, SSL.SSL_OP_NO_SSLv2 | SSL.SSL_OP_NO_SSLv3 | SSL.SSL_OP_NO_TLSv1 |
1841 SSL.SSL_OP_NO_TLSv1_1 | SSL.SSL_OP_NO_TLSv1_2 | SSL.SSL_OP_NO_TLSv1_3);
1842
1843 int opts = 0;
1844 for (int i = 0; i < minProtocolIndex; ++i) {
1845 opts |= OPENSSL_OP_NO_PROTOCOLS[i];
1846 }
1847 assert maxProtocolIndex != MAX_VALUE;
1848 for (int i = maxProtocolIndex + 1; i < OPENSSL_OP_NO_PROTOCOLS.length; ++i) {
1849 opts |= OPENSSL_OP_NO_PROTOCOLS[i];
1850 }
1851
1852
1853 SSL.setOptions(ssl, opts);
1854 } else {
1855 throw new IllegalStateException("failed to enable protocols: " + Arrays.asList(protocols));
1856 }
1857 }
1858
1859 @Override
1860 public final SSLSession getSession() {
1861 return session;
1862 }
1863
1864 @Override
1865 public final synchronized void beginHandshake() throws SSLException {
1866 switch (handshakeState) {
1867 case STARTED_IMPLICITLY:
1868 checkEngineClosed();
1869
1870
1871
1872
1873
1874
1875
1876 handshakeState = HandshakeState.STARTED_EXPLICITLY;
1877 calculateMaxWrapOverhead();
1878
1879 break;
1880 case STARTED_EXPLICITLY:
1881
1882 break;
1883 case FINISHED:
1884 throw new SSLException("renegotiation unsupported");
1885 case NOT_STARTED:
1886 handshakeState = HandshakeState.STARTED_EXPLICITLY;
1887 if (handshake() == NEED_TASK) {
1888
1889 needTask = true;
1890 }
1891 calculateMaxWrapOverhead();
1892 break;
1893 default:
1894 throw new Error();
1895 }
1896 }
1897
1898 private void checkEngineClosed() throws SSLException {
1899 if (isDestroyed()) {
1900 throw new SSLException("engine closed");
1901 }
1902 }
1903
1904 private static SSLEngineResult.HandshakeStatus pendingStatus(int pendingStatus) {
1905
1906 return pendingStatus > 0 ? NEED_WRAP : NEED_UNWRAP;
1907 }
1908
1909 private static boolean isEmpty(Object[] arr) {
1910 return arr == null || arr.length == 0;
1911 }
1912
1913 private static boolean isEmpty(byte[] cert) {
1914 return cert == null || cert.length == 0;
1915 }
1916
1917 private SSLEngineResult.HandshakeStatus handshakeException() throws SSLException {
1918 if (SSL.bioLengthNonApplication(networkBIO) > 0) {
1919
1920 return NEED_WRAP;
1921 }
1922
1923 Throwable exception = pendingException;
1924 assert exception != null;
1925 pendingException = null;
1926 shutdown();
1927 if (exception instanceof SSLHandshakeException) {
1928 throw (SSLHandshakeException) exception;
1929 }
1930 SSLHandshakeException e = new SSLHandshakeException("General OpenSslEngine problem");
1931 e.initCause(exception);
1932 throw e;
1933 }
1934
1935
1936
1937
1938
1939 final void initHandshakeException(Throwable cause) {
1940 if (pendingException == null) {
1941 pendingException = cause;
1942 } else {
1943 ThrowableUtil.addSuppressed(pendingException, cause);
1944 }
1945 }
1946
1947 private SSLEngineResult.HandshakeStatus handshake() throws SSLException {
1948 if (needTask) {
1949 return NEED_TASK;
1950 }
1951 if (handshakeState == HandshakeState.FINISHED) {
1952 return FINISHED;
1953 }
1954
1955 checkEngineClosed();
1956
1957 if (pendingException != null) {
1958
1959
1960 if (SSL.doHandshake(ssl) <= 0) {
1961
1962 SSL.clearError();
1963 }
1964 return handshakeException();
1965 }
1966
1967
1968 engineMap.add(this);
1969
1970 if (!sessionSet) {
1971 if (!parentContext.sessionContext().setSessionFromCache(ssl, session, getPeerHost(), getPeerPort())) {
1972
1973
1974 session.prepareHandshake();
1975 }
1976 sessionSet = true;
1977 }
1978
1979 int code = SSL.doHandshake(ssl);
1980 if (code <= 0) {
1981 int sslError = SSL.getError(ssl, code);
1982 if (sslError == SSL.SSL_ERROR_WANT_READ || sslError == SSL.SSL_ERROR_WANT_WRITE) {
1983 return pendingStatus(SSL.bioLengthNonApplication(networkBIO));
1984 }
1985
1986 if (sslError == SSL.SSL_ERROR_WANT_X509_LOOKUP ||
1987 sslError == SSL.SSL_ERROR_WANT_CERTIFICATE_VERIFY ||
1988 sslError == SSL.SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1989 return NEED_TASK;
1990 }
1991
1992 int errorNumber = SSL.getLastErrorNumber();
1993 if (needWrapAgain(errorNumber)) {
1994
1995
1996 return NEED_WRAP;
1997 }
1998
1999
2000 if (pendingException != null) {
2001 return handshakeException();
2002 }
2003
2004
2005 throw shutdownWithError("SSL_do_handshake", sslError, errorNumber);
2006 }
2007
2008 if (SSL.bioLengthNonApplication(networkBIO) > 0) {
2009 return NEED_WRAP;
2010 }
2011
2012 session.handshakeFinished(SSL.getSessionId(ssl), SSL.getCipherForSSL(ssl), SSL.getVersion(ssl),
2013 SSL.getPeerCertificate(ssl), SSL.getPeerCertChain(ssl),
2014 SSL.getTime(ssl) * 1000L, parentContext.sessionTimeout() * 1000L);
2015 selectApplicationProtocol();
2016 return FINISHED;
2017 }
2018
2019 private SSLEngineResult.HandshakeStatus mayFinishHandshake(
2020 SSLEngineResult.HandshakeStatus hs, int bytesConsumed, int bytesProduced) throws SSLException {
2021 return hs == NEED_UNWRAP && bytesProduced > 0 || hs == NEED_WRAP && bytesConsumed > 0 ?
2022 handshake() : mayFinishHandshake(hs != FINISHED ? getHandshakeStatus() : FINISHED);
2023 }
2024
2025 private SSLEngineResult.HandshakeStatus mayFinishHandshake(SSLEngineResult.HandshakeStatus status)
2026 throws SSLException {
2027 if (status == NOT_HANDSHAKING) {
2028 if (handshakeState != HandshakeState.FINISHED) {
2029
2030
2031 return handshake();
2032 }
2033 if (!isDestroyed() && SSL.bioLengthNonApplication(networkBIO) > 0) {
2034
2035 return NEED_WRAP;
2036 }
2037 }
2038 return status;
2039 }
2040
2041 @Override
2042 public final synchronized SSLEngineResult.HandshakeStatus getHandshakeStatus() {
2043
2044 if (needPendingStatus()) {
2045 if (needTask) {
2046
2047 return NEED_TASK;
2048 }
2049 return pendingStatus(SSL.bioLengthNonApplication(networkBIO));
2050 }
2051 return NOT_HANDSHAKING;
2052 }
2053
2054 private SSLEngineResult.HandshakeStatus getHandshakeStatus(int pending) {
2055
2056 if (needPendingStatus()) {
2057 if (needTask) {
2058
2059 return NEED_TASK;
2060 }
2061 return pendingStatus(pending);
2062 }
2063 return NOT_HANDSHAKING;
2064 }
2065
2066 private boolean needPendingStatus() {
2067 return handshakeState != HandshakeState.NOT_STARTED && !isDestroyed()
2068 && (handshakeState != HandshakeState.FINISHED || isInboundDone() || isOutboundDone());
2069 }
2070
2071
2072
2073
2074 private String toJavaCipherSuite(String openSslCipherSuite) {
2075 if (openSslCipherSuite == null) {
2076 return null;
2077 }
2078
2079 String version = SSL.getVersion(ssl);
2080 String prefix = toJavaCipherSuitePrefix(version);
2081 return CipherSuiteConverter.toJava(openSslCipherSuite, prefix);
2082 }
2083
2084
2085
2086
2087 private static String toJavaCipherSuitePrefix(String protocolVersion) {
2088 final char c;
2089 if (protocolVersion == null || protocolVersion.isEmpty()) {
2090 c = 0;
2091 } else {
2092 c = protocolVersion.charAt(0);
2093 }
2094
2095 switch (c) {
2096 case 'T':
2097 return "TLS";
2098 case 'S':
2099 return "SSL";
2100 default:
2101 return "UNKNOWN";
2102 }
2103 }
2104
2105 @Override
2106 public final void setUseClientMode(boolean clientMode) {
2107 if (clientMode != this.clientMode) {
2108 throw new UnsupportedOperationException();
2109 }
2110 }
2111
2112 @Override
2113 public final boolean getUseClientMode() {
2114 return clientMode;
2115 }
2116
2117 @Override
2118 public final void setNeedClientAuth(boolean b) {
2119 setClientAuth(b ? ClientAuth.REQUIRE : ClientAuth.NONE);
2120 }
2121
2122 @Override
2123 public final boolean getNeedClientAuth() {
2124 return clientAuth == ClientAuth.REQUIRE;
2125 }
2126
2127 @Override
2128 public final void setWantClientAuth(boolean b) {
2129 setClientAuth(b ? ClientAuth.OPTIONAL : ClientAuth.NONE);
2130 }
2131
2132 @Override
2133 public final boolean getWantClientAuth() {
2134 return clientAuth == ClientAuth.OPTIONAL;
2135 }
2136
2137
2138
2139
2140
2141 @UnstableApi
2142 public final synchronized void setVerify(int verifyMode, int depth) {
2143 if (!isDestroyed()) {
2144 SSL.setVerify(ssl, verifyMode, depth);
2145 }
2146 }
2147
2148 private void setClientAuth(ClientAuth mode) {
2149 if (clientMode) {
2150 return;
2151 }
2152 synchronized (this) {
2153 if (clientAuth == mode) {
2154
2155 return;
2156 }
2157 if (!isDestroyed()) {
2158 switch (mode) {
2159 case NONE:
2160 SSL.setVerify(ssl, SSL.SSL_CVERIFY_NONE, ReferenceCountedOpenSslContext.VERIFY_DEPTH);
2161 break;
2162 case REQUIRE:
2163 SSL.setVerify(ssl, SSL.SSL_CVERIFY_REQUIRED, ReferenceCountedOpenSslContext.VERIFY_DEPTH);
2164 break;
2165 case OPTIONAL:
2166 SSL.setVerify(ssl, SSL.SSL_CVERIFY_OPTIONAL, ReferenceCountedOpenSslContext.VERIFY_DEPTH);
2167 break;
2168 default:
2169 throw new Error(mode.toString());
2170 }
2171 }
2172 clientAuth = mode;
2173 }
2174 }
2175
2176 @Override
2177 public final void setEnableSessionCreation(boolean b) {
2178 if (b) {
2179 throw new UnsupportedOperationException();
2180 }
2181 }
2182
2183 @Override
2184 public final boolean getEnableSessionCreation() {
2185 return false;
2186 }
2187
2188 @SuppressJava6Requirement(reason = "Usage guarded by java version check")
2189 @Override
2190 public final synchronized SSLParameters getSSLParameters() {
2191 SSLParameters sslParameters = super.getSSLParameters();
2192
2193 int version = PlatformDependent.javaVersion();
2194 if (version >= 7) {
2195 Java7SslParametersUtils.setEndpointIdentificationAlgorithm(sslParameters, endpointIdentificationAlgorithm);
2196 Java7SslParametersUtils.setAlgorithmConstraints(sslParameters, algorithmConstraints);
2197 if (version >= 8) {
2198 if (sniHostNames != null) {
2199 Java8SslUtils.setSniHostNames(sslParameters, sniHostNames);
2200 }
2201 if (!isDestroyed()) {
2202 Java8SslUtils.setUseCipherSuitesOrder(
2203 sslParameters, (SSL.getOptions(ssl) & SSL.SSL_OP_CIPHER_SERVER_PREFERENCE) != 0);
2204 }
2205
2206 Java8SslUtils.setSNIMatchers(sslParameters, matchers);
2207 }
2208 }
2209 return sslParameters;
2210 }
2211
2212 @SuppressJava6Requirement(reason = "Usage guarded by java version check")
2213 @Override
2214 public final synchronized void setSSLParameters(SSLParameters sslParameters) {
2215 int version = PlatformDependent.javaVersion();
2216 if (version >= 7) {
2217 if (sslParameters.getAlgorithmConstraints() != null) {
2218 throw new IllegalArgumentException("AlgorithmConstraints are not supported.");
2219 }
2220
2221 boolean isDestroyed = isDestroyed();
2222 if (version >= 8) {
2223 if (!isDestroyed) {
2224 if (clientMode) {
2225 final List<String> sniHostNames = Java8SslUtils.getSniHostNames(sslParameters);
2226 for (String name: sniHostNames) {
2227 SSL.setTlsExtHostName(ssl, name);
2228 }
2229 this.sniHostNames = sniHostNames;
2230 }
2231 if (Java8SslUtils.getUseCipherSuitesOrder(sslParameters)) {
2232 SSL.setOptions(ssl, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
2233 } else {
2234 SSL.clearOptions(ssl, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
2235 }
2236 }
2237 matchers = sslParameters.getSNIMatchers();
2238 }
2239
2240 final String endpointIdentificationAlgorithm = sslParameters.getEndpointIdentificationAlgorithm();
2241 if (!isDestroyed) {
2242 configureEndpointVerification(endpointIdentificationAlgorithm);
2243 }
2244 this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm;
2245 algorithmConstraints = sslParameters.getAlgorithmConstraints();
2246 }
2247 super.setSSLParameters(sslParameters);
2248 }
2249
2250 private void configureEndpointVerification(String endpointIdentificationAlgorithm) {
2251
2252
2253 if (clientMode && isEndPointVerificationEnabled(endpointIdentificationAlgorithm)) {
2254 SSL.setVerify(ssl, SSL.SSL_CVERIFY_REQUIRED, -1);
2255 }
2256 }
2257
2258 private static boolean isEndPointVerificationEnabled(String endPointIdentificationAlgorithm) {
2259 return endPointIdentificationAlgorithm != null && !endPointIdentificationAlgorithm.isEmpty();
2260 }
2261
2262 private boolean isDestroyed() {
2263 return destroyed;
2264 }
2265
2266 final boolean checkSniHostnameMatch(byte[] hostname) {
2267 return Java8SslUtils.checkSniHostnameMatch(matchers, hostname);
2268 }
2269
2270 @Override
2271 public String getNegotiatedApplicationProtocol() {
2272 return applicationProtocol;
2273 }
2274
2275 private static long bufferAddress(ByteBuffer b) {
2276 assert b.isDirect();
2277 if (PlatformDependent.hasUnsafe()) {
2278 return PlatformDependent.directBufferAddress(b);
2279 }
2280 return Buffer.address(b);
2281 }
2282
2283
2284
2285
2286 private void selectApplicationProtocol() throws SSLException {
2287 ApplicationProtocolConfig.SelectedListenerFailureBehavior behavior = apn.selectedListenerFailureBehavior();
2288 List<String> protocols = apn.protocols();
2289 String applicationProtocol;
2290 switch (apn.protocol()) {
2291 case NONE:
2292 break;
2293
2294
2295 case ALPN:
2296 applicationProtocol = SSL.getAlpnSelected(ssl);
2297 if (applicationProtocol != null) {
2298 ReferenceCountedOpenSslEngine.this.applicationProtocol = selectApplicationProtocol(
2299 protocols, behavior, applicationProtocol);
2300 }
2301 break;
2302 case NPN:
2303 applicationProtocol = SSL.getNextProtoNegotiated(ssl);
2304 if (applicationProtocol != null) {
2305 ReferenceCountedOpenSslEngine.this.applicationProtocol = selectApplicationProtocol(
2306 protocols, behavior, applicationProtocol);
2307 }
2308 break;
2309 case NPN_AND_ALPN:
2310 applicationProtocol = SSL.getAlpnSelected(ssl);
2311 if (applicationProtocol == null) {
2312 applicationProtocol = SSL.getNextProtoNegotiated(ssl);
2313 }
2314 if (applicationProtocol != null) {
2315 ReferenceCountedOpenSslEngine.this.applicationProtocol = selectApplicationProtocol(
2316 protocols, behavior, applicationProtocol);
2317 }
2318 break;
2319 default:
2320 throw new Error();
2321 }
2322 }
2323
2324 private String selectApplicationProtocol(List<String> protocols,
2325 ApplicationProtocolConfig.SelectedListenerFailureBehavior behavior,
2326 String applicationProtocol) throws SSLException {
2327 if (behavior == ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT) {
2328 return applicationProtocol;
2329 } else {
2330 int size = protocols.size();
2331 assert size > 0;
2332 if (protocols.contains(applicationProtocol)) {
2333 return applicationProtocol;
2334 } else {
2335 if (behavior == ApplicationProtocolConfig.SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL) {
2336 return protocols.get(size - 1);
2337 } else {
2338 throw new SSLException("unknown protocol " + applicationProtocol);
2339 }
2340 }
2341 }
2342 }
2343
2344 private static final X509Certificate[] JAVAX_CERTS_NOT_SUPPORTED = new X509Certificate[0];
2345
2346 private final class DefaultOpenSslSession implements OpenSslInternalSession {
2347 private final OpenSslSessionContext sessionContext;
2348
2349
2350
2351 private X509Certificate[] x509PeerCerts;
2352 private Certificate[] peerCerts;
2353
2354 private boolean valid = true;
2355 private String protocol;
2356 private String cipher;
2357 private OpenSslSessionId id = OpenSslSessionId.NULL_ID;
2358 private long creationTime;
2359
2360
2361 private long lastAccessed = -1;
2362
2363 private volatile int applicationBufferSize = MAX_PLAINTEXT_LENGTH;
2364 private volatile Certificate[] localCertificateChain;
2365 private volatile Map<String, Object> keyValueStorage = new ConcurrentHashMap<String, Object>();
2366
2367 DefaultOpenSslSession(OpenSslSessionContext sessionContext) {
2368 this.sessionContext = sessionContext;
2369 }
2370
2371 private SSLSessionBindingEvent newSSLSessionBindingEvent(String name) {
2372 return new SSLSessionBindingEvent(session, name);
2373 }
2374
2375 @Override
2376 public void prepareHandshake() {
2377 keyValueStorage.clear();
2378 }
2379
2380 @Override
2381 public void setSessionDetails(
2382 long creationTime, long lastAccessedTime, OpenSslSessionId sessionId,
2383 Map<String, Object> keyValueStorage) {
2384 synchronized (ReferenceCountedOpenSslEngine.this) {
2385 if (this.id == OpenSslSessionId.NULL_ID) {
2386 this.id = sessionId;
2387 this.creationTime = creationTime;
2388 this.lastAccessed = lastAccessedTime;
2389
2390
2391
2392
2393 this.keyValueStorage = keyValueStorage;
2394 }
2395 }
2396 }
2397
2398 @Override
2399 public Map<String, Object> keyValueStorage() {
2400 return keyValueStorage;
2401 }
2402
2403 @Override
2404 public OpenSslSessionId sessionId() {
2405 synchronized (ReferenceCountedOpenSslEngine.this) {
2406 if (this.id == OpenSslSessionId.NULL_ID && !isDestroyed()) {
2407 byte[] sessionId = SSL.getSessionId(ssl);
2408 if (sessionId != null) {
2409 id = new OpenSslSessionId(sessionId);
2410 }
2411 }
2412
2413 return id;
2414 }
2415 }
2416
2417 @Override
2418 public void setLocalCertificate(Certificate[] localCertificate) {
2419 this.localCertificateChain = localCertificate;
2420 }
2421
2422 @Override
2423 public byte[] getId() {
2424 return sessionId().cloneBytes();
2425 }
2426
2427 @Override
2428 public OpenSslSessionContext getSessionContext() {
2429 return sessionContext;
2430 }
2431
2432 @Override
2433 public long getCreationTime() {
2434 synchronized (ReferenceCountedOpenSslEngine.this) {
2435 return creationTime;
2436 }
2437 }
2438
2439 @Override
2440 public void setLastAccessedTime(long time) {
2441 synchronized (ReferenceCountedOpenSslEngine.this) {
2442 this.lastAccessed = time;
2443 }
2444 }
2445
2446 @Override
2447 public long getLastAccessedTime() {
2448
2449 synchronized (ReferenceCountedOpenSslEngine.this) {
2450 return lastAccessed == -1 ? creationTime : lastAccessed;
2451 }
2452 }
2453
2454 @Override
2455 public void invalidate() {
2456 synchronized (ReferenceCountedOpenSslEngine.this) {
2457 valid = false;
2458 sessionContext.removeFromCache(id);
2459 }
2460 }
2461
2462 @Override
2463 public boolean isValid() {
2464 synchronized (ReferenceCountedOpenSslEngine.this) {
2465 return valid || sessionContext.isInCache(id);
2466 }
2467 }
2468
2469 @Override
2470 public void putValue(String name, Object value) {
2471 checkNotNull(name, "name");
2472 checkNotNull(value, "value");
2473
2474 final Object old = keyValueStorage.put(name, value);
2475 if (value instanceof SSLSessionBindingListener) {
2476
2477 ((SSLSessionBindingListener) value).valueBound(newSSLSessionBindingEvent(name));
2478 }
2479 notifyUnbound(old, name);
2480 }
2481
2482 @Override
2483 public Object getValue(String name) {
2484 checkNotNull(name, "name");
2485 return keyValueStorage.get(name);
2486 }
2487
2488 @Override
2489 public void removeValue(String name) {
2490 checkNotNull(name, "name");
2491 final Object old = keyValueStorage.remove(name);
2492 notifyUnbound(old, name);
2493 }
2494
2495 @Override
2496 public String[] getValueNames() {
2497 return keyValueStorage.keySet().toArray(EMPTY_STRINGS);
2498 }
2499
2500 private void notifyUnbound(Object value, String name) {
2501 if (value instanceof SSLSessionBindingListener) {
2502
2503 ((SSLSessionBindingListener) value).valueUnbound(newSSLSessionBindingEvent(name));
2504 }
2505 }
2506
2507
2508
2509
2510
2511 @Override
2512 public void handshakeFinished(byte[] id, String cipher, String protocol, byte[] peerCertificate,
2513 byte[][] peerCertificateChain, long creationTime, long timeout)
2514 throws SSLException {
2515 synchronized (ReferenceCountedOpenSslEngine.this) {
2516 if (!isDestroyed()) {
2517 if (this.id == OpenSslSessionId.NULL_ID) {
2518
2519
2520 this.id = id == null ? OpenSslSessionId.NULL_ID : new OpenSslSessionId(id);
2521
2522
2523 this.creationTime = lastAccessed = creationTime;
2524 }
2525 this.cipher = toJavaCipherSuite(cipher);
2526 this.protocol = protocol;
2527
2528 if (clientMode) {
2529 if (isEmpty(peerCertificateChain)) {
2530 peerCerts = EmptyArrays.EMPTY_CERTIFICATES;
2531 if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2532 x509PeerCerts = EmptyArrays.EMPTY_JAVAX_X509_CERTIFICATES;
2533 } else {
2534 x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2535 }
2536 } else {
2537 peerCerts = new Certificate[peerCertificateChain.length];
2538 if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2539 x509PeerCerts = new X509Certificate[peerCertificateChain.length];
2540 } else {
2541 x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2542 }
2543 initCerts(peerCertificateChain, 0);
2544 }
2545 } else {
2546
2547
2548
2549
2550
2551 if (isEmpty(peerCertificate)) {
2552 peerCerts = EmptyArrays.EMPTY_CERTIFICATES;
2553 x509PeerCerts = EmptyArrays.EMPTY_JAVAX_X509_CERTIFICATES;
2554 } else {
2555 if (isEmpty(peerCertificateChain)) {
2556 peerCerts = new Certificate[] {new LazyX509Certificate(peerCertificate)};
2557 if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2558 x509PeerCerts = new X509Certificate[] {
2559 new LazyJavaxX509Certificate(peerCertificate)
2560 };
2561 } else {
2562 x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2563 }
2564 } else {
2565 peerCerts = new Certificate[peerCertificateChain.length + 1];
2566 peerCerts[0] = new LazyX509Certificate(peerCertificate);
2567
2568 if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2569 x509PeerCerts = new X509Certificate[peerCertificateChain.length + 1];
2570 x509PeerCerts[0] = new LazyJavaxX509Certificate(peerCertificate);
2571 } else {
2572 x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2573 }
2574
2575 initCerts(peerCertificateChain, 1);
2576 }
2577 }
2578 }
2579
2580 calculateMaxWrapOverhead();
2581
2582 handshakeState = HandshakeState.FINISHED;
2583 } else {
2584 throw new SSLException("Already closed");
2585 }
2586 }
2587 }
2588
2589 private void initCerts(byte[][] chain, int startPos) {
2590 for (int i = 0; i < chain.length; i++) {
2591 int certPos = startPos + i;
2592 peerCerts[certPos] = new LazyX509Certificate(chain[i]);
2593 if (x509PeerCerts != JAVAX_CERTS_NOT_SUPPORTED) {
2594 x509PeerCerts[certPos] = new LazyJavaxX509Certificate(chain[i]);
2595 }
2596 }
2597 }
2598
2599 @Override
2600 public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
2601 synchronized (ReferenceCountedOpenSslEngine.this) {
2602 if (isEmpty(peerCerts)) {
2603 throw new SSLPeerUnverifiedException("peer not verified");
2604 }
2605 return peerCerts.clone();
2606 }
2607 }
2608
2609 @Override
2610 public boolean hasPeerCertificates() {
2611 synchronized (ReferenceCountedOpenSslEngine.this) {
2612 return !isEmpty(peerCerts);
2613 }
2614 }
2615
2616 @Override
2617 public Certificate[] getLocalCertificates() {
2618 Certificate[] localCerts = this.localCertificateChain;
2619 if (localCerts == null) {
2620 return null;
2621 }
2622 return localCerts.clone();
2623 }
2624
2625 @Override
2626 public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
2627 synchronized (ReferenceCountedOpenSslEngine.this) {
2628 if (x509PeerCerts == JAVAX_CERTS_NOT_SUPPORTED) {
2629
2630
2631 throw new UnsupportedOperationException();
2632 }
2633 if (isEmpty(x509PeerCerts)) {
2634 throw new SSLPeerUnverifiedException("peer not verified");
2635 }
2636 return x509PeerCerts.clone();
2637 }
2638 }
2639
2640 @Override
2641 public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
2642 Certificate[] peer = getPeerCertificates();
2643
2644
2645 return ((java.security.cert.X509Certificate) peer[0]).getSubjectX500Principal();
2646 }
2647
2648 @Override
2649 public Principal getLocalPrincipal() {
2650 Certificate[] local = this.localCertificateChain;
2651 if (local == null || local.length == 0) {
2652 return null;
2653 }
2654 return ((java.security.cert.X509Certificate) local[0]).getSubjectX500Principal();
2655 }
2656
2657 @Override
2658 public String getCipherSuite() {
2659 synchronized (ReferenceCountedOpenSslEngine.this) {
2660 if (cipher == null) {
2661 return SslUtils.INVALID_CIPHER;
2662 }
2663 return cipher;
2664 }
2665 }
2666
2667 @Override
2668 public String getProtocol() {
2669 String protocol = this.protocol;
2670 if (protocol == null) {
2671 synchronized (ReferenceCountedOpenSslEngine.this) {
2672 if (!isDestroyed()) {
2673 protocol = SSL.getVersion(ssl);
2674 } else {
2675 protocol = StringUtil.EMPTY_STRING;
2676 }
2677 }
2678 }
2679 return protocol;
2680 }
2681
2682 @Override
2683 public String getPeerHost() {
2684 return ReferenceCountedOpenSslEngine.this.getPeerHost();
2685 }
2686
2687 @Override
2688 public int getPeerPort() {
2689 return ReferenceCountedOpenSslEngine.this.getPeerPort();
2690 }
2691
2692 @Override
2693 public int getPacketBufferSize() {
2694 return SSL.SSL_MAX_ENCRYPTED_LENGTH;
2695 }
2696
2697 @Override
2698 public int getApplicationBufferSize() {
2699 return applicationBufferSize;
2700 }
2701
2702 @Override
2703 public void tryExpandApplicationBufferSize(int packetLengthDataOnly) {
2704 if (packetLengthDataOnly > MAX_PLAINTEXT_LENGTH && applicationBufferSize != MAX_RECORD_SIZE) {
2705 applicationBufferSize = MAX_RECORD_SIZE;
2706 }
2707 }
2708
2709 @Override
2710 public String toString() {
2711 return "DefaultOpenSslSession{" +
2712 "sessionContext=" + sessionContext +
2713 ", id=" + id +
2714 '}';
2715 }
2716
2717 @Override
2718 public int hashCode() {
2719 return sessionId().hashCode();
2720 }
2721
2722 @Override
2723 public boolean equals(Object o) {
2724 if (o == this) {
2725 return true;
2726 }
2727
2728 if (!(o instanceof OpenSslInternalSession)) {
2729 return false;
2730 }
2731 return sessionId().equals(((OpenSslInternalSession) o).sessionId());
2732 }
2733 }
2734
2735 private interface NativeSslException {
2736 int errorCode();
2737 }
2738
2739 private static final class OpenSslException extends SSLException implements NativeSslException {
2740 private final int errorCode;
2741
2742 OpenSslException(String reason, int errorCode) {
2743 super(reason);
2744 this.errorCode = errorCode;
2745 }
2746
2747 @Override
2748 public int errorCode() {
2749 return errorCode;
2750 }
2751 }
2752
2753 private static final class OpenSslHandshakeException extends SSLHandshakeException implements NativeSslException {
2754 private final int errorCode;
2755
2756 OpenSslHandshakeException(String reason, int errorCode) {
2757 super(reason);
2758 this.errorCode = errorCode;
2759 }
2760
2761 @Override
2762 public int errorCode() {
2763 return errorCode;
2764 }
2765 }
2766 }