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.ThrowableUtil;
35 import io.netty.util.internal.UnstableApi;
36 import io.netty.util.internal.logging.InternalLogger;
37 import io.netty.util.internal.logging.InternalLoggerFactory;
38
39 import java.nio.ByteBuffer;
40 import java.nio.ReadOnlyBufferException;
41 import java.security.AlgorithmConstraints;
42 import java.security.Principal;
43 import java.security.cert.Certificate;
44 import java.util.ArrayList;
45 import java.util.Arrays;
46 import java.util.Collection;
47 import java.util.Collections;
48 import java.util.HashSet;
49 import java.util.LinkedHashSet;
50 import java.util.List;
51 import java.util.Map;
52 import java.util.Set;
53 import java.util.concurrent.ConcurrentHashMap;
54 import java.util.concurrent.locks.Lock;
55 import javax.crypto.spec.SecretKeySpec;
56 import javax.net.ssl.SNIHostName;
57 import javax.net.ssl.SNIMatcher;
58 import javax.net.ssl.SNIServerName;
59 import javax.net.ssl.SSLEngine;
60 import javax.net.ssl.SSLEngineResult;
61 import javax.net.ssl.SSLException;
62 import javax.net.ssl.SSLHandshakeException;
63 import javax.net.ssl.SSLParameters;
64 import javax.net.ssl.SSLPeerUnverifiedException;
65 import javax.net.ssl.SSLSession;
66 import javax.net.ssl.SSLSessionBindingEvent;
67 import javax.net.ssl.SSLSessionBindingListener;
68 import javax.security.cert.X509Certificate;
69
70 import static io.netty.handler.ssl.OpenSsl.memoryAddress;
71 import static io.netty.handler.ssl.SslUtils.SSL_RECORD_HEADER_LENGTH;
72 import static io.netty.util.internal.EmptyArrays.EMPTY_STRINGS;
73 import static io.netty.util.internal.ObjectUtil.checkNotNull;
74 import static io.netty.util.internal.ObjectUtil.checkNotNullArrayParam;
75 import static io.netty.util.internal.ObjectUtil.checkNotNullWithIAE;
76 import static java.lang.Integer.MAX_VALUE;
77 import static java.lang.Math.min;
78 import static javax.net.ssl.SSLEngineResult.HandshakeStatus.FINISHED;
79 import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_TASK;
80 import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
81 import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NEED_WRAP;
82 import static javax.net.ssl.SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
83 import static javax.net.ssl.SSLEngineResult.Status.BUFFER_OVERFLOW;
84 import static javax.net.ssl.SSLEngineResult.Status.BUFFER_UNDERFLOW;
85 import static javax.net.ssl.SSLEngineResult.Status.CLOSED;
86 import static javax.net.ssl.SSLEngineResult.Status.OK;
87
88
89
90
91
92
93
94
95
96
97 public class ReferenceCountedOpenSslEngine extends SSLEngine implements ReferenceCounted, ApplicationProtocolAccessor {
98
99 private static final InternalLogger logger = InternalLoggerFactory.getInstance(ReferenceCountedOpenSslEngine.class);
100
101 private static final ResourceLeakDetector<ReferenceCountedOpenSslEngine> leakDetector =
102 ResourceLeakDetectorFactory.instance().newResourceLeakDetector(ReferenceCountedOpenSslEngine.class);
103 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV2 = 0;
104 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_SSLV3 = 1;
105 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1 = 2;
106 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_1 = 3;
107 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_2 = 4;
108 private static final int OPENSSL_OP_NO_PROTOCOL_INDEX_TLSv1_3 = 5;
109 private static final int[] OPENSSL_OP_NO_PROTOCOLS = {
110 SSL.SSL_OP_NO_SSLv2,
111 SSL.SSL_OP_NO_SSLv3,
112 SSL.SSL_OP_NO_TLSv1,
113 SSL.SSL_OP_NO_TLSv1_1,
114 SSL.SSL_OP_NO_TLSv1_2,
115 SSL.SSL_OP_NO_TLSv1_3
116 };
117
118
119
120
121 static final int MAX_PLAINTEXT_LENGTH = SSL.SSL_MAX_PLAINTEXT_LENGTH;
122
123
124
125 static final int MAX_RECORD_SIZE = SSL.SSL_MAX_RECORD_LENGTH;
126
127 private static final SSLEngineResult NEED_UNWRAP_OK = new SSLEngineResult(OK, NEED_UNWRAP, 0, 0);
128 private static final SSLEngineResult NEED_UNWRAP_CLOSED = new SSLEngineResult(CLOSED, NEED_UNWRAP, 0, 0);
129 private static final SSLEngineResult NEED_WRAP_OK = new SSLEngineResult(OK, NEED_WRAP, 0, 0);
130 private static final SSLEngineResult NEED_WRAP_CLOSED = new SSLEngineResult(CLOSED, NEED_WRAP, 0, 0);
131 private static final SSLEngineResult CLOSED_NOT_HANDSHAKING = new SSLEngineResult(CLOSED, NOT_HANDSHAKING, 0, 0);
132
133
134 private long ssl;
135 private long networkBIO;
136
137 private enum HandshakeState {
138
139
140
141 NOT_STARTED,
142
143
144
145 STARTED_IMPLICITLY,
146
147
148
149 STARTED_EXPLICITLY,
150
151
152
153 FINISHED
154 }
155
156 private HandshakeState handshakeState = HandshakeState.NOT_STARTED;
157 private boolean receivedShutdown;
158 private volatile boolean destroyed;
159 private volatile String applicationProtocol;
160 private volatile boolean needTask;
161 private boolean hasTLSv13Cipher;
162 private boolean sessionSet;
163
164
165 private final ResourceLeakTracker<ReferenceCountedOpenSslEngine> leak;
166 private final AbstractReferenceCounted refCnt = new AbstractReferenceCounted() {
167 @Override
168 public ReferenceCounted touch(Object hint) {
169 if (leak != null) {
170 leak.record(hint);
171 }
172
173 return ReferenceCountedOpenSslEngine.this;
174 }
175
176 @Override
177 protected void deallocate() {
178 shutdown();
179 if (leak != null) {
180 boolean closed = leak.close(ReferenceCountedOpenSslEngine.this);
181 assert closed;
182 }
183 parentContext.release();
184 }
185 };
186
187 private final Set<String> enabledProtocols = new LinkedHashSet<String>();
188
189 private volatile ClientAuth clientAuth = ClientAuth.NONE;
190
191 private String endpointIdentificationAlgorithm;
192
193 private Object algorithmConstraints;
194 private List<String> sniHostNames;
195
196
197 private volatile Collection<SNIMatcher> matchers;
198
199
200 private boolean isInboundDone;
201 private boolean outboundClosed;
202
203 final boolean jdkCompatibilityMode;
204 private final boolean clientMode;
205 final ByteBufAllocator alloc;
206 private final OpenSslEngineMap engineMap;
207 private final OpenSslApplicationProtocolNegotiator apn;
208 private final ReferenceCountedOpenSslContext parentContext;
209 private final OpenSslSession session;
210 private final ByteBuffer[] singleSrcBuffer = new ByteBuffer[1];
211 private final ByteBuffer[] singleDstBuffer = new ByteBuffer[1];
212 private final boolean enableOcsp;
213 private int maxWrapOverhead;
214 private int maxWrapBufferSize;
215 private Throwable pendingException;
216
217
218
219
220
221
222
223
224
225
226
227
228
229 ReferenceCountedOpenSslEngine(ReferenceCountedOpenSslContext context, final ByteBufAllocator alloc, String peerHost,
230 int peerPort, boolean jdkCompatibilityMode, boolean leakDetection,
231 String endpointIdentificationAlgorithm) {
232 super(peerHost, peerPort);
233 OpenSsl.ensureAvailability();
234 engineMap = context.engineMap;
235 enableOcsp = context.enableOcsp;
236 this.jdkCompatibilityMode = jdkCompatibilityMode;
237 this.alloc = checkNotNull(alloc, "alloc");
238 apn = (OpenSslApplicationProtocolNegotiator) context.applicationProtocolNegotiator();
239 clientMode = context.isClient();
240 this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm;
241
242 session = new ExtendedOpenSslSession(new DefaultOpenSslSession(context.sessionContext())) {
243 private String[] peerSupportedSignatureAlgorithms;
244 private List<SNIServerName> requestedServerNames;
245
246 @Override
247 public List<SNIServerName> getRequestedServerNames() {
248 if (clientMode) {
249 return getSniHostNames(sniHostNames);
250 } else {
251 synchronized (ReferenceCountedOpenSslEngine.this) {
252 if (requestedServerNames == null) {
253 if (isDestroyed()) {
254 requestedServerNames = Collections.emptyList();
255 } else {
256 String name = SSL.getSniHostname(ssl);
257 if (name == null) {
258 requestedServerNames = Collections.emptyList();
259 } else {
260
261
262 byte[] hostname = SSL.getSniHostname(ssl).getBytes(CharsetUtil.UTF_8);
263 requestedServerNames = hostname == null || hostname.length == 0 ?
264 Collections.emptyList() :
265 Collections.singletonList(new SNIHostName(hostname));
266 }
267 }
268 }
269 return requestedServerNames;
270 }
271 }
272 }
273
274 @Override
275 public String[] getPeerSupportedSignatureAlgorithms() {
276 synchronized (ReferenceCountedOpenSslEngine.this) {
277 if (peerSupportedSignatureAlgorithms == null) {
278 if (isDestroyed()) {
279 peerSupportedSignatureAlgorithms = EMPTY_STRINGS;
280 } else {
281 String[] algs = SSL.getSigAlgs(ssl);
282 if (algs == null) {
283 peerSupportedSignatureAlgorithms = EMPTY_STRINGS;
284 } else {
285 Set<String> algorithmList = new LinkedHashSet<String>(algs.length);
286 for (String alg: algs) {
287 String converted = SignatureAlgorithmConverter.toJavaName(alg);
288
289 if (converted != null) {
290 algorithmList.add(converted);
291 }
292 }
293 peerSupportedSignatureAlgorithms = algorithmList.toArray(EMPTY_STRINGS);
294 }
295 }
296 }
297 return peerSupportedSignatureAlgorithms.clone();
298 }
299 }
300
301 @Override
302 public List<byte[]> getStatusResponses() {
303 byte[] ocspResponse = null;
304 if (enableOcsp && clientMode) {
305 synchronized (ReferenceCountedOpenSslEngine.this) {
306 if (!isDestroyed()) {
307 ocspResponse = SSL.getOcspResponse(ssl);
308 }
309 }
310 }
311 return ocspResponse == null ?
312 Collections.<byte[]>emptyList() : Collections.singletonList(ocspResponse);
313 }
314 };
315
316 if (!context.sessionContext().useKeyManager()) {
317 session.setLocalCertificate(context.keyCertChain);
318 }
319
320 Lock readerLock = context.ctxLock.readLock();
321 readerLock.lock();
322 final long finalSsl;
323 try {
324 finalSsl = SSL.newSSL(context.ctx, !context.isClient());
325 } finally {
326 readerLock.unlock();
327 }
328 synchronized (this) {
329 ssl = finalSsl;
330 try {
331 networkBIO = SSL.bioNewByteBuffer(ssl, context.getBioNonApplicationBufferSize());
332
333
334
335 setClientAuth(clientMode ? ClientAuth.NONE : context.clientAuth);
336
337 assert context.protocols != null;
338 this.hasTLSv13Cipher = context.hasTLSv13Cipher;
339
340 setEnabledProtocols(context.protocols);
341
342
343
344 if (clientMode && SslUtils.isValidHostNameForSNI(peerHost)) {
345
346 if (isValidHostNameForSNI(peerHost)) {
347 SSL.setTlsExtHostName(ssl, peerHost);
348 sniHostNames = Collections.singletonList(peerHost);
349 }
350 }
351
352 if (enableOcsp) {
353 SSL.enableOcsp(ssl);
354 }
355
356 if (!jdkCompatibilityMode) {
357 SSL.setMode(ssl, SSL.getMode(ssl) | SSL.SSL_MODE_ENABLE_PARTIAL_WRITE);
358 }
359
360 if (isProtocolEnabled(SSL.getOptions(ssl), SSL.SSL_OP_NO_TLSv1_3, SslProtocols.TLS_v1_3)) {
361 final boolean enableTickets = clientMode ?
362 ReferenceCountedOpenSslContext.CLIENT_ENABLE_SESSION_TICKET_TLSV13 :
363 ReferenceCountedOpenSslContext.SERVER_ENABLE_SESSION_TICKET_TLSV13;
364 if (enableTickets) {
365
366
367
368
369
370
371
372 SSL.clearOptions(ssl, SSL.SSL_OP_NO_TICKET);
373 }
374 }
375
376 if (OpenSsl.isBoringSSL() && clientMode) {
377
378
379
380
381 SSL.setRenegotiateMode(ssl, SSL.SSL_RENEGOTIATE_ONCE);
382 }
383
384 calculateMaxWrapOverhead();
385
386
387 configureEndpointVerification(endpointIdentificationAlgorithm);
388 } catch (Throwable cause) {
389
390
391 shutdown();
392
393 PlatformDependent.throwException(cause);
394 }
395 }
396
397
398
399 parentContext = context;
400 parentContext.retain();
401
402
403
404 leak = leakDetection ? leakDetector.track(this) : null;
405 }
406
407 private static boolean isValidHostNameForSNI(String hostname) {
408 try {
409 new SNIHostName(hostname);
410 return true;
411 } catch (IllegalArgumentException illegal) {
412 return false;
413 }
414 }
415
416 final synchronized String[] authMethods() {
417 if (isDestroyed()) {
418 return EMPTY_STRINGS;
419 }
420 return SSL.authenticationMethods(ssl);
421 }
422
423 final boolean setKeyMaterial(OpenSslKeyMaterial keyMaterial) throws Exception {
424 synchronized (this) {
425 if (isDestroyed()) {
426 return false;
427 }
428 SSL.setKeyMaterial(ssl, keyMaterial.certificateChainAddress(), keyMaterial.privateKeyAddress());
429 }
430 session.setLocalCertificate(keyMaterial.certificateChain());
431 return true;
432 }
433
434 final synchronized SecretKeySpec masterKey() {
435 if (isDestroyed()) {
436 return null;
437 }
438 return new SecretKeySpec(SSL.getMasterKey(ssl), "AES");
439 }
440
441 synchronized boolean isSessionReused() {
442 if (isDestroyed()) {
443 return false;
444 }
445 return SSL.isSessionReused(ssl);
446 }
447
448
449
450
451 @UnstableApi
452 public void setOcspResponse(byte[] response) {
453 if (!enableOcsp) {
454 throw new IllegalStateException("OCSP stapling is not enabled");
455 }
456
457 if (clientMode) {
458 throw new IllegalStateException("Not a server SSLEngine");
459 }
460
461 synchronized (this) {
462 if (!isDestroyed()) {
463 SSL.setOcspResponse(ssl, response);
464 }
465 }
466 }
467
468
469
470
471 @UnstableApi
472 public byte[] getOcspResponse() {
473 if (!enableOcsp) {
474 throw new IllegalStateException("OCSP stapling is not enabled");
475 }
476
477 if (!clientMode) {
478 throw new IllegalStateException("Not a client SSLEngine");
479 }
480
481 synchronized (this) {
482 if (isDestroyed()) {
483 return EmptyArrays.EMPTY_BYTES;
484 }
485 return SSL.getOcspResponse(ssl);
486 }
487 }
488
489 @Override
490 public final int refCnt() {
491 return refCnt.refCnt();
492 }
493
494 @Override
495 public final ReferenceCounted retain() {
496 refCnt.retain();
497 return this;
498 }
499
500 @Override
501 public final ReferenceCounted retain(int increment) {
502 refCnt.retain(increment);
503 return this;
504 }
505
506 @Override
507 public final ReferenceCounted touch() {
508 refCnt.touch();
509 return this;
510 }
511
512 @Override
513 public final ReferenceCounted touch(Object hint) {
514 refCnt.touch(hint);
515 return this;
516 }
517
518 @Override
519 public final boolean release() {
520 return refCnt.release();
521 }
522
523 @Override
524 public final boolean release(int decrement) {
525 return refCnt.release(decrement);
526 }
527
528
529
530 public String getApplicationProtocol() {
531 return applicationProtocol;
532 }
533
534
535
536 public String getHandshakeApplicationProtocol() {
537 return applicationProtocol;
538 }
539
540 @Override
541 public final synchronized SSLSession getHandshakeSession() {
542
543
544
545
546 switch(handshakeState) {
547 case NOT_STARTED:
548 case FINISHED:
549 return null;
550 default:
551 return session;
552 }
553 }
554
555
556
557
558
559
560 public final synchronized long sslPointer() {
561 return ssl;
562 }
563
564
565
566
567 public final synchronized void shutdown() {
568 if (!destroyed) {
569 destroyed = true;
570
571
572
573 if (engineMap != null) {
574 engineMap.remove(ssl);
575 }
576 SSL.freeSSL(ssl);
577 ssl = networkBIO = 0;
578
579 isInboundDone = outboundClosed = true;
580 }
581
582
583 SSL.clearError();
584 }
585
586
587
588
589
590
591 private int writePlaintextData(final ByteBuffer src, int len) {
592 final int pos = src.position();
593 final int limit = src.limit();
594 final int sslWrote;
595
596 if (src.isDirect()) {
597 sslWrote = SSL.writeToSSL(ssl, bufferAddress(src) + pos, len);
598 if (sslWrote > 0) {
599 src.position(pos + sslWrote);
600 }
601 } else {
602 ByteBuf buf = alloc.directBuffer(len);
603 try {
604 src.limit(pos + len);
605
606 buf.setBytes(0, src);
607 src.limit(limit);
608
609 sslWrote = SSL.writeToSSL(ssl, memoryAddress(buf), len);
610 if (sslWrote > 0) {
611 src.position(pos + sslWrote);
612 } else {
613 src.position(pos);
614 }
615 } finally {
616 buf.release();
617 }
618 }
619 return sslWrote;
620 }
621
622 synchronized void bioSetFd(int fd) {
623 if (!isDestroyed()) {
624 SSL.bioSetFd(this.ssl, fd);
625 }
626 }
627
628
629
630
631 private ByteBuf writeEncryptedData(final ByteBuffer src, int len) throws SSLException {
632 final int pos = src.position();
633 if (src.isDirect()) {
634 SSL.bioSetByteBuffer(networkBIO, bufferAddress(src) + pos, len, false);
635 } else {
636 final ByteBuf buf = alloc.directBuffer(len);
637 try {
638 final int limit = src.limit();
639 src.limit(pos + len);
640 buf.writeBytes(src);
641
642 src.position(pos);
643 src.limit(limit);
644
645 SSL.bioSetByteBuffer(networkBIO, memoryAddress(buf), len, false);
646 return buf;
647 } catch (Throwable cause) {
648 buf.release();
649 PlatformDependent.throwException(cause);
650 }
651 }
652 return null;
653 }
654
655
656
657
658 private int readPlaintextData(final ByteBuffer dst) throws SSLException {
659 final int sslRead;
660 final int pos = dst.position();
661 if (dst.isDirect()) {
662 sslRead = SSL.readFromSSL(ssl, bufferAddress(dst) + pos, dst.limit() - pos);
663 if (sslRead > 0) {
664 dst.position(pos + sslRead);
665 }
666 } else {
667 final int limit = dst.limit();
668 final int len = min(maxEncryptedPacketLength0(), limit - pos);
669 final ByteBuf buf = alloc.directBuffer(len);
670 try {
671 sslRead = SSL.readFromSSL(ssl, memoryAddress(buf), len);
672 if (sslRead > 0) {
673 dst.limit(pos + sslRead);
674 buf.getBytes(buf.readerIndex(), dst);
675 dst.limit(limit);
676 }
677 } finally {
678 buf.release();
679 }
680 }
681
682 return sslRead;
683 }
684
685
686
687
688 final synchronized int maxWrapOverhead() {
689 return maxWrapOverhead;
690 }
691
692
693
694
695 final synchronized int maxEncryptedPacketLength() {
696 return maxEncryptedPacketLength0();
697 }
698
699
700
701
702
703 final int maxEncryptedPacketLength0() {
704 return maxWrapOverhead + MAX_PLAINTEXT_LENGTH;
705 }
706
707
708
709
710
711
712
713
714
715 final int calculateMaxLengthForWrap(int plaintextLength, int numComponents) {
716 return (int) min(maxWrapBufferSize, plaintextLength + (long) maxWrapOverhead * numComponents);
717 }
718
719
720
721
722
723
724
725
726 final int calculateOutNetBufSize(int plaintextLength, int numComponents) {
727 return (int) min(MAX_VALUE, plaintextLength + (long) maxWrapOverhead * numComponents);
728 }
729
730 final synchronized int sslPending() {
731 return sslPending0();
732 }
733
734
735
736
737 private void calculateMaxWrapOverhead() {
738 maxWrapOverhead = SSL.getMaxWrapOverhead(ssl);
739
740
741
742
743 maxWrapBufferSize = jdkCompatibilityMode ? maxEncryptedPacketLength0() : maxEncryptedPacketLength0() << 4;
744 }
745
746 private int sslPending0() {
747
748
749
750
751 return handshakeState != HandshakeState.FINISHED ? 0 : SSL.sslPending(ssl);
752 }
753
754 private boolean isBytesAvailableEnoughForWrap(int bytesAvailable, int plaintextLength, int numComponents) {
755 return bytesAvailable - (long) maxWrapOverhead * numComponents >= plaintextLength;
756 }
757
758 @Override
759 public final SSLEngineResult wrap(
760 final ByteBuffer[] srcs, int offset, final int length, final ByteBuffer dst) throws SSLException {
761
762 checkNotNullWithIAE(srcs, "srcs");
763 checkNotNullWithIAE(dst, "dst");
764
765 if (offset >= srcs.length || offset + length > srcs.length) {
766 throw new IndexOutOfBoundsException(
767 "offset: " + offset + ", length: " + length +
768 " (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
769 }
770
771 if (dst.isReadOnly()) {
772 throw new ReadOnlyBufferException();
773 }
774
775 synchronized (this) {
776 if (isOutboundDone()) {
777
778 return isInboundDone() || isDestroyed() ? CLOSED_NOT_HANDSHAKING : NEED_UNWRAP_CLOSED;
779 }
780
781 int bytesProduced = 0;
782 ByteBuf bioReadCopyBuf = null;
783 try {
784
785 if (dst.isDirect()) {
786 SSL.bioSetByteBuffer(networkBIO, bufferAddress(dst) + dst.position(), dst.remaining(),
787 true);
788 } else {
789 bioReadCopyBuf = alloc.directBuffer(dst.remaining());
790 SSL.bioSetByteBuffer(networkBIO, memoryAddress(bioReadCopyBuf), bioReadCopyBuf.writableBytes(),
791 true);
792 }
793
794 int bioLengthBefore = SSL.bioLengthByteBuffer(networkBIO);
795
796
797 if (outboundClosed) {
798
799
800
801
802
803 if (!isBytesAvailableEnoughForWrap(dst.remaining(), 2, 1)) {
804 return new SSLEngineResult(BUFFER_OVERFLOW, getHandshakeStatus(), 0, 0);
805 }
806
807
808
809 bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
810 if (bytesProduced <= 0) {
811 return newResultMayFinishHandshake(NOT_HANDSHAKING, 0, 0);
812 }
813
814
815
816 if (!doSSLShutdown()) {
817 return newResultMayFinishHandshake(NOT_HANDSHAKING, 0, bytesProduced);
818 }
819 bytesProduced = bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
820 return newResultMayFinishHandshake(NEED_WRAP, 0, bytesProduced);
821 }
822
823
824 SSLEngineResult.HandshakeStatus status = NOT_HANDSHAKING;
825 HandshakeState oldHandshakeState = handshakeState;
826
827
828 if (handshakeState != HandshakeState.FINISHED) {
829 if (handshakeState != HandshakeState.STARTED_EXPLICITLY) {
830
831 handshakeState = HandshakeState.STARTED_IMPLICITLY;
832 }
833
834
835 bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
836
837 if (pendingException != null) {
838
839
840
841
842
843
844
845
846
847
848
849 if (bytesProduced > 0) {
850 return newResult(NEED_WRAP, 0, bytesProduced);
851 }
852
853
854
855 return newResult(handshakeException(), 0, 0);
856 }
857
858 status = handshake();
859
860
861
862 bytesProduced = bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
863
864 if (status == NEED_TASK) {
865 return newResult(status, 0, bytesProduced);
866 }
867
868 if (bytesProduced > 0) {
869
870
871
872 return newResult(mayFinishHandshake(status != FINISHED ?
873 bytesProduced == bioLengthBefore ? NEED_WRAP :
874 getHandshakeStatus(SSL.bioLengthNonApplication(networkBIO)) : FINISHED),
875 0, bytesProduced);
876 }
877
878 if (status == NEED_UNWRAP) {
879
880 return isOutboundDone() ? NEED_UNWRAP_CLOSED : NEED_UNWRAP_OK;
881 }
882
883
884
885 if (outboundClosed) {
886 bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
887 return newResultMayFinishHandshake(status, 0, bytesProduced);
888 }
889 }
890
891 final int endOffset = offset + length;
892 if (jdkCompatibilityMode ||
893
894
895
896 oldHandshakeState != HandshakeState.FINISHED) {
897 int srcsLen = 0;
898 for (int i = offset; i < endOffset; ++i) {
899 final ByteBuffer src = srcs[i];
900 if (src == null) {
901 throw new IllegalArgumentException("srcs[" + i + "] is null");
902 }
903 if (srcsLen == MAX_PLAINTEXT_LENGTH) {
904 continue;
905 }
906
907 srcsLen += src.remaining();
908 if (srcsLen > MAX_PLAINTEXT_LENGTH || srcsLen < 0) {
909
910
911
912 srcsLen = MAX_PLAINTEXT_LENGTH;
913 }
914 }
915
916
917
918 if (!isBytesAvailableEnoughForWrap(dst.remaining(), srcsLen, 1)) {
919 return new SSLEngineResult(BUFFER_OVERFLOW, getHandshakeStatus(), 0, 0);
920 }
921 }
922
923
924 int bytesConsumed = 0;
925 assert bytesProduced == 0;
926
927
928 bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
929
930 if (bytesProduced > 0) {
931 return newResultMayFinishHandshake(status, bytesConsumed, bytesProduced);
932 }
933
934
935 if (pendingException != null) {
936 Throwable error = pendingException;
937 pendingException = null;
938 shutdown();
939
940
941 throw new SSLException(error);
942 }
943
944 for (; offset < endOffset; ++offset) {
945 final ByteBuffer src = srcs[offset];
946 final int remaining = src.remaining();
947 if (remaining == 0) {
948 continue;
949 }
950
951 final int bytesWritten;
952 if (jdkCompatibilityMode) {
953
954
955
956 bytesWritten = writePlaintextData(src, min(remaining, MAX_PLAINTEXT_LENGTH - bytesConsumed));
957 } else {
958
959
960
961 final int availableCapacityForWrap = dst.remaining() - bytesProduced - maxWrapOverhead;
962 if (availableCapacityForWrap <= 0) {
963 return new SSLEngineResult(BUFFER_OVERFLOW, getHandshakeStatus(), bytesConsumed,
964 bytesProduced);
965 }
966 bytesWritten = writePlaintextData(src, min(remaining, availableCapacityForWrap));
967 }
968
969
970
971
972
973
974 final int pendingNow = SSL.bioLengthByteBuffer(networkBIO);
975 bytesProduced += bioLengthBefore - pendingNow;
976 bioLengthBefore = pendingNow;
977
978 if (bytesWritten > 0) {
979 bytesConsumed += bytesWritten;
980
981 if (jdkCompatibilityMode || bytesProduced == dst.remaining()) {
982 return newResultMayFinishHandshake(status, bytesConsumed, bytesProduced);
983 }
984 } else {
985 int sslError = SSL.getError(ssl, bytesWritten);
986 if (sslError == SSL.SSL_ERROR_ZERO_RETURN) {
987
988 if (!receivedShutdown) {
989 closeAll();
990
991 bytesProduced += bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
992
993
994
995
996 SSLEngineResult.HandshakeStatus hs = mayFinishHandshake(
997 status != FINISHED ? bytesProduced == dst.remaining() ? NEED_WRAP
998 : getHandshakeStatus(SSL.bioLengthNonApplication(networkBIO))
999 : FINISHED);
1000 return newResult(hs, bytesConsumed, bytesProduced);
1001 }
1002
1003 return newResult(NOT_HANDSHAKING, bytesConsumed, bytesProduced);
1004 } else if (sslError == SSL.SSL_ERROR_WANT_READ) {
1005
1006
1007
1008 return newResult(NEED_UNWRAP, bytesConsumed, bytesProduced);
1009 } else if (sslError == SSL.SSL_ERROR_WANT_WRITE) {
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022 if (bytesProduced > 0) {
1023
1024
1025 return newResult(NEED_WRAP, bytesConsumed, bytesProduced);
1026 }
1027 return newResult(BUFFER_OVERFLOW, status, bytesConsumed, bytesProduced);
1028 } else if (sslError == SSL.SSL_ERROR_WANT_X509_LOOKUP ||
1029 sslError == SSL.SSL_ERROR_WANT_CERTIFICATE_VERIFY ||
1030 sslError == SSL.SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
1031
1032 return newResult(NEED_TASK, bytesConsumed, bytesProduced);
1033 } else {
1034
1035 throw shutdownWithError("SSL_write", sslError, SSL.getLastErrorNumber());
1036 }
1037 }
1038 }
1039 return newResultMayFinishHandshake(status, bytesConsumed, bytesProduced);
1040 } finally {
1041 SSL.bioClearByteBuffer(networkBIO);
1042 if (bioReadCopyBuf == null) {
1043 dst.position(dst.position() + bytesProduced);
1044 } else {
1045 assert bioReadCopyBuf.readableBytes() <= dst.remaining() : "The destination buffer " + dst +
1046 " didn't have enough remaining space to hold the encrypted content in " + bioReadCopyBuf;
1047 dst.put(bioReadCopyBuf.internalNioBuffer(bioReadCopyBuf.readerIndex(), bytesProduced));
1048 bioReadCopyBuf.release();
1049 }
1050 }
1051 }
1052 }
1053
1054 private SSLEngineResult newResult(SSLEngineResult.HandshakeStatus hs, int bytesConsumed, int bytesProduced) {
1055 return newResult(OK, hs, bytesConsumed, bytesProduced);
1056 }
1057
1058 private SSLEngineResult newResult(SSLEngineResult.Status status, SSLEngineResult.HandshakeStatus hs,
1059 int bytesConsumed, int bytesProduced) {
1060
1061
1062
1063 if (isOutboundDone()) {
1064 if (isInboundDone()) {
1065
1066 hs = NOT_HANDSHAKING;
1067
1068
1069 shutdown();
1070 }
1071 return new SSLEngineResult(CLOSED, hs, bytesConsumed, bytesProduced);
1072 }
1073 if (hs == NEED_TASK) {
1074
1075 needTask = true;
1076 }
1077 return new SSLEngineResult(status, hs, bytesConsumed, bytesProduced);
1078 }
1079
1080 private SSLEngineResult newResultMayFinishHandshake(SSLEngineResult.HandshakeStatus hs,
1081 int bytesConsumed, int bytesProduced) throws SSLException {
1082 return newResult(mayFinishHandshake(hs, bytesConsumed, bytesProduced), bytesConsumed, bytesProduced);
1083 }
1084
1085 private SSLEngineResult newResultMayFinishHandshake(SSLEngineResult.Status status,
1086 SSLEngineResult.HandshakeStatus hs,
1087 int bytesConsumed, int bytesProduced) throws SSLException {
1088 return newResult(status, mayFinishHandshake(hs, bytesConsumed, bytesProduced), bytesConsumed, bytesProduced);
1089 }
1090
1091
1092
1093
1094 private SSLException shutdownWithError(String operation, int sslError, int error) {
1095 if (logger.isDebugEnabled()) {
1096 String errorString = SSL.getErrorString(error);
1097 logger.debug("{} failed with {}: OpenSSL error: {} {}",
1098 operation, sslError, error, errorString);
1099 }
1100
1101
1102 shutdown();
1103
1104 SSLException exception = newSSLExceptionForError(error);
1105
1106 if (pendingException != null) {
1107 exception.initCause(pendingException);
1108 pendingException = null;
1109 }
1110 return exception;
1111 }
1112
1113 private SSLEngineResult handleUnwrapException(int bytesConsumed, int bytesProduced, SSLException e)
1114 throws SSLException {
1115 int lastError = SSL.getLastErrorNumber();
1116 if (lastError != 0) {
1117 return sslReadErrorResult(SSL.SSL_ERROR_SSL, lastError, bytesConsumed,
1118 bytesProduced);
1119 }
1120 throw e;
1121 }
1122
1123 public final SSLEngineResult unwrap(
1124 final ByteBuffer[] srcs, int srcsOffset, final int srcsLength,
1125 final ByteBuffer[] dsts, int dstsOffset, final int dstsLength) throws SSLException {
1126
1127
1128 checkNotNullWithIAE(srcs, "srcs");
1129 if (srcsOffset >= srcs.length
1130 || srcsOffset + srcsLength > srcs.length) {
1131 throw new IndexOutOfBoundsException(
1132 "offset: " + srcsOffset + ", length: " + srcsLength +
1133 " (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
1134 }
1135 checkNotNullWithIAE(dsts, "dsts");
1136 if (dstsOffset >= dsts.length || dstsOffset + dstsLength > dsts.length) {
1137 throw new IndexOutOfBoundsException(
1138 "offset: " + dstsOffset + ", length: " + dstsLength +
1139 " (expected: offset <= offset + length <= dsts.length (" + dsts.length + "))");
1140 }
1141 long capacity = 0;
1142 final int dstsEndOffset = dstsOffset + dstsLength;
1143 for (int i = dstsOffset; i < dstsEndOffset; i ++) {
1144 ByteBuffer dst = checkNotNullArrayParam(dsts[i], i, "dsts");
1145 if (dst.isReadOnly()) {
1146 throw new ReadOnlyBufferException();
1147 }
1148 capacity += dst.remaining();
1149 }
1150
1151 final int srcsEndOffset = srcsOffset + srcsLength;
1152 long len = 0;
1153 for (int i = srcsOffset; i < srcsEndOffset; i++) {
1154 ByteBuffer src = checkNotNullArrayParam(srcs[i], i, "srcs");
1155 len += src.remaining();
1156 }
1157
1158 synchronized (this) {
1159 if (isInboundDone()) {
1160 return isOutboundDone() || isDestroyed() ? CLOSED_NOT_HANDSHAKING : NEED_WRAP_CLOSED;
1161 }
1162
1163 SSLEngineResult.HandshakeStatus status = NOT_HANDSHAKING;
1164 HandshakeState oldHandshakeState = handshakeState;
1165
1166 if (handshakeState != HandshakeState.FINISHED) {
1167 if (handshakeState != HandshakeState.STARTED_EXPLICITLY) {
1168
1169 handshakeState = HandshakeState.STARTED_IMPLICITLY;
1170 }
1171
1172 status = handshake();
1173
1174 if (status == NEED_TASK) {
1175 return newResult(status, 0, 0);
1176 }
1177
1178 if (status == NEED_WRAP) {
1179 return NEED_WRAP_OK;
1180 }
1181
1182 if (isInboundDone) {
1183 return NEED_WRAP_CLOSED;
1184 }
1185 }
1186
1187 int sslPending = sslPending0();
1188 int packetLength;
1189
1190
1191
1192
1193 if (jdkCompatibilityMode ||
1194
1195
1196
1197 oldHandshakeState != HandshakeState.FINISHED) {
1198 if (len < SSL_RECORD_HEADER_LENGTH) {
1199 return newResultMayFinishHandshake(BUFFER_UNDERFLOW, status, 0, 0);
1200 }
1201
1202 packetLength = SslUtils.getEncryptedPacketLength(srcs, srcsOffset);
1203 if (packetLength == SslUtils.NOT_ENCRYPTED) {
1204 throw new NotSslRecordException("not an SSL/TLS record");
1205 }
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 @Override
2189 public final synchronized SSLParameters getSSLParameters() {
2190 SSLParameters sslParameters = super.getSSLParameters();
2191
2192 sslParameters.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm);
2193 sslParameters.setAlgorithmConstraints((AlgorithmConstraints) algorithmConstraints);
2194 if (sniHostNames != null) {
2195 sslParameters.setServerNames(getSniHostNames(sniHostNames));
2196 }
2197 if (!isDestroyed()) {
2198 sslParameters.setUseCipherSuitesOrder((SSL.getOptions(ssl) & SSL.SSL_OP_CIPHER_SERVER_PREFERENCE) != 0);
2199 }
2200
2201 sslParameters.setSNIMatchers(matchers);
2202 return sslParameters;
2203 }
2204
2205 private static List<SNIServerName> getSniHostNames(List<String> names) {
2206 if (names == null || names.isEmpty()) {
2207 return Collections.emptyList();
2208 }
2209 List<SNIServerName> sniServerNames = new ArrayList<SNIServerName>(names.size());
2210 for (String name: names) {
2211 sniServerNames.add(new SNIHostName(name.getBytes(CharsetUtil.UTF_8)));
2212 }
2213 return sniServerNames;
2214 }
2215
2216 @Override
2217 public final synchronized void setSSLParameters(SSLParameters sslParameters) {
2218 if (sslParameters.getAlgorithmConstraints() != null) {
2219 throw new IllegalArgumentException("AlgorithmConstraints are not supported.");
2220 }
2221
2222 boolean isDestroyed = isDestroyed();
2223 if (!isDestroyed) {
2224 if (clientMode) {
2225 final List<String> sniHostNames = getSniHostNames(sslParameters);
2226 for (String name: sniHostNames) {
2227 SSL.setTlsExtHostName(ssl, name);
2228 }
2229 this.sniHostNames = sniHostNames;
2230 }
2231 if (sslParameters.getUseCipherSuitesOrder()) {
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 final String endpointIdentificationAlgorithm = sslParameters.getEndpointIdentificationAlgorithm();
2240 if (!isDestroyed) {
2241 configureEndpointVerification(endpointIdentificationAlgorithm);
2242 }
2243 this.endpointIdentificationAlgorithm = endpointIdentificationAlgorithm;
2244 algorithmConstraints = sslParameters.getAlgorithmConstraints();
2245 super.setSSLParameters(sslParameters);
2246 }
2247
2248 private void configureEndpointVerification(String endpointIdentificationAlgorithm) {
2249
2250
2251 if (clientMode && isEndPointVerificationEnabled(endpointIdentificationAlgorithm)) {
2252 SSL.setVerify(ssl, SSL.SSL_CVERIFY_REQUIRED, -1);
2253 }
2254 }
2255
2256 private static List<String> getSniHostNames(SSLParameters sslParameters) {
2257 List<SNIServerName> names = sslParameters.getServerNames();
2258 if (names == null || names.isEmpty()) {
2259 return Collections.emptyList();
2260 }
2261 List<String> strings = new ArrayList<String>(names.size());
2262
2263 for (SNIServerName serverName : names) {
2264 if (serverName instanceof SNIHostName) {
2265 strings.add(((SNIHostName) serverName).getAsciiName());
2266 } else {
2267 throw new IllegalArgumentException("Only " + SNIHostName.class.getName()
2268 + " instances are supported, but found: " + serverName);
2269 }
2270 }
2271 return strings;
2272 }
2273
2274 private static boolean isEndPointVerificationEnabled(String endPointIdentificationAlgorithm) {
2275 return endPointIdentificationAlgorithm != null && !endPointIdentificationAlgorithm.isEmpty();
2276 }
2277
2278 private boolean isDestroyed() {
2279 return destroyed;
2280 }
2281
2282 final boolean checkSniHostnameMatch(byte[] hostname) {
2283 Collection<SNIMatcher> matchers = this.matchers;
2284 if (matchers != null && !matchers.isEmpty()) {
2285 SNIHostName name = new SNIHostName(hostname);
2286 for (SNIMatcher matcher : matchers) {
2287
2288 if (matcher.getType() == 0 && matcher.matches(name)) {
2289 return true;
2290 }
2291 }
2292 return false;
2293 }
2294 return true;
2295 }
2296
2297 @Override
2298 public String getNegotiatedApplicationProtocol() {
2299 return applicationProtocol;
2300 }
2301
2302 private static long bufferAddress(ByteBuffer b) {
2303 assert b.isDirect();
2304 if (PlatformDependent.hasUnsafe()) {
2305 return PlatformDependent.directBufferAddress(b);
2306 }
2307 return Buffer.address(b);
2308 }
2309
2310
2311
2312
2313 private void selectApplicationProtocol() throws SSLException {
2314 ApplicationProtocolConfig.SelectedListenerFailureBehavior behavior = apn.selectedListenerFailureBehavior();
2315 List<String> protocols = apn.protocols();
2316 String applicationProtocol;
2317 switch (apn.protocol()) {
2318 case NONE:
2319 break;
2320
2321
2322 case ALPN:
2323 applicationProtocol = SSL.getAlpnSelected(ssl);
2324 if (applicationProtocol != null) {
2325 this.applicationProtocol = selectApplicationProtocol(
2326 protocols, behavior, applicationProtocol);
2327 }
2328 break;
2329 case NPN:
2330 applicationProtocol = SSL.getNextProtoNegotiated(ssl);
2331 if (applicationProtocol != null) {
2332 this.applicationProtocol = selectApplicationProtocol(
2333 protocols, behavior, applicationProtocol);
2334 }
2335 break;
2336 case NPN_AND_ALPN:
2337 applicationProtocol = SSL.getAlpnSelected(ssl);
2338 if (applicationProtocol == null) {
2339 applicationProtocol = SSL.getNextProtoNegotiated(ssl);
2340 }
2341 if (applicationProtocol != null) {
2342 this.applicationProtocol = selectApplicationProtocol(
2343 protocols, behavior, applicationProtocol);
2344 }
2345 break;
2346 default:
2347 throw new Error();
2348 }
2349 }
2350
2351 private static String selectApplicationProtocol(List<String> protocols,
2352 ApplicationProtocolConfig.SelectedListenerFailureBehavior behavior,
2353 String applicationProtocol) throws SSLException {
2354 if (behavior == ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT) {
2355 return applicationProtocol;
2356 } else {
2357 int size = protocols.size();
2358 assert size > 0;
2359 if (protocols.contains(applicationProtocol)) {
2360 return applicationProtocol;
2361 } else {
2362 if (behavior == ApplicationProtocolConfig.SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL) {
2363 return protocols.get(size - 1);
2364 } else {
2365 throw new SSLException("unknown protocol " + applicationProtocol);
2366 }
2367 }
2368 }
2369 }
2370
2371 private static final X509Certificate[] JAVAX_CERTS_NOT_SUPPORTED = new X509Certificate[0];
2372
2373 private final class DefaultOpenSslSession implements OpenSslSession {
2374 private final OpenSslSessionContext sessionContext;
2375
2376
2377
2378 private X509Certificate[] x509PeerCerts;
2379 private Certificate[] peerCerts;
2380
2381 private boolean valid = true;
2382 private String protocol;
2383 private String cipher;
2384 private OpenSslSessionId id = OpenSslSessionId.NULL_ID;
2385 private long creationTime;
2386
2387
2388 private long lastAccessed = -1;
2389
2390 private volatile int applicationBufferSize = MAX_PLAINTEXT_LENGTH;
2391 private volatile Certificate[] localCertificateChain;
2392 private volatile Map<String, Object> keyValueStorage = new ConcurrentHashMap<String, Object>();
2393
2394 DefaultOpenSslSession(OpenSslSessionContext sessionContext) {
2395 this.sessionContext = sessionContext;
2396 }
2397
2398 private SSLSessionBindingEvent newSSLSessionBindingEvent(String name) {
2399 return new SSLSessionBindingEvent(session, name);
2400 }
2401
2402 @Override
2403 public void prepareHandshake() {
2404 keyValueStorage.clear();
2405 }
2406
2407 @Override
2408 public void setSessionDetails(
2409 long creationTime, long lastAccessedTime, OpenSslSessionId sessionId,
2410 Map<String, Object> keyValueStorage) {
2411 synchronized (ReferenceCountedOpenSslEngine.this) {
2412 if (this.id == OpenSslSessionId.NULL_ID) {
2413 this.id = sessionId;
2414 this.creationTime = creationTime;
2415 this.lastAccessed = lastAccessedTime;
2416
2417
2418
2419
2420 this.keyValueStorage = keyValueStorage;
2421 }
2422 }
2423 }
2424
2425 @Override
2426 public Map<String, Object> keyValueStorage() {
2427 return keyValueStorage;
2428 }
2429
2430 @Override
2431 public OpenSslSessionId sessionId() {
2432 synchronized (ReferenceCountedOpenSslEngine.this) {
2433 if (this.id == OpenSslSessionId.NULL_ID && !isDestroyed()) {
2434 byte[] sessionId = SSL.getSessionId(ssl);
2435 if (sessionId != null) {
2436 id = new OpenSslSessionId(sessionId);
2437 }
2438 }
2439
2440 return id;
2441 }
2442 }
2443
2444 @Override
2445 public void setLocalCertificate(Certificate[] localCertificate) {
2446 this.localCertificateChain = localCertificate;
2447 }
2448
2449 @Override
2450 public byte[] getId() {
2451 return sessionId().cloneBytes();
2452 }
2453
2454 @Override
2455 public OpenSslSessionContext getSessionContext() {
2456 return sessionContext;
2457 }
2458
2459 @Override
2460 public long getCreationTime() {
2461 synchronized (ReferenceCountedOpenSslEngine.this) {
2462 return creationTime;
2463 }
2464 }
2465
2466 @Override
2467 public void setLastAccessedTime(long time) {
2468 synchronized (ReferenceCountedOpenSslEngine.this) {
2469 this.lastAccessed = time;
2470 }
2471 }
2472
2473 @Override
2474 public long getLastAccessedTime() {
2475
2476 synchronized (ReferenceCountedOpenSslEngine.this) {
2477 return lastAccessed == -1 ? creationTime : lastAccessed;
2478 }
2479 }
2480
2481 @Override
2482 public void invalidate() {
2483 synchronized (ReferenceCountedOpenSslEngine.this) {
2484 valid = false;
2485 sessionContext.removeFromCache(id);
2486 }
2487 }
2488
2489 @Override
2490 public boolean isValid() {
2491 synchronized (ReferenceCountedOpenSslEngine.this) {
2492 return valid || sessionContext.isInCache(id);
2493 }
2494 }
2495
2496 @Override
2497 public void putValue(String name, Object value) {
2498 checkNotNull(name, "name");
2499 checkNotNull(value, "value");
2500
2501 final Object old = keyValueStorage.put(name, value);
2502 if (value instanceof SSLSessionBindingListener) {
2503
2504 ((SSLSessionBindingListener) value).valueBound(newSSLSessionBindingEvent(name));
2505 }
2506 notifyUnbound(old, name);
2507 }
2508
2509 @Override
2510 public Object getValue(String name) {
2511 checkNotNull(name, "name");
2512 return keyValueStorage.get(name);
2513 }
2514
2515 @Override
2516 public void removeValue(String name) {
2517 checkNotNull(name, "name");
2518 final Object old = keyValueStorage.remove(name);
2519 notifyUnbound(old, name);
2520 }
2521
2522 @Override
2523 public String[] getValueNames() {
2524 return keyValueStorage.keySet().toArray(EMPTY_STRINGS);
2525 }
2526
2527 private void notifyUnbound(Object value, String name) {
2528 if (value instanceof SSLSessionBindingListener) {
2529
2530 ((SSLSessionBindingListener) value).valueUnbound(newSSLSessionBindingEvent(name));
2531 }
2532 }
2533
2534
2535
2536
2537
2538 @Override
2539 public void handshakeFinished(byte[] id, String cipher, String protocol, byte[] peerCertificate,
2540 byte[][] peerCertificateChain, long creationTime, long timeout)
2541 throws SSLException {
2542 synchronized (ReferenceCountedOpenSslEngine.this) {
2543 if (!isDestroyed()) {
2544 if (this.id == OpenSslSessionId.NULL_ID) {
2545
2546
2547 this.id = id == null ? OpenSslSessionId.NULL_ID : new OpenSslSessionId(id);
2548
2549
2550 this.creationTime = lastAccessed = creationTime;
2551 }
2552 this.cipher = toJavaCipherSuite(cipher);
2553 this.protocol = protocol;
2554
2555 if (clientMode) {
2556 if (isEmpty(peerCertificateChain)) {
2557 peerCerts = EmptyArrays.EMPTY_CERTIFICATES;
2558 if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2559 x509PeerCerts = EmptyArrays.EMPTY_JAVAX_X509_CERTIFICATES;
2560 } else {
2561 x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2562 }
2563 } else {
2564 peerCerts = new Certificate[peerCertificateChain.length];
2565 if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2566 x509PeerCerts = new X509Certificate[peerCertificateChain.length];
2567 } else {
2568 x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2569 }
2570 initCerts(peerCertificateChain, 0);
2571 }
2572 } else {
2573
2574
2575
2576
2577
2578 if (isEmpty(peerCertificate)) {
2579 peerCerts = EmptyArrays.EMPTY_CERTIFICATES;
2580 x509PeerCerts = EmptyArrays.EMPTY_JAVAX_X509_CERTIFICATES;
2581 } else {
2582 if (isEmpty(peerCertificateChain)) {
2583 peerCerts = new Certificate[] {new LazyX509Certificate(peerCertificate)};
2584 if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2585 x509PeerCerts = new X509Certificate[] {
2586 new LazyJavaxX509Certificate(peerCertificate)
2587 };
2588 } else {
2589 x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2590 }
2591 } else {
2592 peerCerts = new Certificate[peerCertificateChain.length + 1];
2593 peerCerts[0] = new LazyX509Certificate(peerCertificate);
2594
2595 if (OpenSsl.JAVAX_CERTIFICATE_CREATION_SUPPORTED) {
2596 x509PeerCerts = new X509Certificate[peerCertificateChain.length + 1];
2597 x509PeerCerts[0] = new LazyJavaxX509Certificate(peerCertificate);
2598 } else {
2599 x509PeerCerts = JAVAX_CERTS_NOT_SUPPORTED;
2600 }
2601
2602 initCerts(peerCertificateChain, 1);
2603 }
2604 }
2605 }
2606
2607 calculateMaxWrapOverhead();
2608
2609 handshakeState = HandshakeState.FINISHED;
2610 } else {
2611 throw new SSLException("Already closed");
2612 }
2613 }
2614 }
2615
2616 private void initCerts(byte[][] chain, int startPos) {
2617 for (int i = 0; i < chain.length; i++) {
2618 int certPos = startPos + i;
2619 peerCerts[certPos] = new LazyX509Certificate(chain[i]);
2620 if (x509PeerCerts != JAVAX_CERTS_NOT_SUPPORTED) {
2621 x509PeerCerts[certPos] = new LazyJavaxX509Certificate(chain[i]);
2622 }
2623 }
2624 }
2625
2626 @Override
2627 public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
2628 synchronized (ReferenceCountedOpenSslEngine.this) {
2629 if (isEmpty(peerCerts)) {
2630 throw new SSLPeerUnverifiedException("peer not verified");
2631 }
2632 return peerCerts.clone();
2633 }
2634 }
2635
2636 @Override
2637 public Certificate[] getLocalCertificates() {
2638 Certificate[] localCerts = this.localCertificateChain;
2639 if (localCerts == null) {
2640 return null;
2641 }
2642 return localCerts.clone();
2643 }
2644
2645 @Override
2646 public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
2647 synchronized (ReferenceCountedOpenSslEngine.this) {
2648 if (x509PeerCerts == JAVAX_CERTS_NOT_SUPPORTED) {
2649
2650
2651 throw new UnsupportedOperationException();
2652 }
2653 if (isEmpty(x509PeerCerts)) {
2654 throw new SSLPeerUnverifiedException("peer not verified");
2655 }
2656 return x509PeerCerts.clone();
2657 }
2658 }
2659
2660 @Override
2661 public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
2662 Certificate[] peer = getPeerCertificates();
2663
2664
2665 return ((java.security.cert.X509Certificate) peer[0]).getSubjectX500Principal();
2666 }
2667
2668 @Override
2669 public Principal getLocalPrincipal() {
2670 Certificate[] local = this.localCertificateChain;
2671 if (local == null || local.length == 0) {
2672 return null;
2673 }
2674 return ((java.security.cert.X509Certificate) local[0]).getSubjectX500Principal();
2675 }
2676
2677 @Override
2678 public String getCipherSuite() {
2679 synchronized (ReferenceCountedOpenSslEngine.this) {
2680 if (cipher == null) {
2681 return SslUtils.INVALID_CIPHER;
2682 }
2683 return cipher;
2684 }
2685 }
2686
2687 @Override
2688 public String getProtocol() {
2689 String protocol = this.protocol;
2690 if (protocol == null) {
2691 synchronized (ReferenceCountedOpenSslEngine.this) {
2692 if (!isDestroyed()) {
2693 protocol = SSL.getVersion(ssl);
2694 } else {
2695 protocol = StringUtil.EMPTY_STRING;
2696 }
2697 }
2698 }
2699 return protocol;
2700 }
2701
2702 @Override
2703 public String getPeerHost() {
2704 return ReferenceCountedOpenSslEngine.this.getPeerHost();
2705 }
2706
2707 @Override
2708 public int getPeerPort() {
2709 return ReferenceCountedOpenSslEngine.this.getPeerPort();
2710 }
2711
2712 @Override
2713 public int getPacketBufferSize() {
2714 return SSL.SSL_MAX_ENCRYPTED_LENGTH;
2715 }
2716
2717 @Override
2718 public int getApplicationBufferSize() {
2719 return applicationBufferSize;
2720 }
2721
2722 @Override
2723 public void tryExpandApplicationBufferSize(int packetLengthDataOnly) {
2724 if (packetLengthDataOnly > MAX_PLAINTEXT_LENGTH && applicationBufferSize != MAX_RECORD_SIZE) {
2725 applicationBufferSize = MAX_RECORD_SIZE;
2726 }
2727 }
2728
2729 @Override
2730 public String toString() {
2731 return "DefaultOpenSslSession{" +
2732 "sessionContext=" + sessionContext +
2733 ", id=" + id +
2734 '}';
2735 }
2736
2737 @Override
2738 public int hashCode() {
2739 return sessionId().hashCode();
2740 }
2741
2742 @Override
2743 public boolean equals(Object o) {
2744 if (o == this) {
2745 return true;
2746 }
2747
2748 if (!(o instanceof OpenSslSession)) {
2749 return false;
2750 }
2751 return sessionId().equals(((OpenSslSession) o).sessionId());
2752 }
2753 }
2754
2755 private interface NativeSslException {
2756 int errorCode();
2757 }
2758
2759 private static final class OpenSslException extends SSLException implements NativeSslException {
2760 private final int errorCode;
2761
2762 OpenSslException(String reason, int errorCode) {
2763 super(reason);
2764 this.errorCode = errorCode;
2765 }
2766
2767 @Override
2768 public int errorCode() {
2769 return errorCode;
2770 }
2771 }
2772
2773 private static final class OpenSslHandshakeException extends SSLHandshakeException implements NativeSslException {
2774 private final int errorCode;
2775
2776 OpenSslHandshakeException(String reason, int errorCode) {
2777 super(reason);
2778 this.errorCode = errorCode;
2779 }
2780
2781 @Override
2782 public int errorCode() {
2783 return errorCode;
2784 }
2785 }
2786 }