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